# Waffo Pancake — Full Documentation > Complete official API reference and guides, served directly by the Waffo Pancake website. Source: https://docs.waffo.ai/llms-full.txt Snapshot synced at: 2026-10-29T14:40:53.358Z Source SHA-256: 75b6598f9ae1203e9e27b89e434292f20815eba1f330a5bdd8f1020b0edef913 Refresh: npm run sync:llms-full The content below is a snapshot of the official documentation. Consult the linked source for changes published after the sync time. --- # Authentication Source: https://docs.waffo.ai/api-reference/authentication Secure your API requests with API Key authentication ## Authentication Overview Waffo Pancake supports two authentication methods for API access: | Method | Use Case | Description | | - | - | - | | **API Key** | Server-to-server calls | Permanent authentication using RSA-SHA256 signatures | | **Store Slug** | Public checkout flows | Public access using `X-Store-Slug` and `X-Environment` headers | *** ## API Key Authentication API Keys provide permanent server-to-server authentication using RSA-SHA256 signatures. The private key never leaves your server. ### Request Headers ```bash theme={"system"} X-Merchant-Id: MER_2aUyqjCzEIiEcYMKj7TZtw X-Timestamp: 1705312200 X-Signature: BASE64_ENCODED_SIGNATURE Content-Type: application/json ``` > [!NOTE] > > **API Key authentication does not require the `X-Environment` header.** Each API Key is bound to either test or prod at creation time. The environment is determined by which key successfully verifies the signature. > [!NOTE] > > **One key covers every store.** The API Key and `X-Merchant-Id` are merchant-level: all stores under your merchant account share the same credential, and the store a call acts on comes from the request itself — the `storeId` field on endpoints that take one, or the store that owns the `productId` on checkout sessions. The store ID shown on the Dashboard's Integration page is only an example value (by default your most recently created store) and does not change when you switch stores; copy the ID of the store you actually mean to target. ### Using the SDK (Recommended) ```typescript theme={"system"} import { WaffoPancake } from "@waffo/pancake-ts"; const client = new WaffoPancake({ merchantId: process.env.WAFFO_MERCHANT_ID!, privateKey: process.env.WAFFO_PRIVATE_KEY!, }); // All requests are automatically signed const { store } = await client.stores.create({ name: "My Store" }); ``` ### Signing Algorithm (Manual Integration) If you're not using the SDK, you need to implement RSA-SHA256 request signing: ``` 1. Build the canonical request: canonicalRequest = METHOD + "\n" + PATH + "\n" + TIMESTAMP + "\n" + SHA256_BASE64(BODY) 2. Sign with RSA-SHA256: signature = RSA-SHA256(canonicalRequest, privateKey) 3. Base64 encode: X-Signature = Base64(signature) ``` ### Manual Signing Examples ```javascript Node.js theme={"system"} const crypto = require('crypto'); const MERCHANT_ID = 'MER_2aUyqjCzEIiEcYMKj7TZtw'; const PRIVATE_KEY = `-----BEGIN RSA PRIVATE KEY----- ...your private key... -----END RSA PRIVATE KEY-----`; async function callApiWithSignature(method, path, body) { const timestamp = Math.floor(Date.now() / 1000).toString(); const bodyStr = JSON.stringify(body); const bodyHash = crypto.createHash('sha256').update(bodyStr).digest('base64'); // Build canonical request const canonicalRequest = `${method}\n${path}\n${timestamp}\n${bodyHash}`; // RSA-SHA256 sign const signature = crypto.sign('sha256', Buffer.from(canonicalRequest), PRIVATE_KEY).toString('base64'); const response = await fetch(`https://api.waffo.ai${path}`, { method, headers: { 'Content-Type': 'application/json', 'X-Merchant-Id': MERCHANT_ID, 'X-Timestamp': timestamp, 'X-Signature': signature }, body: bodyStr }); return response.json(); } // Usage const result = await callApiWithSignature('POST', '/v1/actions/store/create-store', { name: 'My Store' }); ``` ```bash cURL theme={"system"} MERCHANT_ID="MER_2aUyqjCzEIiEcYMKj7TZtw" TIMESTAMP=$(date +%s) BODY='{"name":"My Store"}' BODY_HASH=$(echo -n "$BODY" | openssl dgst -sha256 -binary | base64 | tr -d '\n') CANONICAL_REQUEST="POST /v1/actions/store/create-store $TIMESTAMP $BODY_HASH" # Sign with openssl (requires private_key.pem file) SIGNATURE=$(echo -n "$CANONICAL_REQUEST" | openssl dgst -sha256 -sign private_key.pem | base64 | tr -d '\n') curl -X POST "https://api.waffo.ai/v1/actions/store/create-store" \ -H "Content-Type: application/json" \ -H "X-Merchant-Id: $MERCHANT_ID" \ -H "X-Timestamp: $TIMESTAMP" \ -H "X-Signature: $SIGNATURE" \ -d "$BODY" ``` ```python Python theme={"system"} import hashlib import time import base64 import json import requests from cryptography.hazmat.primitives import hashes, serialization from cryptography.hazmat.primitives.asymmetric import padding MERCHANT_ID = 'MER_2aUyqjCzEIiEcYMKj7TZtw' PRIVATE_KEY = '''-----BEGIN RSA PRIVATE KEY----- ...your private key... -----END RSA PRIVATE KEY-----''' def call_api_with_signature(method, path, body): timestamp = str(int(time.time())) body_str = json.dumps(body, separators=(',', ':')) body_hash = base64.b64encode(hashlib.sha256(body_str.encode()).digest()).decode() # Build canonical request canonical_request = f"{method}\n{path}\n{timestamp}\n{body_hash}" # RSA-SHA256 sign private_key = serialization.load_pem_private_key(PRIVATE_KEY.encode(), password=None) signature = private_key.sign(canonical_request.encode(), padding.PKCS1v15(), hashes.SHA256()) signature_b64 = base64.b64encode(signature).decode() response = requests.post( f'https://api.waffo.ai{path}', headers={ 'Content-Type': 'application/json', 'X-Merchant-Id': MERCHANT_ID, 'X-Timestamp': timestamp, 'X-Signature': signature_b64 }, data=body_str ) return response.json() # Usage result = call_api_with_signature('POST', '/v1/actions/store/create-store', { 'name': 'My Store' }) ``` > [!WARNING] > > **Private Key Security** > > * Never expose the private key in client-side code > * Do not commit private keys to version control > * Store private keys in environment variables > * Rotate keys regularly, especially after team changes > * Timestamp must be at most **5 minutes older** than server time and at most **1 minute ahead** of server time > [!NOTE] > > **Keep your server clock NTP-synced** > > The accepted timestamp window is asymmetric: from 5 minutes behind server time to 1 minute ahead of it. A clock running fast is the tighter constraint -- if your server clock is more than 1 minute ahead, every signed request is rejected with `401 Unauthorized` even though the signature itself is correct. *** ## Store Slug Authentication For public-facing checkout flows, use Store Slug authentication. This allows visitors to create checkout sessions and query public store data without API Key credentials. ### Request Headers ```bash theme={"system"} X-Store-Slug: my-awesome-store-k8x2m9ab X-Environment: test | prod Content-Type: application/json ``` ### Example ```bash cURL theme={"system"} curl -X POST https://api.waffo.ai/v1/actions/checkout/create-session \ -H "X-Store-Slug: my-awesome-store-k8x2m9ab" \ -H "X-Environment: test" \ -H "Content-Type: application/json" \ -d '{"productId": "PROD_4cWAslE1GKkGeaOMl9Vbmy", "productType": "onetime", "currency": "USD"}' ``` ```javascript JavaScript theme={"system"} const response = await fetch('https://api.waffo.ai/v1/graphql', { method: 'POST', headers: { 'X-Store-Slug': 'my-awesome-store-k8x2m9ab', 'Content-Type': 'application/json', 'X-Environment': 'prod' }, body: JSON.stringify({ query: `query { store { id name onetimeProducts { id name prices } } }` }) }); ``` *** ## Creating API Keys **1. Go to API & Development Page** Navigate to Dashboard → API & Development → API Keys **2. Create API Key** Click "Create API Key" to generate a new RSA key pair. The public key is sent to the server automatically. **3. Name and Configure** Give it a descriptive name (e.g., "Production Server") and select the target environment (Test or Production). **4. Download Private Key** **Download your private key immediately.** It will not be shown again. > [!WARNING] > > Deleting an API key is immediate and irreversible. Any requests signed with the deleted key will fail with `401 Unauthorized`. *** ## Authentication Method Comparison | Feature | API Key | Store Slug | | - | :-: | :-: | | Server-side use | Yes | No | | Client-side use | No | Yes | | Requires X-Environment | No | Yes | | Issue Session Token | Yes | No | | Create Checkout Session | Yes | Yes | | Product Management | Yes | No | | GraphQL Queries | Yes | Yes (public data only) | | Validity | Permanent (key-controlled) | - | *** ## Authentication Errors | Status | Error | Solution | | - | - | - | | 401 | Invalid signature | Check signing algorithm, private key, and timestamp freshness (accepted window: 5 min behind to 1 min ahead of server time) | | 401 | Invalid or expired token | Re-authenticate or use a valid API Key | | 403 | Insufficient permissions | Check if the role has access to the endpoint | | 400 | Missing authentication | Ensure required headers are present | | 400 | Multiple authentication methods detected | Send exactly ONE credential. `X-Store-Slug` and `Authorization: Bearer` (or API Key headers) are mutually exclusive — a session-token call must drop the slug header, not add to it | ```json theme={"system"} { "data": null, "errors": [ { "message": "Invalid signature", "layer": "gateway" } ] } ``` *** ## Security Best Practices 1. **Never expose private keys** in client-side code, version control, or public repositories 2. **Use HTTPS** for all API requests 3. **Verify Webhook signatures** to prevent forged requests 4. **Separate test and production keys** -- create distinct keys for each environment 5. **Rotate keys regularly**, especially after team member changes 6. **Monitor API usage** in the Dashboard for unusual activity # Issue Session Token Source: https://docs.waffo.ai/api-reference/endpoints/auth/issue-session-token Issue a session token for a customer to create orders in your store, or to sign them into your store's customer portal Issue a Session Token for a customer to create orders in your store, or — with `purpose: "portal"` — to sign an already signed-in customer of your site into your store's customer portal without email verification. This is an **API Key exclusive** endpoint. ``` POST /v1/actions/auth/issue-session-token ``` **Authentication:** API Key ## How It Works 1. Your server calls this endpoint with API Key authentication 2. You receive a short-lived session token 3. Pass the token to the customer's browser 4. The customer uses the token (`Authorization: Bearer `) to create orders and interact with checkout Session tokens are scoped to a single store and expire automatically. ## Customer Portal Mode Pass `purpose: "portal"` to get a link into the customer portal for the customer your site has already signed in. The call is the same; these rules change: | | Without `purpose` | `purpose: "portal"` | | - | - | - | | Store | `storeId` or `productId` | `storeId` required; `productId` is rejected with 400 | | Environment | Chosen per request by the `X-Environment` header | Fixed to the environment of the API Key that signed the call (test key → test portal data, production key → production portal data). There is no environment field | | Response | `token`, `expiresAt` | `token`, `expiresAt`, `portalUrl` | To send the customer into the portal, append `#token=` to `portalUrl` and answer the customer's browser with a 302 redirect to the result. The SDK helpers build this URL for you — see [Let Signed-In Customers Manage Orders](/guides/customer-portal-sso). > [!WARNING] > > The portal link is **not single-use**. Anyone holding it can open the portal as that customer while the session is alive. Treat the token and the full link as bearer credentials: mint them on your server right before the redirect, and never log them, store them, or send them by email. A portal token is bound to its environment. If you also call the [Customer Portal API](/api-reference/endpoints/auth/customer-endpoints) with it, send an `X-Environment` header that matches the API Key's environment; any other value is rejected with 403 `Environment mismatch`. Requests without `purpose` behave exactly as before. ## Request Body | Field | Type | Required | Description | | - | - | - | - | | `storeId` | string | No | Target store ID (Short ID format `STO_xxx`). Required when `productId` is not provided | | `productId` | string | No | Product ID (Short ID format `PROD_xxx`). When provided without `storeId`, the server derives the store from the product | | `buyerIdentity` | string | Yes | Customer identity for order attribution (e.g., email or internal user ID). Encoded into the session JWT. In portal mode it must be the same value you passed when the customer's orders were created | | `purpose` | string | No | Set to `"portal"` to issue a customer portal session (see [Customer Portal Mode](#customer-portal-mode)). Omit it for checkout tokens | ## Example Request ```typescript SDK theme={"system"} // Using storeId const { token, expiresAt } = await client.auth.issueSessionToken({ storeId: "STO_2aUyqjCzEIiEcYMKj7TZtw", buyerIdentity: "customer@example.com", }); // Using productId (storeId derived automatically) const { token, expiresAt } = await client.auth.issueSessionToken({ productId: "PROD_7J3K5L8M2N4P6Q9R", buyerIdentity: "customer@example.com", }); // Customer portal link (calls this endpoint with purpose: "portal"; // portalUrl already ends with #token=...) const { portalUrl } = await client.auth.createCustomerPortalLink({ storeId: "STO_2aUyqjCzEIiEcYMKj7TZtw", buyerIdentity: "user_8f3a2c", }); ``` ```bash cURL (with storeId) theme={"system"} MERCHANT_ID="MER_2aUyqjCzEIiEcYMKj7TZtw" TIMESTAMP=$(date +%s) BODY='{"storeId":"STO_2aUyqjCzEIiEcYMKj7TZtw","buyerIdentity":"customer@example.com"}' BODY_HASH=$(echo -n "$BODY" | openssl dgst -sha256 -binary | base64 | tr -d '\n') CANONICAL_REQUEST="POST /v1/actions/auth/issue-session-token $TIMESTAMP $BODY_HASH" SIGNATURE=$(echo -n "$CANONICAL_REQUEST" | openssl dgst -sha256 -sign private_key.pem | base64 | tr -d '\n') curl -X POST "https://api.waffo.ai/v1/actions/auth/issue-session-token" \ -H "Content-Type: application/json" \ -H "X-Merchant-Id: $MERCHANT_ID" \ -H "X-Timestamp: $TIMESTAMP" \ -H "X-Signature: $SIGNATURE" \ -d "$BODY" ``` ```bash cURL (with productId) theme={"system"} MERCHANT_ID="MER_2aUyqjCzEIiEcYMKj7TZtw" TIMESTAMP=$(date +%s) BODY='{"productId":"PROD_7J3K5L8M2N4P6Q9R","buyerIdentity":"customer@example.com"}' BODY_HASH=$(echo -n "$BODY" | openssl dgst -sha256 -binary | base64 | tr -d '\n') CANONICAL_REQUEST="POST /v1/actions/auth/issue-session-token $TIMESTAMP $BODY_HASH" SIGNATURE=$(echo -n "$CANONICAL_REQUEST" | openssl dgst -sha256 -sign private_key.pem | base64 | tr -d '\n') curl -X POST "https://api.waffo.ai/v1/actions/auth/issue-session-token" \ -H "Content-Type: application/json" \ -H "X-Merchant-Id: $MERCHANT_ID" \ -H "X-Timestamp: $TIMESTAMP" \ -H "X-Signature: $SIGNATURE" \ -d "$BODY" ``` ```bash cURL (customer portal) theme={"system"} MERCHANT_ID="MER_2aUyqjCzEIiEcYMKj7TZtw" TIMESTAMP=$(date +%s) BODY='{"storeId":"STO_2aUyqjCzEIiEcYMKj7TZtw","buyerIdentity":"user_8f3a2c","purpose":"portal"}' BODY_HASH=$(echo -n "$BODY" | openssl dgst -sha256 -binary | base64 | tr -d '\n') CANONICAL_REQUEST="POST /v1/actions/auth/issue-session-token $TIMESTAMP $BODY_HASH" SIGNATURE=$(echo -n "$CANONICAL_REQUEST" | openssl dgst -sha256 -sign private_key.pem | base64 | tr -d '\n') curl -X POST "https://api.waffo.ai/v1/actions/auth/issue-session-token" \ -H "Content-Type: application/json" \ -H "X-Merchant-Id: $MERCHANT_ID" \ -H "X-Timestamp: $TIMESTAMP" \ -H "X-Signature: $SIGNATURE" \ -d "$BODY" ``` ```python Python theme={"system"} # Using storeId result = call_api_with_signature('POST', '/v1/actions/auth/issue-session-token', { 'storeId': 'STO_2aUyqjCzEIiEcYMKj7TZtw', 'buyerIdentity': 'customer@example.com' }) # Using productId result = call_api_with_signature('POST', '/v1/actions/auth/issue-session-token', { 'productId': 'PROD_7J3K5L8M2N4P6Q9R', 'buyerIdentity': 'customer@example.com' }) print(result['data']['token']) # Customer portal: append the token to portalUrl, then 302 the browser there result = call_api_with_signature('POST', '/v1/actions/auth/issue-session-token', { 'storeId': 'STO_2aUyqjCzEIiEcYMKj7TZtw', 'buyerIdentity': 'user_8f3a2c', 'purpose': 'portal' }) redirect_url = result['data']['portalUrl'] + '#token=' + result['data']['token'] ``` ## Success Response (200) ```json theme={"system"} { "data": { "token": "opaque-session-token...", "expiresAt": "2024-01-15T11:00:00.000Z" } } ``` With `purpose: "portal"`: ```json theme={"system"} { "data": { "token": "opaque-session-token...", "expiresAt": "2024-01-15T11:00:00.000Z", "portalUrl": "https://pancake.waffo.ai/consumer/portal/store/STO_2aUyqjCzEIiEcYMKj7TZtw" } } ``` ## Response Fields | Field | Type | Description | | - | - | - | | `token` | string | Session Token | | `expiresAt` | string | Expiration time (ISO 8601) if the session stays idle. The session lasts 15 minutes and each use extends it, so an active session lives past this time | | `portalUrl` | string | Only when `purpose` is `"portal"`. Portal page for this store, without the token. Append `#token=` before redirecting | ## Errors > **Retry policy:** Never retry 4xx — fix the request and resubmit. Retry 5xx with exponential backoff (start 5s, max 3 attempts). | Status | `errors[0].message` | What it means | Recommended handling | | - | - | - | - | | 400 | `Missing required field: buyerIdentity` | `buyerIdentity` is empty or missing | Fix the request body, then resubmit | | 400 | `Missing required field: provide storeId or productId` | Neither `storeId` nor `productId` was provided | Provide one of them, then resubmit | | 400 | `purpose=portal requires storeId and does not accept productId` | `purpose` is `"portal"` and `productId` was sent (with or without `storeId`) | Send `storeId` only (no `productId`), then resubmit | | 400 | `Invalid purpose: expected "portal"` | `purpose` has a value other than `"portal"` | Set `purpose` to `"portal"` or omit it, then resubmit | | 400 | `Expected format: STO_xxx, got "..."` | `storeId` Short ID could not be decoded | Fix the `storeId` format, then resubmit | | 400 | `Expected format: PROD_xxx, got "..."` | `productId` Short ID could not be decoded | Fix the `productId` format, then resubmit | | 400 | `Store is not active` | Store exists but its status is not `active` | Activate the store, then resubmit | | 401 | `Missing merchantId in request context` | API Key authentication did not resolve a merchant | Verify API Key headers and signature | | 403 | `Access denied: you do not have permission to this store` | Merchant does not own the store | Verify store ownership | | 404 | `Store not found` | Store does not exist or has been deleted | Verify the store ID | | 404 | `Product not found` | Product does not exist | Verify the product ID | | 500 | `Internal server error` | Unexpected server-side failure | Retry with exponential backoff (start 5s, max 3 attempts) | ## Two pitfalls worth knowing **Do not reuse one idempotency key to mint tokens.** Sending the same `X-Idempotency-Key` on repeated calls hits the platform's 24-hour cache and replays the FIRST response — handing you a token that expired long ago. The SDKs no longer derive keys, so this only happens if you set the header yourself (directly over REST, or by passing the same `idempotencyKey` twice). If you mint tokens for the same buyer repeatedly (a token-refresh endpoint, a plan-change link generator), use a fresh key per call or none at all. **Mint right before you redirect.** The token lives 15 minutes (sliding), while a checkout or plan-change session lives 24 hours by default. A token minted alongside the session and parked in a queue or an email will be dead by the time the buyer clicks. For plan-change links specifically, the token goes in the URL fragment — see [Building the link the customer opens](/api-reference/endpoints/orders/create-checkout-session#building-the-link-the-customer-opens). # Auth Endpoints Source: https://docs.waffo.ai/api-reference/endpoints/auth/overview Issue session tokens for checkout flows and customer portal sign-in Auth endpoints are **API Key exclusive**. Use these endpoints to issue session tokens that allow customers to interact with your store's checkout flow, or to sign customers who are already signed in on your site into your store's customer portal. ## Typical Flow: Embedded Checkout ```mermaid theme={"system"} sequenceDiagram participant C as Customer Browser participant S as Your Server participant W as Waffo Pancake API C->>S: Click "Buy Now" S->>W: POST /issue-session-token Note over S,W: API Key signature W->>S: { token, expiresAt } S->>C: Return token + checkout URL C->>W: POST /create-order Note over C,W: Bearer sessionToken W->>C: { checkoutUrl } C->>C: Redirect to checkout page ``` ## Typical Flow: Customer Portal Sign-In ```mermaid theme={"system"} sequenceDiagram participant C as Customer Browser participant S as Your Server participant W as Waffo Pancake API participant P as Customer Portal C->>S: Click "Manage orders" (signed in on your site) S->>W: POST /issue-session-token (purpose: "portal") Note over S,W: API Key signature W->>S: { token, expiresAt, portalUrl } S->>C: 302 to portalUrl#token=... C->>P: Open the portal for this store ``` See [Let Signed-In Customers Manage Orders](/guides/customer-portal-sso) for the full integration. ## Endpoints > **[Issue Session Token](/api-reference/endpoints/auth/issue-session-token)** > > Issue a session token for a customer to create orders in your store, or a customer portal link. # Content Safety Endpoints Source: https://docs.waffo.ai/api-reference/endpoints/content-safety/overview Screen generation prompts for content safety before you generate Content safety endpoints let you run a Waffo content safety check on a user's text prompt **before** your product generates an image or video. Send the prompt, receive a clear verdict, and generate only when the verdict is `allow`. The check is stateless — the prompt text is not retained after the response is returned. This is the fastest way to satisfy the pre-generation moderation requirement in [AIGC compliance](/mor/account-reviews/aigc-compliance). Pair it with an output-stage check for full coverage. ## What it checks The check screens the prompt for content that is unsafe to generate, with particular focus on child-unsafe material — the category every major AI generation platform intercepts. When the prompt matches one or more restricted categories, the check returns a non-`allow` verdict and lists the categories it matched. ## Verdicts The `action` field carries the verdict. Continue to generation only on `allow`. | `action` | Meaning | What to do | | - | - | - | | `allow` | The prompt passed the check | Proceed to your generation model as normal | | `review` | The prompt needs a closer look before a decision | Hold the request; a decision usually resolves within about 1 hour | | `block` | The prompt matched restricted content | Do not generate; show the user a friendly message | > [!NOTE] > > Treat `allow` as the only signal to proceed. Both `review` and `block` mean "do not generate yet." ## Reason codes The `reasonCode` field explains the verdict in machine-readable form. | `reasonCode` | Paired `action` | Meaning | | - | - | - | | `allowed` | `allow` | No restricted content detected | | `review_required` | `review` | Held for a closer look before a decision | | `restricted_content` | `block` | Matched one or more restricted categories | | `service_degraded` | `review` | The moderation service was temporarily unavailable, so the request is held rather than generated | > [!NOTE] > > When the moderation service is temporarily unavailable, the check returns `review` (with `service_degraded`) so that nothing is generated without a verdict. Retry the request rather than generating on a degraded response. ## How to use it **1. Collect the user's prompt** Any text description your user submits for image or video generation. **2. Call scan-prompt before generating** Send the prompt to [`scan-prompt`](/api-reference/endpoints/content-safety/scan-prompt) and read the `action` field. **3. Act on the verdict** * `allow` → call your generation model. * `review` → hold the request and retry later; a decision usually resolves within about 1 hour. * `block` → don't generate; show a friendly message such as "This content doesn't meet our usage guidelines." ## Endpoints > **[Scan Prompt](/api-reference/endpoints/content-safety/scan-prompt)** > > Screen a generation prompt and receive an allow / review / block verdict. # Scan Prompt Source: https://docs.waffo.ai/api-reference/endpoints/content-safety/scan-prompt Screen a generation prompt for content safety before generating Run a Waffo content safety check on a user's text prompt before your product generates an image or video. The response carries a verdict in the `action` field — continue to generation only when it is `allow`. The check is stateless and does not retain the prompt text after returning. ``` POST /v1/actions/verification/scan-prompt ``` **Authentication:** API Key ## Request Body | Field | Type | Required | Description | | - | - | - | - | | `prompt` | string | Yes | The user's generation prompt (1-10000 characters) | | `locale` | string | No | Language hint for the check — one of `ja`, `en`, `zh` | | `semantic` | string | No | Semantic-scoring mode — one of `off`, `shadow`, `enforce` | > [!NOTE] > > `semantic` controls the optional semantic-scoring layer: `off` disables it, `shadow` scores without affecting the verdict, and `enforce` lets the score influence the verdict. When omitted, the service applies its default mode. > [!NOTE] > > **Pricing and rate limit.** The check is free of charge during the beta and needs no separate activation — the API Key you already use for payments can call it. The gateway's standard limit applies: 100 requests per 60-second sliding window per merchant per endpoint path. Beyond that the call returns `429` with a `Retry-After` header (see the Errors table); wait that long and retry rather than dropping the generation request. ## Example Request ```typescript SDK theme={"system"} import { WaffoPancake } from "@waffo/pancake-ts"; const client = new WaffoPancake({ merchantId: process.env.WAFFO_MERCHANT_ID!, privateKey: process.env.WAFFO_PRIVATE_KEY!, }); const verdict = await client.contentSafety.scanPrompt({ prompt: "A serene mountain landscape at sunset", locale: "en", semantic: "enforce", }); if (verdict.action === "allow") { // safe to generate } ``` ```typescript TypeScript (fetch) theme={"system"} // Uses callApi() helper from authentication.mdx const result = await callApi("POST", "/v1/actions/verification/scan-prompt", { prompt: "A serene mountain landscape at sunset", locale: "en", semantic: "enforce", }); console.log(result.data.action); // => "allow" console.log(result.data.reasonCode); // => "allowed" ``` ```java Java theme={"system"} // Uses callApi() helper from authentication.mdx String body = """ {"prompt":"A serene mountain landscape at sunset","locale":"en","semantic":"enforce"}"""; String response = callApi("POST", "/v1/actions/verification/scan-prompt", body); System.out.println(response); // => {"data":{"action":"allow","reasonCode":"allowed","matchedCategories":[],...}} ``` ```python Python theme={"system"} # Uses call_api() helper from authentication.mdx result = call_api("POST", "/v1/actions/verification/scan-prompt", { "prompt": "A serene mountain landscape at sunset", "locale": "en", "semantic": "enforce", }) data = result["data"] print(data["action"]) # => "allow" print(data["reasonCode"]) # => "allowed" ``` ```go Go theme={"system"} // Uses callAPI() helper from authentication.mdx body := map[string]interface{}{ "prompt": "A serene mountain landscape at sunset", "locale": "en", "semantic": "enforce", } result, err := callAPI("POST", "/v1/actions/verification/scan-prompt", body) if err != nil { log.Fatal(err) } fmt.Println(string(result)) // => {"data":{"action":"allow","reasonCode":"allowed","matchedCategories":[],...}} ``` ```rust Rust theme={"system"} // Uses call_api() helper from authentication.mdx let body = serde_json::json!({ "prompt": "A serene mountain landscape at sunset", "locale": "en", "semantic": "enforce" }); let result = call_api("POST", "/v1/actions/verification/scan-prompt", &body).await?; println!("{}", result); // => {"data":{"action":"allow","reasonCode":"allowed","matchedCategories":[],...}} ``` ```c C theme={"system"} /* Uses call_api() helper from authentication.mdx */ const char *body = "{\"prompt\":\"A serene mountain landscape at sunset\",\"locale\":\"en\",\"semantic\":\"enforce\"}"; char *response = call_api("POST", "/v1/actions/verification/scan-prompt", body); printf("%s\n", response); free(response); ``` ```cpp C++ theme={"system"} // Uses callApi() helper from authentication.mdx std::string body = R"({"prompt":"A serene mountain landscape at sunset","locale":"en","semantic":"enforce"})"; std::string response = callApi("POST", "/v1/actions/verification/scan-prompt", body); std::cout << response << std::endl; // => {"data":{"action":"allow","reasonCode":"allowed","matchedCategories":[],...}} ``` ```bash cURL theme={"system"} MERCHANT_ID="MER_2aUyqjCzEIiEcYMKj7TZtw" TIMESTAMP=$(date +%s) BODY='{"prompt":"A serene mountain landscape at sunset","locale":"en","semantic":"enforce"}' BODY_HASH=$(echo -n "$BODY" | openssl dgst -sha256 -binary | base64 | tr -d '\n') CANONICAL_REQUEST="POST /v1/actions/verification/scan-prompt $TIMESTAMP $BODY_HASH" SIGNATURE=$(echo -n "$CANONICAL_REQUEST" | openssl dgst -sha256 -sign private_key.pem | base64 | tr -d '\n') curl -X POST "https://api.waffo.ai/v1/actions/verification/scan-prompt" \ -H "Content-Type: application/json" \ -H "X-Merchant-Id: $MERCHANT_ID" \ -H "X-Timestamp: $TIMESTAMP" \ -H "X-Signature: $SIGNATURE" \ -d "$BODY" ``` ```bash wget theme={"system"} MERCHANT_ID="MER_2aUyqjCzEIiEcYMKj7TZtw" TIMESTAMP=$(date +%s) BODY='{"prompt":"A serene mountain landscape at sunset","locale":"en","semantic":"enforce"}' BODY_HASH=$(echo -n "$BODY" | openssl dgst -sha256 -binary | base64 | tr -d '\n') CANONICAL_REQUEST="POST /v1/actions/verification/scan-prompt $TIMESTAMP $BODY_HASH" SIGNATURE=$(echo -n "$CANONICAL_REQUEST" | openssl dgst -sha256 -sign private_key.pem | base64 | tr -d '\n') wget -qO- "https://api.waffo.ai/v1/actions/verification/scan-prompt" \ --header="Content-Type: application/json" \ --header="X-Merchant-Id: $MERCHANT_ID" \ --header="X-Timestamp: $TIMESTAMP" \ --header="X-Signature: $SIGNATURE" \ --post-data="$BODY" ``` ## Success Response (200) ```json theme={"system"} { "data": { "action": "allow", "reasonCode": "allowed", "matchedCategories": [], "requestId": "REQ_2aUyqjCzEIiEcYMKj7TZtw", "semanticStatus": "scored" } } ``` > [!NOTE] > > The `data` envelope above belongs to the raw HTTP response. The SDK unwraps it — `scanPrompt()` resolves to the verdict object itself, so read `verdict.action` directly. ## Response Fields | Field | Type | Description | | - | - | - | | `action` | string | Verdict: `allow`, `review`, or `block`. Continue to generation only on `allow`. | | `reasonCode` | string | Machine-readable reason: `allowed`, `review_required`, `restricted_content`, or `service_degraded` | | `matchedCategories` | string\[] | Restricted categories the prompt matched; empty when the verdict is `allow` | | `requestId` | string | Identifier for this check; include it when referencing the request in an appeal | | `semanticStatus` | string | State of the semantic-scoring layer: `disabled`, `scored`, `shadow_scored`, `provider_error`, etc. | ## Verdict handling | `action` | Recommended handling | | - | - | | `allow` | Call your generation model as normal. | | `review` | Hold the request and retry later; a decision usually resolves within about 1 hour. | | `block` | Do not generate. Show a friendly message such as "This content doesn't meet our usage guidelines." | > [!NOTE] > > When the moderation service is temporarily unavailable, the check returns `action: "review"` with `reasonCode: "service_degraded"` so that nothing is generated without a verdict. Retry the request rather than generating on a degraded response. ## Errors > **Retry policy:** Never retry 4xx — fix the request and resubmit. Retry 5xx with exponential backoff (start 5s, max 3 attempts). | Status | `errors[0].message` | What it means | Recommended handling | | - | - | - | - | | 400 | `Missing required field: prompt` | `prompt` is absent from the body | Fix the input and resubmit. | | 400 | `Prompt cannot be empty or contain only whitespace` | `prompt` is empty after trimming | Fix the input and resubmit. | | 400 | `Prompt cannot exceed 10000 characters` | `prompt` is longer than 10000 characters | Shorten the prompt and resubmit. | | 400 | `Invalid locale. Must be one of: ja, en, zh` | `locale` is not a supported value | Use a supported `locale` and resubmit. | | 400 | `Invalid semantic mode. Must be one of: off, shadow, enforce` | `semantic` is not a supported value | Use a supported `semantic` value and resubmit. | | 429 | `Too many requests` | More than 100 requests in the current 60-second window for this merchant and endpoint. Response headers carry `Retry-After`, `X-RateLimit-Limit`, `X-RateLimit-Remaining` and `X-RateLimit-Reset` | Wait for `Retry-After` seconds, then resubmit. | > [!NOTE] > > Screen prompts before generation and continue only on `allow`. For full coverage, add an output-stage check as described in [AIGC compliance](/mor/account-reviews/aigc-compliance). # Create Coupon Source: https://docs.waffo.ai/api-reference/endpoints/coupons/create-coupon Create a coupon with its code, optionally with its promotion codes, in one request Create a coupon with its own `code` — buyers can type it at checkout — optionally together with up to 20 promotion codes. Everything is created in one request: the coupon, its code and all its promotion codes become usable together, or none of them is created. A coupon limits redemptions only by its expiry (`redeemBy`) and total uses (`maxRedemptions`); put buyer restrictions (buyer emails, uses per buyer, minimum amount) on promotion codes. The coupon can also be applied with `couponId` on a [checkout session](/api-reference/endpoints/orders/create-checkout-session); add promotion codes later with [Create Promotion Code](/api-reference/endpoints/promotion-codes/create-promotion-code). ``` POST /v1/actions/coupon/create-coupon ``` **Authentication:** API Key (store owner or admin) ## Request Body | Field | Type | Required | Description | | - | - | - | - | | `storeId` | string | Yes | Store ID (Short ID format `STO_xxx`) | | `name` | string | Yes | Internal name (max 64 chars). Buyers do not see it | | `code` | string | No | The coupon's own code, which buyers type at checkout: 3–32 letters, digits or `-`, case-insensitive, stored in uppercase. Must not match an active code in the same store and environment, nor a code in `promotionCodes`. Omitted: a random 10-character code is generated | | `discount` | object | Yes | `{ "type": "percentage", "percentOff": 20 }` or `{ "type": "fixed_amount", "amountOff": { "USD": "5.00" } }` (see below) | | `duration` | string | No | How many subscription billing periods get the discount: `once` (default), `repeating` or `forever`. One-time orders are discounted once | | `durationInPeriods` | integer | When `repeating` | Number of billing periods (≥ 1). Only allowed when `duration` is `repeating` | | `productIds` | string\[] | No | Limit the coupon to these products (`PROD_xxx`, max 100). Empty or omitted means the whole store | | `maxRedemptions` | integer \| null | No | Total redemption limit (≥ 1) across the coupon's code and all its promotion codes. Refunds do not give uses back. `null` = unlimited | | `redeemBy` | string \| null | No | Expiry (ISO 8601, more than 60 seconds in the future). Discounts already attached to subscriptions also end at this time | | `promotionCodes` | object\[] | No | Promotion codes to create with the coupon, 0–20 (see [Promotion Code Object](#promotion-code-object)). Omit for a coupon without codes | ## Discount Object | Field | Type | Description | | - | - | - | | `type` | string | `percentage` or `fixed_amount` | | `percentOff` | number | Required for `percentage`. 0 \< x ≤ 100, at most 2 decimals. `100` makes the order free | | `amountOff` | object | Required for `fixed_amount`. Amount off per ISO 4217 currency, as a display-format string, with no more decimal places than the currency allows (USD 2, JPY 0, BHD 3) — extra decimals return 400 and are not rounded. Orders in a currency that is not listed cannot use the coupon — there is no currency conversion | ```json theme={"system"} { "discount": { "type": "fixed_amount", "amountOff": { "USD": "5.00", "EUR": "4.50", "JPY": "800" } } } ``` ## Promotion Code Object Each entry of `promotionCodes` takes the same fields as [Create Promotion Code](/api-reference/endpoints/promotion-codes/create-promotion-code), without `couponId`: | Field | Type | Required | Description | | - | - | - | - | | `code` | string | No | Code buyers type: 3–32 letters, digits or `-`, case-insensitive, stored in uppercase. Must not match an active code in the same store and environment, nor another entry of the request, nor the coupon's `code`. Omitted: a random 10-character code is generated | | `restrictions` | object | No | `customerEmails`, `perCustomerLimit`, `maxRedemptions` (≤ the coupon's `maxRedemptions`), `expiresAt` (more than 60 seconds in the future and ≤ the coupon's `redeemBy`; defaults to it), `minimumAmount` — see [Restrictions Object](/api-reference/endpoints/promotion-codes/create-promotion-code#restrictions-object). `perCustomerLimit`, `maxRedemptions`, `expiresAt` and `minimumAmount` accept `null`, meaning not set (`expiresAt: null` falls back to the coupon's `redeemBy`). `customerEmails` does not accept `null`: omit it, or send `[]` | ## Example Request ```typescript SDK theme={"system"} import { WaffoPancake } from "@waffo/pancake-ts"; const client = new WaffoPancake({ merchantId: process.env.WAFFO_MERCHANT_ID!, privateKey: process.env.WAFFO_PRIVATE_KEY!, }); const { coupon } = await client.coupons.create( { storeId: "STO_2aUyqjCzEIiEcYMKj7TZtw", name: "Black Friday 20% off", discount: { type: "percentage", percentOff: 20 }, duration: "repeating", durationInPeriods: 3, maxRedemptions: 1000, redeemBy: "2026-12-01T00:00:00.000Z", code: "bf2026", promotionCodes: [{ code: "bf-new", restrictions: { perCustomerLimit: 1 } }], }, { idempotencyKey: "MER_2aUyqjCzEIiEcYMKj7TZtw-0f8e2a9c-5b1d-4e7a-9c3f-2d6b8e1a4c70" }, ); console.log(coupon.status, coupon.code, coupon.promotionCodes[0].code); // => "active" "BF2026" "BF-NEW" ``` ```bash cURL theme={"system"} MERCHANT_ID="MER_2aUyqjCzEIiEcYMKj7TZtw" IDEMPOTENCY_KEY="MER_2aUyqjCzEIiEcYMKj7TZtw-0f8e2a9c-5b1d-4e7a-9c3f-2d6b8e1a4c70" TIMESTAMP=$(date +%s) BODY='{"storeId":"STO_2aUyqjCzEIiEcYMKj7TZtw","name":"Black Friday 20% off","discount":{"type":"percentage","percentOff":20},"duration":"repeating","durationInPeriods":3,"maxRedemptions":1000,"redeemBy":"2026-12-01T00:00:00.000Z","code":"bf2026","promotionCodes":[{"code":"bf-new","restrictions":{"perCustomerLimit":1}}]}' BODY_HASH=$(echo -n "$BODY" | openssl dgst -sha256 -binary | base64 | tr -d '\n') CANONICAL_REQUEST="POST /v1/actions/coupon/create-coupon $TIMESTAMP $BODY_HASH" SIGNATURE=$(echo -n "$CANONICAL_REQUEST" | openssl dgst -sha256 -sign private_key.pem | base64 | tr -d '\n') curl -X POST "https://api.waffo.ai/v1/actions/coupon/create-coupon" \ -H "Content-Type: application/json" \ -H "X-Merchant-Id: $MERCHANT_ID" \ -H "X-Timestamp: $TIMESTAMP" \ -H "X-Signature: $SIGNATURE" \ -H "X-Idempotency-Key: $IDEMPOTENCY_KEY" \ -d "$BODY" ``` ```python Python theme={"system"} import hashlib, time, base64, json, requests from cryptography.hazmat.primitives import hashes, serialization from cryptography.hazmat.primitives.asymmetric import padding merchant_id = "MER_2aUyqjCzEIiEcYMKj7TZtw" timestamp = str(int(time.time())) body = { "storeId": "STO_2aUyqjCzEIiEcYMKj7TZtw", "name": "Black Friday 20% off", "discount": {"type": "percentage", "percentOff": 20}, "duration": "repeating", "durationInPeriods": 3, "maxRedemptions": 1000, "redeemBy": "2026-12-01T00:00:00.000Z", "code": "bf2026", "promotionCodes": [{"code": "bf-new", "restrictions": {"perCustomerLimit": 1}}], } body_json = json.dumps(body, separators=(",", ":")) body_hash = base64.b64encode(hashlib.sha256(body_json.encode()).digest()).decode() path = "/v1/actions/coupon/create-coupon" canonical = f"POST\n{path}\n{timestamp}\n{body_hash}" with open("private_key.pem", "rb") as f: private_key = serialization.load_pem_private_key(f.read(), password=None) signature = base64.b64encode( private_key.sign(canonical.encode(), padding.PKCS1v15(), hashes.SHA256()) ).decode() resp = requests.post( f"https://api.waffo.ai{path}", headers={ "Content-Type": "application/json", "X-Merchant-Id": merchant_id, "X-Timestamp": timestamp, "X-Signature": signature, "X-Idempotency-Key": "MER_2aUyqjCzEIiEcYMKj7TZtw-0f8e2a9c-5b1d-4e7a-9c3f-2d6b8e1a4c70", }, data=body_json, ) print(resp.json()) ``` ## Success Response (200) ```json theme={"system"} { "data": { "coupon": { "id": "CPN_5dXBtmF2HLlHfbPNm0Wcnz", "storeId": "STO_2aUyqjCzEIiEcYMKj7TZtw", "name": "Black Friday 20% off", "code": "BF2026", "status": "active", "discountType": "percentage", "percentOff": 20, "amountOff": null, "duration": "repeating", "durationInPeriods": 3, "productIds": [], "maxRedemptions": 1000, "redeemBy": "2026-12-01T00:00:00.000Z", "createdAt": "2026-11-01T08:00:00.000Z", "updatedAt": "2026-11-01T08:00:00.000Z", "promotionCodes": [ { "id": "PMC_7fZDvoH4JNnJhdRPo2Yep1", "couponId": "CPN_5dXBtmF2HLlHfbPNm0Wcnz", "code": "BF-NEW", "status": "active", "restrictions": { "customerEmails": [], "perCustomerLimit": 1, "maxRedemptions": null, "expiresAt": "2026-12-01T00:00:00.000Z", "minimumAmount": null }, "batchId": null, "createdAt": "2026-11-01T08:00:00.000Z" } ] } } } ``` ## Response Fields The response is wrapped in `data.coupon`. | Field | Type | Description | | - | - | - | | `id` | string | Coupon ID (`CPN_xxx`) | | `storeId` | string | Store ID (`STO_xxx`) | | `name` | string | Internal name | | `code` | string | The coupon's own code, in uppercase. Buyers can type it at checkout | | `status` | string | Always `active` in this response (see [Coupon Status Values](/api-reference/endpoints/coupons/overview)) | | `discountType` | string | `percentage` or `fixed_amount` | | `percentOff` | number \| null | Percentage off; `null` for `fixed_amount` | | `amountOff` | object \| null | Amount off per currency (display-format strings); `null` for `percentage`, and in a [response with warnings](#response-with-warnings) | | `duration` | string | `once`, `repeating` or `forever` | | `durationInPeriods` | integer \| null | Billing periods for `repeating`; otherwise `null` | | `productIds` | string\[] | Products the coupon is limited to; empty means the whole store | | `maxRedemptions` | integer \| null | Total redemption limit across the coupon's code and all its promotion codes | | `redeemBy` | string \| null | Expiry (ISO 8601) | | `createdAt` | string | Creation timestamp (ISO 8601) | | `updatedAt` | string | Last update timestamp (ISO 8601) | | `promotionCodes` | object\[] | The promotion codes created in this request, in request order (same fields as the [Create Promotion Code](/api-reference/endpoints/promotion-codes/create-promotion-code) response; `restrictions.minimumAmount` is `null` in a [response with warnings](#response-with-warnings)); empty when none were requested | > [!NOTE] > > Creation either succeeds or fails within the request. A `200` response always carries an `active` coupon. If the payment provider rejects the coupon or does not confirm the creation, the response is a `502`, the coupon is recorded as `failed` and every code of the request is released — create it again, with the same codes if you like. If a request is interrupted before it finishes, its coupon can stay `pending` and hold its codes; such a coupon is cleaned up on the spot — recorded as `failed`, codes released — by the next Create Coupon, Create Promotion Code or Generate Promotion Codes request in the same store and environment once it is more than 10 minutes old. ## Response With Warnings Once the coupon is active its codes are usable, and the request no longer fails. If Pancake cannot convert the amounts to display format at that point, it still returns `200` with the `active` coupon: `amountOff` and every `promotionCodes[].restrictions.minimumAmount` are `null` — the response shape does not change — and a top-level `warnings` array says the amounts were not converted. All other fields are filled in as usual. ```json theme={"system"} { "data": { "coupon": { "id": "CPN_5dXBtmF2HLlHfbPNm0Wcnz", "status": "active", "discountType": "fixed_amount", "amountOff": null, "...": "...", "promotionCodes": [ { "code": "BF-NEW", "restrictions": { "minimumAmount": null, "...": "..." }, "...": "..." } ] } }, "warnings": [ { "message": "Coupon was created, but amounts could not be converted to display format; amountOff and restrictions.minimumAmount are returned as null", "layer": "product", "aiHint": "- Query: read the coupon with the GraphQL `coupon(id)` query to get the display amounts; do not retry the creation" } ] } ``` The coupon has been created as requested — do not create it again. Read it with GraphQL `coupon(id)` to get its amounts. ## Errors > **Retry policy:** Never retry 4xx — fix the request and resubmit. Retry 5xx with exponential backoff (start 5s, max 3 attempts). Always retry with the same `X-Idempotency-Key`. | Status | `errors[0].message` | What it means | Recommended handling | | - | - | - | - | | 400 | `Missing header: x-context-merchant-id` | The merchant context header was not forwarded | Fix your SDK configuration | | 400 | `Missing or invalid header: x-context-environment` | Environment header is missing or not `test` / `prod` | Set `X-Environment` to `test` or `prod` | | 400 | `Invalid JSON body` | The body is not valid JSON | Fix the body, resubmit | | 400 | `Missing required field: storeId` / `Missing required field: name` | A required field was omitted | Add the missing field, resubmit | | 400 | `Expected format: STO_xxx, got "X"` | `storeId` is not a valid Short ID | Use a `STO_` prefixed Short ID | | 400 | `name must not exceed 64 characters` | `name` is too long | Shorten `name`, resubmit | | 400 | `code must be a string` / `promotionCodes[N].code must be a string` | `code`, or the `code` of entry `N` (0-based) of `promotionCodes`, is not a string | Send a string, or omit it for a random code | | 400 | `code must be 3-32 characters of letters, digits or '-'` / `promotionCodes[N].code must be 3-32 characters of letters, digits or '-'` | `code`, or the `code` of entry `N` (0-based), has an invalid character or length | Fix the code, resubmit | | 400 | `promotionCodes must not exceed 20 entries` | More than 20 promotion codes | Create at most 20 with the coupon; add the rest with Create Promotion Code | | 400 | `promotionCodes[N].code "X" duplicates another promotion code in this request` | Entry `N` (0-based) has the same code as an earlier entry (case-insensitive) | Remove the duplicate | | 400 | `promotionCodes[N].code "X" duplicates the coupon code` | Entry `N` (0-based) has the same code as `code` (case-insensitive) | Use another code for the entry | | 400 | `promotionCodes[N].restrictions.maxRedemptions must not exceed the coupon's maxRedemptions (M)` / `promotionCodes[N].restrictions.expiresAt must be more than 60 seconds in the future` / `promotionCodes[N].restrictions.expiresAt must not be later than the coupon's redeemBy (T)` | Entry `N` (0-based) goes beyond the coupon's limits, or its `expiresAt` is less than 60 seconds away | Fix that entry's restrictions | | 400 | `discount.type must be percentage or fixed_amount` / `discount: discount.type must be percentage or fixed_amount` | `discount.type` is not allowed (first form), or `discount` is missing or not an object (second form) | Send `discount` with `type` `percentage` or `fixed_amount` | | 400 | `discount.percentOff is required for percentage` / `discount.percentOff must be greater than 0` / `discount.percentOff must not exceed 100` / `discount.percentOff allows at most 2 decimal places` | `percentOff` is missing or out of range | Use a number with 0 \< x ≤ 100 and at most 2 decimals | | 400 | `discount.amountOff: At least one currency is required` / `promotionCodes[N].restrictions.minimumAmount: At least one currency is required` | `amountOff`, or the `minimumAmount` of entry `N` (0-based) of `promotionCodes`, is an empty object | Add at least one currency | | 400 | `discount.amountOff: Invalid currency code: "X". Must be 3 uppercase letters (e.g., "USD", "EUR", "JPY")` / `promotionCodes[N].restrictions.minimumAmount: Invalid currency code: "X". Must be 3 uppercase letters (e.g., "USD", "EUR", "JPY")` | A key in `amountOff`, or in the `minimumAmount` of entry `N`, is not an ISO 4217 code | Use 3 uppercase letters | | 400 | `discount.amountOff: Invalid amount for X: "Y". Must be a positive number string (e.g., "5.00", "500")` / `promotionCodes[N].restrictions.minimumAmount: Invalid amount for X: "Y". Must be a positive number string (e.g., "5.00", "500")` | A value in `amountOff`, or in the `minimumAmount` of entry `N`, is not a positive number string | Use a positive decimal string | | 400 | `discount.amountOff: Invalid amount for X: "Y". X allows at most D decimal places` / `discount.amountOff: Invalid amount for X: "Y". X does not allow decimal places` / `promotionCodes[N].restrictions.minimumAmount: Invalid amount for X: "Y". X allows at most D decimal places` / `promotionCodes[N].restrictions.minimumAmount: Invalid amount for X: "Y". X does not allow decimal places` | A value in `amountOff`, or in the `minimumAmount` of entry `N`, has more decimal places than the currency allows (e.g. USD `"0.001"`, JPY `"5.5"`). Amounts are not rounded | Use the currency's decimal places (USD 2, JPY 0, BHD 3) | | 400 | `discount.amountOff: Invalid amount for X: "Y". Must be at least Z X` / `promotionCodes[N].restrictions.minimumAmount: Invalid amount for X: "Y". Must be at least Z X` | A value in `amountOff`, or in the `minimumAmount` of entry `N`, is less than one minor unit of the currency | Send at least the currency's minor unit (e.g. USD `"0.01"`) | | 400 | `duration must be once, repeating or forever` | `duration` is not allowed | Use `once`, `repeating` or `forever` | | 400 | `durationInPeriods is required when duration is repeating, and only allowed then` | `durationInPeriods` is missing for `repeating`, or set for another `duration` | Send `durationInPeriods` only with `repeating` | | 400 | `durationInPeriods must be an integer` / `durationInPeriods must be at least 1` / `durationInPeriods must not exceed 2147483647` | `durationInPeriods` is not a positive integer, or is too large | Use an integer from 1 to 2147483647 | | 400 | `maxRedemptions must be an integer` / `maxRedemptions must be at least 1` / `maxRedemptions must not exceed 2147483647` | The coupon's `maxRedemptions` is not a positive integer, or is too large | Use an integer from 1 to 2147483647, or `null` for unlimited | | 400 | `promotionCodes[N].restrictions.X must be an integer` / `promotionCodes[N].restrictions.X must be at least 1` / `promotionCodes[N].restrictions.X must not exceed 2147483647` | `X` (`perCustomerLimit` or `maxRedemptions`) of entry `N` (0-based) is not a positive integer, or is too large — e.g. `promotionCodes[1].restrictions.perCustomerLimit must be at least 1` | Use an integer from 1 to 2147483647, or `null` for unlimited | | 400 | `productIds must not exceed 100 entries` | Too many products | Send at most 100 product IDs | | 400 | `Expected format: PROD_xxx, got "X"` | A `productIds` entry is not a valid Short ID | Use `PROD_` prefixed Short IDs | | 400 | `redeemBy must be an ISO 8601 datetime` / `redeemBy must be more than 60 seconds in the future` | `redeemBy` is malformed, or is less than 60 seconds away | Send an ISO 8601 time with an offset (e.g. `Z`) more than 60 seconds in the future | | 400 | `restrictions is not a coupon field; set it in promotionCodes[].restrictions` | Buyer restrictions were sent on the coupon. A coupon only has `redeemBy` and `maxRedemptions` | Move them to `promotionCodes[].restrictions` (or set them on promotion codes created later) | | 400 | `dailyRedemptionLimit is not supported` | `dailyRedemptionLimit` was sent on the coupon (any value, including `null`). This field is not supported | Remove the field | | 400 | `promotionCodes[N].restrictions.firstTimeOnly is not supported` / `promotionCodes[N].restrictions.dailyRedemptionLimit is not supported` | The `restrictions` of entry `N` (0-based) include `firstTimeOnly` or `dailyRedemptionLimit` (any value, including `null` / `false`). These fields are not supported | Remove the field | | 400 | `promotionCodes[N].restrictions.expiresAt must be an ISO 8601 datetime` | The `expiresAt` of entry `N` (0-based) is malformed | Send an ISO 8601 time with an offset (e.g. `Z`) | | 400 | `promotionCodes[N].restrictions.customerEmails[M] must be a valid email address` / `promotionCodes[N].restrictions.customerEmails must not exceed 100 entries` | Email `M` (0-based) in the `customerEmails` of entry `N` (0-based) is not a valid address, or the list has more than 100 entries | Fix the list, resubmit | | 400 | `X: Invalid input: expected Y, received Z` | Field `X` has the wrong JSON type. `X` is its full path, e.g. `promotionCodes[0].restrictions.maxRedemptions: Invalid input: expected number, received string` or `promotionCodes[0].restrictions.customerEmails: Invalid input: expected array, received null` | Send the field with the type documented above | | 401 | `Authentication required` | Authentication failed | Verify API key, timestamp, and signature | | 403 | `Access denied` | The store does not exist, or the caller is not its owner or admin | Use a key of the store's owner or admin, and verify `storeId` | | 404 | `Product not found in this store: PROD_xxx` | A `productIds` entry does not exist in this store | Remove or fix the product ID | | 409 | `Code "X" is already used by an active code in this store` | Another active code in this store and environment — another coupon's code or a promotion code — has this code; this applies to `code` and to every `promotionCodes[].code`, including codes your first attempt created if you retried without an idempotency key. `errors` holds one entry per taken code; nothing is created | Choose other codes. If this is a retry, look the coupon up with GraphQL instead of creating it again | | 409 | `A generated code collided with an existing code; retry the request` | Random codes (the coupon's or a promotion code's) are generated to avoid codes already in use, but at write time one of them had just been taken — for example by a concurrent request. Pancake regenerated the random codes on each attempt, up to 3 attempts in total, and every attempt collided. Nothing is created | Retry the request | | 409 | `Request is being processed` | A request with the same `X-Idempotency-Key` is still running | **Wait a few seconds, then retry with the same key** | | 502 | `Payment provider rejected the coupon (code: X); its codes have been released` | The payment provider refused the coupon. It is recorded as `failed` and all its codes are free again | Check the discount settings; create the coupon again (with a new idempotency key) | | 502 | `Payment provider did not confirm the coupon creation; its codes have been released, please retry` | The payment provider did not confirm the creation (timeout or provider error) and Pancake could not find the coupon there either. It is handled as a failure: recorded as `failed`, codes released | **Retry the request** — the same codes are free again | | 500 | `Internal server error` | Unexpected server-side failure before the coupon became active. If the coupon had already been recorded, it is marked `failed` and its codes are released. Once the coupon is active the response is `200`, never `500` (see [Response With Warnings](#response-with-warnings)) | Retry with exponential backoff (start 5s, max 3 attempts), same idempotency key | # Deactivate Coupon Source: https://docs.waffo.ai/api-reference/endpoints/coupons/deactivate-coupon Permanently deactivate a coupon and all of its promotion codes Deactivate a coupon. Buyers can no longer redeem it, and all of its promotion codes are deactivated with it. Every code is released and can be used again by a new coupon or promotion code. ``` POST /v1/actions/coupon/deactivate-coupon ``` **Authentication:** API Key > [!WARNING] > > Deactivation is **permanent**. An inactive coupon cannot be reactivated, and coupons cannot be deleted. To offer the discount again, create a new coupon. ## Request Body | Field | Type | Required | Description | | - | - | - | - | | `id` | string | Yes | Coupon ID (Short ID format `CPN_xxx`) | ## Example Request ```typescript SDK theme={"system"} const { coupon } = await client.coupons.deactivate({ id: "CPN_5dXBtmF2HLlHfbPNm0Wcnz" }); console.log(coupon.status); // => "inactive" ``` ```bash cURL theme={"system"} MERCHANT_ID="MER_2aUyqjCzEIiEcYMKj7TZtw" TIMESTAMP=$(date +%s) BODY='{"id":"CPN_5dXBtmF2HLlHfbPNm0Wcnz"}' BODY_HASH=$(echo -n "$BODY" | openssl dgst -sha256 -binary | base64 | tr -d '\n') CANONICAL_REQUEST="POST /v1/actions/coupon/deactivate-coupon $TIMESTAMP $BODY_HASH" SIGNATURE=$(echo -n "$CANONICAL_REQUEST" | openssl dgst -sha256 -sign private_key.pem | base64 | tr -d '\n') curl -X POST "https://api.waffo.ai/v1/actions/coupon/deactivate-coupon" \ -H "Content-Type: application/json" \ -H "X-Merchant-Id: $MERCHANT_ID" \ -H "X-Timestamp: $TIMESTAMP" \ -H "X-Signature: $SIGNATURE" \ -d "$BODY" ``` ```python Python theme={"system"} import hashlib, time, base64, json, requests from cryptography.hazmat.primitives import hashes, serialization from cryptography.hazmat.primitives.asymmetric import padding merchant_id = "MER_2aUyqjCzEIiEcYMKj7TZtw" timestamp = str(int(time.time())) body = {"id": "CPN_5dXBtmF2HLlHfbPNm0Wcnz"} body_json = json.dumps(body, separators=(",", ":")) body_hash = base64.b64encode(hashlib.sha256(body_json.encode()).digest()).decode() path = "/v1/actions/coupon/deactivate-coupon" canonical = f"POST\n{path}\n{timestamp}\n{body_hash}" with open("private_key.pem", "rb") as f: private_key = serialization.load_pem_private_key(f.read(), password=None) signature = base64.b64encode( private_key.sign(canonical.encode(), padding.PKCS1v15(), hashes.SHA256()) ).decode() resp = requests.post( f"https://api.waffo.ai{path}", headers={ "Content-Type": "application/json", "X-Merchant-Id": merchant_id, "X-Timestamp": timestamp, "X-Signature": signature, }, data=body_json, ) print(resp.json()) ``` ## Success Response (200) ```json theme={"system"} { "data": { "coupon": { "id": "CPN_5dXBtmF2HLlHfbPNm0Wcnz", "storeId": "STO_2aUyqjCzEIiEcYMKj7TZtw", "name": "Black Friday 20% off", "code": "BF2026", "status": "inactive", "discountType": "percentage", "percentOff": 20, "amountOff": null, "duration": "repeating", "durationInPeriods": 3, "productIds": [], "maxRedemptions": 1000, "redeemBy": "2026-12-01T00:00:00.000Z", "createdAt": "2026-11-01T08:00:00.000Z", "updatedAt": "2026-12-02T10:00:00.000Z" } } } ``` ## Response Fields Same as [Create Coupon response](/api-reference/endpoints/coupons/create-coupon), without `promotionCodes`. > [!NOTE] > > Existing orders are not affected. Discounts already attached to subscriptions keep applying until the subscription's next plan change. Deactivating an already inactive coupon returns `200` with the coupon unchanged. ## Errors > **Retry policy:** Never retry 4xx — fix the request and resubmit. Retry 5xx with exponential backoff (start 5s, max 3 attempts). | Status | `errors[0].message` | What it means | Recommended handling | | - | - | - | - | | 400 | `Missing or invalid header: x-context-environment` | Environment header is missing or not `test` / `prod` | Set `X-Environment` to `test` or `prod` | | 400 | `Invalid JSON body` | The body is not valid JSON | Fix the body, resubmit | | 400 | `Missing required field: id` | `id` was omitted | Add `id`, resubmit | | 400 | `Expected format: CPN_xxx, got "X"` | `id` is not a valid Short ID | Use a `CPN_` prefixed Short ID | | 401 | `Authentication required` | Authentication failed | Verify API key, timestamp, and signature | | 404 | `Coupon not found` | The coupon does not exist, belongs to another merchant, or is in the other environment | Verify the `id` and the environment of your API key | | 409 | `Coupon is not active (status: pending)` | The coupon is `pending`: its Create Coupon request is still running, or was interrupted and the coupon has not been cleaned up yet | Wait for the Create Coupon request to finish, then retry. An interrupted coupon becomes `failed` once it is cleaned up, and then there is nothing to deactivate | | 409 | `Coupon creation failed; there is nothing to deactivate` | The coupon is `failed`; it was never usable and its code is already released | Nothing to do | | 500 | `Internal server error` | Unexpected server-side failure | Retry with exponential backoff (start 5s, max 3 attempts) | # Coupon Endpoints Source: https://docs.waffo.ai/api-reference/endpoints/coupons/overview Create and manage coupons and the codes buyers type at checkout A coupon defines a discount — a percentage, or a fixed amount per currency — and how many subscription billing periods it applies to. Every coupon has its own `code` (set it when creating the coupon, or let Pancake generate one), and buyers can type it at checkout. To hand out more codes for the same discount, create [promotion codes](/api-reference/endpoints/promotion-codes/overview) — up to 20 together with the coupon, and more at any time. A coupon also applies by its ID (`couponId`) on a checkout session. A coupon only limits redemptions by its expiry and total uses; buyer restrictions — buyer emails, uses per buyer and a minimum amount — are set on promotion codes, so the coupon's own code has none. Coupons belong to a store and to one environment: a coupon created in `test` does not exist in `prod`, and the other way around. ## Coupon Status Values | Status | Description | | - | - | | `active` | Usable at checkout | | `inactive` | Deactivated. This is permanent — an inactive coupon cannot be reactivated | | `failed` | Creation failed: the payment provider rejected the coupon or did not confirm it. The codes of the request have been released. Create the coupon again — the same codes can be used | ## Discount Rules | Rule | Field | Description | | - | - | - | | Discount | `discount` | `percentage` (`percentOff`, 0 \< x ≤ 100, up to 2 decimals) or `fixed_amount` (`amountOff` per currency). A fixed-amount coupon does not apply to an order whose currency is not listed — there is no currency conversion | | Subscription duration | `duration`, `durationInPeriods` | `once` (default), `repeating` (for `durationInPeriods` billing periods) or `forever`. One-time orders are discounted once | | Products | `productIds` | Limit the coupon to these products. Empty or omitted means the whole store | | Expiry | `redeemBy` | After this time the coupon can no longer be redeemed, and discounts already attached to subscriptions also end | | Total uses | `maxRedemptions` | Redemption limit across the coupon's code and all its promotion codes. Refunds do not give uses back | Only `name` can change after creation. To change the discount, create a new coupon and deactivate the old one. ## Code Format The same rules apply to coupon codes and promotion codes: | Rule | Detail | | - | - | | Characters | Letters, digits and `-`. No spaces, `_` or other symbols | | Length | 3–32 characters | | Case | Case-insensitive. Codes are stored and returned in uppercase (`bf2026` becomes `BF2026`) | | Uniqueness | Unique among the store's **active** codes in the same environment, across coupons and promotion codes | | Reuse | Deactivating a coupon or promotion code releases its codes immediately; a new coupon or promotion code can then use them | ## Deactivation Deactivation is **permanent** — there is no reactivate and no delete. Deactivating a coupon also deactivates all of its promotion codes and releases their codes. Existing orders are not affected. Discounts already attached to subscriptions keep applying until the subscription's next plan change. ## Safe Retries Send an `X-Idempotency-Key` header (SDK: the `idempotencyKey` option) when you create a coupon, and reuse the same key when you retry. Without a key, a retry after a timeout returns `409` only when you specified the codes (`code` or `promotionCodes[].code`): the first request already created the coupon and took them. If you let Pancake generate the codes, the retry creates a second coupon. See [Errors](/api-reference/errors) for the key requirements. ## Reading Coupons These endpoints only write. List and read coupons with [GraphQL](/api-reference/endpoints/graphql/overview): `coupons`, `couponsCount` and `coupon(id)`; their promotion codes with `promotionCodes` and `promotionCodesCount`. ```graphql theme={"system"} query Coupons($storeId: String!) { coupons(storeId: $storeId, limit: 20, offset: 0, filter: { status: { eq: active } }) { id name code status timesRedeemed promotionCodesCount } couponsCount(storeId: $storeId, filter: { status: { eq: active } }) } ``` ## Endpoints > **[Create Coupon](/api-reference/endpoints/coupons/create-coupon)** > > Create a coupon with its code and, optionally, its promotion codes. > **[Update Coupon](/api-reference/endpoints/coupons/update-coupon)** > > Rename a coupon. > **[Deactivate Coupon](/api-reference/endpoints/coupons/deactivate-coupon)** > > Permanently deactivate a coupon and all of its promotion codes. # Update Coupon Source: https://docs.waffo.ai/api-reference/endpoints/coupons/update-coupon Rename a coupon Rename a coupon. `name` is the only field that can change: the code, discount, duration, expiry and limits are fixed once the coupon is created. To change them, create a new coupon and deactivate the old one. ``` POST /v1/actions/coupon/update-coupon ``` **Authentication:** API Key ## Request Body | Field | Type | Required | Description | | - | - | - | - | | `id` | string | Yes | Coupon ID (Short ID format `CPN_xxx`) | | `name` | string | Yes | New internal name (max 64 chars). Buyers do not see it | Any other field in the body is ignored. Coupons in any status except `pending` can be renamed, including `inactive` and `failed` ones. ## Example Request ```typescript SDK theme={"system"} const { coupon } = await client.coupons.update({ id: "CPN_5dXBtmF2HLlHfbPNm0Wcnz", name: "Black Friday 20% off (extended)", }); ``` ```bash cURL theme={"system"} MERCHANT_ID="MER_2aUyqjCzEIiEcYMKj7TZtw" TIMESTAMP=$(date +%s) BODY='{"id":"CPN_5dXBtmF2HLlHfbPNm0Wcnz","name":"Black Friday 20% off (extended)"}' BODY_HASH=$(echo -n "$BODY" | openssl dgst -sha256 -binary | base64 | tr -d '\n') CANONICAL_REQUEST="POST /v1/actions/coupon/update-coupon $TIMESTAMP $BODY_HASH" SIGNATURE=$(echo -n "$CANONICAL_REQUEST" | openssl dgst -sha256 -sign private_key.pem | base64 | tr -d '\n') curl -X POST "https://api.waffo.ai/v1/actions/coupon/update-coupon" \ -H "Content-Type: application/json" \ -H "X-Merchant-Id: $MERCHANT_ID" \ -H "X-Timestamp: $TIMESTAMP" \ -H "X-Signature: $SIGNATURE" \ -d "$BODY" ``` ```python Python theme={"system"} import hashlib, time, base64, json, requests from cryptography.hazmat.primitives import hashes, serialization from cryptography.hazmat.primitives.asymmetric import padding merchant_id = "MER_2aUyqjCzEIiEcYMKj7TZtw" timestamp = str(int(time.time())) body = { "id": "CPN_5dXBtmF2HLlHfbPNm0Wcnz", "name": "Black Friday 20% off (extended)", } body_json = json.dumps(body, separators=(",", ":")) body_hash = base64.b64encode(hashlib.sha256(body_json.encode()).digest()).decode() path = "/v1/actions/coupon/update-coupon" canonical = f"POST\n{path}\n{timestamp}\n{body_hash}" with open("private_key.pem", "rb") as f: private_key = serialization.load_pem_private_key(f.read(), password=None) signature = base64.b64encode( private_key.sign(canonical.encode(), padding.PKCS1v15(), hashes.SHA256()) ).decode() resp = requests.post( f"https://api.waffo.ai{path}", headers={ "Content-Type": "application/json", "X-Merchant-Id": merchant_id, "X-Timestamp": timestamp, "X-Signature": signature, }, data=body_json, ) print(resp.json()) ``` ## Success Response (200) ```json theme={"system"} { "data": { "coupon": { "id": "CPN_5dXBtmF2HLlHfbPNm0Wcnz", "storeId": "STO_2aUyqjCzEIiEcYMKj7TZtw", "name": "Black Friday 20% off (extended)", "code": "BF2026", "status": "active", "discountType": "percentage", "percentOff": 20, "amountOff": null, "duration": "repeating", "durationInPeriods": 3, "productIds": [], "maxRedemptions": 1000, "redeemBy": "2026-12-01T00:00:00.000Z", "createdAt": "2026-11-01T08:00:00.000Z", "updatedAt": "2026-11-20T09:15:00.000Z" } } } ``` ## Response Fields Same as [Create Coupon response](/api-reference/endpoints/coupons/create-coupon), without `promotionCodes`. ## Errors > **Retry policy:** Never retry 4xx — fix the request and resubmit. Retry 5xx with exponential backoff (start 5s, max 3 attempts). | Status | `errors[0].message` | What it means | Recommended handling | | - | - | - | - | | 400 | `Missing or invalid header: x-context-environment` | Environment header is missing or not `test` / `prod` | Set `X-Environment` to `test` or `prod` | | 400 | `Invalid JSON body` | The body is not valid JSON | Fix the body, resubmit | | 400 | `Missing required field: id` / `Missing required field: name` | A required field was omitted | Add the missing field, resubmit | | 400 | `name must not exceed 64 characters` | `name` is too long | Shorten `name`, resubmit | | 400 | `Expected format: CPN_xxx, got "X"` | `id` is not a valid Short ID | Use a `CPN_` prefixed Short ID | | 401 | `Authentication required` | Authentication failed | Verify API key, timestamp, and signature | | 404 | `Coupon not found` | The coupon does not exist, belongs to another merchant, or is in the other environment | Verify the `id` and the environment of your API key | | 409 | `Coupon is not active (status: pending)` | The coupon is `pending`: its Create Coupon request is still running, or was interrupted and the coupon has not been cleaned up yet | Wait for the Create Coupon request to finish, then retry | | 500 | `Internal server error` | Unexpected server-side failure | Retry with exponential backoff (start 5s, max 3 attempts) | # Add Recipient Source: https://docs.waffo.ai/api-reference/endpoints/notification-recipients/add-recipient Add an address that receives merchant notification emails for a store Add a merchant notification recipient to a store. Each store can have up to **5 recipients**. A new recipient's 10 event toggles **inherit the store's current `notify*` settings** (any key the store never set counts as subscribed), and `isPrimary` is always `false`. An event you already turned off therefore stays off — adding a recipient never resumes it. Inheritance happens **once, at creation**: all 10 keys are written at that moment, so later changes to the store's `notify*` no longer affect existing recipients — use `update-recipient` instead. For the same reason, a second recipient inherits the store's current values rather than the first recipient's choices, and re-adding a removed address is a fresh inheritance, not a restore. > [!WARNING] > > A new store is seeded with one real recipient — the merchant account email, marked `isPrimary: true`. Recipients added here are appended alongside it; nothing is ever synthesized on the fly. **Remove every recipient and the store sends no merchant notifications at all** — there is no fallback address. ``` POST /v1/actions/store-notification-recipient/add-recipient ``` **Authentication:** API Key (owner or admin role required) ## Request Body | Field | Type | Required | Description | | - | - | - | - | | `storeId` | string | Yes | Store ID (Short ID format `STO_xxx`) | | `email` | string | Yes | Recipient address. Normalized with `lower(trim())` before storage, so addresses differing only by case or surrounding whitespace count as the same recipient. | ## Example Request ```bash cURL theme={"system"} curl -X POST https://api.waffo.com/v1/actions/store-notification-recipient/add-recipient \ -H "Content-Type: application/json" \ -H "X-Merchant-Id: $WAFFO_MERCHANT_ID" \ -H "X-Signature: ..." \ -d '{ "storeId": "STO_2aUyqjCzEIiEcYMKj7TZtw", "email": "ops@acme.com" }' ``` ```javascript JavaScript theme={"system"} const response = await fetch( "https://api.waffo.com/v1/actions/store-notification-recipient/add-recipient", { method: "POST", headers: { "Content-Type": "application/json", "X-Merchant-Id": process.env.WAFFO_MERCHANT_ID, "X-Signature": signature, }, body: JSON.stringify({ storeId: "STO_2aUyqjCzEIiEcYMKj7TZtw", email: "ops@acme.com", }), }, ); const { data } = await response.json(); ``` ## Success Response (200) ```json theme={"system"} { "data": { "recipient": { "id": "11111111-2222-3333-4444-555555555555", "storeId": "STO_2aUyqjCzEIiEcYMKj7TZtw", "email": "ops@acme.com", "isPrimary": false, "preferences": { "notifyNewOrders": true, "notifyNewSubscriptions": true, "notifySubscriptionCanceled": true, "notifySubscriptionRenewed": true, "notifySubscriptionEnded": true, "notifySubscriptionPastDue": true, "notifySubscriptionUncanceled": true, "notifySubscriptionPlanChanged": true, "notifyChargeback": false, "notifyRefundSucceeded": true }, "createdAt": "2026-08-28T00:00:00.000Z" } } } ``` > [!NOTE] > > The returned `recipient.id` is a UUID, not a Short ID. Treat it as an opaque string and pass it back as `recipientId` to `update-recipient` and `remove-recipient`. ## Response Fields | Field | Type | Description | | - | - | - | | `id` | string | Recipient UUID. Pass it back verbatim to `update-recipient` / `remove-recipient` | | `storeId` | string | Owning store Short ID | | `email` | string | Normalized recipient address | | `isPrimary` | boolean | `false` for every recipient added through this endpoint; only the row seeded at store creation is `true`. Provenance only — it carries no privilege and is removable like any other | | `preferences` | object | The 10 event toggles, inherited from the store's current `notify*` at creation | | `createdAt` | string | Creation timestamp (ISO 8601) | ## Errors > **Retry policy:** Never retry 4xx — fix the request and resubmit. Retry 5xx with exponential backoff (start 5s, max 3 attempts). | Status | `errors[0].message` | What it means | Recommended handling | | - | - | - | - | | 400 | `Missing required field: storeId` | `storeId` was not provided | Fix the request body, resubmit | | 400 | `Expected format: STO_xxx, got "..."` | `storeId` Short ID could not be decoded | Fix the `storeId` format, resubmit | | 400 | `Invalid email format` | `email` is not a valid address | Fix the address, resubmit | | 400 | `Notification recipient limit reached (max 5 per store)` | Store already has 5 recipients | Remove an existing recipient first | | 401 | `Missing merchantId in request context` | API Key authentication did not resolve a merchant | Verify API Key headers and signature | | 403 | `Not authorized to manage notification recipients for this store` | Merchant is not `owner` or `admin` of the store | Verify the merchant's role on this store | | 409 | `Recipient with this email already exists for this store` | The normalized address is already a recipient, or a concurrent write won the race | Update the existing recipient instead of adding a duplicate | | 500 | `Internal server error` | Unexpected server-side failure | Retry with exponential backoff (start 5s, max 3 attempts) | # Notification Recipient Endpoints Source: https://docs.waffo.ai/api-reference/endpoints/notification-recipients/overview Manage who receives merchant notification emails for a store Merchant notifications — new order, new subscription, renewal, cancellation, past due — are delivered to the recipients configured on the store. Each recipient has its own address and its own per-event subscription toggles, so two people on the same store can subscribe to different things. When a store has no recipients configured, it sends no merchant notifications at all — there is no fallback address. ## Event catalog | Toggle | Fires on | | - | - | | `notifyNewOrders` | A new one-time order was placed (also covers the first-sale celebration email) | | `notifyNewSubscriptions` | A new subscription was activated | | `notifySubscriptionCanceled` | A subscriber canceled but the access period is still running | | `notifySubscriptionRenewed` | A subscription renewal was charged successfully | | `notifySubscriptionEnded` | A subscription fully ended and access was revoked | | `notifySubscriptionPastDue` | A subscription renewal failed and the subscription is past due | | `notifySubscriptionUncanceled` | A subscriber reverted a pending cancellation | | `notifySubscriptionPlanChanged` | A subscription plan change took effect | | `notifyChargeback` | A payment was disputed by the cardholder (defaults to **off**) | | `notifyRefundSucceeded` | A refund on a payment completed successfully | > [!NOTE] > > All ten toggles above are **per recipient** — including `notifySubscriptionPlanChanged` and `notifyChargeback`. Two people on the same store can subscribe to different events, and `update-recipient` accepts any of the ten. > > Nine of the ten default to on. `notifyChargeback` is the exception: it defaults to **off**, and a recipient receives chargeback mail only when that flag is explicitly `true`. A key missing from a stored recipient reads back as its default, so omitting it never switches chargeback mail on. > > The delivery **address** follows the recipient list: merchant notifications go to the configured recipients, never to `supportEmail`. While the list is empty nothing is sent — no address is substituted. ## Limits Each store may have at most **5 recipients**. Exceeding the limit returns 400. There is no lower bound, and an empty list means silence: emptying it stops this store's merchant notifications entirely (see below). Consumer-facing transactional email (order receipts, subscription confirmations) is a separate pipeline and is unaffected. ## The primary recipient A new store is seeded with one recipient — the merchant account email — marked `isPrimary: true`. That flag is **provenance only**: the row carries no privilege, behaves like any other recipient, and can be removed like any other. It is also the row that `update-store`'s legacy store-level `notify*` write mirrors onto. Removing every recipient, the primary one included, is accepted: the store then sends no merchant notifications, and nothing is synthesized to take its place. Add an address back to resume delivery. ## Environments Recipients are **not environment-scoped**. Requests may carry `X-Environment` as usual, but it does not filter or shape recipient reads and writes — the same store returns the same list in `test` and in `prod`. ## Listing recipients There is no `list-recipients` endpoint — querying the recipient list goes through the top-level GraphQL query `storeNotificationRecipients`, which returns `[]` when the store has no recipients: ```graphql theme={"system"} query GetStoreNotificationRecipients($storeId: String!) { storeNotificationRecipients(storeId: $storeId, limit: 10, offset: 0) { id email isPrimary createdAt preferences { notifyNewOrders notifyNewSubscriptions notifySubscriptionCanceled notifySubscriptionRenewed notifySubscriptionEnded notifySubscriptionPastDue notifySubscriptionUncanceled notifySubscriptionPlanChanged notifyChargeback notifyRefundSucceeded } } } ``` ## Endpoints > **[Add Recipient](/api-reference/endpoints/notification-recipients/add-recipient)** > > Add an address that receives merchant notifications. > **[Update Recipient](/api-reference/endpoints/notification-recipients/update-recipient)** > > Change which events a recipient subscribes to. > **[Remove Recipient](/api-reference/endpoints/notification-recipients/remove-recipient)** > > Remove a recipient from the list. # Remove Recipient Source: https://docs.waffo.ai/api-reference/endpoints/notification-recipients/remove-recipient Remove an address from a store's merchant notification recipients Remove a recipient from a store's recipient list. The address can be added again later. ``` POST /v1/actions/store-notification-recipient/remove-recipient ``` **Authentication:** API Key (owner or admin role required) ## Request Body | Field | Type | Required | Description | | - | - | - | - | | `storeId` | string | Yes | Store ID (Short ID format `STO_xxx`) | | `recipientId` | string | Yes | UUID of a stored recipient. Anything that is not a UUID returns 400 | ## Example Request ```bash cURL theme={"system"} curl -X POST https://api.waffo.com/v1/actions/store-notification-recipient/remove-recipient \ -H "Content-Type: application/json" \ -H "X-Merchant-Id: $WAFFO_MERCHANT_ID" \ -H "X-Signature: ..." \ -d '{ "storeId": "STO_2aUyqjCzEIiEcYMKj7TZtw", "recipientId": "11111111-2222-3333-4444-555555555555" }' ``` ```javascript JavaScript theme={"system"} const response = await fetch( "https://api.waffo.com/v1/actions/store-notification-recipient/remove-recipient", { method: "POST", headers: { "Content-Type": "application/json", "X-Merchant-Id": process.env.WAFFO_MERCHANT_ID, "X-Signature": signature, }, body: JSON.stringify({ storeId: "STO_2aUyqjCzEIiEcYMKj7TZtw", recipientId: "11111111-2222-3333-4444-555555555555", }), }, ); const { data } = await response.json(); ``` ## Success Response (200) ```json theme={"system"} { "data": { "recipientId": "11111111-2222-3333-4444-555555555555", "removed": true } } ``` > [!WARNING] > > Removing the last recipient returns 200 — there is no "keep at least one" guard. The store then sends no merchant notifications at all: there is no fallback address and nothing is synthesized to take its place. > The row seeded at store creation (`isPrimary: true`) is removable like any other — that flag is provenance only and carries no privilege. Add an address back to resume delivery. Consumer-facing transactional email is a separate pipeline and keeps working. ## Response Fields | Field | Type | Description | | - | - | - | | `recipientId` | string | UUID of the removed recipient | | `removed` | boolean | Always `true`; a miss returns 404 rather than `removed: false` | ## Errors > **Retry policy:** Never retry 4xx — fix the request and resubmit. Retry 5xx with exponential backoff (start 5s, max 3 attempts). | Status | `errors[0].message` | What it means | Recommended handling | | - | - | - | - | | 400 | `Missing required field: recipientId` | `recipientId` was not provided | Fix the request body, resubmit | | 400 | `Invalid recipient id format: expected UUID, got "..."` | `recipientId` is not a UUID | Pass the `id` returned by add-recipient or GraphQL verbatim | | 401 | `Missing merchantId in request context` | API Key authentication did not resolve a merchant | Verify API Key headers and signature | | 403 | `Not authorized to manage notification recipients for this store` | Merchant is not `owner` or `admin` of the store | Verify the merchant's role on this store | | 404 | `Notification recipient not found` | No recipient with that id on that store — it was never added, or a concurrent write already removed it | Re-read the list | | 409 | `Notification recipients changed concurrently, please retry` | A concurrent write changed the list between read and write | Re-read the list and retry | | 500 | `Internal server error` | Unexpected server-side failure | Retry with exponential backoff (start 5s, max 3 attempts) | # Update Recipient Source: https://docs.waffo.ai/api-reference/endpoints/notification-recipients/update-recipient Change which merchant notification events a recipient subscribes to Update a recipient's event subscriptions. The update is **partial**: send only the toggles you are changing, and every key you omit keeps its current value. The response always carries the complete, merged object. > [!NOTE] > > `recipientId` must be the UUID of a recipient already stored on that store — including the row seeded at store creation, which is editable like any other. Anything that is not a UUID is rejected with 400; a well-formed UUID that is not on the store returns 404. Nothing is materialized or synthesized by this endpoint. ``` POST /v1/actions/store-notification-recipient/update-recipient ``` **Authentication:** API Key (owner or admin role required) ## Request Body | Field | Type | Required | Description | | - | - | - | - | | `storeId` | string | Yes | Store ID (Short ID format `STO_xxx`) | | `recipientId` | string | Yes | UUID of a stored recipient, passed back verbatim from `add-recipient` or the GraphQL query | | `preferences` | object | Yes | The toggles to change. Only the 10 keys in the event catalog are accepted; anything else is rejected with 400. | ## Example Request ```bash cURL theme={"system"} curl -X POST https://api.waffo.com/v1/actions/store-notification-recipient/update-recipient \ -H "Content-Type: application/json" \ -H "X-Merchant-Id: $WAFFO_MERCHANT_ID" \ -H "X-Signature: ..." \ -d '{ "storeId": "STO_2aUyqjCzEIiEcYMKj7TZtw", "recipientId": "11111111-2222-3333-4444-555555555555", "preferences": { "notifyNewOrders": false } }' ``` ```javascript JavaScript theme={"system"} const response = await fetch( "https://api.waffo.com/v1/actions/store-notification-recipient/update-recipient", { method: "POST", headers: { "Content-Type": "application/json", "X-Merchant-Id": process.env.WAFFO_MERCHANT_ID, "X-Signature": signature, }, body: JSON.stringify({ storeId: "STO_2aUyqjCzEIiEcYMKj7TZtw", recipientId: "11111111-2222-3333-4444-555555555555", preferences: { notifyNewOrders: false }, }), }, ); const { data } = await response.json(); ``` ## Success Response (200) ```json theme={"system"} { "data": { "recipient": { "id": "11111111-2222-3333-4444-555555555555", "storeId": "STO_2aUyqjCzEIiEcYMKj7TZtw", "email": "ops@acme.com", "isPrimary": false, "preferences": { "notifyNewOrders": false, "notifyNewSubscriptions": true, "notifySubscriptionCanceled": true, "notifySubscriptionRenewed": true, "notifySubscriptionEnded": true, "notifySubscriptionPastDue": true, "notifySubscriptionUncanceled": true, "notifySubscriptionPlanChanged": true, "notifyChargeback": false, "notifyRefundSucceeded": true }, "createdAt": "2026-08-28T00:00:00.000Z" } } } ``` > [!NOTE] > > The email address itself is immutable. To move notifications to a different address, add the new recipient and then remove the old one. ## Response Fields | Field | Type | Description | | - | - | - | | `id` | string | Recipient UUID | | `storeId` | string | Owning store Short ID | | `email` | string | Normalized recipient address (unchanged by this endpoint) | | `isPrimary` | boolean | Taken from the stored entry: `true` when the row you patched is the one seeded at store creation, `false` otherwise | | `preferences` | object | The 10 event toggles after merging your patch | | `createdAt` | string | Creation timestamp (ISO 8601) | ## Errors > **Retry policy:** Never retry 4xx — fix the request and resubmit. Retry 5xx with exponential backoff (start 5s, max 3 attempts). | Status | `errors[0].message` | What it means | Recommended handling | | - | - | - | - | | 400 | `Missing required field: recipientId` | `recipientId` was not provided | Fix the request body, resubmit | | 400 | `Invalid recipient id format: expected UUID, got "..."` | `recipientId` is not a UUID | Pass the `id` returned by add-recipient or GraphQL verbatim | | 400 | `Unrecognized key: "notifyUnknownThing"` | A key outside the 9-event catalog was submitted | Remove the unsupported key, resubmit | | 401 | `Missing merchantId in request context` | API Key authentication did not resolve a merchant | Verify API Key headers and signature | | 403 | `Not authorized to manage notification recipients for this store` | Merchant is not `owner` or `admin` of the store | Verify the merchant's role on this store | | 404 | `Notification recipient not found` | No recipient with that id on that store — it was never added, or a concurrent write removed it | Re-read the list | | 409 | `Notification recipients changed concurrently, please retry` | A concurrent write changed the list between read and write | Re-read the list and retry | | 500 | `Internal server error` | Unexpected server-side failure | Retry with exponential backoff (start 5s, max 3 attempts) | # Create Product Source: https://docs.waffo.ai/api-reference/endpoints/onetime-products/create-product Create a new one-time purchase product with multi-currency pricing Create a new one-time purchase product with multi-currency pricing. ``` POST /v1/actions/onetime-product/create-product ``` **Authentication:** API Key ## Request Body | Field | Type | Required | Description | | - | - | - | - | | `storeId` | string | Yes | Store ID (Short ID format `STO_xxx`) | | `name` | string | Yes | Product name (max 64 chars) | | `description` | string \| null | No | Product description (supports Markdown; pass `null` or `""` to clear) | | `prices` | object | Yes | Multi-currency pricing map (see below) | | `media` | array | No | Product images/videos (see below) | | `successUrl` | string \| null | No | Redirect URL after successful purchase (max 512 chars, must be a valid http(s) URL; pass `null` or `""` to clear) | | `metadata` | object | No | Custom key-value data (max 50 keys) | ## Price Object Format Prices are a map of ISO 4217 currency codes to price configuration objects. At least one currency is required. ```json theme={"system"} { "USD": { "amount": "29.00", "taxIncluded": false, "taxCategory": "saas" }, "EUR": { "amount": "27.00", "taxIncluded": true, "taxCategory": "saas" } } ``` | Field | Type | Description | | - | - | - | | `amount` | string | Price as a display format string (e.g., "29.00" = \$29.00) | | `taxIncluded` | boolean | Whether the amount already includes tax | | `taxCategory` | string | Tax category for tax calculation | **Supported `taxCategory` values:** | Value | Description | | - | - | | `digital_goods` | General digital goods | | `saas` | Software as a Service | | `software` | Downloadable software | | `ebook` | Electronic books | | `online_course` | Online courses and education | | `consulting` | Consulting services | | `professional_service` | Professional services | ## Media Item Format ```json theme={"system"} { "type": "image", "url": "https://example.com/product.png", "alt": "Product screenshot", "thumbnail": "https://example.com/product-thumb.png" } ``` | Field | Type | Description | | - | - | - | | `type` | string | `image` or `video` | | `url` | string | Media URL | | `alt` | string | Alt text for accessibility | | `thumbnail` | string | Thumbnail URL (optional for images, recommended for videos) | ## Example Request ```typescript SDK theme={"system"} import { WaffoPancake, TaxCategory } from "@waffo/pancake-ts"; const client = new WaffoPancake({ merchantId: process.env.WAFFO_MERCHANT_ID!, privateKey: process.env.WAFFO_PRIVATE_KEY!, }); const { product } = await client.onetimeProducts.create({ storeId: "STO_2aUyqjCzEIiEcYMKj7TZtw", name: "Premium Template Pack", description: "50 premium design templates for your next project.", prices: { USD: { amount: "49.00", taxIncluded: false, taxCategory: TaxCategory.DigitalGoods }, EUR: { amount: "45.00", taxIncluded: true, taxCategory: TaxCategory.DigitalGoods }, }, media: [ { type: "image", url: "https://example.com/templates-preview.png", alt: "Template preview" }, ], successUrl: "https://example.com/thank-you", metadata: { category: "design", fileCount: "50" }, }); ``` ```bash cURL theme={"system"} MERCHANT_ID="MER_2aUyqjCzEIiEcYMKj7TZtw" TIMESTAMP=$(date +%s) BODY='{ "storeId": "STO_2aUyqjCzEIiEcYMKj7TZtw", "name": "Premium Template Pack", "description": "50 premium design templates for your next project.", "prices": { "USD": { "amount": "49.00", "taxIncluded": false, "taxCategory": "digital_goods" }, "EUR": { "amount": "45.00", "taxIncluded": true, "taxCategory": "digital_goods" } }, "successUrl": "https://example.com/thank-you" }' BODY_HASH=$(echo -n "$BODY" | openssl dgst -sha256 -binary | base64 | tr -d '\n') CANONICAL_REQUEST="POST /v1/actions/onetime-product/create-product $TIMESTAMP $BODY_HASH" SIGNATURE=$(echo -n "$CANONICAL_REQUEST" | openssl dgst -sha256 -sign private_key.pem | base64 | tr -d '\n') curl -X POST "https://api.waffo.ai/v1/actions/onetime-product/create-product" \ -H "Content-Type: application/json" \ -H "X-Merchant-Id: $MERCHANT_ID" \ -H "X-Timestamp: $TIMESTAMP" \ -H "X-Signature: $SIGNATURE" \ -d "$BODY" ``` ```python Python theme={"system"} import hashlib, time, base64, json, requests from cryptography.hazmat.primitives import hashes, serialization from cryptography.hazmat.primitives.asymmetric import padding merchant_id = "MER_2aUyqjCzEIiEcYMKj7TZtw" timestamp = str(int(time.time())) body = { "storeId": "STO_2aUyqjCzEIiEcYMKj7TZtw", "name": "Premium Template Pack", "description": "50 premium design templates for your next project.", "prices": { "USD": {"amount": "49.00", "taxIncluded": False, "taxCategory": "digital_goods"}, "EUR": {"amount": "45.00", "taxIncluded": True, "taxCategory": "digital_goods"}, }, "successUrl": "https://example.com/thank-you", } body_json = json.dumps(body, separators=(",", ":")) body_hash = base64.b64encode(hashlib.sha256(body_json.encode()).digest()).decode() path = "/v1/actions/onetime-product/create-product" canonical = f"POST\n{path}\n{timestamp}\n{body_hash}" with open("private_key.pem", "rb") as f: private_key = serialization.load_pem_private_key(f.read(), password=None) signature = base64.b64encode( private_key.sign(canonical.encode(), padding.PKCS1v15(), hashes.SHA256()) ).decode() resp = requests.post( f"https://api.waffo.ai{path}", headers={ "Content-Type": "application/json", "X-Merchant-Id": merchant_id, "X-Timestamp": timestamp, "X-Signature": signature, }, data=body_json, ) print(resp.json()) ``` ## Success Response (200) ```json theme={"system"} { "data": { "product": { "id": "PROD_3kF9mNpQrStUvWxYz1A2bC", "storeId": "STO_2aUyqjCzEIiEcYMKj7TZtw", "name": "Premium Template Pack", "description": "50 premium design templates for your next project.", "prices": { "USD": { "amount": "49.00", "taxCategory": "digital_goods" }, "EUR": { "amount": "45.00", "taxCategory": "digital_goods" } }, "media": [ { "type": "image", "url": "https://example.com/templates-preview.png", "alt": "Template preview" } ], "successUrl": "https://example.com/thank-you", "metadata": { "category": "design", "fileCount": "50" }, "status": "active", "createdAt": "2026-01-15T10:30:00.000Z", "updatedAt": "2026-01-15T10:30:00.000Z" } } } ``` ## Response Fields The response is wrapped in `data.product`. The product object is a flattened detail view combining product and version fields. | Field | Type | Description | | - | - | - | | `id` | string | Product ID (`PROD_xxx`) | | `storeId` | string | Store ID (`STO_xxx`) | | `name` | string | Product name (from current version) | | `description` | string \| null | Product description (from current version) | | `prices` | object | Multi-currency pricing map (see below) | | `media` | array | Media items (from current version) | | `successUrl` | string \| null | Success redirect URL (from current version) | | `metadata` | object | Custom metadata (from current version) | | `status` | string | Status in the current environment: `active` or `inactive` | | `createdAt` | string | Product creation timestamp (ISO 8601) | | `updatedAt` | string | Product last update timestamp (ISO 8601) | **Response price object** (per currency): | Field | Type | Description | | - | - | - | | `amount` | string | Price as a display format string (e.g., "49.00") | | `taxCategory` | string | Tax category for tax calculation | > [!NOTE] > > The `status` field reflects the environment you are operating in. When created in the **test** environment (default), status is `active`. When created in the **production** environment, the production status is returned. ## Errors > **Retry policy:** Never retry 4xx — fix the request and resubmit. Retry 5xx with exponential backoff (start 5s, max 3 attempts). | Status | `errors[0].message` | What it means | Recommended handling | | - | - | - | - | | 400 | `Missing required field: storeId` | `storeId` not provided | Fix the body, resubmit | | 400 | `Invalid ID format` | The provided Short ID could not be decoded | Fix the `storeId` format, resubmit | | 400 | `Missing required field: name` | `name` not provided | Fix the body, resubmit | | 400 | `Prices must have at least one currency` | `prices` is missing or an empty object | Provide at least one currency entry, resubmit | | 400 | `Invalid currency code` | Currency code must be exactly 3 uppercase letters (ISO 4217, e.g. `USD`, `EUR`, `JPY`) | Use a valid ISO 4217 code, resubmit | | 400 | `Invalid amount` | Amount must be a positive number string (e.g. `"9.99"`, `"100"`) | Use a positive number string, resubmit | | 404 | `Store not found` | Store does not exist or is not accessible | Verify the `storeId` belongs to your merchant account | | 500 | `Internal server error` | Unexpected server-side failure | Retry with exponential backoff (start 5s, max 3 attempts) | # One-Time Product Endpoints Source: https://docs.waffo.ai/api-reference/endpoints/onetime-products/overview Create and manage single-purchase products One-time products represent single-purchase digital goods. Each product supports multi-currency pricing, immutable versioning, and separate test/production environments. ## Product Status Values | Status | Description | | - | - | | `active` | Product is live and purchasable via checkout | | `inactive` | Product is hidden from checkout, existing orders unaffected | ## Typical Workflow ```mermaid theme={"system"} sequenceDiagram participant M as Merchant participant T as Test Environment participant P as Production M->>T: Create Product (test) T-->>M: testStatus=active, prodStatus=inactive M->>T: Update Product (iterate) T-->>M: New version created (v2, v3...) M->>T: Publish Product T->>P: Copy test version to production P-->>M: prodStatus=active, testStatus=active M->>P: Update Product (X-Environment: prod) P-->>M: New production version M->>P: Update Status (inactive) P-->>M: Product hidden from checkout ``` ## Endpoints > **[Create Product](/api-reference/endpoints/onetime-products/create-product)** > > Create a new one-time purchase product with multi-currency pricing. > **[Update Product](/api-reference/endpoints/onetime-products/update-product)** > > Update product content. A new immutable version is created if content changes. > **[Publish Product](/api-reference/endpoints/onetime-products/publish-product)** > > Publish a product from the test environment to production. > **[Update Status](/api-reference/endpoints/onetime-products/update-status)** > > Activate or deactivate a product for checkout visibility. # Publish Product Source: https://docs.waffo.ai/api-reference/endpoints/onetime-products/publish-product Publish a one-time product from the test environment to production Publish a product from the test environment to production. This is a **one-way, first-publish-only** operation that copies the current test version to production. ``` POST /v1/actions/onetime-product/publish-product ``` **Authentication:** API Key > [!WARNING] > > Do **not** include the `X-Environment` header for this endpoint. Publishing is always one-way from test to production. ## Request Body | Field | Type | Required | Description | | - | - | - | - | | `id` | string | Yes | Product ID (Short ID format `PROD_xxx`) | ## Example Request ```typescript SDK theme={"system"} const { product } = await client.onetimeProducts.publish({ id: "PROD_3kF9mNpQrStUvWxYz1A2bC", }); ``` ```typescript TypeScript (fetch) theme={"system"} // Uses callApi() helper from authentication.mdx const result = await callApi("POST", "/v1/actions/onetime-product/publish-product", { id: "PROD_3kF9mNpQrStUvWxYz1A2bC", }); console.log(result.data.product.status); // => "active" ``` ```java Java theme={"system"} // Uses callApi() helper from authentication.mdx String body = """ {"id":"PROD_3kF9mNpQrStUvWxYz1A2bC"}"""; String response = callApi("POST", "/v1/actions/onetime-product/publish-product", body); System.out.println(response); ``` ```python Python theme={"system"} # Uses call_api() helper from authentication.mdx result = call_api("POST", "/v1/actions/onetime-product/publish-product", { "id": "PROD_3kF9mNpQrStUvWxYz1A2bC", }) print(result["data"]["product"]["status"]) # => "active" ``` ```go Go theme={"system"} // Uses callAPI() helper from authentication.mdx body := map[string]interface{}{ "id": "PROD_3kF9mNpQrStUvWxYz1A2bC", } result, err := callAPI("POST", "/v1/actions/onetime-product/publish-product", body) if err != nil { log.Fatal(err) } fmt.Println(string(result)) ``` ```rust Rust theme={"system"} // Uses call_api() helper from authentication.mdx let body = serde_json::json!({ "id": "PROD_3kF9mNpQrStUvWxYz1A2bC" }); let result = call_api("POST", "/v1/actions/onetime-product/publish-product", &body).await?; println!("{}", result); ``` ```c C theme={"system"} /* Uses call_api() helper from authentication.mdx */ const char *body = "{\"id\":\"PROD_3kF9mNpQrStUvWxYz1A2bC\"}"; char *response = call_api("POST", "/v1/actions/onetime-product/publish-product", body); printf("%s\n", response); free(response); ``` ```cpp C++ theme={"system"} // Uses callApi() helper from authentication.mdx std::string body = R"({"id":"PROD_3kF9mNpQrStUvWxYz1A2bC"})"; std::string response = callApi("POST", "/v1/actions/onetime-product/publish-product", body); std::cout << response << std::endl; ``` ```bash cURL theme={"system"} MERCHANT_ID="MER_2aUyqjCzEIiEcYMKj7TZtw" TIMESTAMP=$(date +%s) BODY='{"id":"PROD_3kF9mNpQrStUvWxYz1A2bC"}' BODY_HASH=$(echo -n "$BODY" | openssl dgst -sha256 -binary | base64 | tr -d '\n') CANONICAL_REQUEST="POST /v1/actions/onetime-product/publish-product $TIMESTAMP $BODY_HASH" SIGNATURE=$(echo -n "$CANONICAL_REQUEST" | openssl dgst -sha256 -sign private_key.pem | base64 | tr -d '\n') curl -X POST "https://api.waffo.ai/v1/actions/onetime-product/publish-product" \ -H "Content-Type: application/json" \ -H "X-Merchant-Id: $MERCHANT_ID" \ -H "X-Timestamp: $TIMESTAMP" \ -H "X-Signature: $SIGNATURE" \ -d "$BODY" ``` ```bash wget theme={"system"} MERCHANT_ID="MER_2aUyqjCzEIiEcYMKj7TZtw" TIMESTAMP=$(date +%s) BODY='{"id":"PROD_3kF9mNpQrStUvWxYz1A2bC"}' BODY_HASH=$(echo -n "$BODY" | openssl dgst -sha256 -binary | base64 | tr -d '\n') CANONICAL_REQUEST="POST /v1/actions/onetime-product/publish-product $TIMESTAMP $BODY_HASH" SIGNATURE=$(echo -n "$CANONICAL_REQUEST" | openssl dgst -sha256 -sign private_key.pem | base64 | tr -d '\n') wget -qO- "https://api.waffo.ai/v1/actions/onetime-product/publish-product" \ --header="Content-Type: application/json" \ --header="X-Merchant-Id: $MERCHANT_ID" \ --header="X-Timestamp: $TIMESTAMP" \ --header="X-Signature: $SIGNATURE" \ --post-data="$BODY" ``` ## Success Response (200) ```json theme={"system"} { "data": { "product": { "id": "PROD_3kF9mNpQrStUvWxYz1A2bC", "storeId": "STO_2aUyqjCzEIiEcYMKj7TZtw", "name": "Premium Template Pack", "description": "50 premium design templates for your next project.", "prices": { "USD": { "amount": "49.00", "taxCategory": "digital_goods" }, "EUR": { "amount": "45.00", "taxCategory": "digital_goods" } }, "media": [ { "type": "image", "url": "https://example.com/templates-preview.png", "alt": "Template preview" } ], "successUrl": "https://example.com/thank-you", "metadata": { "category": "design", "fileCount": "50" }, "status": "active", "createdAt": "2026-01-15T10:30:00.000Z", "updatedAt": "2026-01-15T12:00:00.000Z" } } } ``` ## Response Fields Same as [Create Product response](/api-reference/endpoints/onetime-products/create-product#response-fields). > [!NOTE] > > Only the **first publish** is supported. Once a product has a production version, this endpoint cannot be used again for the same product. To update the production version after initial publish, use the [Update Product](/api-reference/endpoints/onetime-products/update-product) endpoint with the `X-Environment: prod` header. ## Errors > **Retry policy:** Never retry 4xx — fix the request and resubmit. Retry 5xx with exponential backoff (start 5s, max 3 attempts). | Status | `errors[0].message` | What it means | Recommended handling | | - | - | - | - | | 400 | `Missing required field: id` | `id` not provided | Fix the body, resubmit | | 400 | `Invalid ID format` | The provided Short ID could not be decoded | Fix the `id` format, resubmit | | 400 | `No test version found` | The product has no version in the test environment yet | Create the product first via [Create Product](/api-reference/endpoints/onetime-products/create-product) | | 400 | `Test version is not active` | The current test version's status is `inactive` | Activate the test version via [Update Status](/api-reference/endpoints/onetime-products/update-status) first | | 400 | `Already published to production` | The product already has a production version | Use [Update Product](/api-reference/endpoints/onetime-products/update-product) with `X-Environment: prod` to make further changes | | 404 | `Product not found` | Product does not exist or is not accessible | Verify the `id` belongs to your merchant account | | 500 | `Internal server error` | Unexpected server-side failure | Retry with exponential backoff (start 5s, max 3 attempts) | # Update Product Source: https://docs.waffo.ai/api-reference/endpoints/onetime-products/update-product Update a one-time product's content with automatic immutable versioning Update a one-time product's content. If the content has changed, a new immutable version is created automatically. If the content is identical to the current version, no new version is created. ``` POST /v1/actions/onetime-product/update-product ``` **Authentication:** API Key > [!WARNING] > > Use the [Update Status](/api-reference/endpoints/onetime-products/update-status) endpoint to change a product's status (`active`/`inactive`). This endpoint is for content updates only. ## Request Body | Field | Type | Required | Description | | - | - | - | - | | `id` | string | Yes | Product ID (Short ID format `PROD_xxx`) | | `name` | string | No | Updated product name (max 64 chars) | | `description` | string \| null | No | Updated description (pass `null` or `""` to clear) | | `prices` | object | No | Updated multi-currency pricing map | | `media` | array | No | Updated media items | | `successUrl` | string \| null | No | Updated redirect URL (max 512 chars, must be a valid http(s) URL; pass `null` or `""` to clear) | | `metadata` | object | No | Updated custom metadata | For the `prices` and `media` object formats, see [Create Product](/api-reference/endpoints/onetime-products/create-product#price-object-format). ## Example Request ```typescript SDK theme={"system"} const { product } = await client.onetimeProducts.update({ id: "PROD_3kF9mNpQrStUvWxYz1A2bC", name: "Premium Template Pack v2", description: "75 premium design templates — expanded collection.", prices: { USD: { amount: "59.00", taxIncluded: false, taxCategory: TaxCategory.DigitalGoods }, EUR: { amount: "55.00", taxIncluded: true, taxCategory: TaxCategory.DigitalGoods }, }, successUrl: "https://example.com/thank-you", }); ``` ```typescript TypeScript (fetch) theme={"system"} // Uses callApi() helper from authentication.mdx const result = await callApi("POST", "/v1/actions/onetime-product/update-product", { id: "PROD_3kF9mNpQrStUvWxYz1A2bC", name: "Premium Template Pack v2", description: "75 premium design templates — expanded collection.", prices: { USD: { amount: "59.00", taxIncluded: false, taxCategory: "digital_goods" }, EUR: { amount: "55.00", taxIncluded: true, taxCategory: "digital_goods" }, }, successUrl: "https://example.com/thank-you", }); console.log(result.data.product.name); // => "Premium Template Pack v2" ``` ```java Java theme={"system"} // Uses callApi() helper from authentication.mdx String body = """ { "id": "PROD_3kF9mNpQrStUvWxYz1A2bC", "name": "Premium Template Pack v2", "description": "75 premium design templates — expanded collection.", "prices": { "USD": { "amount": "59.00", "taxIncluded": false, "taxCategory": "digital_goods" }, "EUR": { "amount": "55.00", "taxIncluded": true, "taxCategory": "digital_goods" } }, "successUrl": "https://example.com/thank-you" }"""; String response = callApi("POST", "/v1/actions/onetime-product/update-product", body); System.out.println(response); ``` ```python Python theme={"system"} # Uses call_api() helper from authentication.mdx result = call_api("POST", "/v1/actions/onetime-product/update-product", { "id": "PROD_3kF9mNpQrStUvWxYz1A2bC", "name": "Premium Template Pack v2", "description": "75 premium design templates — expanded collection.", "prices": { "USD": {"amount": "59.00", "taxIncluded": False, "taxCategory": "digital_goods"}, "EUR": {"amount": "55.00", "taxIncluded": True, "taxCategory": "digital_goods"}, }, "successUrl": "https://example.com/thank-you", }) print(result["data"]["product"]["name"]) # => "Premium Template Pack v2" ``` ```go Go theme={"system"} // Uses callAPI() helper from authentication.mdx body := map[string]interface{}{ "id": "PROD_3kF9mNpQrStUvWxYz1A2bC", "name": "Premium Template Pack v2", "description": "75 premium design templates — expanded collection.", "prices": map[string]interface{}{ "USD": map[string]interface{}{"amount": "59.00", "taxIncluded": false, "taxCategory": "digital_goods"}, "EUR": map[string]interface{}{"amount": "55.00", "taxIncluded": true, "taxCategory": "digital_goods"}, }, "successUrl": "https://example.com/thank-you", } result, err := callAPI("POST", "/v1/actions/onetime-product/update-product", body) if err != nil { log.Fatal(err) } fmt.Println(string(result)) ``` ```rust Rust theme={"system"} // Uses call_api() helper from authentication.mdx let body = serde_json::json!({ "id": "PROD_3kF9mNpQrStUvWxYz1A2bC", "name": "Premium Template Pack v2", "description": "75 premium design templates — expanded collection.", "prices": { "USD": { "amount": "59.00", "taxIncluded": false, "taxCategory": "digital_goods" }, "EUR": { "amount": "55.00", "taxIncluded": true, "taxCategory": "digital_goods" } }, "successUrl": "https://example.com/thank-you" }); let result = call_api("POST", "/v1/actions/onetime-product/update-product", &body).await?; println!("{}", result); ``` ```c C theme={"system"} /* Uses call_api() helper from authentication.mdx */ const char *body = "{\"id\":\"PROD_3kF9mNpQrStUvWxYz1A2bC\"," "\"name\":\"Premium Template Pack v2\"," "\"description\":\"75 premium design templates — expanded collection.\"," "\"prices\":{\"USD\":{\"amount\":\"59.00\",\"taxIncluded\":false,\"taxCategory\":\"digital_goods\"}," "\"EUR\":{\"amount\":\"55.00\",\"taxIncluded\":true,\"taxCategory\":\"digital_goods\"}}," "\"successUrl\":\"https://example.com/thank-you\"}"; char *response = call_api("POST", "/v1/actions/onetime-product/update-product", body); printf("%s\n", response); free(response); ``` ```cpp C++ theme={"system"} // Uses callApi() helper from authentication.mdx std::string body = R"({ "id": "PROD_3kF9mNpQrStUvWxYz1A2bC", "name": "Premium Template Pack v2", "description": "75 premium design templates — expanded collection.", "prices": { "USD": { "amount": "59.00", "taxIncluded": false, "taxCategory": "digital_goods" }, "EUR": { "amount": "55.00", "taxIncluded": true, "taxCategory": "digital_goods" } }, "successUrl": "https://example.com/thank-you" })"; std::string response = callApi("POST", "/v1/actions/onetime-product/update-product", body); std::cout << response << std::endl; ``` ```bash cURL theme={"system"} MERCHANT_ID="MER_2aUyqjCzEIiEcYMKj7TZtw" TIMESTAMP=$(date +%s) BODY='{ "id": "PROD_3kF9mNpQrStUvWxYz1A2bC", "name": "Premium Template Pack v2", "description": "75 premium design templates — expanded collection.", "prices": { "USD": { "amount": "59.00", "taxIncluded": false, "taxCategory": "digital_goods" }, "EUR": { "amount": "55.00", "taxIncluded": true, "taxCategory": "digital_goods" } }, "successUrl": "https://example.com/thank-you" }' BODY_HASH=$(echo -n "$BODY" | openssl dgst -sha256 -binary | base64 | tr -d '\n') CANONICAL_REQUEST="POST /v1/actions/onetime-product/update-product $TIMESTAMP $BODY_HASH" SIGNATURE=$(echo -n "$CANONICAL_REQUEST" | openssl dgst -sha256 -sign private_key.pem | base64 | tr -d '\n') curl -X POST "https://api.waffo.ai/v1/actions/onetime-product/update-product" \ -H "Content-Type: application/json" \ -H "X-Merchant-Id: $MERCHANT_ID" \ -H "X-Timestamp: $TIMESTAMP" \ -H "X-Signature: $SIGNATURE" \ -d "$BODY" ``` ```bash wget theme={"system"} MERCHANT_ID="MER_2aUyqjCzEIiEcYMKj7TZtw" TIMESTAMP=$(date +%s) BODY='{ "id": "PROD_3kF9mNpQrStUvWxYz1A2bC", "name": "Premium Template Pack v2", "description": "75 premium design templates — expanded collection.", "prices": { "USD": { "amount": "59.00", "taxIncluded": false, "taxCategory": "digital_goods" }, "EUR": { "amount": "55.00", "taxIncluded": true, "taxCategory": "digital_goods" } }, "successUrl": "https://example.com/thank-you" }' BODY_HASH=$(echo -n "$BODY" | openssl dgst -sha256 -binary | base64 | tr -d '\n') CANONICAL_REQUEST="POST /v1/actions/onetime-product/update-product $TIMESTAMP $BODY_HASH" SIGNATURE=$(echo -n "$CANONICAL_REQUEST" | openssl dgst -sha256 -sign private_key.pem | base64 | tr -d '\n') wget -qO- "https://api.waffo.ai/v1/actions/onetime-product/update-product" \ --header="Content-Type: application/json" \ --header="X-Merchant-Id: $MERCHANT_ID" \ --header="X-Timestamp: $TIMESTAMP" \ --header="X-Signature: $SIGNATURE" \ --post-data="$BODY" ``` ## Success Response (200) ```json theme={"system"} { "data": { "product": { "id": "PROD_3kF9mNpQrStUvWxYz1A2bC", "storeId": "STO_2aUyqjCzEIiEcYMKj7TZtw", "name": "Premium Template Pack v2", "description": "75 premium design templates — expanded collection.", "prices": { "USD": { "amount": "59.00", "taxCategory": "digital_goods" }, "EUR": { "amount": "55.00", "taxCategory": "digital_goods" } }, "media": [], "successUrl": "https://example.com/thank-you", "metadata": {}, "status": "active", "createdAt": "2026-01-15T10:30:00.000Z", "updatedAt": "2026-01-15T11:00:00.000Z" } } } ``` ## Response Fields Same as [Create Product response](/api-reference/endpoints/onetime-products/create-product#response-fields). > [!NOTE] > > Product versions are **immutable**. Existing orders retain their original version. New purchases always use the latest version. If the submitted content is identical to the current version, no new version is created and the existing version is returned. ## Errors > **Retry policy:** Never retry 4xx — fix the request and resubmit. Retry 5xx with exponential backoff (start 5s, max 3 attempts). | Status | `errors[0].message` | What it means | Recommended handling | | - | - | - | - | | 400 | `Missing required field: id` | `id` not provided | Fix the body, resubmit | | 400 | `Invalid ID format` | The provided Short ID could not be decoded | Fix the `id` format, resubmit | | 400 | `Invalid currency code` | Currency code must be exactly 3 uppercase letters (ISO 4217, e.g. `USD`, `EUR`, `JPY`) | Use a valid ISO 4217 code, resubmit | | 400 | `Invalid amount` | Amount must be a positive number string (e.g. `"9.99"`, `"100"`) | Use a positive number string, resubmit | | 400 | `Product X has no version in environment Y` | The product has no version in the targeted environment (e.g. attempting to update `prod` before publishing) | Publish the product to the target environment first via [Publish Product](/api-reference/endpoints/onetime-products/publish-product) | | 404 | `Product not found` | Product does not exist or is not accessible | Verify the `id` belongs to your merchant account | | 500 | `Internal server error` | Unexpected server-side failure | Retry with exponential backoff (start 5s, max 3 attempts) | # Update Status Source: https://docs.waffo.ai/api-reference/endpoints/onetime-products/update-status Activate or deactivate a one-time product for checkout visibility Activate or deactivate a product. Active products are purchasable; inactive products are hidden from checkout. ``` POST /v1/actions/onetime-product/update-status ``` **Authentication:** API Key ## Request Body | Field | Type | Required | Description | | - | - | - | - | | `id` | string | Yes | Product ID (Short ID format `PROD_xxx`) | | `status` | string | Yes | `active` or `inactive` | ## Example Request ```typescript SDK theme={"system"} import { ProductVersionStatus } from "@waffo/pancake-ts"; const { product } = await client.onetimeProducts.updateStatus({ id: "PROD_3kF9mNpQrStUvWxYz1A2bC", status: ProductVersionStatus.Inactive, }); ``` ```typescript TypeScript (fetch) theme={"system"} // Uses callApi() helper from authentication.mdx const result = await callApi("POST", "/v1/actions/onetime-product/update-status", { id: "PROD_3kF9mNpQrStUvWxYz1A2bC", status: "inactive", }); console.log(result.data.product.status); // => "inactive" ``` ```java Java theme={"system"} // Uses callApi() helper from authentication.mdx String body = """ {"id":"PROD_3kF9mNpQrStUvWxYz1A2bC","status":"inactive"}"""; String response = callApi("POST", "/v1/actions/onetime-product/update-status", body); System.out.println(response); ``` ```python Python theme={"system"} # Uses call_api() helper from authentication.mdx result = call_api("POST", "/v1/actions/onetime-product/update-status", { "id": "PROD_3kF9mNpQrStUvWxYz1A2bC", "status": "inactive", }) print(result["data"]["product"]["status"]) # => "inactive" ``` ```go Go theme={"system"} // Uses callAPI() helper from authentication.mdx body := map[string]interface{}{ "id": "PROD_3kF9mNpQrStUvWxYz1A2bC", "status": "inactive", } result, err := callAPI("POST", "/v1/actions/onetime-product/update-status", body) if err != nil { log.Fatal(err) } fmt.Println(string(result)) ``` ```rust Rust theme={"system"} // Uses call_api() helper from authentication.mdx let body = serde_json::json!({ "id": "PROD_3kF9mNpQrStUvWxYz1A2bC", "status": "inactive" }); let result = call_api("POST", "/v1/actions/onetime-product/update-status", &body).await?; println!("{}", result); ``` ```c C theme={"system"} /* Uses call_api() helper from authentication.mdx */ const char *body = "{\"id\":\"PROD_3kF9mNpQrStUvWxYz1A2bC\",\"status\":\"inactive\"}"; char *response = call_api("POST", "/v1/actions/onetime-product/update-status", body); printf("%s\n", response); free(response); ``` ```cpp C++ theme={"system"} // Uses callApi() helper from authentication.mdx std::string body = R"({"id":"PROD_3kF9mNpQrStUvWxYz1A2bC","status":"inactive"})"; std::string response = callApi("POST", "/v1/actions/onetime-product/update-status", body); std::cout << response << std::endl; ``` ```bash cURL theme={"system"} MERCHANT_ID="MER_2aUyqjCzEIiEcYMKj7TZtw" TIMESTAMP=$(date +%s) BODY='{"id":"PROD_3kF9mNpQrStUvWxYz1A2bC","status":"inactive"}' BODY_HASH=$(echo -n "$BODY" | openssl dgst -sha256 -binary | base64 | tr -d '\n') CANONICAL_REQUEST="POST /v1/actions/onetime-product/update-status $TIMESTAMP $BODY_HASH" SIGNATURE=$(echo -n "$CANONICAL_REQUEST" | openssl dgst -sha256 -sign private_key.pem | base64 | tr -d '\n') curl -X POST "https://api.waffo.ai/v1/actions/onetime-product/update-status" \ -H "Content-Type: application/json" \ -H "X-Merchant-Id: $MERCHANT_ID" \ -H "X-Timestamp: $TIMESTAMP" \ -H "X-Signature: $SIGNATURE" \ -d "$BODY" ``` ```bash wget theme={"system"} MERCHANT_ID="MER_2aUyqjCzEIiEcYMKj7TZtw" TIMESTAMP=$(date +%s) BODY='{"id":"PROD_3kF9mNpQrStUvWxYz1A2bC","status":"inactive"}' BODY_HASH=$(echo -n "$BODY" | openssl dgst -sha256 -binary | base64 | tr -d '\n') CANONICAL_REQUEST="POST /v1/actions/onetime-product/update-status $TIMESTAMP $BODY_HASH" SIGNATURE=$(echo -n "$CANONICAL_REQUEST" | openssl dgst -sha256 -sign private_key.pem | base64 | tr -d '\n') wget -qO- "https://api.waffo.ai/v1/actions/onetime-product/update-status" \ --header="Content-Type: application/json" \ --header="X-Merchant-Id: $MERCHANT_ID" \ --header="X-Timestamp: $TIMESTAMP" \ --header="X-Signature: $SIGNATURE" \ --post-data="$BODY" ``` ## Success Response (200) ```json theme={"system"} { "data": { "product": { "id": "PROD_3kF9mNpQrStUvWxYz1A2bC", "storeId": "STO_2aUyqjCzEIiEcYMKj7TZtw", "name": "Premium Template Pack", "description": "50 premium design templates for your next project.", "prices": { "USD": { "amount": "49.00", "taxCategory": "digital_goods" }, "EUR": { "amount": "45.00", "taxCategory": "digital_goods" } }, "media": [ { "type": "image", "url": "https://example.com/templates-preview.png", "alt": "Template preview" } ], "successUrl": "https://example.com/thank-you", "metadata": { "category": "design", "fileCount": "50" }, "status": "inactive", "createdAt": "2026-01-15T10:30:00.000Z", "updatedAt": "2026-01-15T13:00:00.000Z" } } } ``` ## Response Fields Same as [Create Product response](/api-reference/endpoints/onetime-products/create-product#response-fields). > [!NOTE] > > Setting a product to `inactive` hides it from checkout but does **not** affect existing orders. Customers who already purchased the product retain access. ## Errors > **Retry policy:** Never retry 4xx — fix the request and resubmit. Retry 5xx with exponential backoff (start 5s, max 3 attempts). | Status | `errors[0].message` | What it means | Recommended handling | | - | - | - | - | | 400 | `Missing required field: id` | `id` not provided | Fix the body, resubmit | | 400 | `Invalid ID format` | The provided Short ID could not be decoded | Fix the `id` format, resubmit | | 400 | `Invalid or missing status (must be 'active' or 'inactive')` | `status` is not `active` or `inactive` | Use `active` or `inactive`, resubmit | | 400 | `Product X has no version in environment Y` | The product has no version in the targeted environment (e.g. attempting to update status of `prod` before publishing) | Publish the product to the target environment first via [Publish Product](/api-reference/endpoints/onetime-products/publish-product) | | 404 | `Product not found` | Product does not exist or is not accessible | Verify the `id` belongs to your merchant account | | 500 | `Internal server error` | Unexpected server-side failure | Retry with exponential backoff (start 5s, max 3 attempts) | # Create Store Source: https://docs.waffo.ai/api-reference/endpoints/stores/create-store Create a new store for the authenticated merchant Create a new store for the authenticated merchant. The store slug is auto-generated from the name, and JSONB configuration fields (`notificationSettings`, `checkoutSettings`) are initialized with defaults. Webhooks are managed separately via [`add-webhook`](/api-reference/endpoints/webhooks/add-webhook) — no rows exist on a freshly created store. ``` POST /v1/actions/store/create-store ``` **Authentication:** API Key ## Request Body | Field | Type | Required | Description | | - | - | - | - | | `name` | string | Yes | Store name (1-48 characters, auto-trimmed) | ## Example Request ```typescript SDK theme={"system"} import { WaffoPancake } from "@waffo/pancake-ts"; const client = new WaffoPancake({ merchantId: process.env.WAFFO_MERCHANT_ID!, privateKey: process.env.WAFFO_PRIVATE_KEY!, }); const { store } = await client.stores.create({ name: "My Digital Store" }); console.log(store.id); // => "STO_2aUyqjCzEIiEcYMKj7TZtw" console.log(store.slug); // => "my-digital-store-a1b2c3" ``` ```typescript TypeScript (fetch) theme={"system"} // Uses callApi() helper from authentication.mdx const result = await callApi("POST", "/v1/actions/store/create-store", { name: "My Digital Store", }); console.log(result.data.store.id); // => "STO_2aUyqjCzEIiEcYMKj7TZtw" console.log(result.data.store.slug); // => "my-digital-store-a1b2c3" ``` ```java Java theme={"system"} // Uses callApi() helper from authentication.mdx String body = """ {"name":"My Digital Store"}"""; String response = callApi("POST", "/v1/actions/store/create-store", body); System.out.println(response); // => {"data":{"store":{"id":"STO_2aUyqjCzEIiEcYMKj7TZtw","slug":"my-digital-store-a1b2c3",...}}} ``` ```python Python theme={"system"} # Uses call_api() helper from authentication.mdx result = call_api("POST", "/v1/actions/store/create-store", { "name": "My Digital Store", }) store = result["data"]["store"] print(store["id"]) # => "STO_2aUyqjCzEIiEcYMKj7TZtw" print(store["slug"]) # => "my-digital-store-a1b2c3" ``` ```go Go theme={"system"} // Uses callAPI() helper from authentication.mdx body := map[string]interface{}{ "name": "My Digital Store", } result, err := callAPI("POST", "/v1/actions/store/create-store", body) if err != nil { log.Fatal(err) } fmt.Println(string(result)) // => {"data":{"store":{"id":"STO_2aUyqjCzEIiEcYMKj7TZtw","slug":"my-digital-store-a1b2c3",...}}} ``` ```rust Rust theme={"system"} // Uses call_api() helper from authentication.mdx let body = serde_json::json!({ "name": "My Digital Store" }); let result = call_api("POST", "/v1/actions/store/create-store", &body).await?; println!("{}", result); // => {"data":{"store":{"id":"STO_2aUyqjCzEIiEcYMKj7TZtw","slug":"my-digital-store-a1b2c3",...}}} ``` ```c C theme={"system"} /* Uses call_api() helper from authentication.mdx */ const char *body = "{\"name\":\"My Digital Store\"}"; char *response = call_api("POST", "/v1/actions/store/create-store", body); printf("%s\n", response); free(response); ``` ```cpp C++ theme={"system"} // Uses callApi() helper from authentication.mdx std::string body = R"({"name":"My Digital Store"})"; std::string response = callApi("POST", "/v1/actions/store/create-store", body); std::cout << response << std::endl; // => {"data":{"store":{"id":"STO_2aUyqjCzEIiEcYMKj7TZtw","slug":"my-digital-store-a1b2c3",...}}} ``` ```bash cURL theme={"system"} MERCHANT_ID="MER_2aUyqjCzEIiEcYMKj7TZtw" TIMESTAMP=$(date +%s) BODY='{"name":"My Digital Store"}' BODY_HASH=$(echo -n "$BODY" | openssl dgst -sha256 -binary | base64 | tr -d '\n') CANONICAL_REQUEST="POST /v1/actions/store/create-store $TIMESTAMP $BODY_HASH" SIGNATURE=$(echo -n "$CANONICAL_REQUEST" | openssl dgst -sha256 -sign private_key.pem | base64 | tr -d '\n') curl -X POST "https://api.waffo.ai/v1/actions/store/create-store" \ -H "Content-Type: application/json" \ -H "X-Merchant-Id: $MERCHANT_ID" \ -H "X-Timestamp: $TIMESTAMP" \ -H "X-Signature: $SIGNATURE" \ -d "$BODY" ``` ```bash wget theme={"system"} MERCHANT_ID="MER_2aUyqjCzEIiEcYMKj7TZtw" TIMESTAMP=$(date +%s) BODY='{"name":"My Digital Store"}' BODY_HASH=$(echo -n "$BODY" | openssl dgst -sha256 -binary | base64 | tr -d '\n') CANONICAL_REQUEST="POST /v1/actions/store/create-store $TIMESTAMP $BODY_HASH" SIGNATURE=$(echo -n "$CANONICAL_REQUEST" | openssl dgst -sha256 -sign private_key.pem | base64 | tr -d '\n') wget -qO- "https://api.waffo.ai/v1/actions/store/create-store" \ --header="Content-Type: application/json" \ --header="X-Merchant-Id: $MERCHANT_ID" \ --header="X-Timestamp: $TIMESTAMP" \ --header="X-Signature: $SIGNATURE" \ --post-data="$BODY" ``` ## Success Response (200) ```json theme={"system"} { "data": { "store": { "id": "STO_2aUyqjCzEIiEcYMKj7TZtw", "name": "My Digital Store", "status": "active", "logo": null, "supportEmail": null, "website": null, "slug": "my-digital-store-a1b2c3", "prodEnabled": false, "notificationSettings": { "emailOrderConfirmation": true, "emailSubscriptionConfirmation": true, "emailSubscriptionCycled": true, "emailSubscriptionCanceled": true, "emailSubscriptionRevoked": true, "emailSubscriptionPastDue": true, "notifyNewOrders": true, "notifyNewSubscriptions": true }, "checkoutSettings": { "defaultDarkMode": false, "light": { "checkoutLogo": null, "checkoutColorPrimary": "#000000", "checkoutColorBackground": "#FFFFFF", "checkoutColorCard": "#F5F5F5", "checkoutColorText": "#1A1A1A", "checkoutBorderRadius": "8px" }, "dark": { "checkoutLogo": null, "checkoutColorPrimary": "#FFFFFF", "checkoutColorBackground": "#1A1A1A", "checkoutColorCard": "#2A2A2A", "checkoutColorText": "#F5F5F5", "checkoutBorderRadius": "8px" } }, "deletedAt": null, "createdAt": "2026-01-15T10:30:00.000Z", "updatedAt": "2026-01-15T10:30:00.000Z" } } } ``` ## Response Fields | Field | Type | Description | | - | - | - | | `id` | string | Store ID (Short ID format `STO_xxx`) | | `name` | string | Store display name | | `status` | string | Store status (`active`, `inactive`, or `suspended`) | | `logo` | string \| null | Store logo URL | | `supportEmail` | string \| null | Support email address | | `website` | string \| null | Store website URL | | `slug` | string \| null | Auto-generated URL slug | | `prodEnabled` | boolean | Whether production mode is enabled | | `notificationSettings` | object \| null | Notification preferences (see [Notification Settings](/api-reference/endpoints/stores/update-store#notification-settings)) | | `checkoutSettings` | object \| null | Checkout page theme (see [Checkout Settings](/api-reference/endpoints/stores/update-store#checkout-settings)) | | `deletedAt` | string \| null | Soft-delete timestamp (ISO 8601), `null` if active | | `createdAt` | string | Creation timestamp (ISO 8601) | | `updatedAt` | string | Last update timestamp (ISO 8601) | ## Errors > **Retry policy:** Never retry 4xx — fix the request and resubmit. Retry 5xx with exponential backoff (start 5s, max 3 attempts). | Status | `errors[0].message` | What it means | Recommended handling | | - | - | - | - | | 400 | `Missing merchantId in request context` | API Key did not resolve to a merchant context | **Do not retry.** Check your API Key configuration. | | 400 | `Missing required field: name` | `name` is absent from the body | Fix the input and resubmit. | | 400 | `Store name cannot be empty or contain only whitespace` | `name` is empty after `trim()` | Fix the input and resubmit. | | 400 | `Store name cannot exceed 48 characters` | `name` is longer than 48 characters | Shorten the name and resubmit. | | 400 | `Store name cannot contain control characters` | `name` contains control characters | Remove the control characters and resubmit. | | 400 | `Cannot create more stores. Maximum limit of 100 stores per merchant has been reached.` | The merchant already owns 100 stores | **Do not retry.** Delete an existing store first, or contact support to raise the limit. | > [!NOTE] > > Each merchant can create up to **100 stores**. The store creator is automatically assigned the `owner` role. # Delete Store Source: https://docs.waffo.ai/api-reference/endpoints/stores/delete-store Soft-delete a store (owner only) Soft-delete a store. The store data is retained but becomes inaccessible. Only the store **owner** can perform this action. ``` POST /v1/actions/store/delete-store ``` **Authentication:** API Key (owner role required) ## Request Body | Field | Type | Required | Description | | - | - | - | - | | `id` | string | Yes | Store ID to delete (Short ID format `STO_xxx`) | ## Example Request ```typescript SDK theme={"system"} const { store } = await client.stores.delete({ id: "STO_2aUyqjCzEIiEcYMKj7TZtw", }); console.log(store.deletedAt); // => "2026-01-15T12:00:00.000Z" ``` ```typescript TypeScript (fetch) theme={"system"} // Uses callApi() helper from authentication.mdx const result = await callApi("POST", "/v1/actions/store/delete-store", { id: "STO_2aUyqjCzEIiEcYMKj7TZtw", }); console.log(result.data.store.deletedAt); // => "2026-01-15T12:00:00.000Z" ``` ```java Java theme={"system"} // Uses callApi() helper from authentication.mdx String body = """ {"id":"STO_2aUyqjCzEIiEcYMKj7TZtw"}"""; String response = callApi("POST", "/v1/actions/store/delete-store", body); System.out.println(response); ``` ```python Python theme={"system"} # Uses call_api() helper from authentication.mdx result = call_api("POST", "/v1/actions/store/delete-store", { "id": "STO_2aUyqjCzEIiEcYMKj7TZtw", }) store = result["data"]["store"] print(store["deletedAt"]) # => "2026-01-15T12:00:00.000Z" ``` ```go Go theme={"system"} // Uses callAPI() helper from authentication.mdx body := map[string]interface{}{ "id": "STO_2aUyqjCzEIiEcYMKj7TZtw", } result, err := callAPI("POST", "/v1/actions/store/delete-store", body) if err != nil { log.Fatal(err) } fmt.Println(string(result)) ``` ```rust Rust theme={"system"} // Uses call_api() helper from authentication.mdx let body = serde_json::json!({ "id": "STO_2aUyqjCzEIiEcYMKj7TZtw" }); let result = call_api("POST", "/v1/actions/store/delete-store", &body).await?; println!("{}", result); ``` ```c C theme={"system"} /* Uses call_api() helper from authentication.mdx */ const char *body = "{\"id\":\"STO_2aUyqjCzEIiEcYMKj7TZtw\"}"; char *response = call_api("POST", "/v1/actions/store/delete-store", body); printf("%s\n", response); free(response); ``` ```cpp C++ theme={"system"} // Uses callApi() helper from authentication.mdx std::string body = R"({"id":"STO_2aUyqjCzEIiEcYMKj7TZtw"})"; std::string response = callApi("POST", "/v1/actions/store/delete-store", body); std::cout << response << std::endl; ``` ```bash cURL theme={"system"} MERCHANT_ID="MER_2aUyqjCzEIiEcYMKj7TZtw" TIMESTAMP=$(date +%s) BODY='{"id":"STO_2aUyqjCzEIiEcYMKj7TZtw"}' BODY_HASH=$(echo -n "$BODY" | openssl dgst -sha256 -binary | base64 | tr -d '\n') CANONICAL_REQUEST="POST /v1/actions/store/delete-store $TIMESTAMP $BODY_HASH" SIGNATURE=$(echo -n "$CANONICAL_REQUEST" | openssl dgst -sha256 -sign private_key.pem | base64 | tr -d '\n') curl -X POST "https://api.waffo.ai/v1/actions/store/delete-store" \ -H "Content-Type: application/json" \ -H "X-Merchant-Id: $MERCHANT_ID" \ -H "X-Timestamp: $TIMESTAMP" \ -H "X-Signature: $SIGNATURE" \ -d "$BODY" ``` ```bash wget theme={"system"} MERCHANT_ID="MER_2aUyqjCzEIiEcYMKj7TZtw" TIMESTAMP=$(date +%s) BODY='{"id":"STO_2aUyqjCzEIiEcYMKj7TZtw"}' BODY_HASH=$(echo -n "$BODY" | openssl dgst -sha256 -binary | base64 | tr -d '\n') CANONICAL_REQUEST="POST /v1/actions/store/delete-store $TIMESTAMP $BODY_HASH" SIGNATURE=$(echo -n "$CANONICAL_REQUEST" | openssl dgst -sha256 -sign private_key.pem | base64 | tr -d '\n') wget -qO- "https://api.waffo.ai/v1/actions/store/delete-store" \ --header="Content-Type: application/json" \ --header="X-Merchant-Id: $MERCHANT_ID" \ --header="X-Timestamp: $TIMESTAMP" \ --header="X-Signature: $SIGNATURE" \ --post-data="$BODY" ``` ## Success Response (200) ```json theme={"system"} { "data": { "store": { "id": "STO_2aUyqjCzEIiEcYMKj7TZtw", "name": "My Digital Store", "status": "active", "logo": null, "supportEmail": null, "website": null, "slug": "my-digital-store-a1b2c3", "prodEnabled": false, "notificationSettings": null, "checkoutSettings": null, "deletedAt": "2026-01-15T12:00:00.000Z", "createdAt": "2026-01-15T10:30:00.000Z", "updatedAt": "2026-01-15T12:00:00.000Z" } } } ``` ## Response Fields Same as [Create Store response fields](/api-reference/endpoints/stores/create-store#response-fields), with `deletedAt` populated. ## Errors > **Retry policy:** Never retry 4xx — fix the request and resubmit. Retry 5xx with exponential backoff (start 5s, max 3 attempts). On 409, clean up blocking resources first (AI callers should escalate via `aiHint`). | Status | `errors[0].message` | What it means | Recommended handling | | - | - | - | - | | 400 | `Missing merchantId in request context` | API Key did not resolve to a merchant context | **Do not retry.** Check your API Key configuration. | | 400 | `Missing required field: id` | `id` is absent from the body | Fix the input and resubmit. | | 400 | `Expected format: STO_xxx, got ""` | `id` is not a valid Store Short ID | Fix the `id` value and resubmit. | | 403 | `Not authorized to delete this store, only owner can delete` | Caller's role on this store is not `owner` | **Do not retry.** Use an `owner` API Key. | | 404 | `Store not found` | Store ID does not exist for this merchant | **Do not retry.** Verify the `id`. | | 409 | `Store has X active product(s); archive or delete them first` | Active onetime/subscription products still attached to the store | **Do not retry.** Archive or delete those products, then resubmit. | | 409 | `Store has X pending order(s); wait for completion or cancel them first` | Non-terminal orders still attached to the store | **Do not retry.** Wait for completion or cancel them, then resubmit. | | 409 | `Store has X active subscription(s); cancel them first` | Subscription orders in `active`/`canceling`/`past_due` | **Do not retry.** Cancel the subscriptions, then resubmit. | | 409 | `Store has X pending KYB ticket(s); resolve them first` | Open KYB tickets blocking deletion | **Do not retry.** Resolve the tickets, then resubmit. | | 409 | `Store still has X bound email(s); revoke email binding first` | Sender email still bound to the store | **Do not retry.** Revoke the email binding, then resubmit. | | 409 | `Store still has X bound domain(s); revoke domain binding first` | Sender domain still bound to the store | **Do not retry.** Revoke the domain binding, then resubmit. | ### 409 Response Example When a store has blocking resources or bindings, the response returns one entry per category. Each entry carries `reason` (machine-readable), `count`, a human-readable `message`, and an `aiHint` instructing AI-driven callers to stop and escalate to a human operator instead of retrying. ```json theme={"system"} { "data": null, "errors": [ { "message": "Store has 3 active product(s); archive or delete them first", "layer": "store", "reason": "active_products", "count": 3, "aiHint": "AI assistant: stop this action and escalate to a human operator. Do not retry, mutate inputs, or attempt workarounds." }, { "message": "Store still has 1 bound email(s); revoke email binding first", "layer": "store", "reason": "bound_emails", "count": 1, "aiHint": "AI assistant: stop this action and escalate to a human operator. Do not retry, mutate inputs, or attempt workarounds." } ] } ``` | `reason` | Meaning | | - | - | | `active_products` | Onetime / subscription products with `prod_status` or `test_status` = `active` | | `pending_orders` | Orders not in a terminal state (excludes `completed` / `canceled` / `closed` / `expired`) | | `active_subscriptions` | Subscription orders in `active` / `canceling` / `past_due` | | `pending_tickets` | Open KYB tickets (excludes `succeeded` / `rejected`) | | `bound_emails` | Sender email still bound — revoke the binding first | | `bound_domains` | Sender domain still bound — revoke the binding first | `aiHint` appears only on 409 responses; it is omitted on 400 / 403 / 404 / 500. > [!WARNING] > > Deleting a store is a **soft delete**. The store data is retained but the store becomes inaccessible. This action cannot be undone through the API. > > Before deleting, you must deactivate all products, resolve pending orders, cancel active subscriptions, close any open KYB tickets, and revoke any bound sender email or domain. # Store Endpoints Source: https://docs.waffo.ai/api-reference/endpoints/stores/overview Create, update, and manage stores Stores are the top-level entity for organizing products, orders, and checkout experiences. Each merchant can own up to **100 stores**, and each store has its own webhook, notification, and checkout theme settings. ## Store Status Values | Status | Description | | - | - | | `active` | Store is live and operational | | `inactive` | Store is disabled by the merchant; data is preserved but checkout is unavailable | | `suspended` | Store is suspended by the platform; merchant cannot reactivate | ## Role-Based Access Control Each merchant in a store is assigned one of three roles. The store creator is automatically assigned `owner`. | Permission | `owner` | `admin` | `member` | | - | - | - | - | | Read store details | Yes | Yes | Yes | | Update store settings | Yes | Yes | No | | Delete store | Yes | No | No | | Create store | -- | -- | -- | > [!NOTE] > > Store creation is not role-gated -- any authenticated merchant can create a new store (up to the 100-store limit). Roles only apply to operations on existing stores. ## Endpoints > **[Create Store](/api-reference/endpoints/stores/create-store)** > > Create a new store for the authenticated merchant. > **[Update Store](/api-reference/endpoints/stores/update-store)** > > Update store name, status, or configuration settings. > **[Delete Store](/api-reference/endpoints/stores/delete-store)** > > Soft-delete a store (owner only). # Update Store Source: https://docs.waffo.ai/api-reference/endpoints/stores/update-store Update an existing store's name, status, or configuration settings Update an existing store's name, status, or configuration settings. Only fields included in the request body are updated; omitted fields remain unchanged. ``` POST /v1/actions/store/update-store ``` **Authentication:** API Key (owner or admin role required) > [!NOTE] > > This endpoint does not manage webhook configuration. If a `webhookSettings` field is sent in the request body it is silently ignored and the response includes a top-level `warnings` array; other fields update normally and the call returns 200. Use [`add-webhook`](/api-reference/endpoints/webhooks/add-webhook), [`update-webhook`](/api-reference/endpoints/webhooks/update-webhook), and [`remove-webhook`](/api-reference/endpoints/webhooks/remove-webhook) to configure webhooks, and GraphQL `Store.storeWebhooks` to list them. ## Request Body | Field | Type | Required | Description | | - | - | - | - | | `id` | string | Yes | Store ID (Short ID format `STO_xxx`) | | `name` | string | No | Updated store name (1-48 characters) | | `status` | string | No | `active`, `inactive`, or `suspended` | | `logo` | string \| null | No | Store logo URL (set to `null` to remove) | | `notificationSettings` | object \| null | No | Notification preferences (set to `null` to remove) | | `checkoutSettings` | object \| null | No | Checkout theme configuration (set to `null` to remove) | ## Notification Settings Two categories with different write permissions: **Merchant-writable** (✅ accepted via this endpoint): | Field | Type | Default | Description | | - | - | - | - | | `notifyNewOrders` | boolean | `true` | Notify merchant of new orders | | `notifyNewSubscriptions` | boolean | `true` | Notify merchant of new subscriptions | | `notifySubscriptionCanceled` | boolean | `true` | Notify merchant when a subscriber cancels (still within access period) | | `notifySubscriptionEnded` | boolean | `true` | Notify merchant when a subscription ends | | `notifySubscriptionPastDue` | boolean | `true` | Notify merchant when a subscription enters past-due (payment failure) | | `notifySubscriptionRenewed` | boolean | `true` | Notify merchant when a subscription successfully renews | | `notifySubscriptionUncanceled` | boolean | `true` | Notify merchant when a previously canceled subscription is reactivated | | `notifySubscriptionPlanChanged` | boolean | `true` | Notify merchant when a subscription plan change takes effect | | `notifyChargeback` | boolean | `false` | Notify merchant when a chargeback is filed. **The one `notify*` that defaults to off** — pass `true` explicitly to receive it | | `notifyRefundSucceeded` | boolean | `true` | Notify merchant when a refund on a payment completes | | `emailUpcomingCharge` | boolean | `true` | Send the customer a reminder before an upcoming subscription charge. One of the two customer emails a merchant may switch off; doing so silences it for every billing period in the store, yearly included | | `emailTrialEnding` | boolean | `true` | Send the customer a reminder before a paid trial ends. One of the two customer emails a merchant may switch off; the switch is per store, so it covers every buyer of that store, and passing `true` again restores it | **Platform-managed** (🔒 read-only via merchant API; managed by PANCAKE platform): | Field | Type | Default | Description | | - | - | - | - | | `emailOrderConfirmation` | boolean | `true` | Send email on order confirmation | | `emailSubscriptionConfirmation` | boolean | `true` | Send email on subscription creation | | `emailSubscriptionCycled` | boolean | `true` | Send email on subscription renewal | | `emailSubscriptionCanceled` | boolean | `true` | Send email on subscription cancellation | | `emailSubscriptionRevoked` | boolean | `true` | Send email on subscription revocation | | `emailSubscriptionPastDue` | boolean | `true` | Send email on subscription past due | | `emailTrialStarted` | boolean | `true` | Send email when a free trial is started | | `emailSubscriptionPlanChanged` | boolean | `true` | Send email to the customer when a subscription plan change takes effect | | `emailRefundSucceeded` | boolean | `true` | Send email to the customer when their refund completes | > [!NOTE] > > If your `notificationSettings` payload includes any platform-managed field (the read-only `email*` keys above, or the legacy `notifyPayoutCompleted` / `notifyPayoutFailed` keys — payout result emails are always delivered and have no toggle), the server silently drops it and returns a `200` response with a `warnings[]` entry listing the dropped keys. `emailUpcomingCharge` and `emailTrialEnding` are not among them: both are accepted and applied, and the response carries no `warnings` for them. To toggle any other customer email, contact PANCAKE platform support. ## Checkout Settings | Field | Type | Description | | - | - | - | | `defaultDarkMode` | boolean | Whether to default to dark mode | | `light` | object | Light theme settings (see below) | | `dark` | object | Dark theme settings (see below) | **Checkout Theme Settings** (applies to both `light` and `dark`): | Field | Type | Description | | - | - | - | | `checkoutLogo` | string \| null | Logo URL for checkout page | | `checkoutColorPrimary` | string | Primary color (hex) | | `checkoutColorBackground` | string | Background color (hex) | | `checkoutColorCard` | string | Card/panel color (hex) | | `checkoutColorText` | string | Text color (hex) | | `checkoutBorderRadius` | string | Border radius (CSS value) | ## Partial Update Semantics Both settings objects support partial updates. Each sub-field follows these semantics: | Value | Behavior | Example | | - | - | - | | Omitted (not in JSON) | Keep existing value | Only pass `notifyNewOrders`; other notification flags stay unchanged | | `null` | Clear the field | `"checkoutLogo": null` removes the checkout logo | | Actual value | Create or update | `"checkoutColorPrimary": "#FF6600"` sets a new primary color | Setting the entire object to `null` (e.g., `"notificationSettings": null`) clears all fields in that settings group. `"notificationSettings": null` clears exactly what this endpoint is allowed to write: **every `notify*` toggle plus `emailUpcomingCharge` and `emailTrialEnding`** (each then reads back as its own default: `false` for `notifyChargeback`, `true` for the rest). The platform-managed `email*` toggles are **left untouched** — a merchant can neither write them nor reset them by clearing. The store's **notification recipient list is untouched** too: recipients are managed exclusively through the three `store-notification-recipient` endpoints. > [!WARNING] > > Clearing switches a silenced customer reminder back on. A store that set `emailUpcomingCharge` or `emailTrialEnding` to `false` reads it back as `true` after one `"notificationSettings": null`, and its buyers start receiving that reminder again. > > **Send a partial update instead** — only the keys you actually want to change: > > ```json theme={"system"} > // ❌ also resets emailTrialEnding to true > { "id": "STO_xxx", "notificationSettings": null } > > // ✅ resets only notifyNewOrders; emailTrialEnding stays false > { "id": "STO_xxx", "notificationSettings": { "notifyNewOrders": true } } > ``` ## Example Request ```typescript SDK theme={"system"} import { WaffoPancake, EntityStatus } from "@waffo/pancake-ts"; const client = new WaffoPancake({ merchantId: process.env.WAFFO_MERCHANT_ID!, privateKey: process.env.WAFFO_PRIVATE_KEY!, }); const { store } = await client.stores.update({ id: "STO_2aUyqjCzEIiEcYMKj7TZtw", name: "Updated Store Name", notificationSettings: { notifyNewOrders: true, notifyNewSubscriptions: false, }, }); ``` ```typescript TypeScript (fetch) theme={"system"} // Uses callApi() helper from authentication.mdx const result = await callApi("POST", "/v1/actions/store/update-store", { id: "STO_2aUyqjCzEIiEcYMKj7TZtw", name: "Updated Store Name", notificationSettings: { notifyNewSubscriptions: false, }, }); console.log(result.data.store.name); // => "Updated Store Name" ``` ```java Java theme={"system"} // Uses callApi() helper from authentication.mdx String body = """ { "id": "STO_2aUyqjCzEIiEcYMKj7TZtw", "name": "Updated Store Name", "notificationSettings": { "notifyNewSubscriptions": false } }"""; String response = callApi("POST", "/v1/actions/store/update-store", body); System.out.println(response); ``` ```python Python theme={"system"} # Uses call_api() helper from authentication.mdx result = call_api("POST", "/v1/actions/store/update-store", { "id": "STO_2aUyqjCzEIiEcYMKj7TZtw", "name": "Updated Store Name", "notificationSettings": { "notifyNewSubscriptions": False, }, }) store = result["data"]["store"] print(store["name"]) # => "Updated Store Name" ``` ```go Go theme={"system"} // Uses callAPI() helper from authentication.mdx body := map[string]interface{}{ "id": "STO_2aUyqjCzEIiEcYMKj7TZtw", "name": "Updated Store Name", "notificationSettings": map[string]interface{}{ "notifyNewSubscriptions": false, }, } result, err := callAPI("POST", "/v1/actions/store/update-store", body) if err != nil { log.Fatal(err) } fmt.Println(string(result)) ``` ```rust Rust theme={"system"} // Uses call_api() helper from authentication.mdx let body = serde_json::json!({ "id": "STO_2aUyqjCzEIiEcYMKj7TZtw", "name": "Updated Store Name", "notificationSettings": { "notifyNewSubscriptions": false } }); let result = call_api("POST", "/v1/actions/store/update-store", &body).await?; println!("{}", result); ``` ```c C theme={"system"} /* Uses call_api() helper from authentication.mdx */ const char *body = "{\"id\":\"STO_2aUyqjCzEIiEcYMKj7TZtw\"," "\"name\":\"Updated Store Name\"," "\"notificationSettings\":{\"notifyNewSubscriptions\":false}}"; char *response = call_api("POST", "/v1/actions/store/update-store", body); printf("%s\n", response); free(response); ``` ```cpp C++ theme={"system"} // Uses callApi() helper from authentication.mdx std::string body = R"({ "id": "STO_2aUyqjCzEIiEcYMKj7TZtw", "name": "Updated Store Name", "notificationSettings": { "notifyNewSubscriptions": false } })"; std::string response = callApi("POST", "/v1/actions/store/update-store", body); std::cout << response << std::endl; ``` ```bash cURL theme={"system"} MERCHANT_ID="MER_2aUyqjCzEIiEcYMKj7TZtw" TIMESTAMP=$(date +%s) BODY='{"id":"STO_2aUyqjCzEIiEcYMKj7TZtw","name":"Updated Store Name","notificationSettings":{"notifyNewSubscriptions":false}}' BODY_HASH=$(echo -n "$BODY" | openssl dgst -sha256 -binary | base64 | tr -d '\n') CANONICAL_REQUEST="POST /v1/actions/store/update-store $TIMESTAMP $BODY_HASH" SIGNATURE=$(echo -n "$CANONICAL_REQUEST" | openssl dgst -sha256 -sign private_key.pem | base64 | tr -d '\n') curl -X POST "https://api.waffo.ai/v1/actions/store/update-store" \ -H "Content-Type: application/json" \ -H "X-Merchant-Id: $MERCHANT_ID" \ -H "X-Timestamp: $TIMESTAMP" \ -H "X-Signature: $SIGNATURE" \ -d "$BODY" ``` ```bash wget theme={"system"} MERCHANT_ID="MER_2aUyqjCzEIiEcYMKj7TZtw" TIMESTAMP=$(date +%s) BODY='{"id":"STO_2aUyqjCzEIiEcYMKj7TZtw","name":"Updated Store Name","notificationSettings":{"notifyNewSubscriptions":false}}' BODY_HASH=$(echo -n "$BODY" | openssl dgst -sha256 -binary | base64 | tr -d '\n') CANONICAL_REQUEST="POST /v1/actions/store/update-store $TIMESTAMP $BODY_HASH" SIGNATURE=$(echo -n "$CANONICAL_REQUEST" | openssl dgst -sha256 -sign private_key.pem | base64 | tr -d '\n') wget -qO- "https://api.waffo.ai/v1/actions/store/update-store" \ --header="Content-Type: application/json" \ --header="X-Merchant-Id: $MERCHANT_ID" \ --header="X-Timestamp: $TIMESTAMP" \ --header="X-Signature: $SIGNATURE" \ --post-data="$BODY" ``` ## Success Response (200) ```json theme={"system"} { "data": { "store": { "id": "STO_2aUyqjCzEIiEcYMKj7TZtw", "name": "Updated Store Name", "status": "active", "logo": null, "supportEmail": null, "website": null, "slug": "my-digital-store-a1b2c3", "prodEnabled": false, "notificationSettings": { "emailOrderConfirmation": true, "emailSubscriptionConfirmation": true, "emailSubscriptionCycled": true, "emailSubscriptionCanceled": true, "emailSubscriptionRevoked": true, "emailSubscriptionPastDue": true, "emailTrialStarted": true, "emailTrialEnding": true, "emailUpcomingCharge": true, "emailSubscriptionPlanChanged": true, "emailRefundSucceeded": true, "notifyNewOrders": true, "notifyNewSubscriptions": false, "notifySubscriptionCanceled": true, "notifySubscriptionEnded": true, "notifySubscriptionPastDue": true, "notifySubscriptionRenewed": true, "notifySubscriptionUncanceled": true, "notifySubscriptionPlanChanged": true, "notifyChargeback": false, "notifyRefundSucceeded": true }, "checkoutSettings": { "defaultDarkMode": false, "light": { "checkoutLogo": null, "checkoutColorPrimary": "#000000", "checkoutColorBackground": "#FFFFFF", "checkoutColorCard": "#F5F5F5", "checkoutColorText": "#1A1A1A", "checkoutBorderRadius": "8px" }, "dark": { "checkoutLogo": null, "checkoutColorPrimary": "#FFFFFF", "checkoutColorBackground": "#1A1A1A", "checkoutColorCard": "#2A2A2A", "checkoutColorText": "#F5F5F5", "checkoutBorderRadius": "8px" } }, "deletedAt": null, "createdAt": "2026-01-15T10:30:00.000Z", "updatedAt": "2026-01-15T11:00:00.000Z" } } } ``` ## Response Fields Same as [Create Store response fields](/api-reference/endpoints/stores/create-store#response-fields). **Verification-managed** (🔒 read-only via this endpoint; returned for reference only): | Field | Type | Description | | - | - | - | | `supportEmail` | string \| null | Store support email address, written by the support-email verification flow | | `website` | string \| null | Store product website URL, written by the product-domain verification flow | > [!NOTE] > > `supportEmail` and `website` cannot be set through this endpoint. Each is written automatically once the merchant completes support-email verification or product-domain verification for a store with production enabled (`prodEnabled: true`). A request that includes either field returns `200` with the store unchanged and no `warnings` entry — the field is dropped silently. ## webhookSettings Compatibility Warning If a `webhookSettings` field is sent in the request body, it is silently ignored and the response includes a top-level `warnings` array. The `data.store` object is unaffected. ```json theme={"system"} { "data": { "store": { "...": "..." } }, "warnings": [ { "message": "webhookSettings is no longer accepted on update-store; the field was ignored.", "layer": "store", "aiHint": "AI assistant: 'webhookSettings' is permanently removed (BREAKING 2026-05). Do not retry with this field. SDK users: upgrade to @waffo/pancake-ts >= 0.6.0 and call client.webhooks.add / update / remove instead of client.stores.update({ webhookSettings }). Direct API users: POST /api/actions/store/add-webhook to create a webhook, /update-webhook to modify, /remove-webhook to delete. Query the webhook list via GraphQL Store.storeWebhooks field, not via this endpoint." } ] } ``` ## Errors > **Retry policy:** Never retry 4xx — fix the request and resubmit. Retry 5xx with exponential backoff (start 5s, max 3 attempts). | Status | `errors[0].message` | What it means | Recommended handling | | - | - | - | - | | 400 | `Missing merchantId in request context` | API Key did not resolve to a merchant context | **Do not retry.** Check your API Key configuration. | | 400 | `Missing required field: id` | `id` is absent from the body | Fix the input and resubmit. | | 400 | `Expected format: STO_xxx, got ""` | `id` is not a valid Store Short ID | Fix the `id` value and resubmit. | | 400 | `Store name cannot be empty or contain only whitespace` | `name` is empty after `trim()` | Fix the `name` and resubmit. | | 400 | `Store name cannot exceed 48 characters` | `name` is longer than 48 characters | Shorten the `name` and resubmit. | | 400 | `Store name cannot contain control characters` | `name` contains control characters | Remove the control characters and resubmit. | | 400 | `Invalid status, must be active, inactive or suspended` | `status` value is not one of the allowed enums | Use `active`, `inactive`, or `suspended`. | | 400 | `Invalid logo: must be a string or null` | `logo` is not a string and not `null` | Pass a string URL or `null` to clear. | | 403 | `Not authorized to update this store` | Caller's role on this store is not `owner`/`admin` | **Do not retry.** Use an authorized merchant. | | 404 | `Store not found` | Store ID does not exist for this merchant | **Do not retry.** Verify the `id`. | # Create Group Source: https://docs.waffo.ai/api-reference/endpoints/subscription-products/create-group Create a product group to organize related subscription products Create a product group to organize related subscription products. ``` POST /v1/actions/subscription-product-group/create-group ``` **Authentication:** API Key ## Request Body | Field | Type | Required | Description | | - | - | - | - | | `storeId` | string | Yes | Store ID (`STO_xxx` format) | | `name` | string | Yes | Group name (unique per store + environment) | | `description` | string | No | Group description | | `rules` | object | No | Group switches: `{ sharedTrial: boolean, selfServicePlanChange: boolean }`. Both are optional and both default to `false` — see [Rules](/api-reference/endpoints/subscription-products/overview#rules) | | `productIds` | string\[] | No | Subscription product IDs (`PROD_xxx` format) to include | ## Example Request ```typescript SDK theme={"system"} const { group } = await client.subscriptionProductGroups.create({ storeId: "STO_2D5F8G3H1K4M6N9P", name: "Pricing Plans", description: "Free, Pro, and Enterprise tiers", rules: { sharedTrial: true, selfServicePlanChange: true }, productIds: [ "PROD_3F7H2J5L8N1Q4S6U", "PROD_8B4D6F9H2K5M7P1R", "PROD_1C3E5G7J0L2N4Q6S", ], }); ``` ```bash cURL theme={"system"} curl -X POST https://api.waffo.ai/v1/actions/subscription-product-group/create-group \ -H "Content-Type: application/json" \ -H "X-Merchant-Id: MER_7K3M9P2R5T8W1Y4Z" \ -H "X-Timestamp: 2026-03-30T10:00:00Z" \ -H "X-Signature: BASE64_RSA_SIGNATURE" \ -d '{ "storeId": "STO_2D5F8G3H1K4M6N9P", "name": "Pricing Plans", "description": "Free, Pro, and Enterprise tiers", "rules": { "sharedTrial": true, "selfServicePlanChange": true }, "productIds": [ "PROD_3F7H2J5L8N1Q4S6U", "PROD_8B4D6F9H2K5M7P1R", "PROD_1C3E5G7J0L2N4Q6S" ] }' ``` ```python Python theme={"system"} body = { "storeId": "STO_2D5F8G3H1K4M6N9P", "name": "Pricing Plans", "description": "Free, Pro, and Enterprise tiers", "rules": {"sharedTrial": True, "selfServicePlanChange": True}, "productIds": [ "PROD_3F7H2J5L8N1Q4S6U", "PROD_8B4D6F9H2K5M7P1R", "PROD_1C3E5G7J0L2N4Q6S", ], } response = requests.post( "https://api.waffo.ai/v1/actions/subscription-product-group/create-group", json=body, headers=sign_request("POST", "/v1/actions/subscription-product-group/create-group", body), ) group = response.json()["data"]["group"] ``` ## Success Response (200) ```json theme={"system"} { "data": { "group": { "id": "d4e5f6a7-b8c9-0d1e-2f3a-4b5c6d7e8f9a", "storeId": "STO_2D5F8G3H1K4M6N9P", "name": "Pricing Plans", "description": "Free, Pro, and Enterprise tiers", "rules": { "sharedTrial": true, "selfServicePlanChange": true }, "productIds": [ "PROD_3F7H2J5L8N1Q4S6U", "PROD_8B4D6F9H2K5M7P1R", "PROD_1C3E5G7J0L2N4Q6S" ], "environment": "test", "createdAt": "2026-03-30T10:30:00.000Z", "updatedAt": "2026-03-30T10:30:00.000Z" } } } ``` ## Errors > **Retry policy:** Never retry 4xx — fix the request and resubmit. Retry 5xx with exponential backoff (start 5s, max 3 attempts). | Status | `errors[0].message` | What it means | Recommended handling | | - | - | - | - | | 400 | `Missing or invalid header: x-context-environment` | Environment header missing or not `test` / `prod` | Fix the header, resubmit | | 400 | `Missing required fields: storeId, name` | A required body field was omitted | Add the missing field, resubmit | | 400 | `Expected format: STO_xxx, got "..."` / `Expected format: PROD_xxx, got "..."` | `storeId` or a `productIds` entry could not be decoded as a Short ID | Fix the ID, resubmit | | 400 | `rules.sharedTrial must be a boolean` | The switch was sent as something other than `true` / `false` | Send a boolean, or omit the switch | | 400 | `rules.selfServicePlanChange must be a boolean` | The switch was sent as something other than `true` / `false` | Send a boolean, or omit the switch | | 409 | `A group named "..." already exists in this store and environment` | Another group in the same store and environment already uses this `name`, or a concurrent request created it first | Choose a different `name`, or update the existing group instead | | 500 | `Internal server error` | Internal error or transient downstream failure | Retry with exponential backoff (start 5s, max 3 attempts) | # Create Subscription Product Source: https://docs.waffo.ai/api-reference/endpoints/subscription-products/create-product Create a subscription product with a billing period and multi-currency pricing ``` POST /v1/actions/subscription-product/create-product ``` **Authentication:** API Key ## Request Body | Field | Type | Required | Description | | - | - | - | - | | `storeId` | string | Yes | Store ID (`STO_xxx` format) | | `name` | string | Yes | Product name (max 64 chars) | | `billingPeriod` | string | Yes | `weekly`, `monthly`, `quarterly`, or `yearly` | | `prices` | object | Yes | Multi-currency pricing (see [Price Object Format](#price-object-format)) | | `description` | string \| null | No | Product description (supports Markdown; pass `null` or `""` to clear) | | `media` | array | No | Product images/videos (see [Media Format](/api-reference/endpoints/onetime-products#media-item-format)) | | `successUrl` | string \| null | No | Redirect URL after successful subscription (max 512 chars, must be a valid http(s) URL; pass `null` or `""` to clear) | | `metadata` | object | No | Custom key-value data. May include `trialDays` (integer, 1-365) to offer a trial period | ## Price Object Format Same as [one-time products](/api-reference/endpoints/onetime-products/create-product#price-object-format), with an optional `trialAmount` per currency. ```json theme={"system"} { "USD": { "amount": "29.00", "taxIncluded": false, "taxCategory": "saas", "trialAmount": "1.00" }, "EUR": { "amount": "27.00", "taxIncluded": true, "taxCategory": "saas" } } ``` | Field | Type | Description | | - | - | - | | `trialAmount` | string | Price charged for the trial period, as a display format string. Must be lower than `amount` for the same currency | `trialAmount` takes effect together with `metadata.trialDays`, which sets the trial length for every currency. In the example above, USD subscribers pay \$1.00 for the trial period and EUR subscribers get it free. * `trialAmount` is optional and set independently per currency — a product can offer a paid trial in one currency and a free trial in another. * If `trialAmount` is omitted for a currency, that currency's trial is free. * `trialAmount` is charged once, at checkout, when the trial starts. The full `amount` is billed automatically on the first renewal after the trial period (`metadata.trialDays`) ends. * `trialAmount` follows the same `taxIncluded` / `taxCategory` as the regular price for that currency. * Without `metadata.trialDays`, `trialAmount` has no effect — there is no trial period for it to apply to. ## Example Request ```typescript SDK theme={"system"} import { WaffoPancake, BillingPeriod, TaxCategory } from "@waffo/pancake-ts"; const client = new WaffoPancake({ merchantId: process.env.WAFFO_MERCHANT_ID!, privateKey: process.env.WAFFO_PRIVATE_KEY!, }); const { product } = await client.subscriptionProducts.create({ storeId: "STO_2D5F8G3H1K4M6N9P", name: "Pro Plan", billingPeriod: BillingPeriod.Monthly, prices: { USD: { amount: "29.00", taxIncluded: false, taxCategory: TaxCategory.SaaS }, EUR: { amount: "27.00", taxIncluded: false, taxCategory: TaxCategory.SaaS }, }, description: "Full access to all Pro features.", successUrl: "https://example.com/welcome", metadata: { trialDays: 14 }, }); ``` ```bash cURL theme={"system"} curl -X POST https://api.waffo.ai/v1/actions/subscription-product/create-product \ -H "Content-Type: application/json" \ -H "X-Merchant-Id: MER_7K3M9P2R5T8W1Y4Z" \ -H "X-Timestamp: 2026-03-30T10:00:00Z" \ -H "X-Signature: BASE64_RSA_SIGNATURE" \ -d '{ "storeId": "STO_2D5F8G3H1K4M6N9P", "name": "Pro Plan", "billingPeriod": "monthly", "prices": { "USD": { "amount": "29.00", "taxIncluded": false, "taxCategory": "saas" }, "EUR": { "amount": "27.00", "taxIncluded": false, "taxCategory": "saas" } }, "description": "Full access to all Pro features.", "successUrl": "https://example.com/welcome", "metadata": { "trialDays": 14 } }' ``` ```python Python theme={"system"} import requests # Assumes you have a sign_request() helper for RSA-SHA256 signing headers = sign_request("POST", "/v1/actions/subscription-product/create-product", body) body = { "storeId": "STO_2D5F8G3H1K4M6N9P", "name": "Pro Plan", "billingPeriod": "monthly", "prices": { "USD": {"amount": "29.00", "taxIncluded": False, "taxCategory": "saas"}, "EUR": {"amount": "27.00", "taxIncluded": False, "taxCategory": "saas"}, }, "description": "Full access to all Pro features.", "successUrl": "https://example.com/welcome", "metadata": {"trialDays": 14}, } response = requests.post( "https://api.waffo.ai/v1/actions/subscription-product/create-product", json=body, headers=headers, ) data = response.json() ``` ## Success Response (200) ```json theme={"system"} { "data": { "product": { "id": "PROD_3F7H2J5L8N1Q4S6U", "storeId": "STO_2D5F8G3H1K4M6N9P", "name": "Pro Plan", "description": "Full access to all Pro features.", "billingPeriod": "monthly", "prices": { "USD": { "amount": "29.00", "taxCategory": "saas" }, "EUR": { "amount": "27.00", "taxCategory": "saas" } }, "media": [], "successUrl": "https://example.com/welcome", "metadata": { "trialDays": 14 }, "status": "active", "createdAt": "2026-03-30T10:30:00.000Z", "updatedAt": "2026-03-30T10:30:00.000Z" } } } ``` ## Response Fields The response is wrapped in `data.product`. The product object is a flattened detail view combining product and version fields. | Field | Type | Description | | - | - | - | | `id` | string | Product ID (`PROD_xxx`) | | `storeId` | string | Store ID (`STO_xxx`) | | `name` | string | Product name (from current version) | | `description` | string \| null | Product description (from current version) | | `billingPeriod` | string | Billing period: `weekly`, `monthly`, `quarterly`, or `yearly` | | `prices` | object | Multi-currency pricing map (see below) | | `media` | array | Media items (from current version) | | `successUrl` | string \| null | Success redirect URL (from current version) | | `metadata` | object | Custom metadata (from current version, may include `trialDays`) | | `status` | string | Status in the current environment: `active` or `inactive` | | `createdAt` | string | Product creation timestamp (ISO 8601) | | `updatedAt` | string | Product last update timestamp (ISO 8601) | **Response price object** (per currency): | Field | Type | Description | | - | - | - | | `amount` | string | Price as a display format string (e.g., "29.00") | | `taxCategory` | string | Tax category for tax calculation | ## Errors > **Retry policy:** Never retry 4xx — fix the request and resubmit. Retry 5xx with exponential backoff (start 5s, max 3 attempts). | Status | `errors[0].message` | What it means | Recommended handling | | - | - | - | - | | 400 | `Missing header: x-context-merchant-id` | The merchant context header was not forwarded | Fix your SDK configuration | | 400 | `Missing or invalid header: x-context-environment` | Environment header is missing or not `test` / `prod` | Set `X-Environment` to `test` or `prod` | | 400 | `Missing required field: storeId` / `Missing required field: name` / `Missing required field: prices (must have at least one currency)` | A required body field was omitted | Add the missing field, resubmit | | 400 | `Expected format: STO_xxx, got "X"` | `storeId` is not a valid Short ID | Use a `STO_` prefixed Short ID | | 400 | `Invalid or missing billingPeriod` | `billingPeriod` is not one of `weekly` / `monthly` / `quarterly` / `yearly` | Use one of the four allowed values | | 400 | `Invalid currency code: "X". Must be 3 uppercase letters (e.g., "USD", "EUR", "JPY")` | A key in `prices` is not a valid ISO 4217 code | Use 3 uppercase letters | | 400 | `Invalid amount for X: "Y". Must be a positive number string (e.g., "9.99", "1000")` | Amount string couldn't be parsed | Use a positive decimal string | | 401 | `Unauthorized` | Authentication failed | Verify API key, timestamp, and signature | | 404 | `Store not found` | The decoded `storeId` does not exist (foreign key violation) | Verify the store belongs to your merchant account | | 500 | `Internal server error` | Transient downstream failure | Retry with exponential backoff (start 5s, max 3 attempts) | # Delete Group Source: https://docs.waffo.ai/api-reference/endpoints/subscription-products/delete-group Permanently delete a product group Permanently delete a product group. Products within the group are not affected. ``` POST /v1/actions/subscription-product-group/delete-group ``` **Authentication:** API Key ## Request Body | Field | Type | Required | Description | | - | - | - | - | | `id` | string | Yes | Group ID (UUID format) | ## Example Request ```typescript SDK theme={"system"} await client.subscriptionProductGroups.delete({ id: "d4e5f6a7-b8c9-0d1e-2f3a-4b5c6d7e8f9a", }); ``` ```typescript TypeScript (fetch) theme={"system"} // Uses callApi() helper from authentication.mdx const result = await callApi("POST", "/v1/actions/subscription-product-group/delete-group", { id: "d4e5f6a7-b8c9-0d1e-2f3a-4b5c6d7e8f9a", }); console.log(result.data); ``` ```java Java theme={"system"} // Uses callApi() helper from authentication.mdx String body = """ {"id":"d4e5f6a7-b8c9-0d1e-2f3a-4b5c6d7e8f9a"}"""; String response = callApi("POST", "/v1/actions/subscription-product-group/delete-group", body); System.out.println(response); ``` ```python Python theme={"system"} # Uses call_api() helper from authentication.mdx result = call_api("POST", "/v1/actions/subscription-product-group/delete-group", { "id": "d4e5f6a7-b8c9-0d1e-2f3a-4b5c6d7e8f9a", }) print(result["data"]) ``` ```go Go theme={"system"} // Uses callAPI() helper from authentication.mdx body := map[string]interface{}{ "id": "d4e5f6a7-b8c9-0d1e-2f3a-4b5c6d7e8f9a", } result, err := callAPI("POST", "/v1/actions/subscription-product-group/delete-group", body) if err != nil { log.Fatal(err) } fmt.Println(string(result)) ``` ```rust Rust theme={"system"} // Uses call_api() helper from authentication.mdx let body = serde_json::json!({ "id": "d4e5f6a7-b8c9-0d1e-2f3a-4b5c6d7e8f9a" }); let result = call_api("POST", "/v1/actions/subscription-product-group/delete-group", &body).await?; println!("{}", result); ``` ```c C theme={"system"} /* Uses call_api() helper from authentication.mdx */ const char *body = "{\"id\":\"d4e5f6a7-b8c9-0d1e-2f3a-4b5c6d7e8f9a\"}"; char *response = call_api("POST", "/v1/actions/subscription-product-group/delete-group", body); printf("%s\n", response); free(response); ``` ```cpp C++ theme={"system"} // Uses callApi() helper from authentication.mdx std::string body = R"({"id":"d4e5f6a7-b8c9-0d1e-2f3a-4b5c6d7e8f9a"})"; std::string response = callApi("POST", "/v1/actions/subscription-product-group/delete-group", body); std::cout << response << std::endl; ``` ```bash cURL theme={"system"} MERCHANT_ID="MER_2aUyqjCzEIiEcYMKj7TZtw" TIMESTAMP=$(date +%s) BODY='{"id":"d4e5f6a7-b8c9-0d1e-2f3a-4b5c6d7e8f9a"}' BODY_HASH=$(echo -n "$BODY" | openssl dgst -sha256 -binary | base64 | tr -d '\n') CANONICAL_REQUEST="POST /v1/actions/subscription-product-group/delete-group $TIMESTAMP $BODY_HASH" SIGNATURE=$(echo -n "$CANONICAL_REQUEST" | openssl dgst -sha256 -sign private_key.pem | base64 | tr -d '\n') curl -X POST "https://api.waffo.ai/v1/actions/subscription-product-group/delete-group" \ -H "Content-Type: application/json" \ -H "X-Merchant-Id: $MERCHANT_ID" \ -H "X-Timestamp: $TIMESTAMP" \ -H "X-Signature: $SIGNATURE" \ -d "$BODY" ``` ```bash wget theme={"system"} MERCHANT_ID="MER_2aUyqjCzEIiEcYMKj7TZtw" TIMESTAMP=$(date +%s) BODY='{"id":"d4e5f6a7-b8c9-0d1e-2f3a-4b5c6d7e8f9a"}' BODY_HASH=$(echo -n "$BODY" | openssl dgst -sha256 -binary | base64 | tr -d '\n') CANONICAL_REQUEST="POST /v1/actions/subscription-product-group/delete-group $TIMESTAMP $BODY_HASH" SIGNATURE=$(echo -n "$CANONICAL_REQUEST" | openssl dgst -sha256 -sign private_key.pem | base64 | tr -d '\n') wget -qO- "https://api.waffo.ai/v1/actions/subscription-product-group/delete-group" \ --header="Content-Type: application/json" \ --header="X-Merchant-Id: $MERCHANT_ID" \ --header="X-Timestamp: $TIMESTAMP" \ --header="X-Signature: $SIGNATURE" \ --post-data="$BODY" ``` > [!WARNING] > > This is a **permanent hard delete**. The products within the group are not deleted -- only the grouping relationship is removed. ## Errors > **Retry policy:** Never retry 4xx — fix the request and resubmit. Retry 5xx with exponential backoff (start 5s, max 3 attempts). | Status | `errors[0].message` | What it means | Recommended handling | | - | - | - | - | | 400 | `Missing required field: id` | Request body did not include `id` | Add `id`, resubmit | | 404 | `Group not found` | The group is already gone or never belonged to your store | Verify the `id` | | 500 | `Internal server error` | Internal error or transient downstream failure | Retry with exponential backoff (start 5s, max 3 attempts) | # Subscription Product Endpoints Source: https://docs.waffo.ai/api-reference/endpoints/subscription-products/overview Create and manage subscription products and product groups Subscription products support recurring billing with configurable billing periods and multi-currency pricing. Products can be organized into groups for shared trial management and tiered pricing plans. ## Billing Periods | Period | Frequency | | - | - | | `weekly` | Every 7 days | | `monthly` | Every calendar month | | `quarterly` | Every 3 months | | `yearly` | Every 12 months | ## Group Object Product groups organize related subscription products (e.g., Free, Pro, Enterprise plans), enable shared trial management across products within a group, and scope which plans a customer may switch between. Each group exists per environment -- one row for test and one for production. ```json theme={"system"} { "id": "d4e5f6a7-b8c9-0d1e-2f3a-4b5c6d7e8f9a", "storeId": "STO_2D5F8G3H1K4M6N9P", "name": "Pricing Plans", "description": "Free, Pro, and Enterprise tiers", "rules": { "sharedTrial": true, "selfServicePlanChange": true }, "productIds": [ "PROD_3F7H2J5L8N1Q4S6U", "PROD_8B4D6F9H2K5M7P1R", "PROD_1C3E5G7J0L2N4Q6S" ], "environment": "test", "createdAt": "2026-03-30T10:30:00.000Z", "updatedAt": "2026-03-30T10:30:00.000Z" } ``` > [!NOTE] > > Group IDs are in **UUID format**, not Short ID format. This is the only entity in the API that uses raw UUIDs. | Field | Type | Description | | - | - | - | | `id` | string | Group ID (UUID format) | | `storeId` | string | Store ID (`STO_xxx` format) | | `name` | string | Group name (unique per store + environment) | | `description` | string \| null | Group description | | `rules` | object | Group rules (see below) | | `productIds` | string\[] | List of product IDs (`PROD_xxx` format) | | `environment` | string | `test` or `prod` | | `createdAt` | string | ISO 8601 timestamp | | `updatedAt` | string | ISO 8601 timestamp | ### Rules Each key in `rules` is an independent switch. Both default to `false`. | Field | Type | Default | Description | | - | - | - | - | | `sharedTrial` | boolean | `false` | When `true`, trial usage is shared across all products in the group. Prevents customers from signing up for repeated free trials by switching between products in the same group. | | `selfServicePlanChange` | boolean | `false` | When `true`, a customer may switch between this group's plans on their own from the Customer Portal. The group is what scopes the change — they can move between its members, not to unrelated products. When `false`, a customer-initiated change is rejected with `Self-service plan change is not enabled for this product group`. This switch does not restrict you: a plan change you issue with your API Key is never group-checked. | > [!WARNING] > > **Both switches are off unless you turn them on — including on groups that already exist.** A key absent from a group's stored rules reads back as `false`, so every group created before a switch existed has it off. If customer self-service plan changes are not working, check `selfServicePlanChange` on the group first. > [!NOTE] > > **`update-group` merges `rules` per field, it does not replace the object.** Sending `rules: { selfServicePlanChange: true }` leaves `sharedTrial` at its stored value — you do not need to resend the switches you are not changing. This is the opposite of `productIds`, which replaces the whole list. Unrecognized keys are dropped rather than stored, and `rules: null` is treated the same as omitting the field. ## Endpoints > **[Create Product](/api-reference/endpoints/subscription-products/create-product)** > > Create a subscription product with billing period and multi-currency pricing. > **[Update Product](/api-reference/endpoints/subscription-products/update-product)** > > Update a subscription product's content. Creates a new immutable version if content changed. > **[Publish Product](/api-reference/endpoints/subscription-products/publish-product)** > > Publish a subscription product from test to production (first-publish only). > **[Update Status](/api-reference/endpoints/subscription-products/update-status)** > > Activate or deactivate a subscription product. > **[Create Group](/api-reference/endpoints/subscription-products/create-group)** > > Create a product group to organize related subscription products. > **[Update Group](/api-reference/endpoints/subscription-products/update-group)** > > Update a product group's name, description, rules, or product list. > **[Delete Group](/api-reference/endpoints/subscription-products/delete-group)** > > Permanently delete a product group. > **[Publish Group](/api-reference/endpoints/subscription-products/publish-group)** > > Publish a product group from test to production (supports repeated UPSERT). # Publish Group Source: https://docs.waffo.ai/api-reference/endpoints/subscription-products/publish-group Publish a product group from test to production environment Publish a product group from test to production environment. Uses UPSERT behavior -- you can re-publish after making changes, unlike product publishing which only supports the first publish. ``` POST /v1/actions/subscription-product-group/publish-group ``` **Authentication:** API Key > [!WARNING] > > Do **not** include the `X-Environment` header for this endpoint. Publishing is always one-way from test to production. ## Request Body | Field | Type | Required | Description | | - | - | - | - | | `id` | string | Yes | Group ID (UUID format, must be a test environment group) | ## Example Request ```typescript SDK theme={"system"} await client.subscriptionProductGroups.publish({ id: "d4e5f6a7-b8c9-0d1e-2f3a-4b5c6d7e8f9a", }); ``` ```typescript TypeScript (fetch) theme={"system"} // Uses callApi() helper from authentication.mdx const result = await callApi("POST", "/v1/actions/subscription-product-group/publish-group", { id: "d4e5f6a7-b8c9-0d1e-2f3a-4b5c6d7e8f9a", }); console.log(result.data); ``` ```java Java theme={"system"} // Uses callApi() helper from authentication.mdx String body = """ {"id":"d4e5f6a7-b8c9-0d1e-2f3a-4b5c6d7e8f9a"}"""; String response = callApi("POST", "/v1/actions/subscription-product-group/publish-group", body); System.out.println(response); ``` ```python Python theme={"system"} # Uses call_api() helper from authentication.mdx result = call_api("POST", "/v1/actions/subscription-product-group/publish-group", { "id": "d4e5f6a7-b8c9-0d1e-2f3a-4b5c6d7e8f9a", }) print(result["data"]) ``` ```go Go theme={"system"} // Uses callAPI() helper from authentication.mdx body := map[string]interface{}{ "id": "d4e5f6a7-b8c9-0d1e-2f3a-4b5c6d7e8f9a", } result, err := callAPI("POST", "/v1/actions/subscription-product-group/publish-group", body) if err != nil { log.Fatal(err) } fmt.Println(string(result)) ``` ```rust Rust theme={"system"} // Uses call_api() helper from authentication.mdx let body = serde_json::json!({ "id": "d4e5f6a7-b8c9-0d1e-2f3a-4b5c6d7e8f9a" }); let result = call_api("POST", "/v1/actions/subscription-product-group/publish-group", &body).await?; println!("{}", result); ``` ```c C theme={"system"} /* Uses call_api() helper from authentication.mdx */ const char *body = "{\"id\":\"d4e5f6a7-b8c9-0d1e-2f3a-4b5c6d7e8f9a\"}"; char *response = call_api("POST", "/v1/actions/subscription-product-group/publish-group", body); printf("%s\n", response); free(response); ``` ```cpp C++ theme={"system"} // Uses callApi() helper from authentication.mdx std::string body = R"({"id":"d4e5f6a7-b8c9-0d1e-2f3a-4b5c6d7e8f9a"})"; std::string response = callApi("POST", "/v1/actions/subscription-product-group/publish-group", body); std::cout << response << std::endl; ``` ```bash cURL theme={"system"} MERCHANT_ID="MER_2aUyqjCzEIiEcYMKj7TZtw" TIMESTAMP=$(date +%s) BODY='{"id":"d4e5f6a7-b8c9-0d1e-2f3a-4b5c6d7e8f9a"}' BODY_HASH=$(echo -n "$BODY" | openssl dgst -sha256 -binary | base64 | tr -d '\n') CANONICAL_REQUEST="POST /v1/actions/subscription-product-group/publish-group $TIMESTAMP $BODY_HASH" SIGNATURE=$(echo -n "$CANONICAL_REQUEST" | openssl dgst -sha256 -sign private_key.pem | base64 | tr -d '\n') curl -X POST "https://api.waffo.ai/v1/actions/subscription-product-group/publish-group" \ -H "Content-Type: application/json" \ -H "X-Merchant-Id: $MERCHANT_ID" \ -H "X-Timestamp: $TIMESTAMP" \ -H "X-Signature: $SIGNATURE" \ -d "$BODY" ``` ```bash wget theme={"system"} MERCHANT_ID="MER_2aUyqjCzEIiEcYMKj7TZtw" TIMESTAMP=$(date +%s) BODY='{"id":"d4e5f6a7-b8c9-0d1e-2f3a-4b5c6d7e8f9a"}' BODY_HASH=$(echo -n "$BODY" | openssl dgst -sha256 -binary | base64 | tr -d '\n') CANONICAL_REQUEST="POST /v1/actions/subscription-product-group/publish-group $TIMESTAMP $BODY_HASH" SIGNATURE=$(echo -n "$CANONICAL_REQUEST" | openssl dgst -sha256 -sign private_key.pem | base64 | tr -d '\n') wget -qO- "https://api.waffo.ai/v1/actions/subscription-product-group/publish-group" \ --header="Content-Type: application/json" \ --header="X-Merchant-Id: $MERCHANT_ID" \ --header="X-Timestamp: $TIMESTAMP" \ --header="X-Signature: $SIGNATURE" \ --post-data="$BODY" ``` > [!NOTE] > > Unlike product publishing, group publishing supports **repeated UPSERT operations**. You can update a test group and re-publish it to production at any time. The production group will be created or updated to match the current test group. ## Errors > **Retry policy:** Never retry 4xx — fix the request and resubmit. Retry 5xx with exponential backoff (start 5s, max 3 attempts). | Status | `errors[0].message` | What it means | Recommended handling | | - | - | - | - | | 400 | `Missing required field: id` | Request body did not include `id` | Add `id`, resubmit | | 400 | `Can only publish test environment groups` | The supplied group is already in production (or otherwise not test) | Only test-environment groups are publishable | | 400 | `Cannot publish: product_ids is empty` | The group has no member products | Add at least one product via `update-group`, resubmit | | 404 | `Group not found` | No group exists for the supplied `id` | Verify the `id` belongs to your store | | 500 | `Internal server error` | Internal error or transient downstream failure | Retry with exponential backoff (start 5s, max 3 attempts) | # Publish Product Source: https://docs.waffo.ai/api-reference/endpoints/subscription-products/publish-product Publish a subscription product from test to production environment Publish a subscription product from test to production environment. This is a one-way, first-publish-only operation. ``` POST /v1/actions/subscription-product/publish-product ``` **Authentication:** API Key > [!WARNING] > > Do **not** include the `X-Environment` header for this endpoint. Publishing is always one-way from test to production. ## Request Body | Field | Type | Required | Description | | - | - | - | - | | `id` | string | Yes | Product ID (`PROD_xxx` format) | ## Example Request ```typescript SDK theme={"system"} await client.subscriptionProducts.publish({ id: "PROD_3F7H2J5L8N1Q4S6U", }); ``` ```typescript TypeScript (fetch) theme={"system"} // Uses callApi() helper from authentication.mdx const result = await callApi("POST", "/v1/actions/subscription-product/publish-product", { id: "PROD_3F7H2J5L8N1Q4S6U", }); console.log(result.data); ``` ```java Java theme={"system"} // Uses callApi() helper from authentication.mdx String body = """ {"id":"PROD_3F7H2J5L8N1Q4S6U"}"""; String response = callApi("POST", "/v1/actions/subscription-product/publish-product", body); System.out.println(response); ``` ```python Python theme={"system"} # Uses call_api() helper from authentication.mdx result = call_api("POST", "/v1/actions/subscription-product/publish-product", { "id": "PROD_3F7H2J5L8N1Q4S6U", }) print(result["data"]) ``` ```go Go theme={"system"} // Uses callAPI() helper from authentication.mdx body := map[string]interface{}{ "id": "PROD_3F7H2J5L8N1Q4S6U", } result, err := callAPI("POST", "/v1/actions/subscription-product/publish-product", body) if err != nil { log.Fatal(err) } fmt.Println(string(result)) ``` ```rust Rust theme={"system"} // Uses call_api() helper from authentication.mdx let body = serde_json::json!({ "id": "PROD_3F7H2J5L8N1Q4S6U" }); let result = call_api("POST", "/v1/actions/subscription-product/publish-product", &body).await?; println!("{}", result); ``` ```c C theme={"system"} /* Uses call_api() helper from authentication.mdx */ const char *body = "{\"id\":\"PROD_3F7H2J5L8N1Q4S6U\"}"; char *response = call_api("POST", "/v1/actions/subscription-product/publish-product", body); printf("%s\n", response); free(response); ``` ```cpp C++ theme={"system"} // Uses callApi() helper from authentication.mdx std::string body = R"({"id":"PROD_3F7H2J5L8N1Q4S6U"})"; std::string response = callApi("POST", "/v1/actions/subscription-product/publish-product", body); std::cout << response << std::endl; ``` ```bash cURL theme={"system"} MERCHANT_ID="MER_2aUyqjCzEIiEcYMKj7TZtw" TIMESTAMP=$(date +%s) BODY='{"id":"PROD_3F7H2J5L8N1Q4S6U"}' BODY_HASH=$(echo -n "$BODY" | openssl dgst -sha256 -binary | base64 | tr -d '\n') CANONICAL_REQUEST="POST /v1/actions/subscription-product/publish-product $TIMESTAMP $BODY_HASH" SIGNATURE=$(echo -n "$CANONICAL_REQUEST" | openssl dgst -sha256 -sign private_key.pem | base64 | tr -d '\n') curl -X POST "https://api.waffo.ai/v1/actions/subscription-product/publish-product" \ -H "Content-Type: application/json" \ -H "X-Merchant-Id: $MERCHANT_ID" \ -H "X-Timestamp: $TIMESTAMP" \ -H "X-Signature: $SIGNATURE" \ -d "$BODY" ``` ```bash wget theme={"system"} MERCHANT_ID="MER_2aUyqjCzEIiEcYMKj7TZtw" TIMESTAMP=$(date +%s) BODY='{"id":"PROD_3F7H2J5L8N1Q4S6U"}' BODY_HASH=$(echo -n "$BODY" | openssl dgst -sha256 -binary | base64 | tr -d '\n') CANONICAL_REQUEST="POST /v1/actions/subscription-product/publish-product $TIMESTAMP $BODY_HASH" SIGNATURE=$(echo -n "$CANONICAL_REQUEST" | openssl dgst -sha256 -sign private_key.pem | base64 | tr -d '\n') wget -qO- "https://api.waffo.ai/v1/actions/subscription-product/publish-product" \ --header="Content-Type: application/json" \ --header="X-Merchant-Id: $MERCHANT_ID" \ --header="X-Timestamp: $TIMESTAMP" \ --header="X-Signature: $SIGNATURE" \ --post-data="$BODY" ``` ## Success Response (200) ```json theme={"system"} { "data": { "product": { "id": "PROD_3F7H2J5L8N1Q4S6U", "storeId": "STO_2D5F8G3H1K4M6N9P", "name": "Pro Plan", "description": "Full access to all Pro features.", "billingPeriod": "monthly", "prices": { "USD": { "amount": "29.00", "taxCategory": "saas" }, "EUR": { "amount": "27.00", "taxCategory": "saas" } }, "media": [], "successUrl": "https://example.com/welcome", "metadata": { "trialDays": 14 }, "status": "active", "createdAt": "2026-03-30T10:30:00.000Z", "updatedAt": "2026-03-30T12:00:00.000Z" } } } ``` ## Response Fields Same as [Create Subscription Product response](/api-reference/endpoints/subscription-products/create-product#response-fields). > [!NOTE] > > Only the **first publish** is supported. Once a product has a production version, this endpoint returns an error. To update a published product, use the [Update Product](/api-reference/endpoints/subscription-products/update-product) endpoint in the production environment. ## Errors > **Retry policy:** Never retry 4xx — fix the request and resubmit. Retry 5xx with exponential backoff (start 5s, max 3 attempts). | Status | `errors[0].message` | What it means | Recommended handling | | - | - | - | - | | 400 | `Missing header: x-context-merchant-id` | The merchant context header was not forwarded | Fix your SDK configuration | | 400 | `Missing required field: id` | Request body did not include `id` | Add `id`, resubmit | | 400 | `Expected format: PROD_xxx, got "X"` | `id` is not a valid Short ID | Use a `PROD_` prefixed Short ID | | 400 | `No test version found` | The product has no version in the test environment to publish | Create and activate a test version first via Update Product / Update Status | | 400 | `Test version is not active` | Test version exists but its status is `inactive` | Activate the test version via Update Status, then publish | | 400 | `Already published to production` | Product already has a production version (publish is first-publish-only) | Use Update Product in the production environment instead | | 401 | `Unauthorized` | Authentication failed | Verify API key, timestamp, and signature | | 404 | `Product not found` / `Source version not found` | Product ID does not exist (or its source version is missing) | Verify the product ID | | 500 | `Internal server error` | Transient downstream failure | Retry with exponential backoff (start 5s, max 3 attempts) | # Update Group Source: https://docs.waffo.ai/api-reference/endpoints/subscription-products/update-group Update a product group's name, description, rules, or product list Update a product group's name, description, rules, or product list. ``` POST /v1/actions/subscription-product-group/update-group ``` **Authentication:** API Key ## Request Body | Field | Type | Required | Description | | - | - | - | - | | `id` | string | Yes | Group ID (UUID format) | | `name` | string | No | Updated group name | | `description` | string | No | Updated description | | `rules` | object | No | Group switches to change: `{ sharedTrial: boolean, selfServicePlanChange: boolean }`. **Merged per field** — send only the switches you are changing. See [Rules](/api-reference/endpoints/subscription-products/overview#rules) | | `productIds` | string\[] | No | Updated product list (`PROD_xxx` format). **Replaces the entire list.** | ## Example Request ```typescript SDK theme={"system"} const { group } = await client.subscriptionProductGroups.update({ id: "d4e5f6a7-b8c9-0d1e-2f3a-4b5c6d7e8f9a", name: "Updated Pricing Plans", productIds: [ "PROD_3F7H2J5L8N1Q4S6U", "PROD_8B4D6F9H2K5M7P1R", ], }); ``` ```typescript TypeScript (fetch) theme={"system"} // Uses callApi() helper from authentication.mdx const result = await callApi("POST", "/v1/actions/subscription-product-group/update-group", { id: "d4e5f6a7-b8c9-0d1e-2f3a-4b5c6d7e8f9a", name: "Updated Pricing Plans", productIds: [ "PROD_3F7H2J5L8N1Q4S6U", "PROD_8B4D6F9H2K5M7P1R", ], }); console.log(result.data); ``` ```java Java theme={"system"} // Uses callApi() helper from authentication.mdx String body = """ {"id":"d4e5f6a7-b8c9-0d1e-2f3a-4b5c6d7e8f9a","name":"Updated Pricing Plans","productIds":["PROD_3F7H2J5L8N1Q4S6U","PROD_8B4D6F9H2K5M7P1R"]}"""; String response = callApi("POST", "/v1/actions/subscription-product-group/update-group", body); System.out.println(response); ``` ```python Python theme={"system"} # Uses call_api() helper from authentication.mdx result = call_api("POST", "/v1/actions/subscription-product-group/update-group", { "id": "d4e5f6a7-b8c9-0d1e-2f3a-4b5c6d7e8f9a", "name": "Updated Pricing Plans", "productIds": [ "PROD_3F7H2J5L8N1Q4S6U", "PROD_8B4D6F9H2K5M7P1R", ], }) print(result["data"]) ``` ```go Go theme={"system"} // Uses callAPI() helper from authentication.mdx body := map[string]interface{}{ "id": "d4e5f6a7-b8c9-0d1e-2f3a-4b5c6d7e8f9a", "name": "Updated Pricing Plans", "productIds": []string{ "PROD_3F7H2J5L8N1Q4S6U", "PROD_8B4D6F9H2K5M7P1R", }, } result, err := callAPI("POST", "/v1/actions/subscription-product-group/update-group", body) if err != nil { log.Fatal(err) } fmt.Println(string(result)) ``` ```rust Rust theme={"system"} // Uses call_api() helper from authentication.mdx let body = serde_json::json!({ "id": "d4e5f6a7-b8c9-0d1e-2f3a-4b5c6d7e8f9a", "name": "Updated Pricing Plans", "productIds": [ "PROD_3F7H2J5L8N1Q4S6U", "PROD_8B4D6F9H2K5M7P1R" ] }); let result = call_api("POST", "/v1/actions/subscription-product-group/update-group", &body).await?; println!("{}", result); ``` ```c C theme={"system"} /* Uses call_api() helper from authentication.mdx */ const char *body = "{\"id\":\"d4e5f6a7-b8c9-0d1e-2f3a-4b5c6d7e8f9a\",\"name\":\"Updated Pricing Plans\",\"productIds\":[\"PROD_3F7H2J5L8N1Q4S6U\",\"PROD_8B4D6F9H2K5M7P1R\"]}"; char *response = call_api("POST", "/v1/actions/subscription-product-group/update-group", body); printf("%s\n", response); free(response); ``` ```cpp C++ theme={"system"} // Uses callApi() helper from authentication.mdx std::string body = R"({"id":"d4e5f6a7-b8c9-0d1e-2f3a-4b5c6d7e8f9a","name":"Updated Pricing Plans","productIds":["PROD_3F7H2J5L8N1Q4S6U","PROD_8B4D6F9H2K5M7P1R"]})"; std::string response = callApi("POST", "/v1/actions/subscription-product-group/update-group", body); std::cout << response << std::endl; ``` ```bash cURL theme={"system"} MERCHANT_ID="MER_2aUyqjCzEIiEcYMKj7TZtw" TIMESTAMP=$(date +%s) BODY='{ "id": "d4e5f6a7-b8c9-0d1e-2f3a-4b5c6d7e8f9a", "name": "Updated Pricing Plans", "productIds": [ "PROD_3F7H2J5L8N1Q4S6U", "PROD_8B4D6F9H2K5M7P1R" ] }' BODY_HASH=$(echo -n "$BODY" | openssl dgst -sha256 -binary | base64 | tr -d '\n') CANONICAL_REQUEST="POST /v1/actions/subscription-product-group/update-group $TIMESTAMP $BODY_HASH" SIGNATURE=$(echo -n "$CANONICAL_REQUEST" | openssl dgst -sha256 -sign private_key.pem | base64 | tr -d '\n') curl -X POST "https://api.waffo.ai/v1/actions/subscription-product-group/update-group" \ -H "Content-Type: application/json" \ -H "X-Merchant-Id: $MERCHANT_ID" \ -H "X-Timestamp: $TIMESTAMP" \ -H "X-Signature: $SIGNATURE" \ -d "$BODY" ``` ```bash wget theme={"system"} MERCHANT_ID="MER_2aUyqjCzEIiEcYMKj7TZtw" TIMESTAMP=$(date +%s) BODY='{ "id": "d4e5f6a7-b8c9-0d1e-2f3a-4b5c6d7e8f9a", "name": "Updated Pricing Plans", "productIds": [ "PROD_3F7H2J5L8N1Q4S6U", "PROD_8B4D6F9H2K5M7P1R" ] }' BODY_HASH=$(echo -n "$BODY" | openssl dgst -sha256 -binary | base64 | tr -d '\n') CANONICAL_REQUEST="POST /v1/actions/subscription-product-group/update-group $TIMESTAMP $BODY_HASH" SIGNATURE=$(echo -n "$CANONICAL_REQUEST" | openssl dgst -sha256 -sign private_key.pem | base64 | tr -d '\n') wget -qO- "https://api.waffo.ai/v1/actions/subscription-product-group/update-group" \ --header="Content-Type: application/json" \ --header="X-Merchant-Id: $MERCHANT_ID" \ --header="X-Timestamp: $TIMESTAMP" \ --header="X-Signature: $SIGNATURE" \ --post-data="$BODY" ``` > [!WARNING] > > The `productIds` field **replaces the entire product list**. To add a product, include all existing product IDs plus the new one. To remove a product, omit it from the list. > [!NOTE] > > **`rules` behaves the opposite way — it is merged, not replaced.** Sending `rules: { selfServicePlanChange: true }` leaves `sharedTrial` at its stored value, so you never have to resend a switch you are not changing. Unrecognized keys are dropped, and `rules: null` is treated the same as omitting the field. The response returns the full merged object, so you can confirm the result. ## Success Response (200) ```json theme={"system"} { "data": { "group": { "id": "d4e5f6a7-b8c9-0d1e-2f3a-4b5c6d7e8f9a", "storeId": "STO_2D5F8G3H1K4M6N9P", "name": "Updated Pricing Plans", "description": "Free, Pro, and Enterprise tiers", "rules": { "sharedTrial": true, "selfServicePlanChange": true }, "productIds": [ "PROD_3F7H2J5L8N1Q4S6U", "PROD_8B4D6F9H2K5M7P1R" ], "environment": "test", "createdAt": "2026-03-30T10:30:00.000Z", "updatedAt": "2026-04-02T09:15:00.000Z" } } } ``` The `group` object is the same shape returned by `create-group` — see [Group Object](/api-reference/endpoints/subscription-products/overview#group-object) for every field. `rules` is the **merged** result: switches you did not send keep their stored values. ## Errors > **Retry policy:** Never retry 4xx — fix the request and resubmit. Retry 5xx with exponential backoff (start 5s, max 3 attempts). | Status | `errors[0].message` | What it means | Recommended handling | | - | - | - | - | | 400 | `Missing required field: id` | Request body did not include `id` | Add `id`, resubmit | | 400 | `Expected format: PROD_xxx, got "..."` | A `productIds` entry could not be decoded as a Short ID | Fix the ID, resubmit | | 400 | `rules.sharedTrial must be a boolean` | The switch was sent as something other than `true` / `false` | Send a boolean, or omit the switch | | 400 | `rules.selfServicePlanChange must be a boolean` | The switch was sent as something other than `true` / `false` | Send a boolean, or omit the switch | | 404 | `Group not found` | No group exists for the supplied `id` | Verify the `id` belongs to your store | | 409 | `A group named "..." already exists in this store and environment` | Another group in the same store and environment already uses the new `name`; renaming to the group's own current name is not a conflict | Choose a different `name`; the group is left unchanged | | 500 | `Internal server error` | Internal error or transient downstream failure | Retry with exponential backoff (start 5s, max 3 attempts) | # Update Subscription Product Source: https://docs.waffo.ai/api-reference/endpoints/subscription-products/update-product Update a subscription product's content with automatic immutable versioning Update a subscription product's content. If content has changed, a new immutable version is created automatically. If the content is identical to the current version, no new version is created. ``` POST /v1/actions/subscription-product/update-product ``` **Authentication:** API Key ## Request Body | Field | Type | Required | Description | | - | - | - | - | | `id` | string | Yes | Product ID (`PROD_xxx` format) | | `name` | string | No | Updated product name (max 64 chars) | | `billingPeriod` | string | No | `weekly`, `monthly`, `quarterly`, or `yearly` | | `prices` | object | No | Updated multi-currency pricing (see [Price Object Format](/api-reference/endpoints/subscription-products/create-product#price-object-format)) | | `description` | string \| null | No | Updated description (pass `null` or `""` to clear) | | `media` | array | No | Updated media | | `successUrl` | string \| null | No | Updated redirect URL (max 512 chars, must be a valid http(s) URL; pass `null` or `""` to clear) | | `metadata` | object | No | Updated metadata (may include `trialDays`) | ## Example Request ```typescript SDK theme={"system"} const { product } = await client.subscriptionProducts.update({ id: "PROD_3F7H2J5L8N1Q4S6U", name: "Pro Plan v2", billingPeriod: BillingPeriod.Monthly, prices: { USD: { amount: "39.00", taxIncluded: false, taxCategory: TaxCategory.SaaS }, EUR: { amount: "36.00", taxIncluded: false, taxCategory: TaxCategory.SaaS }, }, metadata: { trialDays: 7 }, }); ``` ```typescript TypeScript (fetch) theme={"system"} // Uses callApi() helper from authentication.mdx const result = await callApi("POST", "/v1/actions/subscription-product/update-product", { id: "PROD_3F7H2J5L8N1Q4S6U", name: "Pro Plan v2", billingPeriod: "monthly", prices: { USD: { amount: "39.00", taxIncluded: false, taxCategory: "saas" }, EUR: { amount: "36.00", taxIncluded: false, taxCategory: "saas" }, }, metadata: { trialDays: 7 }, }); console.log(result.data); ``` ```java Java theme={"system"} // Uses callApi() helper from authentication.mdx String body = """ {"id":"PROD_3F7H2J5L8N1Q4S6U","name":"Pro Plan v2","billingPeriod":"monthly","prices":{"USD":{"amount":"39.00","taxIncluded":false,"taxCategory":"saas"},"EUR":{"amount":"36.00","taxIncluded":false,"taxCategory":"saas"}},"metadata":{"trialDays":7}}"""; String response = callApi("POST", "/v1/actions/subscription-product/update-product", body); System.out.println(response); ``` ```python Python theme={"system"} # Uses call_api() helper from authentication.mdx result = call_api("POST", "/v1/actions/subscription-product/update-product", { "id": "PROD_3F7H2J5L8N1Q4S6U", "name": "Pro Plan v2", "billingPeriod": "monthly", "prices": { "USD": {"amount": "39.00", "taxIncluded": False, "taxCategory": "saas"}, "EUR": {"amount": "36.00", "taxIncluded": False, "taxCategory": "saas"}, }, "metadata": {"trialDays": 7}, }) print(result["data"]) ``` ```go Go theme={"system"} // Uses callAPI() helper from authentication.mdx body := map[string]interface{}{ "id": "PROD_3F7H2J5L8N1Q4S6U", "name": "Pro Plan v2", "billingPeriod": "monthly", "prices": map[string]interface{}{ "USD": map[string]interface{}{"amount": "39.00", "taxIncluded": false, "taxCategory": "saas"}, "EUR": map[string]interface{}{"amount": "36.00", "taxIncluded": false, "taxCategory": "saas"}, }, "metadata": map[string]interface{}{"trialDays": 7}, } result, err := callAPI("POST", "/v1/actions/subscription-product/update-product", body) if err != nil { log.Fatal(err) } fmt.Println(string(result)) ``` ```rust Rust theme={"system"} // Uses call_api() helper from authentication.mdx let body = serde_json::json!({ "id": "PROD_3F7H2J5L8N1Q4S6U", "name": "Pro Plan v2", "billingPeriod": "monthly", "prices": { "USD": {"amount": "39.00", "taxIncluded": false, "taxCategory": "saas"}, "EUR": {"amount": "36.00", "taxIncluded": false, "taxCategory": "saas"} }, "metadata": {"trialDays": 7} }); let result = call_api("POST", "/v1/actions/subscription-product/update-product", &body).await?; println!("{}", result); ``` ```c C theme={"system"} /* Uses call_api() helper from authentication.mdx */ const char *body = "{\"id\":\"PROD_3F7H2J5L8N1Q4S6U\",\"name\":\"Pro Plan v2\",\"billingPeriod\":\"monthly\",\"prices\":{\"USD\":{\"amount\":\"39.00\",\"taxIncluded\":false,\"taxCategory\":\"saas\"},\"EUR\":{\"amount\":\"36.00\",\"taxIncluded\":false,\"taxCategory\":\"saas\"}},\"metadata\":{\"trialDays\":7}}"; char *response = call_api("POST", "/v1/actions/subscription-product/update-product", body); printf("%s\n", response); free(response); ``` ```cpp C++ theme={"system"} // Uses callApi() helper from authentication.mdx std::string body = R"({"id":"PROD_3F7H2J5L8N1Q4S6U","name":"Pro Plan v2","billingPeriod":"monthly","prices":{"USD":{"amount":"39.00","taxIncluded":false,"taxCategory":"saas"},"EUR":{"amount":"36.00","taxIncluded":false,"taxCategory":"saas"}},"metadata":{"trialDays":7}})"; std::string response = callApi("POST", "/v1/actions/subscription-product/update-product", body); std::cout << response << std::endl; ``` ```bash cURL theme={"system"} MERCHANT_ID="MER_2aUyqjCzEIiEcYMKj7TZtw" TIMESTAMP=$(date +%s) BODY='{ "id": "PROD_3F7H2J5L8N1Q4S6U", "name": "Pro Plan v2", "billingPeriod": "monthly", "prices": { "USD": { "amount": "39.00", "taxIncluded": false, "taxCategory": "saas" }, "EUR": { "amount": "36.00", "taxIncluded": false, "taxCategory": "saas" } }, "metadata": { "trialDays": 7 } }' BODY_HASH=$(echo -n "$BODY" | openssl dgst -sha256 -binary | base64 | tr -d '\n') CANONICAL_REQUEST="POST /v1/actions/subscription-product/update-product $TIMESTAMP $BODY_HASH" SIGNATURE=$(echo -n "$CANONICAL_REQUEST" | openssl dgst -sha256 -sign private_key.pem | base64 | tr -d '\n') curl -X POST "https://api.waffo.ai/v1/actions/subscription-product/update-product" \ -H "Content-Type: application/json" \ -H "X-Merchant-Id: $MERCHANT_ID" \ -H "X-Timestamp: $TIMESTAMP" \ -H "X-Signature: $SIGNATURE" \ -d "$BODY" ``` ```bash wget theme={"system"} MERCHANT_ID="MER_2aUyqjCzEIiEcYMKj7TZtw" TIMESTAMP=$(date +%s) BODY='{ "id": "PROD_3F7H2J5L8N1Q4S6U", "name": "Pro Plan v2", "billingPeriod": "monthly", "prices": { "USD": { "amount": "39.00", "taxIncluded": false, "taxCategory": "saas" }, "EUR": { "amount": "36.00", "taxIncluded": false, "taxCategory": "saas" } }, "metadata": { "trialDays": 7 } }' BODY_HASH=$(echo -n "$BODY" | openssl dgst -sha256 -binary | base64 | tr -d '\n') CANONICAL_REQUEST="POST /v1/actions/subscription-product/update-product $TIMESTAMP $BODY_HASH" SIGNATURE=$(echo -n "$CANONICAL_REQUEST" | openssl dgst -sha256 -sign private_key.pem | base64 | tr -d '\n') wget -qO- "https://api.waffo.ai/v1/actions/subscription-product/update-product" \ --header="Content-Type: application/json" \ --header="X-Merchant-Id: $MERCHANT_ID" \ --header="X-Timestamp: $TIMESTAMP" \ --header="X-Signature: $SIGNATURE" \ --post-data="$BODY" ``` ## Success Response (200) ```json theme={"system"} { "data": { "product": { "id": "PROD_3F7H2J5L8N1Q4S6U", "storeId": "STO_2D5F8G3H1K4M6N9P", "name": "Pro Plan v2", "description": null, "billingPeriod": "monthly", "prices": { "USD": { "amount": "39.00", "taxCategory": "saas" }, "EUR": { "amount": "36.00", "taxCategory": "saas" } }, "media": [], "successUrl": null, "metadata": { "trialDays": 7 }, "status": "active", "createdAt": "2026-03-30T10:30:00.000Z", "updatedAt": "2026-03-30T11:00:00.000Z" } } } ``` ## Response Fields Same as [Create Subscription Product response](/api-reference/endpoints/subscription-products/create-product#response-fields). > [!WARNING] > > Product updates create **new immutable versions**. Existing subscriptions retain their original version. New signups use the latest version. If the submitted content is identical to the current version, no new version is created. ## Errors > **Retry policy:** Never retry 4xx — fix the request and resubmit. Retry 5xx with exponential backoff (start 5s, max 3 attempts). | Status | `errors[0].message` | What it means | Recommended handling | | - | - | - | - | | 400 | `Missing header: x-context-merchant-id` | The merchant context header was not forwarded | Fix your SDK configuration | | 400 | `Missing or invalid header: x-context-environment` | Environment header is missing or not `test` / `prod` | Set `X-Environment` to `test` or `prod` | | 400 | `Missing required field: id` | Request body did not include `id` | Add `id`, resubmit | | 400 | `Expected format: PROD_xxx, got "X"` | `id` is not a valid Short ID | Use a `PROD_` prefixed Short ID | | 400 | `Field name must be a non-empty string` | `name` was provided as an empty string | Omit `name` to keep current value, or provide a non-empty string | | 400 | `Invalid billingPeriod` | `billingPeriod` is not one of `weekly` / `monthly` / `quarterly` / `yearly` | Use one of the four allowed values | | 400 | `Field prices must be a non-empty object` | `prices` was provided but empty | Omit `prices` to keep current value, or include at least one currency | | 400 | `Invalid currency code: "X". Must be 3 uppercase letters (e.g., "USD", "EUR", "JPY")` | A key in `prices` is not a valid ISO 4217 code | Use 3 uppercase letters | | 400 | `Invalid amount for X: "Y". Must be a positive number string (e.g., "9.99", "1000")` | Amount string couldn't be parsed | Use a positive decimal string | | 400 | Message contains `has no version` | The target environment (`test` or `prod`) has no version yet | Create a version in this environment first (publish from test, or create in test) | | 401 | `Unauthorized` | Authentication failed | Verify API key, timestamp, and signature | | 404 | `Product not found` / `Current version not found` | Product ID does not exist (or current version missing) | Verify the product ID | | 500 | `Internal server error` | Transient downstream failure | Retry with exponential backoff (start 5s, max 3 attempts) | # Update Status Source: https://docs.waffo.ai/api-reference/endpoints/subscription-products/update-status Activate or deactivate a subscription product Activate or deactivate a subscription product. ``` POST /v1/actions/subscription-product/update-status ``` **Authentication:** API Key ## Request Body | Field | Type | Required | Description | | - | - | - | - | | `id` | string | Yes | Product ID (`PROD_xxx` format) | | `status` | string | Yes | `active` or `inactive` | ## Example Request ```typescript SDK theme={"system"} import { ProductVersionStatus } from "@waffo/pancake-ts"; await client.subscriptionProducts.updateStatus({ id: "PROD_3F7H2J5L8N1Q4S6U", status: ProductVersionStatus.Inactive, }); ``` ```typescript TypeScript (fetch) theme={"system"} // Uses callApi() helper from authentication.mdx const result = await callApi("POST", "/v1/actions/subscription-product/update-status", { id: "PROD_3F7H2J5L8N1Q4S6U", status: "inactive", }); console.log(result.data); ``` ```java Java theme={"system"} // Uses callApi() helper from authentication.mdx String body = """ {"id":"PROD_3F7H2J5L8N1Q4S6U","status":"inactive"}"""; String response = callApi("POST", "/v1/actions/subscription-product/update-status", body); System.out.println(response); ``` ```python Python theme={"system"} # Uses call_api() helper from authentication.mdx result = call_api("POST", "/v1/actions/subscription-product/update-status", { "id": "PROD_3F7H2J5L8N1Q4S6U", "status": "inactive", }) print(result["data"]) ``` ```go Go theme={"system"} // Uses callAPI() helper from authentication.mdx body := map[string]interface{}{ "id": "PROD_3F7H2J5L8N1Q4S6U", "status": "inactive", } result, err := callAPI("POST", "/v1/actions/subscription-product/update-status", body) if err != nil { log.Fatal(err) } fmt.Println(string(result)) ``` ```rust Rust theme={"system"} // Uses call_api() helper from authentication.mdx let body = serde_json::json!({ "id": "PROD_3F7H2J5L8N1Q4S6U", "status": "inactive" }); let result = call_api("POST", "/v1/actions/subscription-product/update-status", &body).await?; println!("{}", result); ``` ```c C theme={"system"} /* Uses call_api() helper from authentication.mdx */ const char *body = "{\"id\":\"PROD_3F7H2J5L8N1Q4S6U\",\"status\":\"inactive\"}"; char *response = call_api("POST", "/v1/actions/subscription-product/update-status", body); printf("%s\n", response); free(response); ``` ```cpp C++ theme={"system"} // Uses callApi() helper from authentication.mdx std::string body = R"({"id":"PROD_3F7H2J5L8N1Q4S6U","status":"inactive"})"; std::string response = callApi("POST", "/v1/actions/subscription-product/update-status", body); std::cout << response << std::endl; ``` ```bash cURL theme={"system"} MERCHANT_ID="MER_2aUyqjCzEIiEcYMKj7TZtw" TIMESTAMP=$(date +%s) BODY='{"id":"PROD_3F7H2J5L8N1Q4S6U","status":"inactive"}' BODY_HASH=$(echo -n "$BODY" | openssl dgst -sha256 -binary | base64 | tr -d '\n') CANONICAL_REQUEST="POST /v1/actions/subscription-product/update-status $TIMESTAMP $BODY_HASH" SIGNATURE=$(echo -n "$CANONICAL_REQUEST" | openssl dgst -sha256 -sign private_key.pem | base64 | tr -d '\n') curl -X POST "https://api.waffo.ai/v1/actions/subscription-product/update-status" \ -H "Content-Type: application/json" \ -H "X-Merchant-Id: $MERCHANT_ID" \ -H "X-Timestamp: $TIMESTAMP" \ -H "X-Signature: $SIGNATURE" \ -d "$BODY" ``` ```bash wget theme={"system"} MERCHANT_ID="MER_2aUyqjCzEIiEcYMKj7TZtw" TIMESTAMP=$(date +%s) BODY='{"id":"PROD_3F7H2J5L8N1Q4S6U","status":"inactive"}' BODY_HASH=$(echo -n "$BODY" | openssl dgst -sha256 -binary | base64 | tr -d '\n') CANONICAL_REQUEST="POST /v1/actions/subscription-product/update-status $TIMESTAMP $BODY_HASH" SIGNATURE=$(echo -n "$CANONICAL_REQUEST" | openssl dgst -sha256 -sign private_key.pem | base64 | tr -d '\n') wget -qO- "https://api.waffo.ai/v1/actions/subscription-product/update-status" \ --header="Content-Type: application/json" \ --header="X-Merchant-Id: $MERCHANT_ID" \ --header="X-Timestamp: $TIMESTAMP" \ --header="X-Signature: $SIGNATURE" \ --post-data="$BODY" ``` ## Success Response (200) ```json theme={"system"} { "data": { "product": { "id": "PROD_3F7H2J5L8N1Q4S6U", "storeId": "STO_2D5F8G3H1K4M6N9P", "name": "Pro Plan", "description": "Full access to all Pro features.", "billingPeriod": "monthly", "prices": { "USD": { "amount": "29.00", "taxCategory": "saas" }, "EUR": { "amount": "27.00", "taxCategory": "saas" } }, "media": [], "successUrl": "https://example.com/welcome", "metadata": { "trialDays": 14 }, "status": "inactive", "createdAt": "2026-03-30T10:30:00.000Z", "updatedAt": "2026-03-30T13:00:00.000Z" } } } ``` ## Response Fields Same as [Create Subscription Product response](/api-reference/endpoints/subscription-products/create-product#response-fields). > [!NOTE] > > Deactivating a subscription product prevents **new signups** but does **not** cancel existing active subscriptions. Subscribers continue their current billing cycle unaffected. ## Errors > **Retry policy:** Never retry 4xx — fix the request and resubmit. Retry 5xx with exponential backoff (start 5s, max 3 attempts). | Status | `errors[0].message` | What it means | Recommended handling | | - | - | - | - | | 400 | `Missing header: x-context-merchant-id` | The merchant context header was not forwarded | Fix your SDK configuration | | 400 | `Missing or invalid header: x-context-environment` | Environment header is missing or not `test` / `prod` | Set `X-Environment` to `test` or `prod` | | 400 | `Missing required field: id` | Request body did not include `id` | Add `id`, resubmit | | 400 | `Expected format: PROD_xxx, got "X"` | `id` is not a valid Short ID | Use a `PROD_` prefixed Short ID | | 400 | `Invalid or missing status (must be 'active' or 'inactive')` | `status` is missing or not one of the two allowed values | Use `active` or `inactive` | | 400 | Message contains `has no version` | The target environment (`test` or `prod`) has no version yet | Create a version in this environment first (publish from test, or create in test) | | 401 | `Unauthorized` | Authentication failed | Verify API key, timestamp, and signature | | 404 | `Product not found` / `Current version not found` | Product ID does not exist (or current version missing) | Verify the product ID | | 500 | `Internal server error` | Transient downstream failure | Retry with exponential backoff (start 5s, max 3 attempts) | # Add Webhook Source: https://docs.waffo.ai/api-reference/endpoints/webhooks/add-webhook Configure a new webhook endpoint for a store Add a webhook endpoint to a store. Each store can have up to **20 webhooks** across all channels. ``` POST /v1/actions/store/add-webhook ``` **Authentication:** API Key (owner or admin role required) ## Request Body | Field | Type | Required | Description | | - | - | - | - | | `storeId` | string | Yes | Store ID (Short ID format `STO_xxx`) | | `channel` | string | Yes | One of `http`, `feishu`, `discord`, `telegram`, `slack` | | `url` | string | Yes | Target webhook URL (HTTPS; merchant ensures URL matches the chosen channel) | | `events` | string\[] | Yes | Subscribed event types — e.g. `["order.completed", "refund.succeeded"]`. Empty array means no events fire to this webhook. | | `testMode` | boolean | Yes | `true` = fires for test transactions; `false` = fires for production | | `secret` | string \| null | No | Channel-specific credential (e.g. Telegram `chat_id`). Stored as opaque text. | ## Example Request ```typescript SDK theme={"system"} import { WaffoPancake } from "@waffo/pancake-ts"; const client = new WaffoPancake({ merchantId: process.env.WAFFO_MERCHANT_ID!, privateKey: process.env.WAFFO_PRIVATE_KEY!, }); // Standard HTTPS webhook (RSA-signed envelope) const { webhook } = await client.webhooks.add({ storeId: "STO_2aUyqjCzEIiEcYMKj7TZtw", channel: "http", url: "https://example.com/webhooks/pancake", events: ["order.completed", "refund.succeeded"], testMode: false, }); ``` ```typescript SDK (Discord) theme={"system"} // Discord webhook — uses Discord's native embed format await client.webhooks.add({ storeId: "STO_2aUyqjCzEIiEcYMKj7TZtw", channel: "discord", url: "https://discord.com/api/webhooks/123456789/abc-def-ghi", events: ["order.completed"], testMode: false, }); ``` ```typescript SDK (Telegram) theme={"system"} // Telegram bot — chat_id goes in secret await client.webhooks.add({ storeId: "STO_2aUyqjCzEIiEcYMKj7TZtw", channel: "telegram", url: "https://api.telegram.org/bot123456:ABC-DEF/sendMessage", events: ["order.completed", "refund.failed"], testMode: false, secret: "8737101383", }); ``` ```bash cURL theme={"system"} curl -X POST https://api.waffo.com/v1/actions/store/add-webhook \ -H "Content-Type: application/json" \ -H "X-Merchant-Id: $WAFFO_MERCHANT_ID" \ -H "X-Signature: ..." \ -d '{ "storeId": "STO_2aUyqjCzEIiEcYMKj7TZtw", "channel": "http", "url": "https://example.com/webhooks/pancake", "events": ["order.completed"], "testMode": false }' ``` ## Success Response (200) ```json theme={"system"} { "data": { "webhook": { "id": "11111111-2222-3333-4444-555555555555", "storeId": "uuid-of-store", "channel": "http", "url": "https://example.com/webhooks/pancake", "events": ["order.completed", "refund.succeeded"], "testMode": false, "secret": null, "createdAt": "2026-05-07T00:00:00.000Z", "updatedAt": "2026-05-07T00:00:00.000Z" } } } ``` > [!NOTE] > > The returned `webhook.id` is a UUID, not a Short ID — webhook IDs are not in the `IdPrefix` scope. Pass it as-is to `update-webhook` and `remove-webhook`. ## Response Fields | Field | Type | Description | | - | - | - | | `id` | string | Webhook UUID | | `storeId` | string | Owning store UUID | | `channel` | string | Webhook channel (`http`, `feishu`, `discord`, `telegram`, or `slack`) | | `url` | string | Target webhook URL | | `events` | string\[] | Subscribed event types | | `testMode` | boolean | `true` for test transactions, `false` for production | | `secret` | string \| null | Channel-specific credential (opaque text), `null` if unset | | `createdAt` | string | Creation timestamp (ISO 8601) | | `updatedAt` | string | Last update timestamp (ISO 8601) | ## Errors > **Retry policy:** Never retry 4xx — fix the request and resubmit. Retry 5xx with exponential backoff (start 5s, max 3 attempts). | Status | `errors[0].message` | What it means | Recommended handling | | - | - | - | - | | 400 | `Missing required field: storeId` | `storeId` was not provided | Fix the request body, resubmit | | 400 | `Expected format: STO_xxx, got "..."` | `storeId` Short ID could not be decoded | Fix the `storeId` format, resubmit | | 400 | `testMode must be a boolean` | `testMode` is not a boolean | Pass a boolean value, resubmit | | 400 | `Invalid channel: must be one of http, feishu, discord, telegram, slack` | `channel` is not in the allowed list | Use one of the allowed channels | | 400 | `Invalid URL format` | `url` is not a valid URL | Fix the URL, resubmit | | 400 | `events must be a string array` | `events` is not an array of strings | Pass a string array, resubmit | | 400 | `secret must be a string or null` | `secret` is not string or null | Pass string or null, resubmit | | 400 | `Webhook limit reached (max 20 per store)` | Store already has 20 webhooks | Remove an existing webhook first | | 401 | `Missing merchantId in request context` | API Key authentication did not resolve a merchant | Verify API Key headers and signature | | 403 | `Not authorized to manage webhooks for this store` | Merchant is not `owner` or `admin` of the store | Verify the merchant's role on this store | | 500 | `Internal server error` | Unexpected server-side failure | Retry with exponential backoff (start 5s, max 3 attempts) | # Webhook Endpoints Source: https://docs.waffo.ai/api-reference/endpoints/webhooks/overview Manage webhook endpoints for HTTP, Feishu, Discord, Telegram, and Slack delivery Pancake supports multiple webhook endpoints per store across five channels: standard HTTPS (RSA-signed envelope), Feishu, Discord, Telegram, and Slack. Each endpoint is an independent record in `store.store_webhooks` with its own URL, subscribed event list, and `test`/`prod` environment binding. ## Channels | Channel | Payload format | Signature | Notes | | - | - | - | - | | `http` | JSON envelope `{ id, eventType, eventId, storeId, mode, data }` | RSA-SHA256 (`X-Waffo-Signature` header) | Default channel; preserves the existing webhook contract. | | `feishu` | Feishu interactive card | None — URL token | Chinese title text, UTC+8 timestamp | | `discord` | Discord embed | None — URL token | English text, client-local timestamp | | `telegram` | `sendMessage` payload (`text` HTML, `chat_id`) | None — bot token in URL | English text, UTC; `chat_id` stored in `secret` | | `slack` | Attachments payload | None — incoming-webhook URL token | English text, UTC | ## URL host Any HTTPS URL is accepted regardless of channel. The merchant is responsible for matching the URL to the channel's expected platform — if a Discord URL is configured under `channel: "slack"`, the dispatcher will encode the payload in Slack's attachments format and send it to the Discord endpoint, which will respond with an error and the failure is recorded in `webhook_deliveries`. ## Multiple webhooks per URL The same URL can be configured under multiple webhooks within a store — webhooks fan out, so different event subscriptions, channels, or `testMode` flags can share a URL. Each webhook delivers independently, which means consumers receiving identical payloads on a shared URL must dedupe by `(eventType, eventId)`. ## Limits Each store may have at most **20 webhooks** across all channels. Exceeding the limit returns 400. ## Listing webhooks There is no `list-webhooks` endpoint — querying the configured webhook list goes through GraphQL `Store.storeWebhooks` (filtered automatically by environment via `test_mode`): ```graphql theme={"system"} query GetStoreWebhooks($storeId: String!) { store(id: $storeId) { storeWebhooks { id channel url events testMode secret createdAt } } } ``` ## Endpoints > **[Add Webhook](/api-reference/endpoints/webhooks/add-webhook)** > > Configure a new webhook endpoint for a store. > **[Update Webhook](/api-reference/endpoints/webhooks/update-webhook)** > > Change a webhook's URL, events, or secret. > **[Remove Webhook](/api-reference/endpoints/webhooks/remove-webhook)** > > Hard-delete a webhook (history retained). # Remove Webhook Source: https://docs.waffo.ai/api-reference/endpoints/webhooks/remove-webhook Hard-delete a webhook (history retained) Remove a webhook from a store. This is a **hard delete** — the row is removed from `store.store_webhooks` immediately, with no soft-delete flag. Historical `webhook_deliveries` records are retained for audit (the `storeWebhookId` foreign key is set to `null`). ``` POST /v1/actions/store/remove-webhook ``` **Authentication:** API Key (owner or admin role required) ## Request Body | Field | Type | Required | Description | | - | - | - | - | | `id` | string | Yes | Webhook UUID | ## Example Request ```typescript SDK theme={"system"} import { WaffoPancake } from "@waffo/pancake-ts"; const client = new WaffoPancake({ merchantId: process.env.WAFFO_MERCHANT_ID!, privateKey: process.env.WAFFO_PRIVATE_KEY!, }); const { webhook } = await client.webhooks.remove({ id: "11111111-2222-3333-4444-555555555555", }); // webhook contains a snapshot of the row before deletion ``` ```bash cURL theme={"system"} curl -X POST https://api.waffo.com/v1/actions/store/remove-webhook \ -H "Content-Type: application/json" \ -H "X-Merchant-Id: $WAFFO_MERCHANT_ID" \ -H "X-Signature: ..." \ -d '{ "id": "11111111-2222-3333-4444-555555555555" }' ``` ## Success Response (200) Returns the webhook entity as it existed immediately before deletion (so the caller can confirm what was removed). Same shape as [`add-webhook`](/api-reference/endpoints/webhooks/add-webhook#success-response-200). ## Response Fields | Field | Type | Description | | - | - | - | | `id` | string | Webhook UUID | | `storeId` | string | Owning store UUID | | `channel` | string | Webhook channel | | `url` | string | Target webhook URL | | `events` | string\[] | Subscribed event types | | `testMode` | boolean | `true` for test transactions, `false` for production | | `secret` | string \| null | Channel-specific credential, `null` if unset | | `createdAt` | string | Creation timestamp (ISO 8601) | | `updatedAt` | string | Last update timestamp (ISO 8601) | ## Errors > **Retry policy:** Never retry 4xx — fix the request and resubmit. Retry 5xx with exponential backoff (start 5s, max 3 attempts). | Status | `errors[0].message` | What it means | Recommended handling | | - | - | - | - | | 400 | `Missing required field: id` | `id` was not provided | Fix the request body, resubmit | | 400 | `id must be a valid UUID` | `id` is not a valid UUID | Fix the `id`, resubmit | | 403 | `Not authorized to manage webhooks for this store` | The caller's merchant role on the owning store is not `owner` or `admin` | Switch to an API Key whose merchant has the required role | | 404 | `Webhook not found` | No webhook matches the supplied `id` (or already removed) | The webhook is already gone — treat as success and reconcile local state | | 500 | `Internal server error` | Unexpected server-side failure | Retry with exponential backoff (start 5s, max 3 attempts) | # Update Webhook Source: https://docs.waffo.ai/api-reference/endpoints/webhooks/update-webhook Update a webhook's URL, events, or secret Update an existing webhook's URL, subscribed events, or channel-specific secret. The `channel` and `testMode` fields are immutable — to change them, remove and re-add the webhook. ``` POST /v1/actions/store/update-webhook ``` **Authentication:** API Key (owner or admin role required) ## Request Body | Field | Type | Required | Description | | - | - | - | - | | `id` | string | Yes | Webhook UUID (returned from `add-webhook` or GraphQL `Store.storeWebhooks`) | | `url` | string | No | Replace target URL. | | `events` | string\[] | No | Replace subscribed event types | | `secret` | string \| null | No | Replace channel-specific credential. Pass `null` to clear. | > [!NOTE] > > `channel` is permanent for a given webhook record — to switch channel, remove and re-add. URL changes are accepted as-is; merchant ensures the new URL matches the channel. ## Example Request ```typescript SDK theme={"system"} import { WaffoPancake } from "@waffo/pancake-ts"; const client = new WaffoPancake({ merchantId: process.env.WAFFO_MERCHANT_ID!, privateKey: process.env.WAFFO_PRIVATE_KEY!, }); // Add more events to an existing webhook await client.webhooks.update({ id: "11111111-2222-3333-4444-555555555555", events: ["order.completed", "refund.succeeded", "subscription.canceled"], }); ``` ```bash cURL theme={"system"} curl -X POST https://api.waffo.com/v1/actions/store/update-webhook \ -H "Content-Type: application/json" \ -H "X-Merchant-Id: $WAFFO_MERCHANT_ID" \ -H "X-Signature: ..." \ -d '{ "id": "11111111-2222-3333-4444-555555555555", "events": ["order.completed", "refund.succeeded"] }' ``` ## Success Response (200) Returns the updated webhook entity. Identical shape to [`add-webhook`](/api-reference/endpoints/webhooks/add-webhook#success-response-200). ## Response Fields | Field | Type | Description | | - | - | - | | `id` | string | Webhook UUID | | `storeId` | string | Owning store UUID | | `channel` | string | Webhook channel (immutable) | | `url` | string | Target webhook URL | | `events` | string\[] | Subscribed event types | | `testMode` | boolean | `true` for test transactions, `false` for production (immutable) | | `secret` | string \| null | Channel-specific credential, `null` if cleared | | `createdAt` | string | Creation timestamp (ISO 8601) | | `updatedAt` | string | Last update timestamp (ISO 8601) | ## Errors > **Retry policy:** Never retry 4xx — fix the request and resubmit. Retry 5xx with exponential backoff (start 5s, max 3 attempts). | Status | `errors[0].message` | What it means | Recommended handling | | - | - | - | - | | 400 | `Missing required field: id` | `id` was not provided | Fix the request body, resubmit | | 400 | `id must be a valid UUID` | `id` is not a valid UUID | Fix the `id`, resubmit | | 400 | `Invalid URL format` | `url` could not be parsed as a valid URL | Fix the URL format (HTTPS, well-formed), resubmit | | 400 | `events must be a string array` | `events` is not a JSON array of strings | Send `events` as a string array (e.g. `["order.completed"]`) | | 400 | `secret must be a string or null` | `secret` is neither a string nor `null` | Send a string value, or `null` to clear | | 403 | `Not authorized to manage webhooks for this store` | The caller's merchant role on the owning store is not `owner` or `admin` | Switch to an API Key whose merchant has the required role | | 404 | `Webhook not found` | No webhook matches the supplied `id` (or deleted by a concurrent request) | Verify the `id`; if just removed, re-list webhooks before retrying | | 500 | `Internal server error` | Unexpected server-side failure | Retry with exponential backoff (start 5s, max 3 attempts) | # Errors Source: https://docs.waffo.ai/api-reference/errors Handle API errors gracefully ## Error Format All error responses follow a consistent structure: ```json theme={"system"} { "data": null, "errors": [ { "message": "Missing required field: name", "layer": "product" } ] } ``` ### Reading the Errors Array The `errors` array is ordered from root cause to top-level caller: * `errors[0]` -- the **root cause** of the failure (most useful for debugging) * `errors[n]` -- the top-level caller that surfaced the error In most cases, you only need to inspect `errors[0].message` for the actionable error description. *** ## HTTP Status Codes | Code | Meaning | Description | | - | - | - | | 200 | Success | Request processed successfully | | 400 | Bad Request | Invalid parameters or malformed request body | | 401 | Unauthorized | Missing or invalid authentication credentials | | 403 | Forbidden | Valid credentials but insufficient permissions | | 404 | Not Found | Requested resource does not exist | | 409 | Conflict | Idempotent request is already being processed | | 429 | Rate Limited | Too many requests in a short period | | 500 | Server Error | Internal server error | | 501 | Not Implemented | Requested feature is not yet available | | 502 | Bad Gateway | Upstream service error | *** ## Error `layer` Field Each error includes a `layer` string indicating which part of the system produced the error. Use the `layer` value alongside `message` to identify the root cause when debugging. *** ## Common Error Scenarios ### Authentication Errors (401) ```json theme={"system"} { "data": null, "errors": [ { "message": "Token has expired", "layer": "user" } ] } ``` **Solutions:** * Verify your Merchant ID and private key are correct * Ensure the SDK is initialized with valid credentials * Check that your private key matches the registered public key ### Validation Errors (400) ```json theme={"system"} { "data": null, "errors": [ { "message": "Store name must be between 1 and 100 characters", "layer": "store" } ] } ``` **Solutions:** * Check required fields are present * Verify field value formats and constraints * Ensure amounts are display format strings (e.g., "29.00") ### Permission Errors (403) ```json theme={"system"} { "data": null, "errors": [ { "message": "Only store owner can delete store", "layer": "store" } ] } ``` **Solutions:** * Verify the API Key has the required permissions * Ensure the user belongs to the correct store ### Idempotency Conflicts (409) ```json theme={"system"} { "data": null, "errors": [ { "message": "Request with this idempotency key is already being processed", "layer": "gateway" } ] } ``` **Solutions:** * Wait for the original request to complete * Use a different `X-Idempotency-Key` for a new request *** ## Handling Errors in Code ### TypeScript SDK ```typescript theme={"system"} import { WaffoPancake, WaffoPancakeError } from "@waffo/pancake-ts"; const client = new WaffoPancake({ merchantId: process.env.WAFFO_MERCHANT_ID!, privateKey: process.env.WAFFO_PRIVATE_KEY!, }); try { const { store } = await client.stores.create({ name: "My Store" }); } catch (err) { if (err instanceof WaffoPancakeError) { const rootCause = err.errors[0]; console.error(`Error [${rootCause.layer}]: ${rootCause.message}`); // err.status contains the HTTP status code } } ``` *** ## Retry Strategy Retry these status codes with exponential backoff: * **429** -- Rate limited (respect `Retry-After` header if present) * **500** -- Internal server error * **502** -- Bad gateway ```javascript theme={"system"} async function retryRequest(fn, maxRetries = 3) { for (let attempt = 0; attempt < maxRetries; attempt++) { try { return await fn(); } catch (error) { const status = error.status; if (![429, 500, 502].includes(status) || attempt === maxRetries - 1) { throw error; } const delay = Math.pow(2, attempt) * 1000; // 1s, 2s, 4s await new Promise(resolve => setTimeout(resolve, delay)); } } } ``` > [!NOTE] > > Do not retry `400`, `401`, `403`, or `404` errors. These indicate issues that must be fixed in the request itself. *** ## Idempotency for Safe Retries A write operation can be retried safely without creating duplicates **when it carries an `X-Idempotency-Key`**. > [!NOTE] > > **Nothing is deduplicated unless you send a key.** The SDKs used to derive one from `merchantId` + path + body; they no longer do, on any credential — so by default a write retried after a timeout executes twice. > > Through an SDK, pass the key per call (`{ idempotencyKey }` in TypeScript and `@waffo/pancake-nextjs`, `pancake.WithIdempotencyKey(key)` in Go). Calling REST directly, set the header yourself. The requirements below apply to both. ```bash theme={"system"} curl -X POST https://api.waffo.ai/v1/actions/checkout/create-session \ -H "Content-Type: application/json" \ -H "X-Store-Slug: your-store-slug" \ -H "X-Environment: test" \ -H "X-Idempotency-Key: MER_2aUyqjCzEIiEcYMKj7TZtw-8f14e45f-ea8c-4b0a-9f7d-3b2c1d0e5a67" \ -d '{"productId": "...", "productType": "onetime", "currency": "USD"}' ``` * Every write endpoint honours the key: all `POST /v1/actions/*` endpoints (including `checkout/create-session`) and `POST /v1/graphql` * Idempotency keys are cached for **24 hours** * Sending the same key returns the cached response * If the original request is still processing, returns `409 Conflict` ### Idempotency Key Requirements | Requirement | Specification | | - | - | | Uniqueness | Globally unique per request within your merchant account | | Max length | 256 characters | | Allowed chars | Letters, numbers, hyphens (`-`), underscores (`_`) | The key is the entire cache identity of the request, so uniqueness is the requirement to plan for. Embed your `merchantId` and a high-entropy component such as a UUID, e.g. `MER_2aUyqjCzEIiEcYMKj7TZtw-8f14e45f-ea8c-4b0a-9f7d-3b2c1d0e5a67`. A key built from a hash of the request body is a poor choice: two legitimately identical writes would collide and the second would replay the first response. A short, guessable key such as `order-abc-123` can match a key already used by a different request. In that case the response you receive is that request's cached response, not a result for your own call. # API Reference Source: https://docs.waffo.ai/api-reference/introduction Integrate Waffo Pancake into your application ## Overview The Waffo Pancake API lets you programmatically manage your entire payment infrastructure: * Create and manage stores * Create products (one-time and subscription) * Generate checkout sessions and process orders * Manage subscriptions and billing * Query data via GraphQL * Handle refunds ## Base URL All API requests are made to: ``` https://api.waffo.ai/v1 ``` > [!NOTE] > > `api.waffo.ai` currently resolves over IPv4 only (A records, no AAAA). From an IPv6-only host, give the process an IPv4 route (dual-stack networking or NAT64/DNS64); otherwise DNS resolution fails before any request is sent. ## Architecture The API uses a hybrid approach: * **REST endpoints** (`/v1/actions/...`) for all write operations (create, update, delete) * **GraphQL** (`/v1/graphql`) for all read operations (queries) All REST endpoints use `POST` method exclusively. There are no GET, PUT, PATCH, or DELETE methods. ## TypeScript SDK The official [`@waffo/pancake-ts`](https://www.npmjs.com/package/@waffo/pancake-ts) SDK wraps the entire API with full type safety. It handles authentication, request signing, and webhook verification automatically. Idempotency keys are the one thing it leaves to you — pass one per call when a retry must not duplicate the write (see [Idempotency](#idempotency)). ```bash theme={"system"} npm install @waffo/pancake-ts ``` ```typescript theme={"system"} import { WaffoPancake } from "@waffo/pancake-ts"; const client = new WaffoPancake({ merchantId: process.env.WAFFO_MERCHANT_ID!, privateKey: process.env.WAFFO_PRIVATE_KEY!, }); ``` Every endpoint documented below includes an SDK example alongside the REST/cURL examples. [Full SDK documentation ->](/integrate/sdks) *** ## Authentication Waffo Pancake uses **API Key authentication** for all programmatic API access. API Key authentication is handled automatically by the SDK. For public-facing checkout flows, use **Store Slug** authentication with the `X-Store-Slug` header. [Learn more about authentication ->](/api-reference/authentication) *** ## Common Headers | Header | Required | Description | | - | - | - | | `Content-Type` | Yes | Always `application/json` | | `X-Store-Slug` | Conditional | Store slug (for public checkout flows) | | `X-Environment` | Conditional | `test` or `prod` (required with Store Slug auth, not needed for API Key) | | `X-Idempotency-Key` | Optional | Globally unique ID per write operation (cached 24h). The SDKs do not set it for you; pass it per call — see [Idempotency](#idempotency) | > [!NOTE] > > API Key authentication headers (`X-Merchant-Id`, `X-Timestamp`, `X-Signature`) are handled automatically by the SDK. You only need to provide your Merchant ID and private key when initializing the client. *** ## Request Format * **Method**: All write endpoints use `POST` * **Body**: JSON * **Timestamps**: ISO 8601 UTC (e.g., `2026-01-23T00:00:00.000Z`) * **Amounts**: Display format strings (e.g., `"29.00"` = \$29.00 USD) * **Currencies**: ISO 4217 codes (e.g., `USD`, `EUR`, `JPY`) * **Status values**: Always lowercase (e.g., `active`, not `ACTIVE`) ### ID Formats All externally-facing entity IDs use **Short ID** format: `{PREFIX}_{base62}`. | Prefix | Entity | Example | | - | - | - | | `MER` | Merchant | `MER_2D5F8G3H1K4M6N9P` | | `STO` | Store | `STO_3bVzrkD0FJjFdZNLk8Ualx` | | `PROD` | Product / Version | `PROD_4cWAslE1GKkGeaOMl9Vbmy` | | `ORD` | Order | `ORD_5dXBtmF2HLlHfbPNm0Wcnz` | | `PAY` | Payment | `PAY_6eYCunG3IMmIgcQOnaXdoA` | | `REF` | Refund | `REF_7fZDvoH4JNnJhdRPobYepB` | | `TKT` | Ticket | `TKT_8gAEwpI5KOoKieSQL1ZfqC` | | `KEY` | API Key | `KEY_4F7H0I5J3K6M8N1P` | | `CPN` | Coupon | `CPN_5dXBtmF2HLlHfbPNm0Wcnz` | | `PMC` | Promotion Code | `PMC_6eYCunG3IMmIgcQOnaXdoA` | > [!NOTE] > > Checkout Session IDs use a special format: `cs_` + UUID (e.g., `cs_550e8400-e29b-41d4-a716-446655440000`). They are not part of the Short ID system. *** ## Response Format ### Success ```json theme={"system"} { "data": { "store": { "id": "STO_3bVzrkD0FJjFdZNLk8Ualx", "name": "My Store", "status": "active", "createdAt": "2026-01-15T10:30:00.000Z" } } } ``` ### Error ```json theme={"system"} { "data": null, "errors": [ { "message": "Store slug already exists", "layer": "store" } ] } ``` > [!NOTE] > > In the `errors` array, `errors[0]` is the **root cause** of the failure. Subsequent entries represent higher-level callers in the request chain. ### Error `layer` Field Each error includes a `layer` string indicating which part of the system produced the error. Use this to identify the root cause when debugging. The value is always one of the predefined layer names (e.g., `"gateway"`, `"store"`, `"product"`). *** ## HTTP Status Codes | Code | Description | | - | - | | 200 | Success | | 400 | Bad Request -- invalid parameters | | 401 | Unauthorized -- authentication failed | | 403 | Forbidden -- insufficient permissions | | 404 | Not Found | | 409 | Conflict -- idempotent request already in progress | | 429 | Rate Limited -- too many requests | | 500 | Internal Server Error | | 501 | Not Implemented | | 502 | Bad Gateway | *** ## Environments API Key authentication determines the environment automatically based on which key verifies successfully. Store Slug authentication requires the `X-Environment` header: | Environment | Header Value | Description | | - | - | - | | Test | `X-Environment: test` | No real charges, isolated data | | Production | `X-Environment: prod` | Real transactions | *** ## Idempotency A write operation is deduplicated only when it carries an `X-Idempotency-Key` header. > [!NOTE] > > **The SDKs do not set this header for you.** They used to derive a key from `merchantId` + path + body; they no longer do, on any credential. Nothing is deduplicated unless you supply a key, so a write retried after a timeout executes twice. > > In the SDKs, pass it per call — `client.stores.create(params, { idempotencyKey })` in TypeScript, `pancake.WithIdempotencyKey(key)` in Go, or the trailing options object of a `@waffo/pancake-nextjs` server action. Calling REST directly, set the header yourself. Either way the requirements below are the ones to meet. The key itself, however you send it: | Item | Specification | | - | - | | Header | `X-Idempotency-Key` | | Uniqueness | Globally unique per request within your merchant account | | Max length | 256 characters | | Allowed chars | Letters, numbers, hyphens (`-`), underscores (`_`) | | Cache duration | 24 hours | Combine your `merchantId` with a UUID: ``` X-Idempotency-Key: MER_2aUyqjCzEIiEcYMKj7TZtw-8f14e45f-ea8c-4b0a-9f7d-3b2c1d0e5a67 ``` A short, guessable key can match one already used by a different request, in which case you receive that request's cached response. See [Errors -> Idempotency for Safe Retries](/api-reference/errors#idempotency-for-safe-retries) for the full requirement. | Scenario | Behavior | Status | | - | - | - | | No key sent | Executes normally, nothing cached or deduplicated | Original | | First request | Executes normally, caches 2xx response | Original | | Duplicate (completed) | Returns cached response without re-executing | Original | | Duplicate (in progress) | Returns conflict error | 409 | | Original failed (non-2xx) | Same key can be retried | -- | *** ## Endpoint Groups > **[Authentication](/api-reference/endpoints/auth)** > > Issue session tokens for checkout flows > **[Stores](/api-reference/endpoints/stores)** > > Create, update, and delete stores > **[One-Time Products](/api-reference/endpoints/onetime-products)** > > Create and manage one-time purchase products > **[Subscription Products](/api-reference/endpoints/subscription-products)** > > Create tiered subscription products and groups > **[Coupons](/api-reference/endpoints/coupons/overview)** > > Create coupons and the codes buyers type > **[Promotion Codes](/api-reference/endpoints/promotion-codes/overview)** > > Add or generate more codes for a coupon > **[Orders](/api-reference/endpoints/orders)** > > Create checkout sessions and orders > **[Subscriptions](/api-reference/endpoints/subscriptions)** > > Manage subscription lifecycle > **[Refunds](/api-reference/endpoints/refunds)** > > Request and process refunds > **[GraphQL](/api-reference/endpoints/graphql)** > > Query all data with GraphQL # Payment Error Codes Source: https://docs.waffo.ai/api-reference/payment-error-codes Reference for every payment failure reason surfaced in the Waffo dashboard When a transaction fails, the **Error code** link in the dashboard's transaction details jumps to the matching entry here. > **[Customer needs to fix input](#customer-needs-to-fix-input)** > > 19 error codes > **[Customer needs a new payment method](#customer-needs-a-new-payment-method)** > > 26 error codes > **[Transient issues — retry later](#transient-issues-retry-later)** > > 23 error codes > **[Terminal — no action available](#terminal-no-action-available)** > > 5 error codes > **[Other](#other)** > > 1 error codes ## Where failures happen Every failure code maps to a stage of the payment journey. The category boxes below link to the matching sections on this page. ```mermaid theme={"system"} flowchart TD A["Customer clicks Pay"] --> B{"Payment initiated"} B -- "initiation failed" --> B1["CREATE_ORDER_ERROR
CREATE_ORDER_FAILED"] B -- "ok" --> C["Customer reaches the payment page"] C -- "page left open too long" --> C1["CREATE_ORDER_EXPIRED_TOKEN"] C --> D{"Payment method"} D -- "QR / wallet" --> E["Handed off to the payment channel —
waiting for the customer
to scan and confirm"] E -- "not completed before expiry" --> E1["TIMEOUT_CHANNEL_CLOSE"] E -- "customer cancels / abandons" --> E2["USER_CANCEL_CLOSE
PAYMENT_FAILED"] E -- "order expires" --> E3["TIMEOUT_CLOSE
(shown as Canceled)"] D -- "Card" --> F["Customer enters card details
+ bank verification"] F -- "input / verification error" --> F1["Customer needs to fix input
(19 codes)"] F -- "verified" --> G["Bank / card network processing"] G -- "this card can't be used" --> G1["Customer needs a new
payment method (26 codes)"] G -- "temporary issue" --> G2["Transient issues — retry later
(23 codes)"] G -- "approved" --> H(["Payment succeeded"]) ``` For subscription renewals the customer isn't present — the saved payment method is charged automatically: ```mermaid theme={"system"} flowchart LR S["Scheduled renewal charge"] --> T{"Saved payment method"} T -- "not verified / card expired" --> T1["PAYMENT_CHANNEL_REJECTION
ask the customer to update it
in the customer portal"] T -- "other failures" --> T2["Same bank-processing stage as above;
the subscription becomes past due"] T -- "charged" --> T3(["Renewal succeeded"]) ``` ## Customer needs to fix input *Your customer needs to correct something on the checkout (card details, CVV, address, OTP, etc.) and retry.*
Code Meaning Why it failed Recommended action
`CARD_ABNORMAL_CARDNUMBER` Invalid card number **Cause:** The card number entered is invalid or does not exist Ask the customer to re-enter it.
`CARD_ABNORMAL_NOTACTIVATED` Card not yet activated **Cause:** The customer's card hasn't been activated Ask them to activate it with their bank.
`CARD_ABNORMAL_NOTACTIVATED_ACCOUNT` Bank account not activated **Cause:** The customer's bank account is inactive Ask them to contact their bank.
`CARD_AMOUNTOVERLIMIT` Exceeds card transaction limit **Cause:** Amount exceeds the card's per-transaction or daily limit Customer may split the charge or use another card.
`CARD_AUTHENTICATION_FAILED` Card details verification failed **Cause:** Couldn't initiate bank verification with the card details Ask the customer to recheck number, expiry, and CVV.
`CARD_AUTHENTICATION_FAILED_ADDRESS` Billing address mismatch **Cause:** The billing address doesn't match the issuer's records Ask the customer to correct it.
`CARD_AUTHENTICATION_FAILED_CVV2` Incorrect CVV **Cause:** The card's security code is wrong Ask the customer to re-enter it.
`CARD_AUTHENTICATION_FAILED_NEED_ADDITIONAL_AUTH` Additional verification required **Cause:** The bank requires extra verification The customer should contact their bank or complete verification on retry.
`CARD_AUTHENTICATION_FAILED_VERIFICATIONDATA` Verification data mismatch **Cause:** Information provided during verification didn't match the issuer's records Ask the customer to retry.
`CARD_AUTHENTICATION_FAILED_VERIFICATIONDATA` 3-D Secure data mismatch **Cause:** Information provided during 3-D Secure didn't match the issuer's records Ask the customer to retry.
`CARD_AUTHENTICATION_FAILED_VERIFICATIONDATA` One-time code incorrect **Cause:** The customer's one-time verification code from the bank was wrong Ask them to request a new code and retry.
`CARD_BANK_REJECT_ISSUER_CONTACT` Issuer requires customer contact **Cause:** The customer's bank wants them to call to verify or lift a restriction before retrying Ask the customer to contact their bank.
`CARD_BANK_REJECT_ISSUER_URGENT` Bank flagged abnormality **Cause:** The customer's bank flagged something and wants them to call immediately Ask the customer to contact their bank right away.
`CARD_OVERLIMIT` Exceeds bank limit **Cause:** Amount exceeds the customer's credit limit or per-transaction cap Suggest splitting the charge or using another card.
`CARD_PIN_INVALID` PIN or CVV incorrect **Cause:** The PIN or CVV entered was wrong Ask the customer to re-verify.
`EXCEED_DAILY_LIMIT` Daily limit reached **Cause:** The customer's daily spending hit the bank's cap Suggest retrying tomorrow or using another card.
`INITIATE_AUTHENTICATION_FAILED` Verification could not start **Cause:** Couldn't start bank verification with this card number Ask the customer to recheck the card number.
`USER_CPF_INVALID` Brazilian Tax ID (CPF) invalid **Cause:** The Brazilian Tax ID the customer entered is malformed or doesn't exist Ask them to correct it.
`CREATE_ORDER_EXPIRED_TOKEN` Checkout page expired **Cause:** The customer took too long on the checkout page Ask them to start a new checkout.
## Customer needs a new payment method *This card can't be used. Ask the customer to use a different card or payment method.*
Code Meaning Why it failed Recommended action
`CARD_ABNORMAL` Card in abnormal status **Cause:** The customer's card has been reported lost or frozen Ask them to use another payment method.
`CARD_ABNORMAL_CLOSED` Bank account closed **Cause:** The customer's bank account is closed Ask them to use another payment method.
`CARD_ABNORMAL_CLOSED_FROMACCOUNT` Source account closed **Cause:** The funding account linked to the customer's card is closed Ask them to use another method.
`CARD_ABNORMAL_EXPIRED` Card expired **Cause:** The customer's card has expired Ask them to update it or use a different card.
`CARD_ABNORMAL_FRAUD` Issuer flagged as fraud **Cause:** The customer's bank blocked this on fraud suspicion Ask them to contact the bank or use another card.
`CARD_ABNORMAL_ISSUER` Issuer not registered **Cause:** The customer's bank isn't registered with the card network Ask them to use a different card.
`CARD_ABNORMAL_LOST` Card reported lost **Cause:** The customer's card was reported lost Ask them to use another payment method.
`CARD_ABNORMAL_NOCREDIT` No linked credit account **Cause:** Couldn't find a credit account tied to the customer's card Ask them to verify or use another card.
`CARD_ABNORMAL_STOLEN` Card reported stolen **Cause:** The customer's card has been reported lost or stolen Ask them to use another payment method.
`CARD_BANK_REJECT_BLOCK` Bank account blocked **Cause:** The customer's bank account is frozen Ask them to use another method or contact the bank.
`CARD_BANK_REJECT_FRAUD` Bank blocked for fraud **Cause:** The customer's bank flagged this transaction as fraud and blocked it Ask them to use another method.
`CARD_BANK_REJECT_LAW` Account restricted by law **Cause:** The customer's account is legally restricted from transactions Ask them to use another method.
`CARD_BANK_REJECT_REVOKEALL_ACCOUNT` Account access revoked **Cause:** The customer's account access has been fully revoked Ask them to use another method.
`CARD_INSUFFICIENT_BALANCE` Insufficient funds **Cause:** The customer's card doesn't have enough funds Ask them to top up or use another card.
`CARD_INVALID_TRANSACTION` Card type not supported **Cause:** The customer's card doesn't support this transaction type Ask them to use a different card.
`CARD_PAYMENT_RETRY_LIMIT` Retry limit reached **Cause:** Too many failed attempts on this card; the network has blocked further retries Ask the customer to use a different card.
`CARD_ABNORMAL_NOCHECKING` Card couldn't be verified **Cause:** The issuer flagged the customer's card as abnormal and couldn't verify it Ask them to use another card.
`CARD_ABNORMAL_RESTRICTED` Card restricted in this region **Cause:** The customer's card is restricted or locked in this region Ask them to use another method.
`CARD_NOTALLOWED_TXN` Transaction type not allowed **Cause:** The issuer prohibits this transaction type on this card (e.g. cross-border) Ask the customer to use a different card.
`PAYMENT_REJECTION` Blocked by Waffo risk **Cause:** This transaction was blocked by Waffo's risk rules Contact support if you think this is wrong.
`PAYMENT_CHANNEL_REJECTION` Payment rejected **Cause:** The payment service rejected this transaction on its own risk rules Ask the customer to use another method.
`PAYMENT_CHANNEL_REJECTION` Subscription charge rejected **Cause:** The saved payment method for this subscription has not been verified Ask the customer to verify it in the customer portal.
`PAYMENT_CHANNEL_REJECTION` Subscription charge failed: card expired **Cause:** The card on file for this subscription has expired Ask the customer to update it in the customer portal.
`PAYMENT_CHANNEL_REJECTION` Invalid mobile number **Cause:** The customer's mobile number format is invalid Ask them to correct it.
`CREATE_ORDER_FAILED` Payment service under maintenance **Cause:** The payment service is undergoing maintenance Ask the customer to retry later.
`CREATE_ORDER_FAILED` Payment service declined **Cause:** The payment service rejected this transaction on its own risk rules Ask the customer to use another method.
## Transient issues — retry later *A temporary glitch in the bank, card network, or payment service. The customer can usually retry in a few minutes.*
Code Meaning Why it failed Recommended action
`CARD_AUTHENTICATION_ERROR` Verification protocol error **Cause:** A protocol or communication issue occurred during verification Ask the customer to retry shortly.
`CARD_BANK_REJECT_REVOKE_SINGLE` Bank revoked this transaction **Cause:** The customer's bank revoked this specific authorization Ask them to retry.
`CARD_BANK_REJECT_SECURITY` Blocked by bank security **Cause:** The customer's bank blocked this for security Ask them to retry later or contact the bank.
`CARD_COUNTOVERLIMIT` Too many attempts **Cause:** The customer's card has hit a frequency limit Ask them to retry later.
`ISSUE_BANK_DECLINE` Issuer declined (no reason) **Cause:** The customer's bank declined without specifying why Ask them to retry later.
`RISK_TRANSACTION_LIMIT` Waffo risk control triggered **Cause:** Waffo's amount or velocity rules blocked this transaction Ask the customer to retry later or use another card.
`TIMEOUT_CHANNEL_CLOSE` Customer didn't complete the payment in the payment channel in time **Cause:** The customer confirmed the payment at checkout and was handed off to the payment channel, but never finished paying there (e.g. the QR code was not scanned or confirmed). The transaction closed automatically when the payment window expired This is not a platform or checkout failure. If the customer still wants to purchase, have them start a new payment.
`CARD_BANK_REJECT` Bank declined **Cause:** The customer's bank declined this without a specific reason Ask them to retry later.
`CARD_GENERAL_ERROR` Bank generic error **Cause:** The bank returned a non-specific error Ask the customer to retry or switch methods.
`CARD_ORG_OTHER_ERROR` Card network error **Cause:** The card network (Visa, Mastercard, etc.) returned an internal error Ask the customer to retry.
`CARD_SYSTEMERROR` Bank temporarily down **Cause:** The customer's bank is having transient issues Ask them to retry shortly.
`CREATE_ORDER_ERROR` Payment initiation timed out **Cause:** Network timeout when creating the transaction Ask the customer to retry.
`PAYMENT_CHANNEL_ERROR` Payment service communication error **Cause:** An unexpected error occurred communicating with the payment service Ask the customer to retry.
`PAYMENT_CHANNEL_ERROR` Payment service network error **Cause:** The network connection to the payment service failed Ask the customer to retry.
`PAYMENT_CHANNEL_ERROR` Payment service communication error **Cause:** An unexpected error occurred communicating with the payment service Ask the customer to retry.
`PAYMENT_CHANNEL_ERROR` Unexpected payment service response **Cause:** The payment service returned an unparseable response Ask the customer to retry.
`PAYMENT_FAILED` Payment failed **Cause:** See the transaction detail for the specific reason Contact support if unclear.
`PAYMENT_FAILED` Customer abandoned checkout **Cause:** The customer left the checkout page without finishing Reach out if you want to recover the sale.
`PAYMENT_FAILED` Payment service notification failed **Cause:** The payment may have succeeded but the notification didn't arrive Check the order status again later.
`PAYMENT_FAILED` Payment service error **Cause:** The payment service didn't give specific details Ask the customer to retry or switch methods.
`SYSTEM_ERROR` Internal system error **Cause:** A transient internal error in Waffo Ask the customer to retry; contact support if persistent.
`UNKNOWN_ERROR` Unknown error **Cause:** An undefined exception occurred Ask the customer to retry; contact support if it keeps happening.
`UNSPECIFIED_PAYMENT_FAILURE` Payment failed (no specific reason) **Cause:** The bank or payment service didn't give a specific reason Ask the customer to try another method.
## Terminal — no action available *The payment never went through and the transaction is closed. No remediation is possible; you can still reach out to the customer if you want to recover the sale.*
Code Meaning Why it failed Recommended action
`CANCEL_CLOSE` Order closed **Cause:** This order was closed No action needed.
`TIMEOUT_CLOSE` Customer payment timeout **Cause:** The customer didn't pay in time and the order was closed Send a new payment link if needed.
`USER_CANCEL_CLOSE` Customer canceled **Cause:** The customer canceled this order Reach out if you want to recover the sale.
`CARD_CARDHOLDER_REJECT` Customer declined at bank **Cause:** The customer canceled the payment at their bank Reach out if you want to recover the sale.
`MERCHANT_ORDER_TIMEOUT` Order expired **Cause:** The order's expiration passed without payment and was auto-closed Send a new payment link if needed.
## Other *Bank-side duplicate detection.*
Code Meaning Why it failed Recommended action
`CARD_BANK_REJECT_DUPLICATE` Duplicate transaction **Cause:** The bank detected this as a duplicate and blocked it to prevent double-charging The customer should contact the bank if it isn't.
# Webhooks Source: https://docs.waffo.ai/api-reference/webhooks Receive real-time event notifications ## Overview Webhooks deliver real-time notifications to your server when events occur — orders, payments, subscriptions, and refunds. ``` Event occurs → Waffo Pancake → fan-out → Your channel(s) ``` A single store can have **multiple webhooks**, each delivering to a different channel. The available channels are: | Channel | Delivery target | Payload format | | - | - | - | | `http` | Your HTTPS endpoint | RSA-SHA256-signed JSON envelope | | `feishu` | Lark / Feishu bot incoming webhook | Interactive card (Lark format) | | `discord` | Discord channel webhook | Embed message (Discord format) | | `telegram` | Telegram bot `sendMessage` URL | HTML-formatted text | | `slack` | Slack incoming webhook | Attachment with mrkdwn fields | The `http` channel uses the JSON envelope and signature verification described on this page — most of this guide covers that channel. For the IM channels, payloads use each platform's native format and authentication is handled by the URL token; you don't need to verify signatures. > [!TIP] > > **Using TypeScript?** The [`@waffo/pancake-ts`](https://www.npmjs.com/package/@waffo/pancake-ts) SDK has built-in public keys and auto-detects the environment — one line to verify the `http` channel. *** ## Setup **1. Choose a channel and prepare its URL** * **HTTP** — build a server endpoint that accepts POST requests and returns `200`. * **Feishu / Discord / Telegram / Slack** — create a bot or incoming webhook in the target platform and copy its URL. For Telegram, also note the chat ID that should receive messages. **2. (HTTP only) Copy the verification public key** Waffo uses one fixed key pair per environment — Test and Production — shared across all stores. You don't get a key back when registering a webhook; you read it from the Dashboard. Open the [Dashboard](https://pancake.waffo.ai/merchant/dashboard) → any store → **Settings → Webhooks**, and copy the **Webhook Public Key** for the environment you're integrating (Test or Production). Store it in your server's config; you'll use it to verify every incoming HTTP webhook. > [!NOTE] > > Every store's Dashboard shows the same Test key and the same Production key — they're platform-level. Adding, editing, or deleting webhook URLs does not change them. **3. Register the webhook** Add a webhook in **Dashboard → Settings → Webhooks**, or call [`POST /v1/actions/store/add-webhook`](/api-reference/endpoints/webhooks/add-webhook). Each webhook record specifies one channel, one URL, the subscribed events, and the target environment (`testMode: true` for Test, `false` for Production). You can register multiple webhooks per store. **4. Send a test event** Use the Dashboard "Send Test Event" button to deliver a sample event to one or all of your registered webhooks. **5. Verify and handle events** For the HTTP channel, use the code examples below to verify signatures before processing events. IM channels deliver pre-rendered messages and require no handling on your side. *** ## Environment Isolation Each webhook is registered for a single environment via the `testMode` flag. Test and Production are fully independent: | Aspect | Test | Production | | - | - | - | | Webhook record | `testMode: true` | `testMode: false` | | Signing key (HTTP only) | Test key pair | Production key pair | | Verification public key (HTTP only) | Dashboard Test key | Dashboard Production key | | Selector when delivering | Header `X-Environment: test` | Header `X-Environment: prod` (or omitted) | The `mode` field in each HTTP payload indicates the source environment: `"test"` or `"prod"`. > [!WARNING] > > Always use the public key matching the event's `mode`. A Test key cannot verify Production events, and vice versa. *** ## Payload Format ### Headers | Header | Description | | - | - | | `Content-Type` | `application/json` | | `X-Waffo-Signature` | Signature string: `t=,v1=` | | `X-Waffo-Event` | Event type (e.g., `order.completed`) | ### Body ```json theme={"system"} { "id": "PAY_6eYCunG3IMmIgcQOnaXdoA", "timestamp": "2026-03-10T08:30:00.000Z", "eventType": "order.completed", "eventId": "PAY_6eYCunG3IMmIgcQOnaXdoA", "storeId": "STO_3bVzrkD0FJjFdZNLk8Ualx", "storeName": "My Store", "mode": "prod", "data": { "orderId": "ORD_5dXBtmF2HLlHfbPNm0Wcnz", "orderStatus": "completed", "buyerEmail": "customer@example.com", "currency": "USD", "chargedAmount": "98.00", "amount": "98.00", "taxAmount": "8.00", "taxRate": 8, "taxName": "Consumption Tax", "subtotal": "100.00", "total": "108.00", "listPrice": { "total": "108.00", "subtotal": "100.00", "taxAmount": "8.00", "taxRate": 8, "taxName": "Consumption Tax" }, "productName": "Pro Plan", "orderMetadata": { "planId": "pro" }, "orderMerchantExternalId": "ORDER-2026-00891", "productMetadata": {}, "paymentId": "PAY_6eYCunG3IMmIgcQOnaXdoA", "paymentStatus": "succeeded", "paymentMethod": "card", "paymentLast4": "4242", "paymentDate": "2026-03-10" } } ``` ### Top-level Fields | Field | Type | Description | | - | - | - | | `id` | string | Event entity ID — same as `eventId` for most events | | `timestamp` | string | Event time (ISO 8601 UTC) | | `eventType` | string | Event type (see [Event Types](#event-types)) | | `eventId` | string | Business event identifier — maps to different entities per event type (see [eventId Mapping](#eventid-mapping)) | | `storeId` | string | Store ID | | `storeName` | string | Store name | | `mode` | string | `"test"` or `"prod"` | ### `data` Fields The table below defines every `data` field — its type, when it appears, and what it means. For the exact field set of a given event, see the complete body under [Event Details](#event-details). In the **Present** column, "Payment events" means `order.completed` and `subscription.payment_succeeded`; "Subscription events" means every `subscription.*` event **except** `subscription.payment_succeeded`. That one event is a pure payment event: it describes a single charge and carries neither the subscription period nor its status. | Field | Type | Present | Description | | - | - | - | - | | `orderId` | string | Always | Order ID | | `orderStatus` | string | All but `subscription.payment_succeeded` | `completed` for one-time orders; `active` / `canceling` / `canceled` / `past_due` for subscriptions | | `buyerEmail` | string | Always | Customer email address | | `currency` | string | Always | ISO 4217 currency code (e.g., `"USD"`, `"JPY"`) | | `orderMetadata` | object | Always | Order-level metadata from the checkout session (merchant-defined key-value pairs) | | `productMetadata` | object | Always | Product-level metadata set when creating or updating the product | | `merchantProvidedBuyerIdentity` | string | When set at checkout | Merchant's own customer identifier | | `orderMerchantExternalId` | string | When set at checkout | Order's business-side identifier (max 128 chars). Also present on `refund.*`, inherited from the original order | | `refundTicketMerchantExternalId` | string | `refund.*`, when set | Refund ticket's business-side identifier (max 128 chars) | | `billingDetail` | object | When set at checkout | Billing address (`country`, `isBusiness`, …) | | `chargedAmount` | string | Payment events, when the channel reported an amount | What this charge actually took, tax included (display format). Omitted — never zeroed — when the channel reported no amount | | `refundedAmount` | string | `refund.*`, when the channel reported an amount | What this refund actually returned (display format). Omitted — never zeroed — when the channel reported no amount | | `listPrice` | object | Payment events | The amounts expected for this payment, after any discount: `total` / `subtotal` / `taxAmount` / `taxRate` / `taxName`. Differs from `chargedAmount` when a prorated credit or a zero-amount card check applies. On one-time and subscription orders, new payment events always carry `listTotal` (price before the discount, tax inclusive) and `discountAmount` (tax-inclusive discount) in the block: without a discount `discountAmount` is zero and `listTotal` equals `total`. With a coupon or promotion code, `total` and `taxAmount` are the discounted amounts while `subtotal` stays the pre-discount amount excluding tax, so `subtotal + taxAmount` does not equal `total` — use `listTotal − discountAmount = total`. On a subscription each payment carries the amounts expected for that period: `listTotal` is the period's list price (the trial price for a trial charge) and `discountAmount` is the discount for that period — zero once the coupon's duration has run out or its expiry has passed. Payments recorded before these keys were introduced do not carry them | | `originalChargedAmount` | string | `refund.*`, when the channel reported an amount for that payment | What the payment being refunded actually collected (display format). This is the ceiling a refund can reach; `originalPayment.total` next to it is the amount expected for that payment (after any discount; the price before the discount is `originalPayment.listTotal`), and the two differ when a prorated credit or a zero-amount card check applied to that payment. Omitted — never zeroed — when the channel reported no amount | | `originalPayment` | object | `refund.*` | The payment being refunded, as originally charged: `total` / `subtotal` / `taxAmount` / `taxRate` / `taxName`. Its `taxAmount` is the original order's real tax. When that payment was recorded with these fields, the block also carries `listTotal` and `discountAmount`, read the same way as in `listPrice` | | `planPrice` | object | Subscription events | The subscription's list price for the current phase: `total` / `subtotal` / `taxAmount` / `taxRate` / `taxName`. Always before any coupon discount — the discounted amount of a charge is in `listPrice` on `subscription.payment_succeeded` | | `amount` | string | Always | **Deprecated** — Amount for this event, tax included (display format). On payment events this is what was actually charged; on `refund.*` it is the refund amount, **not** the order amount. See [Deprecated amount fields](#deprecated-amount-fields) | | `taxAmount` | string | Always | **Deprecated** — Tax amount (display format). Always `"0"` on `refund.*` — refunds carry no tax breakdown | | `taxRate` | number | When tax applied | **Deprecated** — Tax rate as a percentage number (e.g., `10` for 10%) | | `taxName` | string | When tax applied | **Deprecated** — Tax name (e.g., `"Consumption Tax"`) | | `subtotal` | string | When available | **Deprecated** — Subtotal before tax (display format). On `refund.*` this describes the original payment | | `total` | string | When available | **Deprecated** — Total after tax (display format). On `refund.*` this describes the original payment | | `productName` | string | Always | Product name | | `productDescription` | string | When set on product | Product description | | `paymentId` | string | Payment & `refund.*` events | Payment ID. On `refund.*` this is the payment being refunded | | `paymentStatus` | string | Payment & `refund.*` events | Payment status (`"succeeded"`, `"failed"`) | | `paymentDate` | string | Payment & `refund.*` events | Payment date (ISO 8601 date, e.g., `"2026-03-10"`) | | `paymentMethod` | string | Payment & `refund.*`, when known | Payment method type (e.g., `"card"`) | | `paymentLast4` | string | Payment & `refund.*`, when known | Last 4 digits of the payment instrument | | `paymentFailureReason` | string | Payment events, when set | Payment failure reason | | `periodNumber` | number | Subscription events, `subscription.payment_succeeded` & subscription `refund.*` | Which billing period the event refers to, as reported by the payment channel. See the note below | | `billingPeriod` | string | Subscription events | `"weekly"`, `"monthly"`, `"quarterly"`, `"yearly"` | | `currentPeriodStart` | string | Subscription events | Current billing period start (ISO 8601 date) | | `currentPeriodEnd` | string | Subscription events | Current billing period end (ISO 8601 date) | | `canceledAt` | string | `subscription.canceling` / `canceled` | When cancellation was requested (ISO 8601) — not when access ends | | `refundStatus` | string | `refund.*` | `"succeeded"` or `"failed"` | | `refundReason` | string | `refund.*`, when set | Refund reason | | `refundCreatedAt` | string | `refund.*` | Refund creation timestamp (ISO 8601) | ### Deprecated amount fields `amount` / `total` / `subtotal` / `taxAmount` / `taxRate` / `taxName` name one thing but describe three: the charge on a payment event, the refund on a refund event, the plan's price on a subscription status event. Each now has a replacement that names its own subject. | Deprecated | Payment events | `refund.*` | Subscription events | | - | - | - | - | | `amount` | `chargedAmount` | `refundedAmount` | `planPrice.total` | | `total` | `listPrice.total` | `originalPayment.total` | `planPrice.total` | | `subtotal` | `listPrice.subtotal` | `originalPayment.subtotal` | `planPrice.subtotal` | | `taxAmount` | `listPrice.taxAmount` | `originalPayment.taxAmount` | `planPrice.taxAmount` | | `taxRate` | `listPrice.taxRate` | `originalPayment.taxRate` | `planPrice.taxRate` | | `taxName` | `listPrice.taxName` | `originalPayment.taxName` | `planPrice.taxName` | > [!WARNING] > > **On payment events, `amount` changes value on 2026-09-21.** From that date, `order.completed` and `subscription.payment_succeeded` report the amount the payment channel actually charged — the same value as `chargedAmount` — where they previously reported the list price recorded when the order was placed. The two differ only when a prorated credit or a zero-amount card check applies; for every other charge the value is identical. If the channel reported no amount for that charge, `amount` falls back to the list price total and `chargedAmount` is omitted. > > If you reconcile on `amount == total`, that assertion starts failing on payment events from this date. Switch to `chargedAmount` (what was taken) and `listPrice.total` (what was listed). > > **Nothing else changes value.** On `refund.*` and on subscription events `amount` is exactly what it was, and `total` / `subtotal` / `taxAmount` / `taxRate` / `taxName` are unchanged on every event. **Removal is no earlier than 2027-09-20 — 12 months from this notice — and ships with the next major version.** Until then all six keep being delivered with unchanged types and trigger conditions. New integrations should read the replacement fields; existing integrations need no change to keep working. The deprecation is not signalled at runtime: the payload carries no deprecation metadata, and no `Deprecation` or `Sunset` headers are sent. This page and the SDK type definitions (`@deprecated` in TypeScript, `// Deprecated:` in Go) are where it is stated. > [!NOTE] > > `periodNumber` is the billing period number the payment channel itself reports, passed through unchanged — Waffo never computes, counts or infers it. > > * `1` on the first charge, `N` on the Nth renewal. > * **A failed charge still consumes a period.** This is not a count of successful charges — use it to align with the period numbers you reconcile from the channel, not as a payment tally. > * `0` means the channel has authorized the subscription but has not charged it yet. It appears on a scheduled plan change before its switch time. > * On `subscription.payment_succeeded` it is the period of that charge, and it is the one subscription-shaped field that event carries. > * On `refund.*` it is the period of the **refunded** charge, not the period the refund happened in. > * On `subscription.canceling`, `subscription.uncanceled` and `subscription.plan_change_failed` the channel sends no notification of its own, so the value is the subscription's current period as last reported by the channel. > * **Not a deduplication key.** Several events in the same period carry the same number. Deduplicate on `id` or `eventId`. > * Absent on one-time orders and their refunds, and on subscriptions and payments created before this field shipped. > > **The same concept appears under three names**, one per anchor. They are not three different numbers — each is this same channel value read at a different point: > > | Where you read it | Field | What the value is anchored to | > | - | - | - | > | Webhook payload | `data.periodNumber` | the entity the event is about (see the rules above) | > | GraphQL `Payment` | `periodNumber` | **that charge** — which period it paid for | > | GraphQL `SubscriptionOrder` | `currentPeriodNumber` | **that subscription right now** — which period it is in | > > The GraphQL subscription field is named differently on purpose: a subscription that has renewed > three times is in period `3`, while its first charge is forever `periodNumber: 1`. Reading one > where you meant the other is the mistake the two names exist to prevent. > [!NOTE] > > Amounts are **display format strings**, already converted from minor units. For example, USD `"29.00"` = 2900 cents; JPY `"4500"` = ¥4500. Zero is a legitimate value (a zero-amount card check) and is formatted the same way — `"0.00"` for USD, `"0"` for JPY. For an itemized display, use the block that matches the event: `listPrice`, `originalPayment` or `planPrice`. > [!NOTE] > > `taxRate` in webhook payloads is a **percentage number** — `10` means 10%. The unit convention is being unified across the API surface; another surface (the TypeScript SDK types) still describes it as a decimal fraction. Tax collection is not enabled yet, so `taxRate` is `0` on every order today — read the value from the payload rather than hard-coding an assumption about its unit. ### Payment amount in GraphQL > [!NOTE] > > **This is a defect fix, not a contract change.** GraphQL's `Payment.amount` has always been documented as the total charged to the buyer, but the implementation read the list price snapshot taken when the order was placed. It now reads what the payment channel actually charged — and so do amount filtering, amount sorting and the "fully refunded" test. All four read one source, so a list can no longer sort by one figure while the detail view shows another. > > **Which payments change value.** Only those where the two figures differ, which begins with the plan upgrades and downgrades that shipped on **2026-09-07** — before that date the list price and the actual charge never diverged on any charge. To date that is **7 live payments and 111 test payments**. Every other payment reads exactly as it did. If you reconciled any of those charges from GraphQL after 2026-09-07, their amounts move to what the channel took, and a payment already refunded in full is now reported as fully refunded. > > **When the channel reported no amount for a charge**, the field falls back to the list price total and the fallback is logged server-side. Filtering and sorting fall back the same way, so such a payment is never silently missing from a filtered or sorted list. > > **Webhook payloads are unaffected.** No field on this page changes value; the only addition is `originalChargedAmount` on refund events. > [!WARNING] > > **Some Dashboard and Admin pages still show the list price.** They read the list price snapshot directly rather than this field and have not been updated yet: the consumer invoice page, the Admin payment list, the Admin PSP reconciliation page, the merchant revenue page, the buyer portal, the sidebar, and the analytics page's fallback. Until they are, one payment can show two different numbers — the GraphQL API and the webhook payload report what was charged, those pages report what was listed. Reconcile against the API, not the page. > [!NOTE] > > **A payment that collected nothing counts as fully refunded.** "Fully refunded" is decided by comparing the refunds against the amount that payment collected, so a payment that collected `0` satisfies it with no refund existing at all: it reports `isFullyRefunded: true` and shows up in the "fully refunded" filter. These are charges that were never meant to take money — a zero-amount card check, the first charge of a free trial, or an order fully covered by a credit or coupon. > > Read it as **the buyer was never charged**, not **money was returned**. To tell the two apart, look for an actual refund: `refundedAmount` above zero, a non-empty `refunds` list, or `refundStatus: refunded` — that last one is decided purely by the existence of a succeeded refund and is unaffected by this fix. > > The rule itself is not new: an order whose list price was also `0` has always been reported this way. What the fix widens is the range — payments that collected `0` against a **non-zero** list price now join the set. That is **3 of the 7 affected live payments** (39 of the 111 in test mode). No payment leaves the set because of this fix. ### eventId Mapping The `eventId` identifies the business entity that triggered the event: | Event Type | eventId maps to | Example | | - | - | - | | `order.completed` | Payment ID | `PAY_6eYCunG3IMmIgcQOnaXdoA` | | `subscription.activated` | Order ID | `ORD_5dXBtmF2HLlHfbPNm0Wcnz` | | `subscription.payment_succeeded` | Payment ID | `PAY_6eYCunG3IMmIgcQOnaXdoA` | | `subscription.renewed` | Order ID + period end | `ORD_5dXBtmF2HLlHfbPNm0Wcnz-renewed-2026-05-10` | | `subscription.recovered` | Order ID + event timestamp | `ORD_5dXBtmF2HLlHfbPNm0Wcnz-2026-04-12T08:30:00.000Z` | | `subscription.canceling` | Order ID + event timestamp | `ORD_5dXBtmF2HLlHfbPNm0Wcnz-2026-04-10T08:31:00.000Z` | | `subscription.uncanceled` | Order ID + event timestamp | `ORD_5dXBtmF2HLlHfbPNm0Wcnz-2026-04-10T08:31:00.000Z` | | `subscription.plan_changed` | Order ID | `ORD_5dXBtmF2HLlHfbPNm0Wcnz` | | `subscription.plan_change_scheduled` | Order ID | `ORD_5dXBtmF2HLlHfbPNm0Wcnz` | | `subscription.plan_change_failed` | Order ID | `ORD_5dXBtmF2HLlHfbPNm0Wcnz` | | `subscription.canceled` | Order ID | `ORD_5dXBtmF2HLlHfbPNm0Wcnz` | | `subscription.past_due` | Order ID + event timestamp | `ORD_5dXBtmF2HLlHfbPNm0Wcnz-2026-04-10T08:31:00.000Z` | | `refund.succeeded` | Refund ID | `REF_4cWAtlE1GKkGebONl9Xbnx` | | `refund.failed` | Refund ID | `REF_4cWAtlE1GKkGebONl9Xbnx` | > [!NOTE] > > Some events can happen more than once on the same subscription, so their eventId carries a suffix and each occurrence becomes its own delivery. > > **Four events append the event timestamp** (full ISO 8601): `subscription.canceling`, `subscription.uncanceled`, `subscription.past_due` and `subscription.recovered` — a subscriber can cancel and un-cancel, or fall overdue and recover, any number of times. > > **`subscription.renewed` appends the new period end instead**, so consecutive renewals each get their own key. That suffix is a date at day granularity (`YYYY-MM-DD`), so two period rolls inside the same calendar day would collapse into one delivery — reachable only with compressed test billing cycles, not with real weekly or monthly billing. > > Every other event uses the bare entity ID, because it happens at most once per entity. ### Correlating a Payment with Its Billing Period A renewal produces two independent deliveries: `subscription.payment_succeeded` (keyed to the charge) and `subscription.renewed` (keyed to the order). They leave in the same batch, but neither order nor spacing is guaranteed, so do not join them at receive time. Store each on its own, then correlate on `data.orderId` + `data.periodNumber`: the charge for period `N` and the renewal into period `N` normally carry the same pair, and the join is unaffected by reordering, delays and retries. Both values are the channel's own period number passed through unchanged, so this consistency comes from the channel's numbering, not from a Waffo guarantee — keep the timestamp fallback below for the rare case they disagree. The same pair ties `subscription.activated` to the first charge (`periodNumber: 1`) and `subscription.recovered` to the charge that cleared the overdue period. `periodNumber` is absent on subscriptions created before the field shipped. For those, fall back to `data.orderId` plus the top-level `timestamp` (event creation time, unchanged by retries) matched within a few minutes. In both cases deduplicate each event type on `id` or `eventId` before correlating. *** ## Event Types ### Overview | Event | Trigger | eventId | | - | - | - | | `order.completed` | One-time order payment succeeded | Payment ID | | `subscription.activated` | Subscription first payment succeeded | Order ID | | `subscription.payment_succeeded` | Any subscription charge succeeded — first payment and renewals. Pure payment event: no subscription period or status | Payment ID | | `subscription.renewed` | Current billing period rolled forward (renewal) | Order ID + period end | | `subscription.recovered` | An overdue subscription was brought back to active by a successful retry | Order ID + event timestamp | | `subscription.canceling` | Cancellation requested — active until period ends | Order ID | | `subscription.uncanceled` | Cancellation withdrawn | Order ID | | `subscription.plan_changed` | Plan change took effect (upgrade/downgrade) | Order ID | | `subscription.plan_change_scheduled` | Plan change confirmed, effective next billing period | Order ID | | `subscription.plan_change_failed` | Plan change did not complete, the current plan stays in effect | Order ID | | `subscription.canceled` | Subscription terminated (period ended) | Order ID | | `subscription.past_due` | Renewal payment failed | Order ID + event timestamp | | `refund.succeeded` | Refund completed | Refund ID | | `refund.failed` | Refund failed | Refund ID | > [!NOTE] > > `subscription.plan_changed` fires when a subscription switches to another plan. `direction` is `upgrade`, `downgrade`, or `same_price`; `planChange.chargedAmount` is what was actually charged this time, which differs from the plan's list price when a prorated credit or a merchant-specified amount applies. > > `subscription.plan_change_scheduled` fires when the change is confirmed but effective next period, and `subscription.plan_change_failed` when it does not complete. All three are live in production — handle all three, or you will miss outcomes. Which ones you receive depends on the timing tier: > > | Outcome | Events, in order | > | - | - | > | Immediate change | `subscription.plan_changed` only | > | Next-period change | `subscription.plan_change_scheduled` at confirmation, then `subscription.plan_changed` at the switch | > | Change did not complete | `subscription.plan_change_failed` only — the original plan stays in effect | > > A next-period change therefore produces two events for one change, and the plan takes effect only on the second. Do not grant the new plan's access on `plan_change_scheduled`. For where each event sits in the order, subscription, and refund lifecycles — and for the transitions that emit nothing — see [Lifecycle and Trigger Timing](#lifecycle-and-trigger-timing). ### Event Details > **order.completed** > > **Trigger**: One-time order payment succeeds for the first time. > > **Body**: > > ```json theme={"system"} > { > "id": "PAY_6eYCunG3IMmIgcQOnaXdoA", > "timestamp": "2026-03-10T08:30:00.000Z", > "eventType": "order.completed", > "eventId": "PAY_6eYCunG3IMmIgcQOnaXdoA", > "storeId": "STO_3bVzrkD0FJjFdZNLk8Ualx", > "storeName": "My Store", > "mode": "prod", > "data": { > "orderId": "ORD_5dXBtmF2HLlHfbPNm0Wcnz", > "orderStatus": "completed", > "buyerEmail": "customer@example.com", > "currency": "USD", > "orderMetadata": { "planId": "pro" }, > "productMetadata": {}, > "orderMerchantExternalId": "ORDER-2026-00891", > "billingDetail": { "country": "JP", "isBusiness": false }, > "chargedAmount": "98.00", > "amount": "98.00", > "taxAmount": "8.00", > "taxRate": 8, > "taxName": "Consumption Tax", > "subtotal": "100.00", > "total": "108.00", > "listPrice": { > "total": "108.00", > "subtotal": "100.00", > "taxAmount": "8.00", > "taxRate": 8, > "taxName": "Consumption Tax" > }, > "productName": "Pro Plan", > "paymentId": "PAY_6eYCunG3IMmIgcQOnaXdoA", > "paymentStatus": "succeeded", > "paymentDate": "2026-03-10", > "paymentMethod": "card", > "paymentLast4": "4242" > } > } > ``` > > `amount` equals `chargedAmount` here — what the channel actually took. `listPrice` is what the order was priced at; the two differ in this example because a prorated credit applied. No subscription or refund fields appear. Omitted when empty: `productDescription`, `merchantProvidedBuyerIdentity`, `billingDetail`, `orderMerchantExternalId`, `taxRate`, `taxName`, `subtotal`, `total`, `paymentMethod`, `paymentLast4`, `chargedAmount`, `listPrice`. > > **Recommended actions**: > > * Deliver digital goods (license keys, download links, activation codes) > * Update your order management system > * Send customer confirmation (if not using Waffo's built-in emails) > > The same order only triggers `order.completed` once. Refunds are notified via `refund.succeeded` / `refund.failed`. > **subscription.activated** > > **Trigger**: First payment on a new subscription succeeds (`pending` → `active`). > > **Body**: > > ```json theme={"system"} > { > "id": "ORD_5dXBtmF2HLlHfbPNm0Wcnz", > "timestamp": "2026-03-10T08:30:00.000Z", > "eventType": "subscription.activated", > "eventId": "ORD_5dXBtmF2HLlHfbPNm0Wcnz", > "storeId": "STO_3bVzrkD0FJjFdZNLk8Ualx", > "storeName": "My Store", > "mode": "prod", > "data": { > "orderId": "ORD_5dXBtmF2HLlHfbPNm0Wcnz", > "orderStatus": "active", > "buyerEmail": "customer@example.com", > "currency": "USD", > "orderMetadata": { "planId": "pro" }, > "productMetadata": {}, > "orderMerchantExternalId": "ORDER-2026-00891", > "billingDetail": { "country": "JP", "isBusiness": false }, > "amount": "29.00", > "taxAmount": "2.90", > "taxRate": 10, > "taxName": "Consumption Tax", > "subtotal": "26.10", > "total": "29.00", > "planPrice": { > "total": "29.00", > "subtotal": "26.10", > "taxAmount": "2.90", > "taxRate": 10, > "taxName": "Consumption Tax" > }, > "productName": "Pro Plan", > "periodNumber": 1, > "billingPeriod": "monthly", > "currentPeriodStart": "2026-03-10", > "currentPeriodEnd": "2026-04-10" > } > } > ``` > > > [!WARNING] > > > > `amount` is the subscription's regular-phase price, not what was charged. With a trial or an introductory discount the first charge differs — use `subscription.payment_succeeded` for the amount actually collected. > > This event is keyed to the order, not to a charge — **no `paymentId` or other payment fields appear**. The billing period is written and the event published inside the same request, so `billingPeriod`, `currentPeriodStart` and `currentPeriodEnd` are always present. Omitted when empty: `productDescription`, `merchantProvidedBuyerIdentity`, `billingDetail`, `orderMerchantExternalId`, `taxRate`, `taxName`, `subtotal`, `total`, `planPrice`. > > **Recommended actions**: > > * Provision the subscriber's account and grant access > * Record the subscription start date > > Fires only on the first `pending` → `active` transition. The same first payment also emits `subscription.payment_succeeded` for the charge itself — see [Subscription Lifecycle](#subscription-lifecycle). > **subscription.payment\_succeeded** > > **Trigger**: A subscription charge succeeds — the first payment, every renewal, and the charge that clears an overdue period. > > **Body**: > > ```json theme={"system"} > { > "id": "PAY_7fZDvoH4JNnJhdRPobYepB", > "timestamp": "2026-04-10T08:30:00.000Z", > "eventType": "subscription.payment_succeeded", > "eventId": "PAY_7fZDvoH4JNnJhdRPobYepB", > "storeId": "STO_3bVzrkD0FJjFdZNLk8Ualx", > "storeName": "My Store", > "mode": "prod", > "data": { > "orderId": "ORD_5dXBtmF2HLlHfbPNm0Wcnz", > "buyerEmail": "customer@example.com", > "currency": "USD", > "orderMetadata": { "planId": "pro" }, > "productMetadata": {}, > "orderMerchantExternalId": "ORDER-2026-00891", > "billingDetail": { "country": "JP", "isBusiness": false }, > "chargedAmount": "98.00", > "amount": "98.00", > "taxAmount": "8.00", > "taxRate": 8, > "taxName": "Consumption Tax", > "subtotal": "100.00", > "total": "108.00", > "listPrice": { > "total": "108.00", > "subtotal": "100.00", > "taxAmount": "8.00", > "taxRate": 8, > "taxName": "Consumption Tax" > }, > "productName": "Pro Plan", > "paymentId": "PAY_7fZDvoH4JNnJhdRPobYepB", > "paymentStatus": "succeeded", > "paymentDate": "2026-04-10", > "paymentMethod": "card", > "paymentLast4": "4242", > "periodNumber": 2 > } > } > ``` > > Unlike the other `subscription.*` events, this one is keyed to a charge, so it carries the payment fields. `amount` is what was charged for this period and equals `chargedAmount`; `listPrice` is the price the period was billed at, which a prorated credit or a zero-amount card check can make higher. Omitted when empty: `productDescription`, `merchantProvidedBuyerIdentity`, `billingDetail`, `orderMerchantExternalId`, `taxRate`, `taxName`, `subtotal`, `total`, `paymentMethod`, `paymentLast4`, `chargedAmount`, `listPrice`. > > > [!WARNING] > > > > **This is a pure payment event.** It carries no `billingPeriod`, `currentPeriodStart`, `currentPeriodEnd`, `canceledAt` or `orderStatus` — those describe the subscription, not the charge, and now travel on the subscription domain events, where they are written and published inside the same request and no longer arrive empty. > > > > If your handler reads any of those five fields here: > > > > | You used it for | Read it from instead | > > | - | - | > > | Extending access after a renewal | `subscription.renewed` — emitted whenever the current period actually rolls forward | > > | Detecting the first paid period | `subscription.activated` — now always carries the full period | > > | Knowing the subscription is healthy | `subscription.recovered` — emitted when a retried charge brings a past-due subscription back to active | > > | Reading the subscription status | any subscription domain event (`orderStatus`), or query the order via GraphQL | > > > > `periodNumber` is the exception: it describes **this charge**, so it stays on this event. It tells you which billing period was just paid for. > > > > A handler that only uses the payment fields and `orderId` needs no change. > > **Recommended actions**: > > * Record the receipt for this charge > * Generate an invoice for this billing cycle > * Extend the service period on `subscription.renewed`, and restore full access on `subscription.recovered` > **subscription.renewed** > > **Trigger**: The current billing period rolls forward — the paid period just ended and the next one began. The first period of a subscription is not a renewal and does not emit this event. > > **Body**: > > ```json theme={"system"} > { > "id": "ORD_5dXBtmF2HLlHfbPNm0Wcnz", > "timestamp": "2026-04-10T08:30:02.000Z", > "eventType": "subscription.renewed", > "eventId": "ORD_5dXBtmF2HLlHfbPNm0Wcnz-renewed-2026-05-10", > "storeId": "STO_3bVzrkD0FJjFdZNLk8Ualx", > "storeName": "My Store", > "mode": "prod", > "data": { > "orderId": "ORD_5dXBtmF2HLlHfbPNm0Wcnz", > "orderStatus": "active", > "buyerEmail": "customer@example.com", > "currency": "USD", > "orderMetadata": { "planId": "pro" }, > "productMetadata": {}, > "orderMerchantExternalId": "ORDER-2026-00891", > "billingDetail": { "country": "JP", "isBusiness": false }, > "amount": "29.00", > "taxAmount": "2.90", > "taxRate": 10, > "taxName": "Consumption Tax", > "subtotal": "26.10", > "total": "29.00", > "planPrice": { > "total": "29.00", > "subtotal": "26.10", > "taxAmount": "2.90", > "taxRate": 10, > "taxName": "Consumption Tax" > }, > "productName": "Pro Plan", > "periodNumber": 2, > "billingPeriod": "monthly", > "currentPeriodStart": "2026-04-10", > "currentPeriodEnd": "2026-05-10" > } > } > ``` > > No payment fields on this event — it reports the new period, not the charge. `amount` is the subscription's per-period price. Omitted when empty: `productDescription`, `merchantProvidedBuyerIdentity`, `billingDetail`, `orderMerchantExternalId`, `taxRate`, `taxName`, `subtotal`, `total`, `planPrice`. > > **Recommended actions**: > > * Extend the service period to the new `currentPeriodEnd` > > **Deduplication**: `eventId` carries the new period end, so consecutive renewals of the same subscription each get their own delivery, while a redelivered provider notification does not produce a second one. > **subscription.recovered** > > **Trigger**: A retried charge succeeds on an overdue subscription and brings it back to `active` (`past_due` → `active`). Closes the loop opened by `subscription.past_due`. First payments and ordinary renewals do not emit it. > > **Body**: > > ```json theme={"system"} > { > "id": "ORD_5dXBtmF2HLlHfbPNm0Wcnz", > "timestamp": "2026-05-12T09:15:00.000Z", > "eventType": "subscription.recovered", > "eventId": "ORD_5dXBtmF2HLlHfbPNm0Wcnz-2026-05-12T09:15:00.000Z", > "storeId": "STO_3bVzrkD0FJjFdZNLk8Ualx", > "storeName": "My Store", > "mode": "prod", > "data": { > "orderId": "ORD_5dXBtmF2HLlHfbPNm0Wcnz", > "orderStatus": "active", > "buyerEmail": "customer@example.com", > "currency": "USD", > "orderMetadata": { "planId": "pro" }, > "productMetadata": {}, > "orderMerchantExternalId": "ORDER-2026-00891", > "billingDetail": { "country": "JP", "isBusiness": false }, > "amount": "29.00", > "taxAmount": "2.90", > "taxRate": 10, > "taxName": "Consumption Tax", > "subtotal": "26.10", > "total": "29.00", > "planPrice": { > "total": "29.00", > "subtotal": "26.10", > "taxAmount": "2.90", > "taxRate": 10, > "taxName": "Consumption Tax" > }, > "productName": "Pro Plan", > "periodNumber": 2, > "billingPeriod": "monthly", > "currentPeriodStart": "2026-04-10", > "currentPeriodEnd": "2026-05-10" > } > } > ``` > > No payment fields on this event — the charge itself is reported by `subscription.payment_succeeded`, which is delivered independently for the same retry. Omitted when empty: `productDescription`, `merchantProvidedBuyerIdentity`, `billingDetail`, `orderMerchantExternalId`, `taxRate`, `taxName`, `subtotal`, `total`, `planPrice`. > > **Recommended actions**: > > * Restore any access you degraded on `subscription.past_due` > > **Deduplication**: `eventId` carries the event timestamp, so a subscription that goes overdue and recovers repeatedly produces one delivery per recovery. > **subscription.canceling** > > **Trigger**: Customer or merchant requests cancellation. The subscription remains active until the current paid period ends. > > **Body**: > > ```json theme={"system"} > { > "id": "ORD_5dXBtmF2HLlHfbPNm0Wcnz", > "timestamp": "2026-03-25T11:02:00.000Z", > "eventType": "subscription.canceling", > "eventId": "ORD_5dXBtmF2HLlHfbPNm0Wcnz", > "storeId": "STO_3bVzrkD0FJjFdZNLk8Ualx", > "storeName": "My Store", > "mode": "prod", > "data": { > "orderId": "ORD_5dXBtmF2HLlHfbPNm0Wcnz", > "orderStatus": "canceling", > "buyerEmail": "customer@example.com", > "currency": "USD", > "orderMetadata": { "planId": "pro" }, > "productMetadata": {}, > "orderMerchantExternalId": "ORDER-2026-00891", > "billingDetail": { "country": "JP", "isBusiness": false }, > "amount": "29.00", > "taxAmount": "2.90", > "taxRate": 10, > "taxName": "Consumption Tax", > "subtotal": "26.10", > "total": "29.00", > "planPrice": { > "total": "29.00", > "subtotal": "26.10", > "taxAmount": "2.90", > "taxRate": 10, > "taxName": "Consumption Tax" > }, > "productName": "Pro Plan", > "periodNumber": 1, > "billingPeriod": "monthly", > "currentPeriodStart": "2026-03-10", > "currentPeriodEnd": "2026-04-10", > "canceledAt": "2026-03-25T11:02:00.000Z" > } > } > ``` > > > [!WARNING] > > > > `canceledAt` is when cancellation was requested, not when access ends. The customer has paid through `currentPeriodEnd` — revoking access at `canceledAt` cuts off service they already paid for. > > No payment fields on this event. `amount` is the subscription's per-period price, not a charge. Omitted when empty: `productDescription`, `merchantProvidedBuyerIdentity`, `billingDetail`, `orderMerchantExternalId`, `taxRate`, `taxName`, `subtotal`, `total`, `currentPeriodStart`, `currentPeriodEnd`, `planPrice`. > > **Recommended actions**: > > * Show "Subscription expires on \[date]" notice > * Offer a retention flow (e.g., discounted renewal) > * **Do not** revoke access — the customer has paid for the current period > > The customer can withdraw the cancellation before the period ends (triggers `subscription.uncanceled`). > **subscription.uncanceled** > > **Trigger**: Cancellation is withdrawn before the current period ends. > > **Body**: > > ```json theme={"system"} > { > "id": "ORD_5dXBtmF2HLlHfbPNm0Wcnz", > "timestamp": "2026-03-28T14:20:00.000Z", > "eventType": "subscription.uncanceled", > "eventId": "ORD_5dXBtmF2HLlHfbPNm0Wcnz", > "storeId": "STO_3bVzrkD0FJjFdZNLk8Ualx", > "storeName": "My Store", > "mode": "prod", > "data": { > "orderId": "ORD_5dXBtmF2HLlHfbPNm0Wcnz", > "orderStatus": "active", > "buyerEmail": "customer@example.com", > "currency": "USD", > "orderMetadata": { "planId": "pro" }, > "productMetadata": {}, > "orderMerchantExternalId": "ORDER-2026-00891", > "billingDetail": { "country": "JP", "isBusiness": false }, > "amount": "29.00", > "taxAmount": "2.90", > "taxRate": 10, > "taxName": "Consumption Tax", > "subtotal": "26.10", > "total": "29.00", > "planPrice": { > "total": "29.00", > "subtotal": "26.10", > "taxAmount": "2.90", > "taxRate": 10, > "taxName": "Consumption Tax" > }, > "productName": "Pro Plan", > "periodNumber": 1, > "billingPeriod": "monthly", > "currentPeriodStart": "2026-03-10", > "currentPeriodEnd": "2026-04-10" > } > } > ``` > > No payment fields on this event. `canceledAt` is cleared when the cancellation is withdrawn, so it does not appear. Omitted when empty: `productDescription`, `merchantProvidedBuyerIdentity`, `billingDetail`, `orderMerchantExternalId`, `taxRate`, `taxName`, `subtotal`, `total`, `currentPeriodStart`, `currentPeriodEnd`, `planPrice`. > > **Recommended actions**: > > * Remove the "expiring soon" notice > * Restore auto-renewal status > **subscription.plan\_changed** > > **Trigger**: Subscription product changes (upgrade or downgrade). > > **Body**: > > ```json theme={"system"} > { > "id": "ORD_5dXBtmF2HLlHfbPNm0Wcnz", > "timestamp": "2026-04-02T10:05:00.000Z", > "eventType": "subscription.plan_changed", > "eventId": "ORD_5dXBtmF2HLlHfbPNm0Wcnz", > "storeId": "STO_3bVzrkD0FJjFdZNLk8Ualx", > "storeName": "My Store", > "mode": "prod", > "data": { > "orderId": "ORD_5dXBtmF2HLlHfbPNm0Wcnz", > "orderStatus": "active", > "buyerEmail": "customer@example.com", > "currency": "USD", > "orderMetadata": { "planId": "pro" }, > "productMetadata": {}, > "orderMerchantExternalId": "ORDER-2026-00891", > "billingDetail": { "country": "JP", "isBusiness": false }, > "amount": "49.00", > "taxAmount": "4.90", > "taxRate": 10, > "taxName": "Consumption Tax", > "subtotal": "44.10", > "total": "49.00", > "planPrice": { > "total": "49.00", > "subtotal": "44.10", > "taxAmount": "4.90", > "taxRate": 10, > "taxName": "Consumption Tax" > }, > "productName": "Business Plan", > "periodNumber": 1, > "billingPeriod": "monthly", > "currentPeriodStart": "2026-04-02", > "currentPeriodEnd": "2026-05-02", > "planChange": { > "direction": "upgrade", > "oldPlanName": "Starter Plan", > "oldAmount": "29.00", > "newPlanName": "Business Plan", > "newAmount": "49.00", > "chargedAmount": "24.50", > "effectiveDate": "2026-04-02T10:04:58.312Z" > } > } > } > ``` > > The top-level fields describe the state **after** the change; `data.planChange` carries the before/after pair, so you do not need to keep your own record of the previous plan. `direction` is `upgrade`, `downgrade`, or `same_price`. > > **`amount` is not what the buyer paid.** The top-level `amount` / `total` / `subtotal` / `taxAmount` are the new plan's list price; `planChange.chargedAmount` is what was actually charged this time. On a plan change the two always differ — either a prorated credit applies, or the merchant specified the amount. Reconcile against `chargedAmount`. > > `planChange` appears only on plan-change events; the `data` of every other event does not carry the key at all. Each field inside it may be `null` when unknown: `chargedAmount` is `null` before a successful payment, `effectiveDate` may be `null` for an immediate change, and `direction` falls back to `null` rather than passing through an unrecognized value. Omitted when empty: `productDescription`, `merchantProvidedBuyerIdentity`, `billingDetail`, `orderMerchantExternalId`, `taxRate`, `taxName`, `subtotal`, `total`, `currentPeriodStart`, `currentPeriodEnd`, `planPrice`. > > **Recommended actions**: > > * Update the customer's access level (add/remove features) > * Update billing records > **subscription.plan\_change\_scheduled** > > **Trigger**: A plan change is confirmed but takes effect at the start of the next billing period. The customer keeps the current plan until then. > > **Body**: > > ```json theme={"system"} > { > "id": "ORD_5dXBtmF2HLlHfbPNm0Wcnz", > "timestamp": "2026-04-02T10:05:00.000Z", > "eventType": "subscription.plan_change_scheduled", > "eventId": "ORD_5dXBtmF2HLlHfbPNm0Wcnz", > "storeId": "STO_3bVzrkD0FJjFdZNLk8Ualx", > "storeName": "My Store", > "mode": "prod", > "data": { > "orderId": "ORD_5dXBtmF2HLlHfbPNm0Wcnz", > "orderStatus": "pending", > "buyerEmail": "customer@example.com", > "currency": "USD", > "orderMetadata": { "planId": "starter" }, > "productMetadata": {}, > "billingDetail": { "country": "JP", "isBusiness": false }, > "amount": "29.00", > "taxAmount": "2.90", > "taxRate": 10, > "taxName": "Consumption Tax", > "subtotal": "26.10", > "total": "29.00", > "planPrice": { > "total": "29.00", > "subtotal": "26.10", > "taxAmount": "2.90", > "taxRate": 10, > "taxName": "Consumption Tax" > }, > "productName": "Starter Plan", > "periodNumber": 0, > "billingPeriod": "monthly", > "planChange": { > "direction": "downgrade", > "oldPlanName": "Business Plan", > "oldAmount": "49.00", > "newPlanName": "Starter Plan", > "newAmount": "29.00", > "chargedAmount": null, > "effectiveDate": "2026-05-02T00:00:01.000Z" > } > } > } > ``` > > **The change has not taken effect yet.** `effectiveDate` is the future moment the new plan starts, `orderStatus` is `pending`, and `currentPeriodStart` / `currentPeriodEnd` are absent because the new subscription has no billing period until then. `chargedAmount` is `null` — a next-period change is charged at the switch, not at confirmation. Do not grant the new plan's access on this event; wait for `subscription.plan_changed`. > > The `id` and `eventId` are the **new** subscription order, which is also the order `subscription.plan_changed` will carry at the switch. The customer's currently active subscription is a different order and is not named in this payload. That order is marked for the upcoming switch at this point, but `subscription.canceling` is **not** emitted for it — this event is the only signal you get. > > If several confirmations arrive before the switch, you receive one delivery — they collapse on `eventType` + `eventId`. The later `plan_changed` is a different event type and is never collapsed into it. > > **Recommended actions**: > > * Record the pending change and its `effectiveDate` > * Leave the current plan's access untouched > * Optionally tell the customer when the new plan starts > **subscription.plan\_change\_failed** > > **Trigger**: A plan change did not complete — the payment was not authorized, or the channel reported a failure. The original plan stays in effect. > > **Body**: > > ```json theme={"system"} > { > "id": "ORD_5dXBtmF2HLlHfbPNm0Wcnz", > "timestamp": "2026-04-02T10:05:00.000Z", > "eventType": "subscription.plan_change_failed", > "eventId": "ORD_5dXBtmF2HLlHfbPNm0Wcnz", > "storeId": "STO_3bVzrkD0FJjFdZNLk8Ualx", > "storeName": "My Store", > "mode": "prod", > "data": { > "orderId": "ORD_5dXBtmF2HLlHfbPNm0Wcnz", > "orderStatus": "canceled", > "buyerEmail": "customer@example.com", > "currency": "USD", > "orderMetadata": { "planId": "pro" }, > "productMetadata": {}, > "billingDetail": { "country": "JP", "isBusiness": false }, > "amount": "49.00", > "taxAmount": "4.90", > "taxRate": 10, > "taxName": "Consumption Tax", > "subtotal": "44.10", > "total": "49.00", > "planPrice": { > "total": "49.00", > "subtotal": "44.10", > "taxAmount": "4.90", > "taxRate": 10, > "taxName": "Consumption Tax" > }, > "productName": "Business Plan", > "periodNumber": 1, > "billingPeriod": "monthly", > "planChange": { > "direction": null, > "oldPlanName": "Starter Plan", > "oldAmount": null, > "newPlanName": "Business Plan", > "newAmount": null, > "chargedAmount": null, > "effectiveDate": null > } > } > } > ``` > > **`planChange` is mostly null on this event, by design.** Nothing took effect, so there is no direction, no effective moment, and no amounts to report: only `oldPlanName` and `newPlanName` are populated, and the other five fields are always `null`. A handler written against the `subscription.plan_changed` body will read nulls here — branch on `eventType` before touching those fields. > > > [!WARNING] > > > > **`orderStatus` is `canceled`, but the customer has not lost their subscription.** The cancelled order is the new one that failed to open; the original subscription is untouched and still active. Revoking access on this event is a bug. A genuine cancellation always arrives as `subscription.canceled`. > > A retry creates a fresh subscription order, so a second failure arrives with a different `id` / `eventId` rather than collapsing into this one. > > **Recommended actions**: > > * Leave the customer's access exactly as it is > * Clear any pending change you recorded from `subscription.plan_change_scheduled` > * Optionally prompt the customer to try the change again > **subscription.canceled** > > **Trigger**: Subscription is terminated — the paid period has ended and no further renewals will occur. > > **Body**: > > ```json theme={"system"} > { > "id": "ORD_5dXBtmF2HLlHfbPNm0Wcnz", > "timestamp": "2026-04-10T00:05:00.000Z", > "eventType": "subscription.canceled", > "eventId": "ORD_5dXBtmF2HLlHfbPNm0Wcnz", > "storeId": "STO_3bVzrkD0FJjFdZNLk8Ualx", > "storeName": "My Store", > "mode": "prod", > "data": { > "orderId": "ORD_5dXBtmF2HLlHfbPNm0Wcnz", > "orderStatus": "canceled", > "buyerEmail": "customer@example.com", > "currency": "USD", > "orderMetadata": { "planId": "pro" }, > "productMetadata": {}, > "orderMerchantExternalId": "ORDER-2026-00891", > "billingDetail": { "country": "JP", "isBusiness": false }, > "amount": "29.00", > "taxAmount": "2.90", > "taxRate": 10, > "taxName": "Consumption Tax", > "subtotal": "26.10", > "total": "29.00", > "planPrice": { > "total": "29.00", > "subtotal": "26.10", > "taxAmount": "2.90", > "taxRate": 10, > "taxName": "Consumption Tax" > }, > "productName": "Pro Plan", > "periodNumber": 1, > "billingPeriod": "monthly", > "currentPeriodStart": "2026-03-10", > "currentPeriodEnd": "2026-04-10", > "canceledAt": "2026-03-25T11:02:00.000Z" > } > } > ``` > > No payment fields on this event. `canceledAt` is when cancellation was requested, which is earlier than this event — the subscription stayed active until `currentPeriodEnd`. `amount` is the per-period price, not a final charge. Omitted when empty: `productDescription`, `merchantProvidedBuyerIdentity`, `billingDetail`, `orderMerchantExternalId`, `taxRate`, `taxName`, `subtotal`, `total`, `currentPeriodStart`, `currentPeriodEnd`, `canceledAt`, `planPrice`. > > **Recommended actions**: > > * Revoke access (or downgrade to a free tier) > * Retain data for a grace period (in case the customer re-subscribes) > * Send a "subscription ended" confirmation > > This is a terminal state. The subscription is irreversibly ended. > **subscription.past\_due** > > **Trigger**: Renewal payment fails and the subscription enters an overdue state. > > **Body**: > > ```json theme={"system"} > { > "id": "ORD_5dXBtmF2HLlHfbPNm0Wcnz", > "timestamp": "2026-05-10T08:31:00.000Z", > "eventType": "subscription.past_due", > "eventId": "ORD_5dXBtmF2HLlHfbPNm0Wcnz-2026-05-10T08:31:00.000Z", > "storeId": "STO_3bVzrkD0FJjFdZNLk8Ualx", > "storeName": "My Store", > "mode": "prod", > "data": { > "orderId": "ORD_5dXBtmF2HLlHfbPNm0Wcnz", > "orderStatus": "past_due", > "buyerEmail": "customer@example.com", > "currency": "USD", > "orderMetadata": { "planId": "pro" }, > "productMetadata": {}, > "orderMerchantExternalId": "ORDER-2026-00891", > "billingDetail": { "country": "JP", "isBusiness": false }, > "amount": "29.00", > "taxAmount": "2.90", > "taxRate": 10, > "taxName": "Consumption Tax", > "subtotal": "26.10", > "total": "29.00", > "planPrice": { > "total": "29.00", > "subtotal": "26.10", > "taxAmount": "2.90", > "taxRate": 10, > "taxName": "Consumption Tax" > }, > "productName": "Pro Plan", > "periodNumber": 2, > "billingPeriod": "monthly", > "currentPeriodStart": "2026-04-10", > "currentPeriodEnd": "2026-05-10" > } > } > ``` > > `eventId` carries the event timestamp as a suffix, so each time the subscription goes overdue gets its own delivery. No payment fields appear, so the payload does not say why the charge failed; `amount` is the amount due. Omitted when empty: `productDescription`, `merchantProvidedBuyerIdentity`, `billingDetail`, `orderMerchantExternalId`, `taxRate`, `taxName`, `subtotal`, `total`, `currentPeriodStart`, `currentPeriodEnd`, `planPrice`. > > **Recommended actions**: > > * Notify the customer to update their payment method > * Optionally degrade the service (limit features rather than fully revoking) > * **Do not** revoke access immediately — the PSP may retry the charge automatically > > **Deduplication**: One delivery per entry into the overdue state. The subscription only enters `past_due` again after a successful charge has brought it back to `active` (which emits `subscription.recovered`), so repeated retry failures within one overdue spell do not fan out into repeated events. > **refund.succeeded** > > **Trigger**: Refund has been completed and funds returned. > > **Body** (partial refund: 10.00 refunded against a 29.00 original payment): > > ```json theme={"system"} > { > "id": "REF_4cWAtlE1GKkGebONl9Xbnx", > "timestamp": "2026-03-12T09:15:23.481Z", > "eventType": "refund.succeeded", > "eventId": "REF_4cWAtlE1GKkGebONl9Xbnx", > "storeId": "STO_3bVzrkD0FJjFdZNLk8Ualx", > "storeName": "My Store", > "mode": "prod", > "data": { > "orderId": "ORD_5dXBtmF2HLlHfbPNm0Wcnz", > "orderStatus": "completed", > "buyerEmail": "customer@example.com", > "currency": "USD", > "orderMetadata": { "planId": "pro" }, > "productMetadata": {}, > "orderMerchantExternalId": "ORDER-2026-00891", > "refundTicketMerchantExternalId": "REF-2026-00891", > "billingDetail": { "country": "JP", "isBusiness": false }, > "refundedAmount": "10.00", > "amount": "10.00", > "taxAmount": "0.00", > "taxRate": 10, > "taxName": "Consumption Tax", > "subtotal": "26.10", > "total": "29.00", > "originalChargedAmount": "29.00", > "originalPayment": { > "total": "29.00", > "subtotal": "26.10", > "taxAmount": "2.90", > "taxRate": 10, > "taxName": "Consumption Tax" > }, > "productName": "Pro Plan", > "paymentId": "PAY_6eYCunG3IMmIgcQOnaXdoA", > "paymentStatus": "succeeded", > "paymentDate": "2026-03-10", > "paymentMethod": "card", > "paymentLast4": "4242", > "periodNumber": 1, > "refundStatus": "succeeded", > "refundReason": "Customer requested refund", > "refundCreatedAt": "2026-03-12T09:15:00.000Z" > } > } > ``` > > > [!WARNING] > > > > `amount` is the refund amount; `total` is the original payment. On a partial refund they differ — record the refund with `refundedAmount` (or the deprecated `amount`), never `total`. > > `subtotal` / `total` / `taxRate` / `taxName` describe the original payment and are kept for comparison. `taxAmount` is always `"0"` because refunds carry no tax breakdown — the original order's real tax is in `originalPayment.taxAmount`. Record the refund with `refundedAmount` and the order it came from with `originalPayment`. **Compute how much of this payment is still refundable from `originalChargedAmount`, not from `originalPayment.total`** — the former is what the buyer was actually charged, and refunding up to the list price is rejected by the channel whenever the two differ (a payment charged 5.00 against a 50.00 list price accepts at most 5.00). `paymentId` identifies the charge being refunded — for a subscription this is the specific renewal, which is how you tell which period was refunded. The payload does not report how much of the payment has been refunded in total, so track that yourself if a payment can be refunded more than once. Omitted when empty: `productDescription`, `merchantProvidedBuyerIdentity`, `billingDetail`, `orderMerchantExternalId`, `refundTicketMerchantExternalId`, `taxRate`, `taxName`, `subtotal`, `total`, `paymentMethod`, `paymentLast4`, `refundReason`, `refundedAmount`, `originalChargedAmount`, `originalPayment`. > > **Recommended actions**: > > * Revoke delivered digital goods (revoke licenses, disable downloads) > * Update order status to "refunded" > **refund.failed** > > **Trigger**: Refund processing failed. > > **Body**: > > ```json theme={"system"} > { > "id": "REF_4cWAtlE1GKkGebONl9Xbnx", > "timestamp": "2026-03-12T09:15:23.481Z", > "eventType": "refund.failed", > "eventId": "REF_4cWAtlE1GKkGebONl9Xbnx", > "storeId": "STO_3bVzrkD0FJjFdZNLk8Ualx", > "storeName": "My Store", > "mode": "prod", > "data": { > "orderId": "ORD_5dXBtmF2HLlHfbPNm0Wcnz", > "orderStatus": "completed", > "buyerEmail": "customer@example.com", > "currency": "USD", > "orderMetadata": { "planId": "pro" }, > "productMetadata": {}, > "orderMerchantExternalId": "ORDER-2026-00891", > "refundTicketMerchantExternalId": "REF-2026-00891", > "billingDetail": { "country": "JP", "isBusiness": false }, > "refundedAmount": "10.00", > "amount": "10.00", > "taxAmount": "0.00", > "taxRate": 10, > "taxName": "Consumption Tax", > "subtotal": "26.10", > "total": "29.00", > "originalChargedAmount": "29.00", > "originalPayment": { > "total": "29.00", > "subtotal": "26.10", > "taxAmount": "2.90", > "taxRate": 10, > "taxName": "Consumption Tax" > }, > "productName": "Pro Plan", > "paymentId": "PAY_6eYCunG3IMmIgcQOnaXdoA", > "paymentStatus": "succeeded", > "paymentDate": "2026-03-10", > "paymentMethod": "card", > "paymentLast4": "4242", > "periodNumber": 1, > "refundStatus": "failed", > "refundReason": "Customer requested refund", > "refundCreatedAt": "2026-03-12T09:15:00.000Z" > } > } > ``` > > > [!WARNING] > > > > No money moved. `refundedAmount` (and the deprecated `amount`) is the amount that was **attempted** — do not record it as a refund. > > Same shape as `refund.succeeded` otherwise. `refundStatus` is the only field that distinguishes the two events, so branch on it rather than on the presence of any field. The payload does not carry a failure cause; check the refund ticket in the Dashboard. Omitted when empty: same list as `refund.succeeded`. > > **Recommended actions**: > > * Log the failure for manual review > * Do not revoke goods (the refund was not completed) *** ## Lifecycle and Trigger Timing An event fires when the underlying business fact is settled — not when the buyer clicks. Payment events are emitted after the payment provider confirms the charge; subscription state events are emitted after the provider confirms the state change. Delivery to your endpoint then normally completes within a few seconds. The `timestamp` field carries the moment the event was created. Retries reuse it, so it does not move with delivery attempts. ### Delivery Timeline ```mermaid theme={"system"} sequenceDiagram participant B as Buyer participant C as Checkout participant P as Payment provider participant W as Waffo Pancake participant Y as Your endpoint B->>C: Submit payment C->>P: Authorize charge P-->>W: Confirm result W->>W: Write order and payment records W->>Y: POST signed event Y-->>W: 200 OK Note over W,Y: Non-2xx or timeout, retry with backoff ``` Treat the event — not the checkout redirect — as the point where money is confirmed. A buyer can close the browser before the redirect; the event still arrives. ### One-Time Order Lifecycle ```mermaid theme={"system"} stateDiagram-v2 [*] --> pending: Checkout session created pending --> completed: Payment confirmed
order.completed pending --> pending: Payment declined
no event, buyer can retry pending --> canceled: Checkout expired or buyer canceled
no event completed --> completed: Refund settled
refund.succeeded / refund.failed canceled --> [*] completed --> [*] ``` | Moment | Event | | - | - | | Payment confirmed | `order.completed` | | Payment declined — the order stays payable | None | | Checkout expired or the buyer canceled | None | | Refund settled against the payment | `refund.succeeded` / `refund.failed` | A declined payment leaves the order in `pending`, so the buyer can pay again on the same order. `order.completed` fires once per order — the retry that finally succeeds is the one that emits it. ### Subscription Lifecycle ```mermaid theme={"system"} stateDiagram-v2 [*] --> pending: Subscription order created pending --> active: First payment confirmed
subscription.activated + subscription.payment_succeeded pending --> closed: Payment window elapsed
no event pending --> canceled: Canceled before the first payment
no event active --> active: Renewal confirmed
subscription.payment_succeeded + subscription.renewed active --> active: Product changed
subscription.plan_changed active --> canceling: Cancellation requested
subscription.canceling active --> past_due: Renewal declined
subscription.past_due active --> expired: Fixed term ended
no event canceling --> active: Cancellation withdrawn
subscription.uncanceled canceling --> canceled: Termination confirmed
subscription.canceled past_due --> active: Overdue payment recovered
subscription.payment_succeeded + subscription.recovered past_due --> canceled: Next renewal also declined
subscription.canceled canceled --> [*] closed --> [*] expired --> [*] ``` | Moment | Event | | - | - | | First payment confirmed | `subscription.activated` **and** `subscription.payment_succeeded` | | Renewal confirmed | `subscription.payment_succeeded` **and** `subscription.renewed` | | Overdue subscription pays successfully | `subscription.payment_succeeded` **and** `subscription.recovered` | | Renewal declined while `active` | `subscription.past_due` | | Renewal declined again while `past_due` | `subscription.canceled` — the subscription is terminated | | Cancellation requested | `subscription.canceling`, immediately | | Cancellation withdrawn | `subscription.uncanceled`, immediately | | Termination confirmed | `subscription.canceled`, around `currentPeriodEnd` | | Billing period rolled forward | `subscription.renewed` | | Canceled or timed out before the first payment | None | > [!WARNING] > > The first payment emits **two** events: `subscription.activated` (keyed to the order) and `subscription.payment_succeeded` (keyed to the charge). They are delivered independently, so neither order nor spacing is guaranteed. Provision access on `activated` and record the receipt on `payment_succeeded` — handling both as "a new subscriber" runs your onboarding twice. Cancellation splits into two moments. `subscription.canceling` fires the instant cancellation is requested; the termination itself is scheduled for the end of the paid period, and `subscription.canceled` fires once the payment provider confirms it — around `currentPeriodEnd`, not at the moment of the request. Between the two, the subscription is still active and the customer can withdraw the cancellation. An overdue subscription is terminated by the *next* failed renewal: the first decline moves `active` → `past_due` and emits `subscription.past_due`; a further decline in `past_due` ends the subscription and emits `subscription.canceled`. | Terminal State | Meaning | Event | | - | - | - | | `canceled` | Terminated after activation, or canceled before the first payment | `subscription.canceled` — only if it had been active | | `closed` | The payment window elapsed without a first payment | None | | `expired` | Fixed-term subscription reached its end | None | ### Refund Lifecycle ```mermaid theme={"system"} stateDiagram-v2 [*] --> pending: Customer-initiated ticket [*] --> processing: Merchant-initiated ticket, auto-approved pending --> approved: Approved
no event pending --> rejected: Rejected
no event approved --> processing: Dispatched to payment provider processing --> succeeded: Funds returned
refund.succeeded processing --> failed: Provider returned failure
refund.failed failed --> processing: Ticket resubmitted rejected --> [*] succeeded --> [*] ``` Refund events fire at the last step only — when the provider settles the outcome. Creating, approving, rejecting, or resubmitting a refund ticket produces no webhook, so a ticket sitting in review is invisible to your endpoint until it settles. Refunds requested through the API are auto-approved and go straight to `processing`; see [Refund Endpoints](/api-reference/endpoints/refunds/overview) for the ticket states and how to query them. ### When No Event Fires | Situation | Why | | - | - | | One-time payment declined | The order stays `pending` and remains payable — nothing has settled | | Checkout expired or the buyer canceled | The order ends `canceled` without ever being paid | | Subscription canceled or timed out before its first payment | It never activated, so `canceled` / `closed` carry no notification | | Fixed-term subscription reached its end | The end date was known at purchase | | Refund ticket created, approved, rejected, or resubmitted | Only the settled outcome is reported | *** ## Signature Verification **Always verify signatures in production.** Without verification, anyone can send forged requests to your endpoint. ### Algorithm ``` 1. Parse t (timestamp in ms) and v1 (Base64 signature) from X-Waffo-Signature header 2. Build signature input: `${t}.${rawRequestBody}` 3. Verify v1 using RSA-SHA256 with the Waffo public key 4. (Recommended) Check that t is within 45 minutes of current time. NOT 5: retries replay the ORIGINAL signature header — t is never re-stamped, and the final retry lands 31+ minutes after first delivery, so a 5-minute window rejects legitimate retries with 401. Replay protection comes from deduplicating on the payload id, not from tightening this window ``` ### Using the SDK (Recommended) The SDK embeds public keys, auto-detects the environment, and handles format normalization: ```typescript theme={"system"} import { verifyWebhook, WebhookEventType } from "@waffo/pancake-ts"; app.post("/webhooks", express.raw({ type: "application/json" }), (req, res) => { try { const event = verifyWebhook( req.body.toString("utf-8"), req.headers["x-waffo-signature"] as string, ); res.status(200).send("OK"); switch (event.eventType) { case WebhookEventType.OrderCompleted: // Deliver digital goods break; case WebhookEventType.SubscriptionActivated: // Provision subscription access break; case WebhookEventType.SubscriptionCanceled: // Revoke access break; } } catch { res.status(401).send("Invalid signature"); } }); ``` See the full [SDK Webhook documentation](/integrate/webhooks). ### Manual Verification If you're not using the TypeScript SDK, implement signature verification manually. ```javascript Node.js (Express) theme={"system"} const crypto = require('crypto'); // From Dashboard → API & Development → Webhook Public Key (PEM format) const WAFFO_WEBHOOK_PUBLIC_KEY = `-----BEGIN PUBLIC KEY----- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A... -----END PUBLIC KEY-----`; function parseSignatureHeader(header) { const parts = {}; for (const pair of header.split(',')) { const [key, ...rest] = pair.split('='); parts[key.trim()] = rest.join('=').trim(); } return parts; } function verifyWebhookSignature(rawBody, signatureHeader, publicKey) { const { t, v1 } = parseSignatureHeader(signatureHeader); if (!t || !v1) return false; // 45 minutes, NOT 5: retries carry the original t (it is never re-signed), // and the last retry arrives 31+ minutes after first delivery. True replay // protection is deduplicating on the payload id. const tolerance = 45 * 60 * 1000; if (Math.abs(Date.now() - Number(t)) > tolerance) return false; // Verify RSA-SHA256 signature const signatureInput = `${t}.${rawBody}`; const verifier = crypto.createVerify('RSA-SHA256'); verifier.update(signatureInput); return verifier.verify(publicKey, v1, 'base64'); } app.post('/webhooks', express.raw({ type: 'application/json' }), (req, res) => { const sig = req.headers['x-waffo-signature']; const rawBody = req.body.toString('utf-8'); if (!sig || !verifyWebhookSignature(rawBody, sig, WAFFO_WEBHOOK_PUBLIC_KEY)) { return res.status(401).send('Invalid signature'); } const event = JSON.parse(rawBody); res.status(200).send('OK'); // Process asynchronously handleEvent(event).catch(console.error); } ); async function handleEvent(event) { switch (event.eventType) { case 'order.completed': await grantAccess(event.data.buyerEmail, event.data.productName); break; case 'subscription.activated': await createSubscription(event.data.buyerEmail, event.data.orderId); break; case 'subscription.payment_succeeded': await recordReceipt(event.data.orderId, event.data.paymentId); break; case 'subscription.renewed': await extendSubscription(event.data.orderId, event.data.currentPeriodEnd); break; case 'subscription.recovered': await restoreAccess(event.data.orderId); break; case 'subscription.canceling': await markCanceling(event.data.orderId); break; case 'subscription.canceled': await revokeAccess(event.data.orderId); break; case 'subscription.past_due': await notifyPastDue(event.data.buyerEmail, event.data.orderId); break; case 'refund.succeeded': await revokeAccess(event.data.orderId); break; case 'refund.failed': await flagForReview(event.data.orderId); break; } } ``` ```python Python (Flask) theme={"system"} import json, time from base64 import b64decode from cryptography.hazmat.primitives import hashes, serialization from cryptography.hazmat.primitives.asymmetric import padding from flask import Flask, request app = Flask(__name__) WAFFO_WEBHOOK_PUBLIC_KEY = """-----BEGIN PUBLIC KEY----- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A... -----END PUBLIC KEY-----""" def verify_webhook_signature(raw_body, signature_header, public_key_pem): parts = dict(p.split("=", 1) for p in signature_header.split(",") if "=" in p) t, v1 = parts.get("t"), parts.get("v1") if not t or not v1: return False # 45 minutes, NOT 5: retries carry the original t (never re-signed), and # the last retry arrives 31+ minutes after first delivery. True replay # protection is deduplicating on the payload id. if abs(int(time.time() * 1000) - int(t)) > 45 * 60 * 1000: return False signature_input = f"{t}.{raw_body}".encode("utf-8") public_key = serialization.load_pem_public_key(public_key_pem.encode("utf-8")) try: public_key.verify(b64decode(v1), signature_input, padding.PKCS1v15(), hashes.SHA256()) return True except Exception: return False @app.route("/webhooks", methods=["POST"]) def handle_webhook(): sig = request.headers.get("X-Waffo-Signature", "") raw_body = request.get_data(as_text=True) if not verify_webhook_signature(raw_body, sig, WAFFO_WEBHOOK_PUBLIC_KEY): return "Invalid signature", 401 event = json.loads(raw_body) # Process event... return "OK", 200 ``` ```go Go (net/http) theme={"system"} package main import ( "crypto" "crypto/rsa" "crypto/sha256" "crypto/x509" "encoding/base64" "encoding/pem" "fmt" "io" "math" "net/http" "strconv" "strings" "time" ) const waffoPublicKeyPEM = `-----BEGIN PUBLIC KEY----- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A... -----END PUBLIC KEY-----` func verifyWebhookSignature(rawBody []byte, signatureHeader string) bool { var t, v1 string for _, pair := range strings.Split(signatureHeader, ",") { parts := strings.SplitN(pair, "=", 2) if len(parts) != 2 { continue } switch strings.TrimSpace(parts[0]) { case "t": t = strings.TrimSpace(parts[1]) case "v1": v1 = strings.TrimSpace(parts[1]) } } if t == "" || v1 == "" { return false } ts, err := strconv.ParseInt(t, 10, 64) if err != nil || math.Abs(float64(time.Now().UnixMilli()-ts)) > 45*60*1000 { return false } block, _ := pem.Decode([]byte(waffoPublicKeyPEM)) if block == nil { return false } pub, err := x509.ParsePKIXPublicKey(block.Bytes) if err != nil { return false } rsaPub, ok := pub.(*rsa.PublicKey) if !ok { return false } hash := sha256.Sum256([]byte(fmt.Sprintf("%s.%s", t, string(rawBody)))) sig, err := base64.StdEncoding.DecodeString(v1) if err != nil { return false } return rsa.VerifyPKCS1v15(rsaPub, crypto.SHA256, hash[:], sig) == nil } func webhookHandler(w http.ResponseWriter, r *http.Request) { rawBody, _ := io.ReadAll(r.Body) if !verifyWebhookSignature(rawBody, r.Header.Get("X-Waffo-Signature")) { http.Error(w, "Invalid signature", http.StatusUnauthorized) return } w.WriteHeader(http.StatusOK) w.Write([]byte("OK")) } func main() { http.HandleFunc("/webhooks", webhookHandler) http.ListenAndServe(":8080", nil) } ``` > [!WARNING] > > **You must use the raw request body for signature verification.** If your framework parses JSON automatically, the signature check will fail. Ensure you capture the unmodified raw string before verification. *** ## Response Requirements * Return **2xx** status code (recommended: `200`) * Respond within **10 seconds** * Response body does not matter ```javascript theme={"system"} // Recommended: respond immediately, process async app.post('/webhooks', (req, res) => { res.status(200).send('OK'); processEventAsync(req.body); }); ``` Non-2xx responses or timeouts trigger retries. *** ## Retry Policy Failed deliveries are retried automatically with exponential backoff: | Item | Details | | - | - | | Retries | Up to 3 (4 total attempts including the first) | | Backoff | Scheduled by the delivery queue with its default exponential backoff; Waffo does not configure the intervals, and there is no manual resend | | Timeout | Non-2xx or no response within the timeout window | | Final failure | Delivery marked as `failed` after all retries exhausted | ### Delivery Status | Status | Description | | - | - | | `pending` | Created, awaiting delivery or retrying | | `success` | Delivered successfully (your server returned 2xx) | | `failed` | All retries exhausted | View delivery history in the Dashboard webhook logs, including status, HTTP response code, and response body (truncated to 1000 characters). *** ## Handling Duplicates Network issues may cause the same event to be delivered multiple times. **Ensure your event handling is idempotent.** Use the `eventType` + `eventId` combination (which has a unique constraint in the system) for deduplication: ```javascript theme={"system"} async function handleEvent(event) { const exists = await db.query( 'SELECT 1 FROM processed_webhooks WHERE event_type = $1 AND event_id = $2', [event.eventType, event.eventId] ); if (exists.rows.length > 0) return; // Already processed await processEventLogic(event); await db.query( 'INSERT INTO processed_webhooks (event_type, event_id, processed_at) VALUES ($1, $2, NOW())', [event.eventType, event.eventId] ); } ``` > [!NOTE] > > The same business event (identical `eventType` + `eventId`) only creates one delivery record — it won't be duplicated. However, a single delivery may reach your endpoint multiple times due to retries. *** ## Best Practices > **Always verify signatures** > > Always verify `X-Waffo-Signature`. Without verification, anyone can send forged requests to your endpoint. > **Use HTTPS** > > Production webhook URLs must use HTTPS to protect data in transit. > **Respond fast, process async** > > Return `200` immediately and process business logic in the background. Slow responses cause unnecessary retries. > **Deduplicate with eventType + eventId** > > Use the `eventType` + `eventId` combination to deduplicate. Ensure the same delivery processed multiple times has no side effects. > **Check timestamps** > > Allow `t` up to **45 minutes** old. Retries replay the original signature header — `t` is never re-stamped — and the final retry lands 31+ minutes after first delivery, so a 5-minute window turns your own outage recovery into 401s. Deduplicate on the payload `id` for replay protection instead; it is unique per event and stable across retries. > **Use the correct environment key** > > Test and Production use different key pairs. Match the public key to the `mode` field in the payload. > **Log incoming payloads** > > Store received payloads for debugging. The Dashboard also provides delivery log queries. > **Handle all subscribed events** > > Add a branch for every event you subscribe to, even if you don't need it yet. Return `200` for unhandled events — returning an error triggers unnecessary retries. *** ## Testing ### Send Test Events (Recommended) Use the Dashboard "Send Test Event" button to send test events without triggering real transactions. Test events use fixed sample data (amount 0, taxAmount 0, product "\[TEST] Webhook Verification") and are always signed with the Test key. All 10 event types are supported — test each one to verify your handler. > [!WARNING] > > **`periodNumber` behaves differently in test events than in production.** > > | Event in a test send | `periodNumber` | > | - | - | > | Any `subscription.*` event (including `subscription.payment_succeeded`) | always `1` | > | `refund.succeeded` / `refund.failed` | **not sent** | > | `order.completed` | **not sent** | > > A test send has no subscription behind it, so the refund sample cannot say which period it > refunds. **In production a refund of a subscription charge does carry `periodNumber`** — the > period of the charge being refunded. Do not conclude from a test event that subscription > refunds lack the field; code your handler to read it when present. ### Use Test Mode 1. Configure the Test environment Webhook URL and events in the Dashboard 2. Perform real operations in Test mode (create orders, process payments) 3. Events are sent to your Test Webhook URL with Test signing keys ### Local Development Use a tunnel to expose your local server: ```bash theme={"system"} ngrok http 8080 # Use the generated URL as your Test Webhook URL # e.g., https://abc123.ngrok.io/webhooks ``` *** ## Delivery Logs View webhook delivery history in the Dashboard: * **Status**: pending / success / failed * **HTTP status code**: Your server's response code * **Response body**: Your server's response (truncated to 1000 chars) * **Timestamp**: Last delivery attempt *** ## FAQ ### Not receiving webhooks 1. Confirm the Webhook URL is configured in the Dashboard and publicly accessible 2. Confirm you've subscribed to the correct event types 3. Confirm you're using the correct environment (Test / Production) 4. Check that your firewall allows requests from Waffo 5. Try the Dashboard "Send Test Event" to isolate the issue ### Signature verification fails 1. Confirm you're using the correct environment's public key (Test vs Production) 2. Confirm you're using the **raw request body** — not a parsed JSON object 3. Check if any middleware or proxy modified the request body 4. Confirm the signature input format is `${t}.${rawBody}` (timestamp + dot + raw body) 5. If using TypeScript, switch to the [`@waffo/pancake-ts`](https://www.npmjs.com/package/@waffo/pancake-ts) SDK — it handles key selection and format normalization automatically ### Receiving duplicate events This is normal retry behavior. If your endpoint returned non-2xx or timed out, the system retries. Ensure your handler is idempotent — use the `eventType` + `eventId` combination for deduplication. ### Why does the first subscription payment produce two events? The first charge settles two facts at once: the subscription becomes active (`subscription.activated`, keyed to the order) and a payment was collected (`subscription.payment_succeeded`, keyed to the charge). They travel independently, so neither order nor spacing is guaranteed. Provision access on `activated`, record the receipt on `payment_succeeded`, and your first-payment path runs exactly once. ### When exactly does `subscription.canceled` arrive? Around `currentPeriodEnd` — not when the cancellation was requested. Requesting cancellation emits `subscription.canceling` immediately and schedules the termination for the end of the paid period; `subscription.canceled` follows once the payment provider confirms the termination. Use `currentPeriodEnd` from the `canceling` payload to know when access should end. ### Difference between `subscription.canceling` and `subscription.canceled` * **`canceling`**: Cancellation requested, but the current paid period hasn't ended. The subscription is still active and the customer can withdraw the cancellation (triggers `uncanceled`). **Do not revoke access.** * **`canceled`**: Subscription is terminated. This is irreversible — revoke access or downgrade permissions. ### What does `data.amount` mean for different events? All events: `data.amount` is the **transaction amount for that specific event** (including tax): * `order.completed` / `subscription.activated` — Payment amount * `subscription.payment_succeeded` — Amount charged for this period * `subscription.renewed` / `subscription.recovered` — Subscription per-period amount * `subscription.past_due` — Amount due for this period * `refund.succeeded` / `refund.failed` — Refund amount * `subscription.canceling` / `subscription.canceled` / `subscription.uncanceled` — Subscription per-period amount # Checkout Flow Source: https://docs.waffo.ai/checkout/checkout-flow How your customers complete purchases ## Checkout Overview Waffo Pancake uses a **two-step checkout flow** optimized for conversion. This design collects customer details first, then payment information, reducing abandonment and supporting accurate tax calculation. ## Two Ways to Check Out Waffo Pancake supports two checkout methods — choose the one that fits your use case: > **Product Purchase Link** > > **Permanent link** — never expires, stays valid even when you update the product. > > * Best for: sharing on websites, social media, email > * No code required > **Checkout Session (API)** > > **Dynamic link** — created via API with custom parameters. > > * Best for: custom checkout flows, dynamic pricing, metadata > * 24-hour default TTL (configurable, 1 minute to 7 days recommended) ### Product Purchase Links Every product gets a permanent purchase link: ``` https://pancake.waffo.ai/store/{store-slug}/product/{productId} ``` Test mode: ``` https://pancake.waffo.ai/store/{store-slug}/product/{productId}?test=true ``` A checkout session is created automatically when the customer opens the link. Just click "Copy Link" in the Dashboard. Add query parameters to pre-fill the checkout: | Parameter | Description | | - | - | | `currency` | Currency code (ISO 4217). Omit to let the page pick one | | `email` | Pre-fill the customer's email | | `success_url` | Redirect URL after a successful payment | | `country` | Pre-fill the billing country (ISO 3166-1 alpha-2) | | `is_business` | `true` for a business purchase. Only takes effect together with `country` | | `discount_code` | Apply a coupon code or promotion code. The code is locked — the customer cannot change or remove it, and no code entry field is shown. Works for one-time and subscription products (not for plan changes). See [Discounts](/guides/discounts#product-link-with-a-code) | | `test` | `true` opens the test-mode checkout | Without `discount_code`, the product page shows a code entry field when the store has a coupon or promotion code that can be used on the product. See [Code Entry Field](/guides/discounts#code-entry-field). ### Checkout Sessions (API) For advanced use cases, create a checkout session via the API: ```bash theme={"system"} POST /v1/actions/checkout/create-session ``` ### Authenticated vs Anonymous Checkout When creating sessions via the API, you can choose between two modes: * **Authenticated**: Provide `buyerIdentity` to bind orders to a stable identifier. Pre-fills the checkout form and enables post-purchase self-service. * **Anonymous**: No identity required. Buyer fills in details manually. Suitable for shared links and template stores. > [!WARNING] > > Authenticated checkout is strongly recommended when you know the buyer. See [SDK Checkout Modes](/integrate/sdks#checkout-modes) for details. The resulting checkout URL follows this structure: ``` https://checkout.waffo.ai/{store-slug}/checkout/{sessionId} ``` | Component | Description | | - | - | | `store-slug` | Your store's unique URL slug | | `sessionId` | Checkout session identifier (default 24-hour TTL, configurable, 1 minute to 7 days recommended) | > [!NOTE] > > Checkout sessions are generated server-side and lock the product version and price at creation time. ## Two-Step Checkout Flow **1. Consumer Details** Collect email, country, and billing info for tax calculation and order processing. **2. Payment** Enter card details or use Apple Pay / Google Pay to complete payment. ![Checkout page — Consumer details](https://mintcdn.com/waffo/fAGQ8sa2qycWEk2d/images/checkout/checkout-step1.png?fit=max\&auto=format\&n=fAGQ8sa2qycWEk2d\&q=85\&s=e7454a2c64f08d42fe0fa1ac4084b712) *** ## Session Lifecycle * **One session, one order.** A checkout session can produce exactly one order. Once the buyer submits, the session is consumed; opening the same `checkoutUrl` again shows "This checkout link has expired". That is expected — call create-session again for every purchase instead of reusing links. * **Browser back button.** Before handing off to the payment provider, the cashier swaps the current history entry for a replacement session that the server derives from the original one, and the provider's cancel URL points to the same address. Both ways back therefore land on a live session that keeps your `orderMerchantExternalId` and `metadata` — in any browser, because the values live in the session itself. The replacement session's TTL resets to the default 24 hours regardless of the `expiresInSeconds` you set. * **When the swap fails.** If that swap fails, or the buyer comes back to a session that has already been consumed or has expired, what happens depends on how the checkout was opened. A session you created with create-session shows "This checkout link has expired" and is never re-created, so your `orderMerchantExternalId`, `metadata` and custom price are never silently dropped — create a new session for the buyer. A Product Purchase Link jumps back to the product page and creates a fresh session; parameters you put on the link (`currency`, `email`, `success_url`) are not carried over. *** ## Step 1: Consumer Details The first step collects information needed for tax calculation and order processing. ### Required Fields | Field | Purpose | | - | - | | Email address | Receipt, account creation, Customer Portal access | | Country | Tax jurisdiction determination | ### Conditional Fields (Based on Country) | Field | When Required | | - | - | | ZIP/Postal Code | US, CA, UK, and most countries | | State/Province | US, CA, AU, IN | | City | EU countries (for VAT) | | Street Address | EU countries (full address for compliance) | ### Business Purchase Option Customers can toggle "I'm purchasing as a business" to provide: * Business name * Full billing address * Tax ID (optional, for VAT exemption) > [!NOTE] > > EU tax compliance requires full address for accurate VAT calculation and invoicing. *** ## Step 2: Payment ![Checkout — Payment](https://mintcdn.com/waffo/YbM_n4_eoBfrCsTT/images/checkout/checkout-step2.png?fit=max\&auto=format\&n=YbM_n4_eoBfrCsTT\&q=85\&s=e424a83d42c68d5946214be7f18cbbb7) The second step collects payment information. ### Payment Methods > **Card Payment** > > * Card number > * Expiry date (MM/YY) > * CVC/CVV > * Cardholder name > **Digital Wallets** > > * Apple Pay (iOS, Safari) > * Google Pay (Android, Chrome) > * One-click with biometric auth ### Order Summary Displayed alongside payment form: | Element | Description | | - | - | | Product name | What customer is buying | | Product image | Visual confirmation | | Subtotal | Product price | | Tax | Calculated from Step 1 location | | Total | Final amount to charge | ### Terms Agreement Customer must agree to terms before completing purchase. Links to: * Terms of Service * Privacy Policy * Merchant of Record disclosure *** ## Processing After payment submission: 1. **Card validation** - Luhn check, expiry, CVC 2. **3D Secure** - Bank verification (if required) 3. **Fraud check** - Risk assessment 4. **Authorization** - Charge to card 5. **Order creation** - Record in system Customer sees: * Animated loading indicator * "Processing your payment" message * Real-time status updates *** ## Result Pages ### Success Page On successful payment: * Order confirmation number * "Receipt sent to your email" message * Next steps or access instructions * Customer Portal link ### Failed Page On payment failure: * Clear error explanation * Suggested action * Retry button * Support contact option *** ## Subscription Checkout For subscription products, additional information displays: ### Billing Preview | Element | Example | | - | - | | Billing frequency | "Billed monthly" | | Recurring amount | "\$29.00/month" | | Next billing date | Calculated from today | ### Trial Information (if enabled) | Element | Example | | - | - | | Trial duration | "7-day free trial" | | First charge date | Date after trial ends | | Cancel anytime | Reassurance message | *** ## Multi-Language Support Checkout follows the shopper's browser language automatically, across 19 languages: | Language | Code | Language | Code | | - | - | - | - | | English | `en` | Italian | `it` | | Chinese (Simplified) | `zh` | Russian | `ru` | | Chinese (Traditional) | `zh-Hant` | Arabic | `ar` | | Japanese | `ja` | Hindi | `hi` | | Korean | `ko` | Thai | `th` | | German | `de` | Vietnamese | `vi` | | French | `fr` | Indonesian | `id` | | Spanish | `es` | Dutch | `nl` | | Portuguese | `pt` | Polish | `pl` | | | | Turkish | `tr` | Unsupported languages fall back to English. Shoppers can also switch languages from the selector in the checkout footer, and the payment page opens in whichever language they were using when they clicked Pay. See [Checkout Language](/features/checkout#checkout-language) for details. *** ## Test Checkout Use Test Mode to try the checkout flow without real charges. ### Test Card Numbers | Card | Number | Result | | - | - | - | | Visa Credit | `4576 7500 0000 0110` | Success | | Mastercard Credit | `2226 9000 0000 0110` | Success | | Visa Debit | `4001 7000 0000 0110` | Success | | Mastercard Debit | `2226 9300 0000 0110` | Success | | Visa Credit | `4576 7500 0000 0220` | Declined | | Mastercard Credit | `2226 9000 0000 0220` | Declined | Any future expiry date and any 3-digit CVC will work. > [!NOTE] > > Test mode is indicated by a banner: "Test Mode - No real charges will be made" *** ## Error Handling ### Common Payment Errors | Error | Cause | Customer Action | | - | - | - | | Card declined | Insufficient funds or bank block | Try different card | | Invalid card | Incorrect card number | Check and re-enter | | Expired card | Card past expiration | Use valid card | | CVC mismatch | Wrong security code | Re-enter CVC | | 3DS failed | Bank verification failed | Contact bank | ### Error Display Error messages are: * Clear and actionable * Non-technical language * Include helpful next steps * Do not expose sensitive data *** ## Checkout Security ### Product Purchase Links * Link is permanent and public — no sensitive data is embedded * A fresh checkout session is created server-side each time a customer opens the link * Product version and pricing are resolved at the moment of access ### Checkout Sessions (API) * Sessions lock the product version and price snapshot at creation time * Sessions include a cryptographic signature and cannot be tampered with * Sessions expire after 24 hours by default (configurable via `expiresInSeconds`, 1 minute to 7 days recommended) > [!WARNING] > > Checkout sessions expire after 24 hours by default. Use `expiresInSeconds` to change this (1 minute to 7 days recommended). Customers must start a new session after expiration. *** ## Merchant of Record Notice At checkout footer, customers see: > "This order is processed by our online reseller & Merchant of Record, Waffo Pancake, who also handles order-related inquiries and returns." This disclosure is required for MoR compliance and helps customers understand the payment relationship. *** ## Next Steps > **[Payment Methods](/payments/methods)** > > Supported cards and wallets > **[Customization](/features/checkout)** > > Brand your checkout experience # Checkout Customization Source: https://docs.waffo.ai/checkout/customization Brand your checkout experience with custom colors, logo, and style import ## Customization Overview Make your checkout page match your brand. Customize colors manually, or import styles directly from your website URL. ## Accessing Checkout Settings 1. Go to Dashboard → Settings 2. Select the "Checkout" tab 3. Customize and preview changes in real-time 4. Save to apply to both light and dark themes *** ## Import from Website URL The fastest way to brand your checkout — paste your website URL and Waffo Pancake automatically extracts your brand colors, border radius, and favicon. **1. Enter Your Website URL** In the Checkout Settings panel, find the "Import from Website" section and paste your website URL (e.g., `https://yoursite.com`). **2. Click Extract** Click the **Extract** button. The system analyzes your website's CSS and extracts brand colors. **3. Review & Adjust** Extracted colors are applied to the current theme mode. Review the live preview and fine-tune any values if needed. ### How It Works Style extraction uses a 3-tier strategy for maximum accuracy: | Tier | Method | What It Extracts | | - | - | - | | **1** | CSS Variables | `--primary`, `--brand`, `--accent` and similar CSS custom properties | | **2** | CSS Rule Parsing | Button backgrounds, heading colors, body styles from actual CSS rules | | **3** | AI Fallback | When tiers 1-2 yield insufficient results, an AI model analyzes the HTML/CSS context to identify brand colors | ### Extracted Properties | Property | Source | | - | - | | Primary Color | Brand/accent color from buttons and CTAs | | Background Color | Page background color | | Card Color | Derived from background color (slightly lighter/darker) | | Text Color | Main body text color | | Border Radius | Most common border-radius used on the site | | Logo | Site favicon (converted to base64) | > [!TIP] > > If your store's website URL is already set in Store Settings, it will be pre-filled automatically. > [!NOTE] > > AI-assisted extraction is rate-limited to 10 requests per store per day. CSS-based extraction (tiers 1-2) has no limit. *** ## Logo Upload your brand logo to appear on the checkout page. | Setting | Specification | | - | - | | Format | PNG, JPG, SVG | | Recommended Size | 200 × 50 px | | Max File Size | 2 MB | | Background | Transparent recommended | > [!TIP] > > Use a horizontal logo for best results. When importing from a website URL, the site's favicon is automatically used as the logo. *** ## Theme Mode Each theme maintains its own set of color values. Switch between modes to customize each independently. > **Light Theme** > > White background, dark text. Best for most brands. Professional appearance. > **Dark Theme** > > Dark background, light text. Modern aesthetic. Reduces eye strain. *** ## Color Settings Customize the checkout color scheme for the current theme mode: | Setting | Field Name | Default (Light) | Default (Dark) | | - | - | - | - | | **Primary Color** | `checkoutColorPrimary` | #111111 | #FEFDFD | | **Background Color** | `checkoutColorBackground` | #F4F4F4 | #111315 | | **Card Color** | `checkoutColorCard` | #FFFFFF | #181A1B | | **Text Color** | `checkoutColorText` | #111111 | #FFFFFF | For each color setting, click the color swatch to open the color picker, or enter a hex code directly. > [!NOTE] > > Ensure sufficient contrast between text and background colors for accessibility. WCAG recommends a contrast ratio of at least 4.5:1. ### Border Radius Control the roundness of UI elements with the `checkoutBorderRadius` setting. In the Dashboard this is a slider from **0 to 24px** in 1px steps — any value in that range is valid, not a fixed set of presets. | Value | Style | | - | - | | `0px` | Sharp corners | | `4px` | Subtle rounding | | `8px` | Standard (default) | | `16px` | Large rounding | | `24px` | Maximum rounding | *** ## Live Preview The preview panel shows your checkout page in real-time as you make changes. * **Desktop view** — Full-width checkout layout * **Mobile view** — Phone-sized checkout layout * **Product selector** — Preview with different products from your store Changes update instantly in the preview without saving. *** ## API Reference Checkout settings are saved as part of the store's `checkoutSettings` object: ```json theme={"system"} { "checkoutSettings": { "light": { "checkoutLogo": "https://...", "checkoutColorPrimary": "#111111", "checkoutColorBackground": "#F4F4F4", "checkoutColorCard": "#FFFFFF", "checkoutColorText": "#111111", "checkoutBorderRadius": "8px" }, "dark": { "checkoutLogo": null, "checkoutColorPrimary": "#FEFDFD", "checkoutColorBackground": "#111315", "checkoutColorCard": "#181A1B", "checkoutColorText": "#FFFFFF", "checkoutBorderRadius": "8px" } } } ``` Update via the [Update Store](/api-reference/endpoints/stores/update-store) endpoint with `checkoutSettings` in the request body. *** ## Store Information | Option | Description | | - | - | | Store Name | Shown in checkout header | | Support Email | For customer questions | | Terms Link | Link to your terms of service (required) | | Privacy Link | Link to your privacy policy (required) | *** ## Best Practices > **Brand Consistency** > > * Use the **Import from Website** feature to automatically match your site's colors > * Use the same logo as your main site > * Consistent color palette builds trust > **Customize Both Themes** > > * Many customers use dark mode — customize both light and dark themes > * Ensure your logo works on both light and dark backgrounds > * Test color contrast in both modes > **Mobile Optimization** > > * Use the mobile preview to check layout > * Ensure logos scale properly on small screens > * Verify touch targets are adequate > **Accessibility** > > * Maintain sufficient color contrast (4.5:1 minimum) > * Readable font sizes > * Test with different color vision profiles *** ## Reset to Default To reset the current theme mode to default: 1. Click "Reset" in the Checkout Settings 2. Default Waffo Pancake colors will be restored for the current mode (light or dark) > [!WARNING] > > Resetting cannot be undone. Your current customizations for that theme mode will be lost. *** ## Checkout Language Checkout language needs no configuration here — it follows the shopper's browser language automatically, and shoppers can switch it themselves. See [Multi-Language Support](/features/checkout#checkout-language) for the 19 supported languages and the resolution order. # Analytics Source: https://docs.waffo.ai/dashboard/analytics Business insights and performance metrics ## Analytics Overview The Analytics page provides comprehensive insights into your business performance with interactive charts and key metrics. ![Analytics Dashboard](https://mintcdn.com/waffo/5dRlk76Jm-9Zm6Tj/images/dashboard/analytics.png?fit=max\&auto=format\&n=5dRlk76Jm-9Zm6Tj\&q=85\&s=a563e9b0e5a674b8f5be91baad2bf10e) *** ## Key Metrics Six KPI cards sit at the top of the page, each with a sparkline and a comparison against the previous period: | Metric | Description | | - | - | | **Gross Volume** | Total value of successful payments in the period | | **MRR** | Monthly Recurring Revenue — a point-in-time snapshot, not a period sum | | **Subscriptions** | Active subscriptions at the end of the period | | **New Customers** | Customers acquired in the period | | **Payment Success** | Share of payment attempts that succeeded | | **Refund Rate** | Share of volume refunded | > [!NOTE] > > MRR and Subscriptions are **snapshots**, so their sparklines show the value at each point rather than a total accumulated over the period. *** ## Cancellation Reasons A card at the bottom of the page breaks down why customers left. | | | | - | - | | **Shows** | Each reason with a share bar, a count, and a total | | **Source** | The optional picker in the [Customer Portal](/features/customer-portal#cancellation-feedback) cancellation dialog | | **Skipped** | Counted as *not provided*, so the denominator stays honest | > [!WARNING] > > Counts **cancellation actions, not subscriptions**. Cancel → reactivate → cancel contributes two, so this total can exceed the number of subscriptions that actually ended. *** ## Charts & Visualizations ### Revenue Chart Interactive line chart showing: * Daily/weekly/monthly revenue * Trend lines and comparisons * Period-over-period growth **Time Ranges:** * Last 7 days * Last 30 days * Last 90 days * Last 12 months * Custom range ### Transaction Volume Bar chart displaying: * Number of transactions per period * Successful vs failed breakdown * Average transaction size ### Customer Geography Visual breakdown of customers by location: * Country distribution map * Top markets by revenue * Regional growth trends > **Top Countries** > > See which countries generate the most revenue. > **Currency Split** > > Revenue breakdown by transaction currency. *** ## Date Range Selection ### Quick Filters | Filter | Period | | - | - | | 7d | Last 7 days | | 30d | Last 30 days | | 90d | Last 90 days | | 1y | Last year | | All | Everything on record | ### Custom Range Select specific start and end dates for detailed analysis. ### Comparison Enable comparison mode to see: * Period-over-period changes * Percentage growth/decline * Trend indicators *** ## Metric Cards Each metric card displays: | Element | Description | | - | - | | **Value** | Current metric value | | **Change** | % change from previous period | | **Trend Arrow** | Up (green) or down (red) indicator | | **Sparkline** | Mini chart showing recent trend | > [!TIP] > > Click on any metric card to see a detailed breakdown and drill-down analysis. *** ## Export Analytics exports to **CSV** — a revenue file and a summary file, covering the currently selected date range. For programmatic access to the same figures, query the [GraphQL analytics endpoints](/api-reference/endpoints/graphql/analytics) rather than exporting. *** ## Breakdowns The page is scoped by **date range and granularity only** — there are no product, customer-segment, or payment-method filters. Breakdowns come from the charts themselves: | Breakdown | Where | | - | - | | Revenue by product | Product revenue chart — click the legend to show or hide individual products | | Revenue by country | Geographic revenue chart | | Top items | Top items list | > [!NOTE] > > Legend clicks change what the chart draws, not what the data covers. KPI cards and totals are unaffected. *** ## Understanding Your Data ### Test vs Live Mode > [!WARNING] > > Analytics data is separate for Test and Live modes. Ensure you're viewing the correct environment. ### Data Freshness | Data Type | Update Frequency | | - | - | | Transactions | Real-time | | Aggregated Metrics | Every 5 minutes | | Charts | Every 15 minutes | ### Timezone All analytics use UTC timezone. Timestamps are converted to your local timezone for display. *** ## Best Practices > **Track Key KPIs** > > Focus on metrics that matter: > > * MRR for subscription health > * Churn rate for retention > * LTV for customer value > **Set Benchmarks** > > Compare against: > > * Your historical performance > * Industry averages > * Growth targets > **Review Regularly** > > Schedule time to review: > > * Daily: Transaction volume > * Weekly: Revenue trends > * Monthly: Full business review # Customers Source: https://docs.waffo.ai/dashboard/customers Manage your customer database and relationships ## Customer Management The Customers page provides a complete view of everyone who has interacted with your products. ![Customers List](https://mintcdn.com/waffo/5dRlk76Jm-9Zm6Tj/images/dashboard/customers-list.png?fit=max\&auto=format\&n=5dRlk76Jm-9Zm6Tj\&q=85\&s=5f3ea2b1ef174570603c9dba6c5774ba) ## Customer List View all your customers in a sortable, filterable table: | Column | Description | | - | - | | First Seen | When the customer first appeared | | Email | Customer email address | | Country | Customer location (with flag) | | Status | Current customer status | | Subscriptions | Active subscription count | | Payments | Total payment count | | MRR | Monthly Recurring Revenue from this customer | | Revenue | Total lifetime revenue | ## Customer Statuses > **Active** > > Has made payments but no active subscriptions. > **Subscribed** > > Has one or more active subscriptions. > **Churned** > > Previously had subscriptions that are now canceled. > **Inactive** > > No recent activity or purchases. ## Customer Details Click on a customer row to view their full profile: ### Overview Tab * Email and name * Location * Account creation date * Total lifetime value * Current MRR ### Subscriptions Tab * All subscriptions (active and past) * Subscription status * Billing interval * Next billing date * Actions (pause, cancel) ### Payments Tab * Full payment history * Payment status * Amounts and currencies * Refund status * Associated products ## Filtering Customers Use filters to segment your customer base: | Filter | Options | | - | - | | Status | Active, Subscribed, Churned, Inactive | | Country | Any country | | Date Range | First seen date | | Has Subscription | Yes/No | ### Search Search customers by: * Email address * Customer name * Customer ID ## Customer Metrics ### Statistics Cards | Metric | Description | | - | - | | Total Customers | All unique customers | | Active | Customers with recent activity | | Countries | Number of different countries | | Avg. LTV | Average customer lifetime value | ### Geography Distribution A breakdown of your customers by country: * Top 5 countries displayed * Customer count per country * Revenue per region ## Customer Actions > **View Customer Portal** > > Generate a link to let customers manage their own subscriptions. > **Create Manual Payment** > > Process a one-time charge for an existing customer. > **Cancel Subscription** > > Cancel a customer's active subscription immediately or at period end. > **Refund Payment** > > Issue a full or partial refund for a past payment. > **Export Customer Data** > > Download customer information for GDPR compliance or analysis. ## Customer Portal Waffo Pancake provides a self-service portal where customers can: * View their active subscriptions * Update payment methods * Download invoices * Cancel subscriptions * View payment history To give a customer access: 1. Go to customer details 2. Click "Generate Portal Link" 3. Send the secure link to the customer > [!NOTE] > > Portal links are time-limited for security. Generate a new link if the customer needs extended access. ## Data Export Click **Export** to download your customer data as CSV. > [!WARNING] > > The export always contains **every customer**, not just the rows matching your current filters. Filter the file after downloading it. The column set is fixed — there is no field picker: | Column | Contents | | - | - | | Email | Customer email address | | Country | ISO-2 country code | | Status | Customer status | | Currency | Currency they transact in | | Revenue | Total revenue from this customer | | Subscriptions | Number of subscriptions | | Payments | Number of payments | | First Purchase | ISO-8601 date | | Last Active | ISO-8601 date | # Coupons Source: https://docs.waffo.ai/dashboard/discounts Create coupons and promotion codes, hand out codes per channel, and see how often they are used ## Coupon Management The Coupons page is where you set up discounts for your store. A **coupon** defines the offer — how much off, which products, when it ends and how many times it can be claimed — and comes with one **promotion code** that customers enter at checkout. To hand the same offer out per channel or audience, add more promotion codes to the coupon, each with its own conditions. For how discounts behave at checkout and on subscriptions, see [Discounts & Promotions](/guides/discounts). Coupons belong to one environment: the page follows the **Test Mode** switch, and a coupon created in test mode does not work in live mode. Use [Copy to live](#copying-a-coupon-to-live) once it is ready. ![Coupons list](https://mintcdn.com/waffo/fzyQe5Jh5yF_yUiY/images/dashboard/discounts-list.png?fit=max\&auto=format\&n=fzyQe5Jh5yF_yUiY\&q=85\&s=997ad1e53892442a1a6cd14a0f056120) ## Coupon List The overview cards show active coupons, redemptions across all coupons, the most used coupon and how many extra promotion codes you have added. Below them, coupons are listed with: | Column | Description | | - | - | | Name | The coupon's name (only you see it) and its discount, duration and limits | | Promotion code | The coupon's default code. Expand a row to see its extra codes | | Status | Active, Used up, Expired, Deactivated or Failed — hover a status for what it means | | Used / limit | Redemptions across all of the coupon's codes, against its total limit | | Expires | The coupon's redeem-by date, or no expiry | | Products | All products, or how many products it is limited to | Filter the list with the **All / Active / Ended / Deactivated / Failed** tabs, or search by name or by promotion code — a search by code also matches the extra codes of a coupon. ### Coupon Status | Status | Meaning | | - | - | | Active | Customers can claim the coupon now by entering one of its codes | | Used up | Claimed as many times as its limit allows; its codes are rejected at checkout | | Expired | Past its redeem-by date; its codes are rejected. The date cannot be changed — create a new coupon to extend | | Deactivated | Deactivated by you; its codes are rejected. Discounts already on subscriptions keep running until the subscription's next plan change | | Failed | The coupon could not be created. Its code has been released, so you can create it again with the same code | ## Creating a Coupon ![Create coupon](https://mintcdn.com/waffo/fzyQe5Jh5yF_yUiY/images/dashboard/discounts-create.png?fit=max\&auto=format\&n=fzyQe5Jh5yF_yUiY\&q=85\&s=e28dc699e3ebfceea1892fda047e679b) **1. Click 'New coupon'** Find the button in the top right of the Coupons page. **2. Name the coupon** The name helps you spot the coupon in the list; customers only ever see the promotion code. **3. Choose the products** The coupon applies to every product by default. Switch on **Limit to specific products** to pick the products it works for. **4. Set the discount** A percentage off, or a fixed amount off with one amount for each currency the selected products are priced in. **5. Set the duration** For subscriptions only: discount the first payment, the first N billing cycles, or every payment. **6. Set the promotion code and limits** A code is generated for you; keep it or type your own. Optionally add an expiry date, a total redemption limit, and extra promotion codes. **7. Create** The summary on the right shows what the coupon does. Click **Create coupon**. > [!WARNING] > > Only the name can be changed after creation. To change the promotion code, discount, products, expiry or redemption limit, create a new coupon. ### Coupon Fields | Field | Required | Description | | - | - | - | | Name | Yes | Internal name, not shown to customers | | Products | No | All products by default, or a selection. A product not published to the current environment cannot be selected | | Type | Yes | Percentage or fixed amount | | Percent off | For percentage | Above 0 and up to 100, with at most 2 decimals | | Amount off | For fixed amount | One amount per currency, following the currencies your products are priced in. A currency not listed gets no discount — there is no conversion | | Duration | Yes | Once (first payment only), multiple billing cycles, or forever. One-time products are always discounted once | | Promotion code | Yes | 3–32 letters, digits or `-`, case-insensitive. Must not be in use by another active code in this store | | Expiry date | No | Redeemable until the end of that day in your time zone. When the coupon expires, discounts already applied to subscriptions also end | | Redemption limit | No | How many times the coupon can be claimed in total, across all of its promotion codes | > [!NOTE] > > A paid trial period uses the discount: a once coupon is used up by the trial, and a multi-cycle coupon counts the trial as its first cycle. Free trials don't use it. ### Adding Promotion Codes While Creating Switch on **Add more promotion codes** to hand out extra codes for the same coupon right away — up to 20 single codes, each with its own conditions, or a batch generated with a prefix. Every extra code claims the same coupon with the same discount; its uses and expiry cannot exceed the coupon's. You can also add codes later on the coupon page. ## Coupon Details Click a coupon row to open its details. The panel shows the discount, the default promotion code, the duration, redemptions against the limit, the expiry, the products it applies to, and all of its promotion codes. ![Coupon details](https://mintcdn.com/waffo/fzyQe5Jh5yF_yUiY/images/dashboard/discounts-detail.png?fit=max\&auto=format\&n=fzyQe5Jh5yF_yUiY\&q=85\&s=073f24c5e9fa5a0e15b7d36eb4f4a19f) From here you can: * **Rename** the coupon * **Add promotion code** — a single code, or a batch (see below) * **Export CSV** of the promotion codes * **Deactivate** the coupon or one of its promotion codes * **Copy to live** a test-mode coupon ### Promotion Codes Whichever of a coupon's codes a customer enters at checkout, they claim that coupon. A promotion code only adds conditions of its own: | Condition | Description | | - | - | | Only specific customers can use it | Customer emails, separated by commas or new lines | | This code can be used up to N times | Cannot exceed the coupon's limit | | Each customer can use it up to N times | Lifetime uses per customer | | This code's expiry date | Cannot be later than the coupon's expiry | | Minimum order amount | Per currency, before discount and tax. Other currencies have no minimum | Filter the codes by **All / Active / Deactivated** or search by code. A code can be deactivated on its own; this is permanent, and the code can then be reused by a new promotion code. > [!NOTE] > > A promotion code cannot be added to a coupon that is deactivated, expired, or failed to create. ### Generating Codes in Bulk In **Add promotion code**, switch to **Generate in bulk** to create up to 500 codes at once, with an optional prefix (up to 12 characters) and the same conditions for every code — for example single-use codes for a newsletter. When they are ready you can copy them all or download them as CSV; the CSV can be exported again from the coupon details at any time. ![Generated promotion codes](https://mintcdn.com/waffo/fzyQe5Jh5yF_yUiY/images/dashboard/discounts-generated.png?fit=max\&auto=format\&n=fzyQe5Jh5yF_yUiY\&q=85\&s=810ffc9166b0e92141b693a93c6c1458) ### Deactivating a Coupon Deactivating is permanent: the coupon and all of its promotion codes stop working for new orders, and their codes are released for reuse. Discounts already on subscriptions continue until the subscription's next plan change — see [Discounts & Promotions](/guides/discounts#when-the-discount-ends). ## Copying a Coupon to Live A coupon created in test mode can be copied to the live environment from its details once your store has passed review. The copy is a new coupon with the same settings and its redemptions start at 0. Optionally copy its active, unexpired promotion codes along with it, with the same conditions. * Products not yet published to live are left out of the copy; if none of the coupon's products are published, publish them first. * If the coupon's expiry has already passed, the live coupon gets no expiry, and its expired promotion codes are not copied. * A code already in use on live stops the copy — deactivate it there first, or copy without promotion codes. ## Next Steps > **[Discounts & Promotions](/guides/discounts)** > > How codes are checked at checkout and how subscriptions are discounted > **[Coupon Endpoints](/api-reference/endpoints/coupons/overview)** > > Create coupons and promotion codes from your server # Home Source: https://docs.waffo.ai/dashboard/home Your business overview at a glance ## Home Page Overview The Dashboard Home page provides a comprehensive view of your business performance with key metrics, charts, and recent activity. ![Dashboard Home](https://mintcdn.com/waffo/5dRlk76Jm-9Zm6Tj/images/dashboard/dashboard-home.png?fit=max\&auto=format\&n=5dRlk76Jm-9Zm6Tj\&q=85\&s=ef7a656db04f495080b0c7ae09968e92) ## Statistics Cards At the top of the Home page, you'll find key performance indicators: | Metric | Description | | - | - | | **Total Revenue** | Sum of all successful payments | | **MRR** | Monthly Recurring Revenue from active subscriptions | | **Customers** | Total number of unique customers | | **Sales** | Number of successful one-time payments | | **Active Subscriptions** | Currently active subscription count | > [!NOTE] > > Statistics are calculated based on your current mode (Test or Live). Make sure you're viewing the correct mode for accurate data. ## Charts and Visualizations ### Transaction Volume Chart An interactive line chart showing: * Daily transaction counts * Revenue trends over time * Selectable date ranges (7 days, 30 days, 90 days) ### Customer Geography A visual breakdown of your customers by region: * Country distribution * Top markets * Geographic revenue concentration ## Recent Activity ### Recent Transactions A table showing your latest payments: | Column | Description | | - | - | | Date | Transaction timestamp | | Customer | Customer email | | Amount | Payment amount with currency | | Status | Payment status (Paid, Pending, etc.) | | Product | Associated product name | ### Recent Customers Your newest customer signups with: * Customer email * Sign-up date * Country * First purchase status ## Quick Actions From the Home page, you can quickly: > **Create Product** > > Add a new product to your catalog > **View Payments** > > See all transactions > [!NOTE] > > CSV export lives on the individual pages — [Payments](/dashboard/payments#exporting-payments), [Customers](/dashboard/customers#data-export), Subscriptions, and [Analytics](/dashboard/analytics#export) — not on the home page. ## Data Refresh Dashboard data updates automatically. You can also: * Pull to refresh on mobile * Click the refresh icon to force update * Data typically updates within seconds of new transactions ## Time Periods Filter your Home page data by time period: * **Today** - Current day only * **Last 7 Days** - Previous week * **Last 30 Days** - Previous month * **Last 90 Days** - Previous quarter * **Custom Range** - Select specific dates ## Currency Display * Main totals show in your default currency * Individual transactions show in their original currency * Exchange rates are applied for aggregations # Payments Source: https://docs.waffo.ai/dashboard/payments Track transactions and manage refunds ## Payments Overview The Payments page shows all transactions processed through your store, including one-time purchases and subscription charges. ![Payments List](https://mintcdn.com/waffo/5dRlk76Jm-9Zm6Tj/images/dashboard/payments-list.png?fit=max\&auto=format\&n=5dRlk76Jm-9Zm6Tj\&q=85\&s=132d6aa291132199c1cb507c4eefea64) ## Payment List View all payments in a comprehensive table: | Column | Description | | - | - | | Date | Transaction timestamp | | Amount Paid | Gross payment amount | | Tax Amount | Tax collected | | Status | Payment status | | Payment Method | Card type and last 4 digits | | Description | Payment description or product name | | Customer | Customer email | | Product | Associated product | ## Payment Statuses > **Paid** > > Successfully processed and funds received. > **Pending** > > Payment initiated but not yet confirmed. > **Refunded** > > Full amount has been refunded. > **Partial Refund** > > Part of the payment has been refunded. > **Declined** > > Payment was rejected by the payment processor. > **Disputing** > > The customer filed a refund ticket that is still open. > **Chargeback** > > Customer disputed the charge with their bank. > [!NOTE] > > **Disputing** and **Chargeback** are different escalations: > > * **Disputing** — a refund ticket filed with you. Resolve it directly. > * **Chargeback** — escalated to the cardholder's bank. Carries fees and affects your merchant reputation. > > Settling a dispute is what stops it becoming a chargeback. ## Filtering Payments Filter your payment list by: | Filter | Options | | - | - | | Status | All, Paid, Pending, Refunded, Declined, Disputing, Chargeback | | Product | Any product in your catalog | | Date Range | Custom start and end dates | | Customer | Search by email | | Amount | Min/Max amount range | ### Search Search payments by: * Payment ID * Customer email * Product name * Last 4 digits of card ## Payment Details Click on any payment to view full details: ### Transaction Info * Payment ID * Amount and currency * Tax amount * Net amount (after fees) * Timestamp * Test/Live mode indicator ### Payment Method * Card brand (Visa, Mastercard) * Last 4 digits * Expiration date * Country of issue ### Customer Info * Email * Name (if provided) * IP address * Country ### Associated Records * Product purchased * Subscription ID (if applicable) * Invoice link ## Processing Refunds **1. Find the Payment** Locate the payment in the list or use search. **2. Click 'Refund'** Open the payment details and click the Refund button. **3. Choose Refund Type** * **Full Refund** - Return the entire amount * **Partial Refund** - Enter a custom amount **4. Add Reason (Optional)** Document why the refund is being processed. **5. Confirm** Review and confirm the refund. > [!WARNING] > > Refunds typically take 5-10 business days to appear on the customer's statement. Refunds cannot be reversed once processed. ### Refund Policies | Scenario | Recommendation | | - | - | | Duplicate charge | Full refund | | Partial service used | Partial refund | | Service issue | Full or partial based on situation | | Fraud | Full refund + review account | ## Payment Statistics At the top of the Payments page: | Metric | Description | | - | - | | Total Revenue | Sum of all paid transactions | | Net Revenue | Total revenue minus refunds | | Total Refunded | Sum of all refunds issued | | Successful | Count of successful payments | | Avg. Order Value | Average payment amount | ## Payment Methods Buyers can pay by card or digital wallet. Which options appear at checkout depend on the buyer's device, region, and — most importantly — the order's pricing currency. ### Global Methods Available to buyers worldwide. > **Cards** > > Visa and Mastercard — credit, debit, and prepaid, worldwide. > **Apple Pay** > > iOS and Safari, where Apple Pay is enabled. > **Google Pay** > > Android and Chrome, where Google Pay is enabled. ### Local Methods Region-specific methods, shown to buyers in their market. > **WeChat Pay** > > Mainland China and Hong Kong, for USD and CNY orders. > [!NOTE] > > **Alipay is not available to buyers yet.** The Alipay you see on the payout pages is a payout destination for merchants, not a buyer payment method. Buyer-side Alipay is in progress and will be announced when it opens. ### Method and Currency Support Each method supports a specific set of currencies. The order's pricing currency decides which methods a buyer sees at checkout. | Pricing currency | Cards | Apple Pay | Google Pay | WeChat Pay | | - | :-: | :-: | :-: | :-: | | USD | ✓ | ✓ | ✓ | ✓ | | EUR | ✓ | ✓ | ✓ | — | | GBP | ✓ | ✓ | ✓ | — | | JPY | ✓ | ✓ | ✓ | — | | HKD | ✓ | ✓ | ✓ | — | | CNY | — | — | — | ✓ | > [!NOTE] > > **CNY is WeChat Pay only.** An order priced in CNY can be paid **only** with WeChat Pay — cards and other wallets don't accept CNY. WeChat Pay itself accepts only **USD and CNY**. ### Per-Order Price Limits A product's price must fall within the range allowed for its currency. Prices outside the range are rejected when you create or edit the product. | Currency | Minimum | Maximum | | - | - | - | | USD | \$1.00 | \$10,000.00 | | EUR | €1.00 | €9,400.00 | | GBP | £1.00 | £8,150.00 | | JPY | JP¥100 | JP¥1,600,000 | | CNY | CN¥1.00 | CN¥1,000.00 | | HKD | HK\$8.00 | HK\$77,600.00 | ### WeChat Pay Notes Beyond the currency rules above, WeChat Pay only appears at checkout when: * The order is a **one-time payment** — WeChat Pay does not support subscriptions. * The buyer is within the WeChat limit: **¥1,000 CNY (roughly \$140 USD) per buyer, per merchant, per calendar month**, counted across all of that buyer's WeChat payments to you. It is a cumulative monthly cap, not a per-order cap — a repeat buyer can reach it mid-month. When an order doesn't qualify, WeChat Pay is hidden and the buyer pays by card, Apple Pay or Google Pay. The limit is set by WeChat and may change. > [!NOTE] > > **USD-priced orders paid with WeChat Pay settle via HKD.** The USD price is converted to HKD for settlement, then to CNY when the buyer pays. The two conversions may use different rates, so the CNY amount the buyer actually pays can differ slightly from a direct USD-to-CNY conversion. Card payments convert too — see [Local Currency Pricing](/features/local-currency). > [!NOTE] > > **Three practical points.** > > * WeChat Pay acquiring is provided by Waffo under its own agreement with WeChat Pay HK. You do not apply for a WeChat merchant account of your own. > * On Android, the buyer must open the cashier in a browser that can launch the `weixin://` scheme. Some in-app browsers cannot; have the buyer open the page in the system browser, or pay on desktop by scanning the QR code. > * For CNY-priced products the WeChat payment sheet also shows an HKD-converted amount. That reflects the channel's settlement path and is expected. > **[Request a payment method](https://docs.google.com/forms/d/e/1FAIpQLSdJY9RDcUsUQ83bkUNWB_irQ0uFl4D_BhznFQ9p9cOhrKxK6A/viewform)** > > Need a regional method we don't list yet? Tell us which one and where you sell — submissions feed directly into our roadmap prioritization. ## Chargebacks When a customer disputes a charge: 1. You'll receive a notification 2. Payment status changes to "Chargeback" 3. Funds are held pending resolution 4. You can submit evidence to fight the dispute > [!NOTE] > > Chargebacks carry fees and can impact your merchant reputation. Prevent them with clear product descriptions, good customer service, and recognizable billing descriptors. ## Exporting Payments Export payment data for accounting or analysis: 1. Apply desired filters 2. Click "Export" 3. Select format (CSV or PDF) 4. Download the file Export includes: * All payment details * Customer information * Tax amounts * Refund status * Timestamps * Your external order ID, when one was set at checkout > [!TIP] > > Set `orderMerchantExternalId` on [`checkout/create-session`](/api-reference/endpoints/orders/create-checkout-session) to carry your own order number into the transaction detail view and the CSV export — exported rows then reconcile against your system without a lookup table. # Products Source: https://docs.waffo.ai/dashboard/products Create and manage your product catalog ## Product Management The Products page is where you manage your entire product catalog. Create one-time purchase items or subscription products. ![Products List](https://mintcdn.com/waffo/5dRlk76Jm-9Zm6Tj/images/dashboard/products-list.png?fit=max\&auto=format\&n=5dRlk76Jm-9Zm6Tj\&q=85\&s=2068cb755f3bad4349d93aadbaa7a94f) ## Product List Your products are displayed in a table with: | Column | Description | | - | - | | Name | Product name and image thumbnail | | Price | Price with currency and billing interval | | Status | Active or Inactive | | Subscribers | Number of active subscriptions (for subscription products) | | Created | Creation date | | Actions | Edit, copy link, toggle status | ## Creating a Product ![Create Product](https://mintcdn.com/waffo/5dRlk76Jm-9Zm6Tj/images/dashboard/products-create.png?fit=max\&auto=format\&n=5dRlk76Jm-9Zm6Tj\&q=85\&s=afb107e0fe3b6c245f273109473fca24) **1. Click 'Create Product'** Find the button in the top right of the Products page. **2. Enter Basic Information** **Required Fields:** * Product Name * Price * Currency * Pricing Type (One-Time or Subscription) **3. Add Details (Optional)** * Product Description (supports Markdown) * Product Image * Tax settings **4. Configure Subscription Settings** For subscription products only: * Billing Interval * Trial Period (optional) **5. Save Product** Click "Create" to publish your product. ## Product Fields ### Basic Information | Field | Required | Description | | - | - | - | | Name | Yes | Display name (shown to customers) | | Description | No | Product details in Markdown format | | Image | No | Product image (recommended: 400x400px) | ### Pricing | Field | Options | Description | | - | - | - | | Price | Number | The product price (in smallest currency unit) | | Currency | USD, EUR, GBP, JPY, HKD (CNY for one-time products only — see Price Limits below) | Transaction currency | | Pricing Type | One-Time, Subscription | Payment model | | Tax Category | SaaS, Digital Goods, Software, eBook, etc. | Tax calculation rules | | Tax Behavior | Inclusive, Exclusive | Price includes or excludes tax | ### Price Limits Each currency has a minimum and maximum price you can set on a product. Values outside this range are rejected when you save the product. | Currency | Minimum | Maximum | | - | -: | -: | | USD | \$1.00 | \$10,000.00 | | EUR | €1.00 | €9,400.00 | | GBP | £1.00 | £8,150.00 | | JPY | JP¥100 | JP¥1,600,000 | | CNY | CN¥1.00 | CN¥1,000.00 | | HKD | HK\$8.00 | HK\$77,600.00 | > [!NOTE] > > **CNY prices one-time products only** — subscription products cannot be priced in CNY. CNY-priced orders are payable by WeChat Pay only, up to roughly 1,000 CNY per order. See [Method and currency support](/dashboard/payments#method-and-currency-support). ### Subscription Settings Only applicable for subscription products: | Field | Options | Description | | - | - | - | | Interval | Weekly, Monthly, Quarterly, Yearly | Billing frequency | | Trial Enabled | Yes/No | Offer free trial | | Trial Days | Number | Trial duration (default: 7) | ### Tax Configuration | Field | Options | Description | | - | - | - | | Tax Category | SaaS, Digital Goods | Tax calculation rules | | Tax Behavior | Inclusive, Exclusive | Price includes or excludes tax | ## Product Status > **Active** > > * Product is live and purchasable > * Payment links work > * Shown in checkout > **Inactive** > > * Product is hidden > * Payment links return error > * Existing subscriptions continue To toggle status, use the switch in the product row or edit the product. ## Editing Products 1. Click on a product row or the edit icon 2. Modify any fields 3. Click "Save Changes" > [!WARNING] > > Changing the price of a subscription product only affects new subscribers. Existing subscribers keep their original price. ## Product Purchase Links Every product gets a permanent purchase link that never expires: ``` https://pancake.waffo.ai/store/{store-slug}/product/{productId} ``` Test mode: ``` https://pancake.waffo.ai/store/{store-slug}/product/{productId}?test=true ``` **Get your link:** * Click the "Copy Link" button on any product * For advanced use cases, create a Checkout Session via API with custom parameters (dynamic link, 24-hour default TTL, configurable, 1 minute to 7 days recommended) **Test vs Live:** * Toggle Test Mode in Dashboard header to preview with test links * Test links add `?test=true` ## Best Practices > **Product Naming** > > * Use clear, descriptive names > * Include the billing period for subscriptions (e.g., "Pro Plan - Monthly") > * Avoid special characters > **Descriptions** > > * List key features > * Use bullet points for readability > * Include what customers get > * Mention support or guarantees > **Images** > > * Use high-quality images (400x400px minimum) > * PNG or JPG format > * Keep file size under 5MB > * Consistent style across products > **Pricing Strategy** > > * Research competitor pricing > * Consider regional purchasing power > * Round prices for simplicity ## Managing Multiple Products Products are managed one at a time — there is no multi-select or bulk action. Activate, deactivate, and edit each product from its own row or detail page. # Revenue Source: https://docs.waffo.ai/dashboard/revenue Per-store income from successful payments The **Revenue** page in the sidebar shows the income flow for the **current store**. Each row is a successful payment that contributed revenue. ![Store Revenue page](https://mintcdn.com/waffo/hlQqsHXE08bUGqyq/images/dashboard/store-revenue.png?fit=max\&auto=format\&n=hlQqsHXE08bUGqyq\&q=85\&s=4a965f310291169da4a14ae24d130bfc) ## Income Table | Column | Description | | - | - | | Date | When the payment was completed | | Description | Payment details (product name, subscription renewal, etc.) | | Gross | Total amount the buyer paid | | Fees | Processing fees deducted from the gross amount | | Net | Net amount after fees | ## How it relates to Merchant Finance Each store's settled revenue flows automatically into your **merchant balance** — there is no per-store withdrawal. To request a payout or see your pooled balance, open [Merchant Finance](/merchant/finance) from the user menu (top-right avatar). # Subscriptions Source: https://docs.waffo.ai/dashboard/subscriptions Manage recurring billing and subscriber relationships ## Subscription Management The Subscriptions page shows all recurring billing arrangements with your customers. ![Subscriptions List](https://mintcdn.com/waffo/5dRlk76Jm-9Zm6Tj/images/dashboard/subscriptions-list.png?fit=max\&auto=format\&n=5dRlk76Jm-9Zm6Tj\&q=85\&s=e1952d496dfb35c7bf74a8d95f733bbb) ## Subscription List View all subscriptions in a detailed table: | Column | Description | | - | - | | Status | Current subscription status | | Product | Product name and image | | Customer | Subscriber email | | Amount | Subscription price with currency | | Interval | Billing frequency | | Next Billing | Next charge date | | Created | When subscription started | ## Subscription Statuses > **Active** > > Subscription is live and billing normally. > **Trialing** > > Customer is in free trial period. > **Past Due** > > Payment failed, awaiting retry. > **Canceling** > > Cancellation requested, active until period end. > **Expired** > > Subscription has expired. > **Canceled** > > Subscription has been terminated. ## Billing Intervals | Interval | Billing Frequency | MRR Calculation | | - | - | - | | Weekly | Every 7 days | Amount × 4.33 | | Monthly | Every month | Amount × 1 | | Quarterly | Every 3 months | Amount ÷ 3 | | Yearly | Every 12 months | Amount ÷ 12 | ## Filtering Subscriptions | Filter | Options | | - | - | | Status | Active, Trialing, Past Due, Canceling, Expired, Canceled | | Product | Any subscription product | | Interval | Weekly, Monthly, Quarterly, Yearly | | Customer | Search by email | ## Subscription Details Click on a subscription to view: ### Overview * Subscription ID * Status and status history * Product details * Pricing and currency * Billing interval ### Billing Info * Current period start/end * Next billing date * Payment method on file * Billing history ### Customer * Customer email * Account details * Other subscriptions from same customer ### Payment History * All charges for this subscription * Successful and failed attempts * Refunds ### Cancellation Record Lists each cancellation on this subscription, newest first. | | | | - | - | | **Per entry** | Reason, the customer's comment, timestamp | | **Repeat cancellations** | One entry each — cancel → resume → cancel shows two | | **Hidden when** | No cancellation carried a reason, as with cancellations you performed yourself | Store-wide breakdown: [Cancellation Reasons](/dashboard/analytics#cancellation-reasons). ## Plan Change Markers A [plan change](/features/subscriptions#changing-plans) closes one order and opens another, so the history spans two records. The Dashboard links them rather than leaving two unrelated rows. | Where | Marker | | - | - | | Subscription list | **Plan changed** tag on the status column | | Details drawer | **Superseded by a plan change** / **Created by a plan change** — hover reveals the counterpart order ID | Follow either marker to move between the orders before and after the change. ## Managing Subscriptions ### Cancel Subscription **1. Open Subscription Details** Click on the subscription you want to cancel. **2. Click 'Cancel Subscription'** Find the button in the actions menu. **3. Confirm Cancellation** Cancellation takes effect at the end of the current billing period. The subscription enters "Canceling" status until the period ends, then becomes "Canceled". > [!NOTE] > > The customer retains access until the end of their current paid billing period. ### Simulate a Renewal (Test Mode) Test subscriptions carry two extra buttons in the detail drawer, next to "Cancel Subscription". They advance the subscription by one billing period so you can see what your integration receives when the next charge succeeds or fails — no waiting for the real due date, and no help from support. **1. Switch to Test Mode** The buttons only exist for test subscriptions. Live subscriptions never show them, and the API rejects live requests regardless. **2. Open a subscription in Active, Trialing or Past Due status** Canceled, terminated and expired subscriptions have no next period, so the buttons are not offered. **3. Click 'Simulate renewal success' or 'Simulate renewal failure'** Failure always asks for confirmation first; success runs immediately. Both buttons are disabled while a request is in flight. **4. Refresh after a moment** The click only triggers the simulation. The new payment, the new status and the webhook delivery arrive asynchronously from the payment provider. | Action | Subscription before | Subscription after | Webhook events | | - | - | - | - | | Simulate renewal success | Active / Trialing | Active, next billing date moved forward one period | `subscription.payment_succeeded`, `subscription.renewed` | | Simulate renewal success | Past Due | Active (recovered) | `subscription.payment_succeeded`, `subscription.recovered` | | Simulate renewal failure | Active / Trialing | Past Due, one failed payment recorded | `subscription.past_due` | | Simulate renewal failure | Past Due | Canceling, then Canceled | `subscription.canceled` | > [!WARNING] > > Simulated failures accumulate and the last step is irreversible: two failures in a row terminate the subscription (`active` --> `past_due` --> `canceled`) and it cannot be restored. Each click advances exactly one period; there is no rewind, reset or "advance N periods". > [!NOTE] > > Payments produced by a simulation are test data — they never enter settlement, balance or payouts. ### Resume Subscription A subscription in **Canceling** can be resumed before its period ends — it returns to `active` and renews as usual, with no new charge. This is a customer action, taken in the Customer Portal. There is no Dashboard button for it. ## Subscription Metrics ### Statistics Cards | Metric | Description | | - | - | | MRR | Monthly Recurring Revenue | | Active | Count of active subscriptions | | Trialing | Count of subscriptions in trial | | Canceled | Count of canceled (this period) | | ARPU | Average Revenue Per User | ### MRR Calculation MRR is calculated from all active subscriptions: ``` MRR = Σ (Subscription Amount × Interval Factor) Where Interval Factor: - Weekly: 4.33 - Monthly: 1 - Quarterly: 0.33 - Yearly: 0.083 ``` ## Failed Payments When a renewal charge is not collected: 1. Status changes to **Past Due** 2. The customer is emailed a *Subscription past due* notice 3. Collection is retried according to the dunning policy 4. If recovery does not succeed, the subscription ends `past_due` is a recovery state, not an immediate termination — access can continue while the customer sorts out their payment method. See [Renewal Recovery](/features/subscriptions#renewal-recovery). > [!NOTE] > > One email is sent to the customer when a renewal fails. There is no separate sequence of retry reminders or final warnings. > > To be alerted yourself, subscribe a recipient to **Subscription past due** under [notification settings](/features/notifications) — it is the one event tied to revenue you have already lost. ## Trial Periods For products with trials enabled: | Field | Description | | - | - | | Trial Status | Active trial indicator | | Trial Days | Total trial length | | Days Remaining | Time left in trial | | Conversion Date | When first charge occurs | Track trial conversions: * Trial → Active (converted) * Trial → Canceled (churned before conversion) ### Platform Trial Protection Waffo Pancake automatically tracks consumer trial history at the platform level. The actual trial days granted to a consumer may be less than the configured value if the consumer has used trials before. This prevents trial abuse without requiring any action from the merchant. For Product Groups with **shared trial** enabled, trial usage is shared across all products in the group. ## Changing a Subscriber's Plan Moving a subscriber to a different plan is not done from this page yet — the **Manage** entry on each row is visible but disabled, marked *coming soon*. Two routes work today: | Route | How | | - | - | | **Customer Portal** | The customer switches plans themselves, provided both plans are in one [product group](/guides/subscriptions#step-2-organize-plans-with-product-groups) with `selfServicePlanChange` enabled | | **Merchant API** | You issue a change link with your API Key and send it to the customer | > **[How plan changes work](/features/subscriptions#changing-plans)** > > Timing rules, proration, the API flow, and the webhook events to expect. > [!NOTE] > > Payment methods cannot be updated from the Dashboard, and the platform does not send "update your card" links. A customer whose card is expiring needs a new checkout — see [Payment Method](/customers/payment-method). # Feature Overview Source: https://docs.waffo.ai/feature-list Everything Waffo Pancake offers at a glance ## Platform Features Waffo Pancake is an all-in-one Merchant of Record payment platform. Here's everything it offers, organized by module. *** ## Products & Pricing > **[Product Management](/features/products)** > > Create one-time and subscription products. Multi-currency pricing, tax categories, immutable versioning. Manage product lifecycle via Dashboard or API. > **[Subscription Management](/features/subscriptions)** > > Full subscription lifecycle: weekly/monthly/quarterly/yearly billing, free trials, dunning, cancellation, and reactivation. Product groups for plan switching. *** ## Payments & Checkout > **[Checkout](/features/checkout)** > > Two-step optimized checkout flow. Theme customization (brand colors, logo, dark mode), 19 languages, Apple Pay and Google Pay. > **[Orders & Payments](/features/orders-payments)** > > Real-time order status and payment tracking. One-time and subscription orders with automatic tax calculation and collection. > **[Coupons & Promotion Codes](/guides/discounts)** > > Percentage or fixed-amount coupons with product, expiry and usage limits. Hand out promotion codes per channel, each with its own customer rules; customers enter them at checkout, or you apply them from a link or your server. > **[Refunds](/features/refunds)** > > Ticket-based refund system. Partial and full refunds, no refund time limit, built-in approval workflow. > **[Finance & Payouts](/features/finance)** > > View balance, payout history, and transaction details. Configure bank accounts for payouts. Multiple payout schedules. *** ## Customers & Operations > **[Customer Management](/features/customer-management)** > > View customer list, purchase history, and subscription status. Automatic email-based customer association. > **[Customer Portal](/features/customer-portal)** > > Built-in self-service portal. Customers log in via Magic Link to view orders, manage subscriptions, request refunds, and update payment methods. > **[Notifications](/features/notifications)** > > 8 customer emails (order confirmation, subscription confirmation, renewals, plan changes, cancellations, past due, upcoming charge) plus 7 merchant notification events, delivered to up to 5 recipients per store. > **[Analytics](/features/analytics)** > > Real-time revenue dashboard: MRR, Churn Rate, LTV, ARPU, and more. Trend analysis, distribution analysis, and customer insights — no SQL needed. *** ## Developer Tools > **[SDK & API](/features/integrations)** > > TypeScript SDK, REST API + GraphQL, Webhook notifications, API Key management. AI-friendly SDK Skill integration. > **[Test Mode](/features/test-mode)** > > Complete test environment isolated from production. Use test card numbers to simulate payments and test the full flow. One-click test/live toggle. *** ## Compliance & Review > **[MoR Compliance](/mor/what-is-mor)** > > Waffo Pancake acts as your Merchant of Record, handling global tax calculation, collection, and reporting. Accept payments compliantly without registering a company. > **[KYB Review](/mor/account-reviews)** > > Submit store details for qualification review. Production mode automatically enabled after approval. *** ## Get Started > **[Quickstart](/quickstart)** > > Complete flow from sign-up to your first payment. > **[AI Integration](/integrate/ai-integration)** > > One-click payment integration with AI coding assistants. # Analytics Source: https://docs.waffo.ai/features/analytics Monitor store performance with charts, metrics, and flexible date ranges ## Analytics Overview The Analytics page lets you monitor your store's performance over time. It provides revenue charts, metric cards, and configurable date ranges so you can understand how your business is trending. *** ## Date Range & Granularity ### Date Range Picker Select a preset or custom date range to scope all charts and metrics on the page. | Preset | Period | | - | - | | **7d** | Last 7 days | | **30d** | Last 30 days | | **90d** | Last 90 days | | **1y** | Last year | | **All** | Everything on record | | **Custom** | Choose specific start and end dates | ### Granularity Control how data points are grouped in charts. | Granularity | Description | | - | - | | **Daily** | One data point per day | | **Weekly** | One data point per week | | **Monthly** | One data point per month | > [!TIP] > > Your selected date range and granularity are saved automatically and persist across sessions, so the dashboard remembers your preferences. *** ## Revenue Charts The main visualization is a revenue chart that plots performance over the selected date range at the chosen granularity. Use the date range and granularity controls to adjust the view. *** ## Metric Cards The analytics page displays summary metric cards for key performance indicators such as revenue and customer counts. Each card shows the metric value for the selected period. *** ## Showing and Hiding Products in Charts Charts that break revenue down by product have a legend you can click to show or hide individual lines — useful when one large product flattens the rest. > [!NOTE] > > This is a **display toggle on the chart only**. It does not filter the underlying data, so the KPI cards and totals stay unchanged. *** ## Test vs Live Environment > [!WARNING] > > Analytics data is separate for Test and Live modes. Make sure you are viewing the correct environment using the mode toggle in the dashboard header. Switching between test and production mode updates all charts and metrics to reflect data from that environment only. Test mode data is never mixed with live data. *** ## Locale-Aware Formatting Numbers, currencies, and dates are formatted according to your locale setting. The dashboard supports English, Chinese, and Japanese formatting conventions. # Checkout Source: https://docs.waffo.ai/features/checkout A two-step checkout flow optimized for conversion ## Checkout Overview Waffo Pancake uses a **two-step checkout flow** optimized for conversion. This design collects customer details first, then payment information, reducing abandonment and supporting accurate tax calculation. *** ## Checkout URLs ### Product Purchase Links (Recommended) Every product gets a permanent purchase link that never expires: ``` https://pancake.waffo.ai/store/{store-slug}/product/{productId} ``` Test mode: ``` https://pancake.waffo.ai/store/{store-slug}/product/{productId}?test=true ``` Just click "Copy Link" in the Dashboard. The link stays the same even when you update the product. A checkout session is created automatically when the customer opens the link. Add query parameters to pre-fill the checkout: | Parameter | Description | | - | - | | `currency` | Currency code (ISO 4217). Omit to let the page pick one | | `email` | Pre-fill the customer's email | | `success_url` | Redirect URL after a successful payment | | `country` | Pre-fill the billing country (ISO 3166-1 alpha-2) | | `is_business` | `true` for a business purchase. Only takes effect together with `country` | | `discount_code` | Apply a coupon code or promotion code. The code is locked — the customer cannot change or remove it, and no code entry field is shown. Works for one-time and subscription products (not for plan changes). See [Discounts](/guides/discounts#product-link-with-a-code) | | `test` | `true` opens the test-mode checkout | Without `discount_code`, the product page shows a code entry field when the store has a coupon or promotion code that can be used on the product. See [Code Entry Field](/guides/discounts#code-entry-field). ### Checkout Sessions (API) For advanced use cases (dynamic pricing, custom metadata, programmatic checkout), create a session via the API: ``` https://checkout.waffo.ai/{store-slug}/checkout/{sessionId} ``` | Component | Description | | - | - | | `store-slug` | Your store's unique URL slug | | `sessionId` | Checkout session identifier (24-hour default TTL, adjustable with `expiresInSeconds`, 1 minute to 7 days recommended) | > [!NOTE] > > Checkout sessions are generated server-side and lock the product version, pricing, and currency at creation time. *** ## Two-Step Flow **1. Consumer Details** Collect email, country, and billing info for tax calculation and order processing. **2. Payment** Enter card details or use Apple Pay / Google Pay to complete payment. ![Checkout page — Consumer details](https://mintcdn.com/waffo/fAGQ8sa2qycWEk2d/images/checkout/checkout-step1.png?fit=max\&auto=format\&n=fAGQ8sa2qycWEk2d\&q=85\&s=e7454a2c64f08d42fe0fa1ac4084b712) ### Step 1: Consumer Details Collects information needed for tax calculation and order processing. **Required Fields:** | Field | Purpose | | - | - | | Email address | Receipt, account creation, Customer Portal access | | Country | Tax jurisdiction determination | **Conditional Fields (Based on Country):** | Field | When Shown | | - | - | | ZIP/Postal Code | Most countries (US, CA, UK, etc.) | | State/Province | US, CA, AU, IN, and other applicable countries | **Business Purchase Option:** Customers can toggle "I'm purchasing as a business" to provide: * Business name * Tax ID (for VAT/tax exemption) ### Step 2: Payment ![Checkout — Payment](https://mintcdn.com/waffo/YbM_n4_eoBfrCsTT/images/checkout/checkout-step2.png?fit=max\&auto=format\&n=YbM_n4_eoBfrCsTT\&q=85\&s=e424a83d42c68d5946214be7f18cbbb7) > **Card Payment** > > * Card number > * Expiry date (MM/YY) > * CVC/CVV > * Cardholder name > **Digital Wallets** > > * Apple Pay (iOS, Safari) > * Google Pay (Android, Chrome) > * One-click with biometric auth **Order Summary** is displayed alongside the payment form with product name, image, subtotal, tax, and total. *** ## Session Lifecycle * **One session, one order.** A checkout session can produce exactly one order. Once the buyer submits, the session is consumed; opening the same `checkoutUrl` again shows "This checkout link has expired". That is expected — call create-session again for every purchase instead of reusing links. * **Browser back button.** Before handing off to the payment provider, the cashier swaps the current history entry for a replacement session that the server derives from the original one, and the provider's cancel URL points to the same address. Both ways back therefore land on a live session that keeps your `orderMerchantExternalId` and `metadata` — in any browser, because the values live in the session itself. The replacement session's TTL resets to the default 24 hours regardless of the `expiresInSeconds` you set. * **When the swap fails.** If that swap fails, or the buyer comes back to a session that has already been consumed or has expired, what happens depends on how the checkout was opened. A session you created with create-session shows "This checkout link has expired" and is never re-created, so your `orderMerchantExternalId`, `metadata` and custom price are never silently dropped — create a new session for the buyer. A Product Purchase Link jumps back to the product page and creates a fresh session; parameters you put on the link (`currency`, `email`, `success_url`) are not carried over. *** ## Subscription Checkout For subscription products, additional billing information displays: | Element | Example | | - | - | | Billing frequency | "Billed monthly" | | Recurring amount | "\$29.00/month" | | Next billing date | Calculated from today | | Trial duration | "7-day free trial" (if the product has trials enabled) | *** ## Customization Make your checkout page match your brand through the Checkout Settings in your dashboard. ### Logo Upload a custom logo displayed on the checkout page. Supported formats include PNG, JPG, and SVG. ### Theme Mode > **Light Mode** > > White background, dark text. Best for most brands. > **Dark Mode** > > Dark background, light text. Modern aesthetic. Switch between Light and Dark mode presets. Each mode maintains its own set of color values. ### Color Settings | Setting | Field Name | Default (Light) | Default (Dark) | | - | - | - | - | | **Primary Color** | `checkoutColorPrimary` | #111111 | #FEFDFD | | **Background Color** | `checkoutColorBackground` | #F4F4F4 | #111315 | | **Card Color** | `checkoutColorCard` | #FFFFFF | #181A1B | | **Text Color** | `checkoutColorText` | #111111 | #FFFFFF | ### Border Radius Control the roundness of UI elements with the `checkoutBorderRadius` setting. Default is `8px`. Options range from 0px (sharp corners) to 16px (extra-large rounding). > [!NOTE] > > Ensure sufficient contrast between text and background colors for accessibility. WCAG recommends a contrast ratio of at least 4.5:1. ### Store Information | Option | Description | | - | - | | Store Name | Shown in header | | Support Email | For customer questions | | Terms Link | Link to your terms of service (required) | | Privacy Link | Link to your privacy policy (required) | *** ## Multi-Language Support The hosted checkout is multilingual and requires no merchant configuration: * **Automatic detection** — the checkout UI opens in the shopper's browser language and falls back to English when the language isn't supported yet. * **Shopper choice** — shoppers can switch languages at any time via the selector in the checkout footer. * **Payment page follows** — the payment page opens in the language the shopper was using when they clicked Pay (22 payment-page languages supported). The checkout UI supports 19 languages: | Language | Code | Language | Code | | - | - | - | - | | English | `en` | Italian | `it` | | Chinese (Simplified) | `zh` | Russian | `ru` | | Chinese (Traditional) | `zh-Hant` | Arabic | `ar` | | Japanese | `ja` | Hindi | `hi` | | Korean | `ko` | Thai | `th` | | German | `de` | Vietnamese | `vi` | | French | `fr` | Indonesian | `id` | | Spanish | `es` | Dutch | `nl` | | Portuguese | `pt` | Polish | `pl` | | | | Turkish | `tr` | ### Language priority When checkout first opens, the UI language is resolved in this order — the first match wins: | Priority | Source | Notes | | - | - | - | | 1 | **Shopper's manual choice** | Once the shopper picks a language in the footer selector, that choice wins | | 2 | **Merchant-specified default** | The [`language`](/api-reference/endpoints/orders/create-checkout-session) parameter passed when creating the checkout session | | 3 | **Shopper's browser language** | Used when `language` was not provided | | 4 | **English** | Fallback when none of the above match a supported language | > [!NOTE] > > Language is fully decoupled from currency — the shopper can switch to any of the 19 supported languages regardless of the order's currency. *** ## Processing & Results After payment submission: 1. **Card validation** -- Luhn check, expiry, CVC verification 2. **3D Secure** -- Bank verification (if required by the issuing bank) 3. **Authorization** -- Charge to card 4. **Order creation** -- Record in system **Success Page:** Order confirmation number, receipt email notification, next steps, Customer Portal link. **Failed Page:** Clear error explanation, suggested action, retry button, support contact option. *** ## Error Handling | Error | Cause | Customer Action | | - | - | - | | Card declined | Insufficient funds or bank block | Try different card | | Invalid card | Incorrect card number | Check and re-enter | | Expired card | Card past expiration | Use valid card | | CVC mismatch | Wrong security code | Re-enter CVC | | 3DS failed | Bank verification failed | Contact bank | *** ## Test Checkout Use [Test Mode](/features/test-mode) to try the checkout flow without real charges. | Card | Number | Result | | - | - | - | | Visa Credit | `4576 7500 0000 0110` | Success | | Mastercard Credit | `2226 9000 0000 0110` | Success | | Visa Credit | `4576 7500 0000 0220` | Declined | > [!NOTE] > > Test mode is indicated by a banner: "Test Mode - No real charges will be made" *** ## Merchant of Record Notice At checkout footer, customers see: > "This order is processed by our online reseller & Merchant of Record, Waffo Pancake, who also handles order-related inquiries and returns." This disclosure is required for MoR compliance and helps customers understand the payment relationship. # Customer Management Source: https://docs.waffo.ai/features/customer-management View and track your customers from the merchant dashboard ## Customer Management The Customers page in the merchant dashboard gives you a consolidated view of every consumer who has purchased from your store. Track revenue, monitor subscriptions, and drill into individual customer details. *** ## Customer Data Each customer record contains the following fields, sourced from the backend `Customer` type: | Field | Description | | - | - | | `id` | Unique customer identifier (UUID) | | `email` | Customer email address | | `name` | Customer name | | `country` | Customer country | | `totalRevenue` | Lifetime revenue from this customer (display format string) | | `mrr` | Monthly Recurring Revenue attributed to this customer | | `subscriptionCount` | Number of subscriptions (active and past) | | `paymentCount` | Total number of payments | | `createdAt` | When the customer record was created | | `updatedAt` | When the customer record was last updated | | `storeId` | The store this customer belongs to | > [!NOTE] > > The backend `Customer` type does not have a `status` field. Any status labels shown in the dashboard UI (such as "Active" or "Subscribed") are derived from the customer's subscription and payment activity, not stored as a property on the customer record itself. *** ## Customer List The dashboard displays customers in a sortable, filterable table with these columns: | Column | Description | | - | - | | Email | Customer email address | | Country | Customer country (displayed with flag emoji) | | Revenue | Total lifetime revenue | | MRR | Monthly Recurring Revenue | | Subscriptions | Subscription count | | Payments | Payment count | | Created | When the customer first appeared | ### Search and Filtering The customer list supports: * **Text search** -- Search by customer email or name * **Status filtering** -- Filter by derived status categories based on subscription and payment activity * **Date range filtering** -- Filter by customer creation date *** ## Customer Details Click on a customer row to view their full profile. ### Overview * Email and name * Country (with flag emoji) * Account creation date * Total lifetime revenue * Current MRR * Subscription count and payment count ### Subscriptions View all subscriptions associated with this customer: * Subscription status * Product and tier information * Billing period * Dates and amounts ### Payments View the full payment history for this customer: * Payment status * Amounts and currencies * Associated orders and products * Refund status where applicable *** ## Customer Portal Customers also have access to a self-service **Customer Portal** where they can manage their own subscriptions and view payment history. The portal is a separate feature -- see the [Customer Portal](/features/customer-portal) page for details. Key capabilities available to customers through the portal: * View subscriptions and payments * Change subscription tier (upgrade or downgrade) * Cancel subscriptions * Update billing details * Download invoices and receipts > [!TIP] > > The Customer Portal uses secure email-based authentication. Consumers authenticate via a verification link sent to their email. *** ## Related > **[Customer Portal](/features/customer-portal)** > > Self-service portal for consumers to manage orders and subscriptions. > **[Orders & Payments](/features/orders-payments)** > > View and manage orders and payment records. # Customer Portal Source: https://docs.waffo.ai/features/customer-portal Self-service portal for consumers to manage orders and subscriptions The Customer Portal gives your consumers a self-service interface to manage their purchases, view invoices, update billing details, and manage subscriptions — no password required. Consumers log in via **Magic Link** — they enter their email, receive a login link, and click to access the portal. Customers who are already signed in on your site can also go straight in from a link your server creates. > **[Consumer Portal](https://pancake.waffo.ai/consumer/portal/login)** > > Log in to the Consumer Portal to view orders, manage subscriptions, and download invoices. *** ## What Can Customers Do in the Customer Portal? > **Subscription Management** > > View active subscriptions, next billing date, change plan, cancel or reactivate. > **Orders & Payments** > > Browse all past orders and payment history with status details. > **Invoice Download** > > Download PDF invoices and receipts in 16 languages with full billing details. > **Billing Details** > > Update billing address, add business name and tax ID for invoicing. *** ## Cancellation Feedback The cancellation dialog asks why the customer is leaving. | | | | - | - | | **Optional** | Never blocks the cancellation | | **Other** | Reveals a free-text comment box | | **Skipped** | Recorded as `not_provided`, not omitted | | **Stored** | One record per successful cancellation | Because the portal always asks, a skip is meaningfully different from an integration that never presented the question — recording it keeps the "declined to answer" share readable. > **[Reason storage rules](/api-reference/endpoints/subscriptions/cancel-subscription-customer)** > > The `cancelReason` / `cancelComment` contract, and how to read reasons through GraphQL. *** ## Portal Access The unified Consumer Portal URL: ``` https://pancake.waffo.ai/consumer/portal/login ``` Consumers enter the email used for their purchase on the login page, receive a one-time Magic Link, and click to access the portal. No password required. ### Linking to the portal from your own site You have two options: | Option | How the customer signs in | What the portal shows | | - | - | - | | Link to the URL above | Email Magic Link | Orders placed with that email, across stores | | [Signed-in portal link](/guides/customer-portal-sso) created by your server | No extra step — your site already signed them in | Orders placed with your `buyerIdentity`, in one store and one environment | For the signed-in link, your server calls the API with your API Key and redirects the customer. In that portal, customers can view orders, payments, invoices and subscriptions, and cancel, reactivate or change plans; refund tickets are view-only in this version. If you want the customer to stay on your site, use the [Customer Portal API](/api-reference/endpoints/auth/customer-endpoints): obtain a customer session token and call the cancel, reactivate, and billing endpoints from your own pages. *** ## Can't Log In? > **Didn't receive the login email?** > > 1. Make sure you're using the email address from your original purchase (check your receipt email) > 2. Check your spam folder for emails from `auth@waffo.ai` > 3. Go back to the login page and request a new Magic Link > **Still can't log in?** > > Email `support@waffo.ai` with your purchase email and order details, and we'll help you out. # Finance & Payouts Source: https://docs.waffo.ai/features/finance Track income from payments and request payouts The Finance area covers two related concepts, accessed from different parts of the dashboard: * **Merchant Finance** — your pooled balance across all stores, where you request payouts. * **Store Revenue** — per-store income from successful payments. ## Merchant Finance Open from the merchant menu (top-right avatar → **Merchant Finance**), or at `/merchant/dashboard/finance`. At the top of the page, three KPI cards show your balance at a glance: | Card | Description | | - | - | | **Available to withdraw** | Net amount that has fully settled and is ready to pay out | | **Processing** | Payments still in the clearing window (≈ 10 business days) | | **Total withdrawals** | Cumulative amount you have paid out so far | Below the cards are two tabs: * **Pay out** — request a payout from your available balance. See [Payouts](/merchant/payout-flow) for the full flow. * **Withdrawal records** — historical payouts and their statuses. If you haven't bound a payout account yet, a banner at the top of the page links to **Payout Accounts**. > **[How payouts work](/merchant/payout-flow)** > > Read the end-to-end payout flow: from sale to settlement to your bank. ## Store Revenue Each store has its own Revenue page (`/merchant/dashboard/{storeId}/revenue`) showing the income that store has generated. Settled funds from all your stores flow automatically into Merchant Finance — there is no per-store withdrawal. ## Payout Accounts Payout accounts live at the **merchant level** — every store you own shares the same set. Manage them at `/merchant/dashboard/payout-accounts` or via the merchant menu. See [Payout Accounts](/merchant/payout-accounts) for the supported methods, identity prerequisites, and how to add or switch accounts. > [!NOTE] > > Receiving payouts requires identity verification. If you haven't completed it yet, the Payout Accounts page shows a Basic Identity card that links to [Identity Verification](/merchant/identity-kyc). # Integrations Source: https://docs.waffo.ai/features/integrations Choose the right integration path for your application ## Choose Your Integration Path > **[AI Integration](/integrate/ai-integration)** > > **Fastest to ship** > > Best for teams with an existing codebase that want Claude Code or another coding agent to plan the model, implement the integration, and drive validation. > **[API / SDK](/integrate/sdks)** > > **Most control** > > Best when you need custom checkout flows, server-side orchestration, dynamic pricing, or tighter control over integration behavior. > **[Hosted Checkout](/quickstart)** > > **Simplest** > > Best when you want to launch a payment link quickly first and deepen the integration later. *** ## How To Choose | If you care most about | Recommended path | Why | | - | - | - | | Shipping the first usable version quickly | AI Integration | Best when you want a coding agent to turn an existing codebase into a working integration fast | | Full control over payment flow and server logic | API / SDK | Best for custom checkout, dynamic pricing, permissions, and internal orchestration | | Validating the payment funnel before deeper engineering | Hosted Checkout | Best for low engineering overhead and fast launch | > [!NOTE] > > Many teams start with Hosted Checkout or AI Integration for the first version, then move deeper into the API / SDK path as requirements grow. *** ## What An Integration Usually Includes Most Waffo Pancake integrations include four parts: * **Authentication** for server-side requests * **Products and checkout** for one-time or subscription billing * **Webhooks** for payment and subscription events * **Environment rollout** from test mode to production ``` Your application | +-- Authentication --> API / SDK requests | +-- Product + Checkout --> Payments | +-- Webhooks --> Order and subscription sync ``` > [!NOTE] > > You do not need every layer on day one. Many teams start with hosted checkout or AI-assisted integration, then deepen their API usage later. *** ## What Each Path Usually Delivers ### AI Integration * let an AI coding assistant read `llms-full.txt` and the official skill context * generate integration code, webhook handling, and validation steps for your stack * best when you already have a codebase and want to shorten implementation time ### API / SDK * gives your server full control over products, checkout, webhooks, and state sync * fits dynamic pricing, fine-grained permissions, and custom backend orchestration * best for long-term customization and more complex billing logic ### Hosted Checkout * use dashboard-generated checkout links or public payment entry points directly * best for validating the commercial flow before investing in deeper engineering * usually the best first-stage integration path *** ## Recommended Rollout Order **1. Create Account** Sign up at [Merchant Dashboard](https://pancake.waffo.ai/merchant/auth/signin) and create your first store. **2. Set Up Authentication** Prepare your Merchant ID and API Key in the merchant dashboard. **3. Create Products** Define the product type, pricing, and billing interval, then create products via the Dashboard or API. **4. Implement Checkout** Create checkout sessions through the API, or use Dashboard-generated checkout links. **5. Handle Webhooks** Set up webhook endpoints for payment, refund, and subscription events. **6. Test End-to-End** Use [Test Mode](/features/test-mode) with test cards to verify the full flow. **7. Go Live** Publish products and switch to the production environment. *** ## What To Prepare Before Implementation Before writing code, define these clearly: * whether you sell one-time products, subscriptions, or both * whether you need dynamic pricing for overage, credits, or quoted amounts * what access, entitlements, or resources should be granted after payment * which webhook events should drive your business state changes * which capabilities should stay in test mode until production rollout > [!TIP] > > If these decisions are still fuzzy, start with the AI Integration path. If these rules are already well-defined, the API / SDK path is usually the stronger choice. *** ## Core Entry Points > **[Authentication](/integrate/authentication)** > > Configure Merchant ID, API Key, and server-side authentication. > **[Test Mode](/features/test-mode)** > > Test the full integration flow without real charges. > **[Webhooks](/integrate/webhooks)** > > Receive real-time events and keep orders and subscriptions in sync. > **[SDKs](/integrate/sdks)** > > Browse official SDKs, framework patterns, and code samples. > **[AI Integration](/integrate/ai-integration)** > > Use an AI coding assistant for planning, implementation, and validation. > **[Quickstart](/quickstart)** > > Start from the first payment flow and learn the end-to-end path quickly. *** ## Developer Settings The API & Development page provides tools for integrating Waffo Pancake with your applications. ## API Keys ### Overview API keys authenticate server-to-server requests to the Waffo Pancake API. > **Test Keys** > > * Created for `test` environment > * Use for development > * No real charges > * Separate from production data > **Live Keys** > > * Created for `prod` environment > * Use for production > * Process real payments > * Keep private key secure ### Key Types | Key Type | Use Case | Description | | - | - | - | | **API Key** | Server-side only | Signed requests for full API access | ### API Key Authentication > [!NOTE] > > API Key authentication is handled automatically by the SDK. Install `@waffo/pancake-ts`, provide your Merchant ID and private key, and the SDK will handle request signing automatically. ```typescript theme={"system"} import { WaffoPancake } from "@waffo/pancake-ts"; const client = new WaffoPancake({ merchantId: process.env.WAFFO_MERCHANT_ID!, privateKey: process.env.WAFFO_PRIVATE_KEY!, }); ``` > [!WARNING] > > Never expose your private key in client-side code, version control, or public repositories. ### Creating API Keys **1. Navigate to API & Development** Go to Dashboard --> API & Development --> API Keys **2. Click 'Create API Key'** The API Key Generator opens. **3. Generate Key Pair** Click "Generate" to create a key pair. * Public key is sent to the server * Private key stays with you **4. Name Your Key** Give it a descriptive nickname (e.g., "Production Server"). **5. Select Environment** Choose **Test** or **Production** environment. **6. Download Private Key** **Critical:** Download and securely store your private key. > [!WARNING] > > Your private key is only shown once. Store it securely -- you will need it for API authentication. ### Managing Keys | Action | Description | | - | - | | View | See key nickname, creation date, environment | | Delete | Permanently remove the key | ## Webhooks ### What Are Webhooks? Webhooks notify your server when events occur in Waffo Pancake. ### Available Events | Event | Trigger | | - | - | | `order.completed` | Order completed | | `subscription.activated` | Subscription activated | | `subscription.payment_succeeded` | Subscription payment succeeded | | `subscription.plan_changed` | Subscription updated | | `subscription.canceling` | Subscription cancellation scheduled | | `subscription.canceled` | Subscription ended | | `subscription.uncanceled` | Subscription cancellation reversed | | `subscription.past_due` | Subscription payment past due | | `refund.succeeded` | Refund processed successfully | | `refund.failed` | Refund processing failed | ### Setting Up Webhooks **1. Add Endpoint** Enter your webhook URL (must be HTTPS). **2. Select Events** Choose which events to receive. **3. Save Configuration** Save your webhook endpoint. ### Webhook Payload Example ```json theme={"system"} { "event": "order.completed", "data": { "id": "550e8400-e29b-41d4-a716-446655440000", "orderId": "660e8400-e29b-41d4-a716-446655440001", "amount": 2900, "currency": "USD", "status": "completed", "createdAt": "2026-01-15T10:30:00.000Z" } } ``` > [!NOTE] > > All IDs are UUID v4 format. Amounts are in the smallest currency unit. Timestamps are ISO 8601 UTC. ### Webhook Best Practices > **Respond Quickly** > > Return 2xx status within 30 seconds. Process heavy work asynchronously. > **Handle Duplicates** > > Events may be sent multiple times. Use event IDs for deduplication. > **Retry Logic** > > Failed webhooks retry up to 5 times with increasing delays (5min, 30min, 2h, 24h). > **Monitor Failures** > > Check webhook delivery logs in the Dashboard for failures. ## API Documentation ### Base URL ``` https://api.waffo.ai/v1 ``` ### Architecture Waffo Pancake uses a hybrid API: * **REST (POST)** for all write operations via `/v1/actions/...` * **GraphQL** for all read operations via `/v1/graphql` ### Authentication Example **API Key (Server-to-Server) using SDK:** ```typescript theme={"system"} import { WaffoPancake } from "@waffo/pancake-ts"; const client = new WaffoPancake({ merchantId: process.env.WAFFO_MERCHANT_ID!, privateKey: process.env.WAFFO_PRIVATE_KEY!, }); const { store } = await client.stores.create({ name: "My Store" }); ``` ### Common Endpoints | Endpoint | Method | Description | | - | - | - | | `/v1/actions/onetime-product/create-product` | POST | Create one-time product | | `/v1/actions/subscription-product/create-product` | POST | Create subscription product | | `/v1/actions/onetime-order/create-order` | POST | Create checkout session | | `/v1/actions/subscription-order/create-order` | POST | Create subscription checkout | | `/v1/graphql` | POST | Query data (GraphQL) | > **[Full API Reference](/api-reference/introduction)** > > Complete endpoint documentation with request/response examples. ## Security Best Practices > **Environment Variables** > > Store private keys in environment variables, never in code. > **Key Rotation** > > Regularly rotate keys, especially after team changes. > **Separate Keys** > > Use different API keys for test and production environments. > **Secure Storage** > > Store private keys using your platform's secret management. ## Testing ### Test Mode Use test mode for development: * All endpoints work identically * No real charges processed * Test card numbers available * Full webhook testing ### Test Cards | Card Number | Behavior | | - | - | | `4576 7500 0000 0110` | Success (Visa) | | `2226 9000 0000 0110` | Success (Mastercard) | | `4576 7500 0000 0220` | Declined | ## Logs and Debugging ### Webhook Logs Track webhook deliveries: * Event type * Delivery status (success/failed) * HTTP response from your endpoint * Retry attempts and timestamps # Local Currency Pricing Source: https://docs.waffo.ai/features/local-currency Let buyers pay in their local currency. Local currency pricing lets your buyers pay in their local currency across the markets listed below. Waffo Pancake determines the payment currency from the buyer's IP location when they open the payment page, automatically calculates the localized price, and handles all currency conversion. Use local currency pricing to: * Display prices in the buyer's local currency based on their location * Charge in real time at an exchange rate that is guaranteed through settlement and refund * Settle in USD regardless of the currency the buyer paid in **Integration effort:** none. Local currency pricing is on for every hosted checkout. **Fees:** see [Pricing](#pricing) below. *** ## How the currency is chosen The payment currency is determined by the buyer's **IP location** when they open the payment page: 1. After the buyer confirms their details on the first checkout page and continues to payment, Waffo Pancake detects their country from the IP address at that moment. 2. If that country's currency is a [supported currency](#supported-currencies) and differs from your pricing currency, the buyer pays in that currency. Otherwise the buyer pays in your pricing currency. Neither the **billing country** the buyer selects on the first checkout page nor the `billingDetail` you pass when you [create the checkout session](/api-reference/endpoints/orders/create-checkout-session#billing-detail-object) affects the payment currency. The billing country is used only to calculate tax and decide which address fields to show. For example, a buyer whose IP is in Hong Kong still pays in HKD even after changing the billing country to the United States. The card the buyer uses has no effect on the presentment currency. If the card is in a third currency, the issuing bank converts the charge on the buyer's statement at its own rate. *** ## Reporting Orders and payments reflect what the buyer paid in your pricing currency, which is the currency you set on the product. If a buyer paid in their local currency, the payment's `amountDetails` also carries `settlementCurrency` and `settlementAmount` — the currency and amount the buyer was actually charged: ```json theme={"system"} { "currency": "USD", "amount": "10.00", "settlementCurrency": "HKD", "settlementAmount": "81.23" } ``` Query them through the [`payment` GraphQL field](/features/orders-payments#amount-details). Webhook events carry the pricing currency only; look up the payment by `orderId` when you need the presentment amount. *** ## Restrictions Local currency pricing cannot be turned off per store or per checkout session. To have buyers in a market pay a round figure, price the product in that market's currency — see [Tailor Checkout to Your Audience](/guides/checkout-session#tailor-checkout-to-your-audience). Local currency pricing does not apply to: * Buyer locations whose currency is not in the supported list. The buyer pays in your pricing currency. * WeChat Pay. USD-priced WeChat Pay orders are routed via HKD and the WeChat sheet shows CNY — see [WeChat Pay notes](/dashboard/payments#wechat-pay-notes). *** ## Supported currencies Buyers located in a country that uses one of these currencies pay in that currency: | Region | Currencies | | - | - | | Americas | USD, CAD, MXN | | Europe | EUR, GBP | | Asia-Pacific | JPY, HKD, CNY, SGD, KRW, TWD, THB, IDR, AUD | *** ## Pricing * **You pay 0%** * **Your buyers pay 2–4%** You pay no additional Waffo Pancake fee for local currency pricing; all such fees are paid by your buyers. The exchange rate presented to the buyer includes a 2–4% conversion fee, which increases their purchase price by a corresponding amount. Waffo Pancake determines the fee. A buyer whose location uses your pricing currency does not pay this fee, but their bank's exchange rate and fees might apply. For example, a product priced at USD 10.00 is charged as HKD 81.23 to a buyer in Hong Kong, where the mid-market rate would give about HKD 78.50. *** ## Exchange rate Waffo Pancake uses the mid-market exchange rate and applies the conversion fee to guarantee the rate through settlement. The rate is fixed when the buyer is charged. *** ## Refunds You issue a refund in your pricing currency, and Waffo Pancake refunds the buyer in the currency they used to make the payment. The refund uses the same exchange rate as the original charge, so there are no extra costs for you, and the buyer gets back the exact amount they paid. The [refund fee](/mor/fees#refunds) applies as usual. *** ## Settlement Your settlement currency is USD for every store. For USD-priced products you receive the listed price; for products priced in another currency the listed price is converted to USD at settlement. Fees follow the [fee schedule](/mor/fees). The buyer's presentment currency has no effect on what you receive. See [Preferences](/merchant/preferences). # Notifications Source: https://docs.waffo.ai/features/notifications Email notifications for you and your customers Waffo Pancake sends two independent streams of email, both configured under **Settings → Notifications** and controlled separately: > **Customer emails** > > Go to your buyers — receipts, renewals, cancellations. > **Merchant notifications** > > Go to your team, via a per-store recipient list. > [!NOTE] > > The bell icon in the Dashboard header is a preview of an in-app notification centre not yet connected to live data — it stays empty. Email is how notifications reach you today. *** ## Notification Settings Configure which notifications you receive in **Settings → Notifications**. ### Customer Emails Transactional email the platform sends your buyers under your store's name: | Email | Sent when | | - | - | | Order confirmation | A one-time purchase completes | | Subscription confirmation | A subscription starts | | Subscription cycled | A subscription renews | | Subscription plan changed | A plan change takes effect | | Subscription canceled | A subscription is canceled | | Subscription revoked | A canceled subscription permanently ends | | Subscription past due | A subscription payment fails | | Upcoming charge | Before the next subscription charge | > [!NOTE] > > All of these are **always on** except **Upcoming charge**, which you can switch off per store under **Settings → Notifications → Customer Emails**. Switching it off stops the reminder for every subscription in that store, yearly plans included — card networks expect buyers to get advance notice of an annual renewal, so meeting that expectation is then your responsibility. The rest are transactional records the platform must send as Merchant of Record; they go out automatically and need nothing from you. ### Merchant Email Notifications Merchant notifications go to a **recipient list**, not a single fixed mailbox. | | | | - | - | | **Limit** | Up to 5 recipients per store | | **Per recipient** | Its own selection of events | | **Environments** | Shared — the same list applies in Test and Live | | **Saving** | Automatic | So finance takes chargebacks and past-due while operations takes only new orders. Add recipients under **Settings → Notifications**. | Event | Fires on | | - | - | | New orders | A new one-time order was placed | | New subscriptions | A new subscription was activated | | Subscription canceled | A subscriber canceled but the access period is still running | | Subscription renewed | A renewal was charged successfully | | Subscription ended | A subscription fully ended and access was revoked | | Subscription past due | A renewal failed and the subscription is past due | | Subscription uncanceled | A subscriber reverted a pending cancellation | > [!WARNING] > > Emptying the list **stops merchant notifications entirely** — there is no fallback address. Removing the last recipient asks you to confirm, because from then on nobody is notified. Customer emails are a separate pipeline, unaffected by this list. > **[Manage recipients via API](/api-reference/endpoints/notification-recipients/overview)** > > Add, update, and remove notification recipients programmatically. *** ## Webhooks Email suits people; webhooks suit systems. If you need events delivered to your own service — to revoke access, sync a CRM, or drive your own alerting — subscribe to [webhooks](/api-reference/webhooks) instead of parsing email. Webhook events and email notifications are configured independently: turning off a merchant email does not stop the matching webhook, and vice versa. *** ## Best Practices > **Route by role, not by person** > > Give each recipient only the events they act on — finance takes chargebacks and past-due, operations takes new orders. A mailbox that receives everything gets filtered into a folder nobody reads. > **Cover past-due deliberately** > > `Subscription past due` is the one notification tied to money you have already lost. Make sure at least one recipient subscribes to it. > **Use a shared mailbox for continuity** > > Recipients are addresses, not accounts. Pointing one at a team alias rather than an individual keeps notifications flowing when someone is away or leaves. > **Don't rely on email for automation** > > If a system needs to react to an event, subscribe to the [webhook](/api-reference/webhooks). Email is for people. # Orders & Payments Source: https://docs.waffo.ai/features/orders-payments Track transactions and manage your payment lifecycle ## Overview Every purchase in Waffo Pancake creates an **order** and an associated **payment** record. Orders represent the customer's intent to buy, while payments track the actual money movement. *** ## Order Statuses Orders have different status sets depending on the product type. ### One-Time Orders | Status | Description | | - | - | | `pending` | Order created, awaiting payment | | `paid` | Payment succeeded, order fulfilled | | `canceled` | Order was canceled before completion | ### Subscription Orders | Status | Description | | - | - | | `pending` | Subscription created, awaiting first payment | | `active` | Subscription is live and billing normally | | `trialing` | Customer is in a free trial period | | `past_due` | Payment failed, retrying | | `canceling` | Cancellation requested, active until period end | | `canceled` | Subscription canceled (access continues until period end) | | `expired` | Subscription expired | | `closed` | Never activated — payment timed out | *** ## Payment Statuses > **Pending** > > Payment initiated, awaiting processing. > **Processing** > > Payment is being processed. > **Succeeded** > > Payment completed successfully. > **Failed** > > Payment failed during processing. > **Canceled** > > Payment was canceled (timeout, merchant action, or buyer cancellation before processing). > **Refunded** > > Full refund has been processed. > **Partially Refunded** > > A partial refund has been processed. > [!NOTE] > > `processing` may appear in the Dashboard UI but is not returned by the API or GraphQL. Payment statuses from the API are: `pending`, `succeeded`, `failed`, `canceled`. > [!NOTE] > > Refund status is tracked separately via the `refundStatus` field on Payment (`none` / `pending` / `refunded` / `failed`), not as a payment status value. *** ## Payment List View all payments in a table with the following columns: | Column | Description | | - | - | | Date | Transaction timestamp | | Amount | Payment amount as a display format string | | Tax Amount | Tax collected on the transaction | | Status | Current payment status | | Payment Method | `card`, `bank_transfer`, or `wallet` | | Customer | Customer email address | | Currency | ISO 4217 currency code | ### Filtering | Filter | Options | | - | - | | Status | `pending`, `processing`, `succeeded`, `failed`, `refunded`, `partially_refunded` | | Date Range | Custom start and end dates | *** ## Payment Details Click any payment to view its full record. ### Transaction Info | Field | Description | | - | - | | Payment ID | UUID v4 identifier | | Order ID | Associated order | | Store ID | Store that received the payment | | Amount | Gross payment amount (display format string) | | Currency | ISO 4217 currency code | | Status | Current payment status | | Created At | ISO 8601 timestamp | | Updated At | ISO 8601 timestamp | ### Amount Details | Field | Description | | - | - | | `amount` | Total charged amount | | `taxAmount` | Tax portion of the amount | | `settlementCurrency` | Currency the buyer's card was actually charged in (may differ from `currency`) — see [Local Currency Pricing](/features/local-currency) | | `settlementAmount` | Amount charged in that currency (display format string) | | `refundedAmount` | Total amount refunded so far | ### Billing Detail | Field | Description | | - | - | | `country` | Customer's billing country | | `state` | Billing state or region | | `postcode` | Billing postal code | | `isBusiness` | Whether this is a business purchase | | `businessName` | Business name (if applicable) | | `taxId` | Tax ID (if applicable) | ### Payment Method Payments record which method was used: | Method | Value | | - | - | | Credit/Debit Card | `card` | | Bank Transfer | `bank_transfer` | | Digital Wallet | `wallet` | Additional method-specific details may be available in the `paymentMethodDetails` field. The structure of this field varies by payment method. *** ## Supported Payment Methods > **Card** > > Credit and debit card payments. > **Bank Transfer** > > Direct bank-to-bank transfers. > **Wallet** > > Digital wallet payments (Apple Pay, Google Pay, etc.). *** ## Refunds Refunds are handled through a separate ticket-based workflow. Merchants create a refund ticket specifying the payment and reason, from the Dashboard or through the API. > [!NOTE] > > For full details on the refund process, statuses, and policies, see the [Refunds](/features/refunds) page. **Key rules:** * One-time product refunds have **no time limit** and can be issued at any time after payment * Subscription cancellations take effect at the end of the current billing period * Refund tickets track their own status: `pending`, `approved`, `rejected`, `processing`, `succeeded`, `failed` *** ## API Reference ### Creating Orders Orders are created through a two-step checkout session flow: **Step 1: Create a checkout session** (API Key or Store Slug auth) The cURL examples use API Key authentication — the three signature headers, not a Bearer token. See [API Key Authentication](/api-reference/authentication) for how `X-Signature` is computed, or let the SDK sign for you. ```bash One-Time Product theme={"system"} curl -X POST https://api.waffo.ai/v1/actions/checkout/create-session \ -H "Content-Type: application/json" \ -H "X-Merchant-Id: MER_xxx" \ -H "X-Timestamp: 1705312200" \ -H "X-Signature: BASE64_RSA_SHA256_SIGNATURE" \ -d '{ "productId": "PROD_2aUyqjCzEIiEcYMKj7TZtw", "currency": "USD" }' ``` ```bash Subscription Product theme={"system"} curl -X POST https://api.waffo.ai/v1/actions/checkout/create-session \ -H "Content-Type: application/json" \ -H "X-Merchant-Id: MER_xxx" \ -H "X-Timestamp: 1705312200" \ -H "X-Signature: BASE64_RSA_SHA256_SIGNATURE" \ -d '{ "productId": "PROD_5dXBtmF2HLlHfbPNm0Wcnz", "currency": "USD" }' ``` This returns `sessionId`, `checkoutUrl` and `expiresAt`. The product type is resolved from `productId` — the same call serves one-time and subscription products. The session locks the product version and price snapshot; it expires after 24 hours by default, and API Key callers can change that with `expiresInSeconds` (1 minute to 7 days recommended). **Step 2: Create the order** (API Key auth) ```bash One-Time Order theme={"system"} curl -X POST https://api.waffo.ai/v1/actions/onetime-order/create-order \ -H "Content-Type: application/json" \ -H "X-Merchant-Id: MER_xxx" \ -H "X-Timestamp: 1705312200" \ -H "X-Signature: BASE64_RSA_SHA256_SIGNATURE" \ -d '{ "checkoutSessionId": "cs_550e8400-e29b-41d4-a716-446655440000", "language": "en", "billingDetail": { "country": "US", "isBusiness": false, "state": "CA" } }' ``` ```bash Subscription Order theme={"system"} curl -X POST https://api.waffo.ai/v1/actions/subscription-order/create-order \ -H "Content-Type: application/json" \ -H "X-Merchant-Id: MER_xxx" \ -H "X-Timestamp: 1705312200" \ -H "X-Signature: BASE64_RSA_SHA256_SIGNATURE" \ -d '{ "checkoutSessionId": "cs_550e8400-e29b-41d4-a716-446655440000", "language": "en", "billingDetail": { "country": "US", "isBusiness": false, "state": "CA" } }' ``` `language` is required and must be one of the supported cashier languages. Both endpoints return a `checkoutUrl` to redirect the buyer to for payment, plus a `nextCheckoutUrl` — the replacement session the buyer lands on if they come back from the payment provider (see [Session Lifecycle](/features/checkout#session-lifecycle)). ### Querying Payments Use the GraphQL endpoint to query payment records: ```graphql theme={"system"} query { payments(storeId: "store-uuid", limit: 20) { id orderId amount currency status paymentMethod amountDetails { amount taxAmount settlementCurrency settlementAmount refundedAmount } billingDetail { country state postcode isBusiness businessName taxId } createdAt } } ``` > [!TIP] > > All amounts are display format strings. For example, `"29.00"` in USD means \$29.00. For zero-decimal currencies like JPY, `"4500"` means 4500 yen. # Products Source: https://docs.waffo.ai/features/products One-time or recurring. Your revenue, your rules. ## Product = Billing Object In Waffo Pancake, a **product** is the object used for checkout, taxation, and reporting. It is the commercial offer you charge for, not just a storefront card. > [!NOTE] > > For professional use, think of products as billing entities: > > * a fixed-price offer > * a subscription plan > * or a base product used with dynamic pricing at checkout *** ## Core Models > **One-Time** > > Customer pays once for a predefined offer. > > * Digital downloads > * Lifetime licenses > * Templates, courses, assets > **Subscription** > > Customer is billed on a recurring schedule. > > * SaaS plans > * Memberships > * Service retainers > **Dynamic Pricing** > > Amount is calculated at checkout time. > > * Usage overage > * Credit top-ups > * Negotiated quotes *** ## Create a Product Dashboard --> Products --> **Create Product** ```json theme={"system"} { "storeId": "your-store-uuid", "name": "Pro Plan", "prices": { "USD": { "amount": "29.00", "taxIncluded": false, "taxCategory": "saas" } } } ``` **Done.** You get a permanent purchase link for fixed-price selling, or a reusable billing object for programmatic checkout. *** ## Product Fields ### Required | Field | What It Is | | - | - | | Name | What customers see | | Price | How much you charge | | Currency | USD, EUR, GBP, JPY, HKD — CNY for one-time products only. Several currencies can apply at once; see [Multi-Currency Pricing](#multi-currency-pricing) | | Type | One-time or Subscription | | Tax Category | SaaS, Digital Goods, Software, etc. | ### Optional | Field | Default | Purpose | | - | - | - | | Description | — | Markdown. Sell your product. | | Image | — | 400x400px recommended | | Redirect URL | — | Where the customer lands after checkout. Used for both successful and failed payments — only one URL is configurable. | ### Price Limits Each currency has a minimum and maximum price you can set on a product. Values outside this range are rejected when you save the product. | Currency | Minimum | Maximum | | - | -: | -: | | USD | \$1.00 | \$10,000.00 | | EUR | €1.00 | €9,400.00 | | GBP | £1.00 | £8,150.00 | | JPY | JP¥100 | JP¥1,600,000 | | CNY | CN¥1.00 | CN¥1,000.00 | | HKD | HK\$8.00 | HK\$77,600.00 | > [!NOTE] > > **CNY prices one-time products only** — subscription products cannot be priced in CNY. CNY-priced orders are payable by WeChat Pay only, and each buyer can pay you at most ¥1,000 via WeChat per calendar month. See [Method and currency support](/dashboard/payments#method-and-currency-support). *** ## Multi-Currency Pricing Price the same product deliberately per market — `$9.99`, `JP¥980`, `CN¥68` — instead of pushing one base price through a live rate into awkward numbers. | | | | - | - | | **Where** | Product create / edit form | | **Per currency** | Own price and tax category | | **Validation** | Each currency checked against its own [price limits](#price-limits) | | **At checkout** | Display currency resolved deterministically; amounts localized | ### Reference prices Adding a currency prefills the amount by converting your existing price at the current rate. > [!WARNING] > > That figure is a **reference price**, not a commitment. Round it to whatever suits the market — the rate hint stays beside the currency while more than one is configured. ### Yen disambiguation `CN¥` for Chinese yuan, `JP¥` for Japanese yen — applied everywhere, so the two are never confused at checkout. > [!NOTE] > > Currencies are priced independently rather than converted, so a subscription cannot change plan across currencies. See [Changing Plans](/features/subscriptions#changing-plans). *** ## Dynamic Pricing Dynamic pricing is the right model when the final amount is not known until runtime. Examples: * usage-based overage billing * prepaid credit packs with variable size * contract-specific quotes * temporary discounts calculated on your server ### How It Works 1. Create a **base one-time product** in Waffo Pancake 2. Calculate the final amount on your server 3. Pass `priceSnapshot` when creating the checkout session ```typescript theme={"system"} const session = await client.checkout.createSession({ storeId: "store_id", productId: "usage-overage-product-id", productType: "onetime", currency: "USD", priceSnapshot: { amount: calculatedAmount, taxIncluded: false, taxCategory: "saas", }, }); ``` > [!WARNING] > > `priceSnapshot` overrides the stored product price for that checkout session. Use it only from your server, never from untrusted client code. > [!TIP] > > If the amount is event-based, keep it as a one-time charge even if the customer is already on a subscription. *** ## Trial Periods Let customers try subscription products before they commit. A trial can be free or carry a price — see [Paid Trials](/features/subscriptions#paid-trials). ### Trial Abuse Protection Waffo Pancake automatically tracks consumer trial history at the platform level. When a consumer starts a new subscription, the platform calculates the maximum available trial days based on their history — preventing repeated trial abuse without any effort from the merchant. Merchants can also pass `requested_trial_days` via the API to shorten or skip the trial for specific customers. > [!WARNING] > > Effective trial abuse prevention requires `buyerIdentity`. Use [authenticated checkout](/integrate/sdks#authenticated-checkout-recommended) to ensure each buyer can only claim one trial per product. *** ## Billing Intervals | Interval | When | Best For | | - | - | - | | Weekly | Every 7 days | High-usage products | | Monthly | Every month | Standard SaaS | | Quarterly | Every 3 months | B2B software | | Yearly | Every 12 months | Committed customers | *** ## Product Purchase Links Every product gets a permanent purchase link that never expires: ``` https://pancake.waffo.ai/store/{store-slug}/product/{productId} ``` Test mode: ``` https://pancake.waffo.ai/store/{store-slug}/product/{productId}?test=true ``` **Add to your website:** * Website button * Twitter bio * Email signature * Discord server **Key benefits:** * Link is permanent — it stays the same even when you update product details * No session or token management needed * A checkout session is created automatically when the customer opens the link **Getting your link:** * **Dashboard**: Click "Copy Link" on any product * **API**: For advanced use cases, create a Checkout Session via API with custom parameters (dynamic link, 24-hour default TTL, configurable, 1 minute to 7 days recommended) **Test vs Live:** * Toggle Test Mode in Dashboard header to preview with test links * Test links add `?test=true` *** ## Product Status > **Active** > > Live. Customers can buy. > **Inactive** > > Hidden from checkout; existing subscriptions continue. Products cannot be deleted — completed orders, invoices and settlement records reference them. Renaming or repricing adds a new version and keeps the product ID. *** ## Updating Products Products use **immutable versioning**: > [!WARNING] > > Updates create new versions. Existing subscriptions keep their original version. | Field | Impact | | - | - | | Name/Description | Creates new version | | Image | Creates new version | | Price | New purchases only | | Interval | Cannot change after creation | ### Environment Sync Publish product versions from test to production: ```bash theme={"system"} POST /v1/actions/onetime-product/publish-product { "id": "product-id" } ``` > [!NOTE] > > Publishing is one-way (test → prod) and only needed for the first publish. *** ## Best Practices > **Naming** > > Include billing period: > > * "Pro Plan - Monthly" > * "Pro Plan - Annual" > **Pricing** > > * Round numbers ($29, not $28.73) > * Research competitors > **Images** > > * 400x400px minimum > * PNG or JPG > * Under 5MB # Refunds Source: https://docs.waffo.ai/features/refunds Manage refund tickets, process full or partial refunds, and track refund status ## Overview Waffo Pancake uses a **refund ticket** system. Merchants issue refunds from the Dashboard or through the API, and each refund creates a ticket that moves through a defined lifecycle. *** ## Business Rules > [!NOTE] > > These rules are enforced by the API and cannot be overridden. * **One-time products** can be refunded by the merchant at any time after payment — there is **no refund time limit**. * **Subscriptions** do not use the refund ticket system. Cancellation takes effect at the end of the current billing period. * **Partial refunds** are supported by providing a custom `amount` (as a display format string, e.g., "15.00") when creating a ticket. *** ## Refund Ticket Statuses Every refund ticket moves through the following lifecycle: > **pending** > > Refund ticket created, awaiting review. > **approved** > > Refund approved by the merchant. > **rejected** > > Refund ticket rejected. > **processing** > > Refund is being processed by the payment provider. > **succeeded** > > Refund completed successfully. > **failed** > > Refund processing failed. *** > [!NOTE] > > **Arrival time, and what "processing" means.** Card refunds are handled by the buyer's issuing bank and typically arrive within 3–10 business days (no later than 14); WeChat Pay refunds arrive immediately. A ticket in `processing` is at the payment-provider / bank stage — Waffo does not run an internal finance review on top of it. ## Creating a Refund Ticket Refund tickets are created by calling the API with API Key authentication. ### Endpoint ``` POST /v1/actions/refund-ticket/create-ticket ``` **Authentication:** API Key ### Request Body **paymentId** `string` *required* The ID of the payment to refund (UUID v4). **reason** `string` *required* A description of why the refund is being requested. **amount** `string` Amount to refund as a display format string (e.g., "15.00"). Omit for a full refund. ### Response **ticketId** `string` The unique ID of the created refund ticket. **status** `string` Initial status of the ticket. Always `pending` on creation. **requestedAmount** `string` The refund amount as a display format string. ### Example The cURL tab uses API Key authentication — the three signature headers, not a Bearer token. See [API Key Authentication](/api-reference/authentication) for how `X-Signature` is computed. ```bash cURL theme={"system"} curl -X POST https://api.waffo.ai/v1/actions/refund-ticket/create-ticket \ -H "Content-Type: application/json" \ -H "X-Merchant-Id: MER_xxx" \ -H "X-Timestamp: 1705312200" \ -H "X-Signature: BASE64_RSA_SHA256_SIGNATURE" \ -d '{ "paymentId": "550e8400-e29b-41d4-a716-446655440000", "reason": "Product not as described", "amount": "15.00" }' ``` > [!NOTE] > > The merchant SDK (`@waffo/pancake-ts`) does not wrap this endpoint yet — call the REST endpoint with your own signature as shown above. `createRefundTicket()` exists only on the customer-token client (`client.customer(token)`); it is not a merchant-side call. *** ## Querying Refund Tickets Use GraphQL to retrieve refund ticket data. ```graphql theme={"system"} query { refundTickets(storeId: "STORE_ID") { id paymentId storeId customerId reason status requestedAmount approvedAmount currency createdAt updatedAt resolvedAt } } ``` | Field | Type | Description | | - | - | - | | `id` | string | Refund ticket ID | | `paymentId` | string | Associated payment ID | | `storeId` | string | Store that owns the payment | | `customerId` | string | Buyer who made the original payment | | `reason` | string | Reason for the refund | | `status` | string | Current ticket status | | `requestedAmount` | string | Amount the buyer requested (display format string) | | `approvedAmount` | string | Amount approved (may differ from requested) | | `currency` | string | ISO 4217 currency code | | `createdAt` | string | ISO 8601 timestamp | | `updatedAt` | string | ISO 8601 timestamp | | `resolvedAt` | string | ISO 8601 timestamp (null if unresolved) | *** ## Webhook Notifications You can configure webhooks to receive notifications when refund ticket events occur. See the [Webhooks guide](/integrate/webhooks) for setup instructions. *** ## Reducing Refund Requests > **Clear Product Descriptions** > > Accurate descriptions reduce "not as expected" refund requests. > **Trial Periods** > > Let customers try before buying to reduce post-purchase regret. > **Responsive Support** > > Address issues quickly before they become refund requests. > **Recognizable Billing** > > Use a clear billing descriptor so customers recognize charges. # Subscriptions Source: https://docs.waffo.ai/features/subscriptions Recurring revenue on autopilot ## Recurring Revenue. Automated. Customers subscribe. We handle billing cycles, renewal recovery, and lifecycle management. You focus on your product. *** ## How It Works ``` Customer subscribes → Billing cycle → Auto-charge → Repeat ``` If a renewal charge fails, the subscription enters `past_due`. Waffo schedules no retries of its own: the payment channel retries the charge **once**, typically the next day. If that retry succeeds the subscription returns to `active` (`subscription.recovered`); if it fails, the subscription is canceled immediately (`subscription.canceled`) and the customer has to subscribe again. There is no separate grace-period timer. Customers receive a reminder email before each renewal (1 day ahead for weekly plans, 3 days for monthly and quarterly, 7 days for yearly; 1 day before a trial ends) and a receipt after each successful charge. *** ## Subscription Plan Structure In Waffo Pancake, each **separately purchasable subscription option** is an independent subscription product. The most common distinction is billing interval, such as: * monthly * yearly If you offer both monthly and yearly billing, you would normally create **two subscription products**. | Business offer | Waffo model | | - | - | | Monthly plan | 1 subscription product | | Yearly plan | 1 subscription product | *** ## Subscription States | Status | Description | | - | - | | `pending` | Awaiting first payment | | `active` | Live and billing normally | | `trialing` | In trial period (free or paid) | | `past_due` | Renewal charge failed; awaiting the channel's single retry | | `canceling` | Cancellation requested, access continues until current period ends | | `canceled` | Will not renew after current period | | `expired` | Subscription has reached the end of its term | | `closed` | Never activated — payment timed out | *** ## Billing Intervals | Interval | Frequency | Best For | | - | - | - | | Weekly | Every 7 days | Usage-heavy products | | Monthly | Every month | Standard SaaS | | Quarterly | Every 3 months | B2B software | | Yearly | Every 12 months | Committed customers | *** ## Trial Periods Reduce signup friction. Let customers try before they commit — free, or for a small charge. ### Configure Trials When creating a subscription product, enable the trial toggle and set the number of days in the Dashboard. ### Platform-Level Trial Protection Waffo Pancake acts as the Merchant of Record and automatically prevents trial abuse: | Layer | How It Works | | - | - | | **Platform (Pancake)** | Tracks each consumer's trial history across all merchants. Calculates the maximum available trial days for each new subscription. | | **Merchant** | Can pass `requested_trial_days` when creating an order via API to customize the trial length per customer. | **How the two layers interact:** * If the merchant requests ≤ the platform maximum → the merchant's requested value is used * If the merchant requests > the platform maximum → falls back to the platform maximum * If the merchant doesn't specify → the full platform maximum is used ### Paid Trials Trials don't have to be free. You can charge a small, reduced amount during the trial period instead of waiving it entirely — the classic "\$1 trial" pattern. It's optional, can be set per currency, and always stays lower than the regular price. When the trial ends, billing switches automatically to the full price. > [!TIP] > > Paid trials filter out low-intent signups better than free trials, at the cost of some conversion friction. A small symbolic charge (e.g. \$1) is usually enough to confirm payment method validity without deterring genuine buyers. > **[Set a trial price via API](/api-reference/endpoints/subscription-products/create-product#price-object-format)** > > See the `trialAmount` field reference for request format and rules. ### Buyer Identity & Trial Protection Trial eligibility is tracked by `buyerIdentity` — a stable identifier you provide via [authenticated checkout](/integrate/sdks#authenticated-checkout-recommended). The platform uses this to detect repeat trial claims across sessions. > [!WARNING] > > Without `buyerIdentity` (anonymous checkout), trial eligibility checks are skipped entirely. Any buyer can claim unlimited trials by changing their email address. > [!TIP] > > 7-14 day trials work best. Too short = not enough time to evaluate. Too long = forgotten. *** ## Renewal Recovery When a renewal charge fails, the subscription transitions to `past_due` and you receive `subscription.past_due`. The recovery window is short and fixed by the payment channel: it retries the charge once, typically the next day. * **Retry succeeds** — the subscription returns to `active` and you receive `subscription.recovered` plus `subscription.payment_succeeded`. * **Retry fails** — the subscription is canceled immediately and you receive `subscription.canceled`. The customer must subscribe again; there is no further retry and no grace-period timer. Keep access on during the `past_due` day and prompt the customer to update their payment method before the retry, since a second failure ends the subscription. > [!NOTE] > > Treat `past_due` as "renewal requires recovery", not simply "payment failed and service stopped". *** ## Managing Subscriptions ### Cancel Cancellation is always effective at the end of the current billing period. When a cancellation is requested, the subscription enters the `canceling` intermediate state. The customer retains access until the current billing period ends, at which point the status transitions to `canceled`. ```bash theme={"system"} POST /v1/actions/subscription-order/cancel-order { "orderId": "ORD_5dXBtmF2HLlHfbPNm0Wcnz" } ``` Response includes `currentPeriodEnd` so you know when access expires. The returned status will be `canceling` (or `canceled` if the period has already ended). > [!NOTE] > > There is no immediate cancellation option. Customers always retain access through the end of their paid period. The `canceling` → `canceled` transition happens automatically when the current billing period expires. > > A refund does **not** change subscription status: refunding a payment leaves `status`, `isInTrial` and `willRenew` exactly as they were, and the subscription keeps renewing. To stop future charges, cancel the subscription separately. ### Resume Subscription If a subscription is still in `canceling`, the customer can resume it before the current period ends. After resuming: * the subscription returns to `active` * access continues without interruption * future renewals continue on the original billing cycle > [!NOTE] > > Resuming applies to subscriptions that were canceled but have not reached the end of the current period yet. It is effectively an undo for cancellation, not a brand-new purchase. ### Changing Plans A plan change moves a subscriber to a different plan without making them cancel and buy again. It is modelled as **one cancellation plus one new subscription** — the old order closes, a new one opens. There is no in-place edit of a subscription's plan. The customer always confirms on a hosted **change confirmation page**: old and new plans side by side, the prorated difference itemized, and the effective date stated. #### Direction decides the default timing | Direction | Default timing | Can it take effect immediately? | | - | - | - | | **Upgrade** (higher pre-tax price) | Immediate | Yes | | **Downgrade** | Next period | Only if the merchant sets `changeAmount`, or passes `withTrial: true` | | **Same price** | Next period | Same rule as a downgrade | On an immediate change the unused value of the current plan is credited against the new plan's charge. That credit is recalculated **at submission time** from the days actually remaining — the figure shown when the link was issued is an estimate, not a promise. The credit is based on what the customer pays for the current period, after any discount. A discount on the subscription carries over to the new plan, unless the change comes with a new code that replaces it, or the discount can no longer continue. See [Plan Changes](/guides/discounts#plan-changes). > [!WARNING] > > **The last 24 hours are asymmetric.** An immediate change needs at least 24 hours before the next charge; a next-period change needs only 1 hour before the period ends. > > So inside that final day an upgrade fails with 400 (`Immediate plan change requires at least 24 hours before the next charge`) unless you explicitly pass `changeTiming: "next_period"` — it does **not** silently fall back. Downgrades already default to next period, so they still work. *** #### Who can start one Two routes, and they follow different rules: | Route | Who initiates | Constraints | | - | - | - | | **Customer Portal** | The customer, for themselves | Both plans in the same [product group](/guides/subscriptions#step-2-organize-plans-with-product-groups), with `selfServicePlanChange` on | | **Merchant API** | You, on their behalf | None — you choose the target plan, and can set the amount and trial | > [!WARNING] > > `selfServicePlanChange` is a product-group rule and **counts as off when unset**. While it is off, portal plan changes are rejected with 403 — merchant-issued changes are unaffected. Turn it on before telling customers they can switch plans themselves. > [!NOTE] > > Starting a plan change from the **Dashboard UI** is not available yet — the entry point on the subscriptions page is marked *coming soon*. The API works today. *** #### Customer self-service Self-service happens in the **Customer Portal**, and it needs no integration work from you. The customer signs in, opens the subscription, picks another plan in the same group, and confirms. To enable it: put the plans in one product group and turn on `selfServicePlanChange`. > [!NOTE] > > The portal is not the only self-service surface. You can offer the same thing in your own UI with a customer session token — `customer.createPlanChangeSession()` in the SDKs — which runs under the customer's own credential and is gated by exactly the same three conditions: their own subscription, same product group, `selfServicePlanChange` on. Issuing the link with your **API Key** instead is a different path: none of the three apply, and you can move a subscription to any plan — see below. *** #### Merchant-initiated changes via API **1. Issue the change link** Call [`checkout/create-session`](/api-reference/endpoints/orders/create-checkout-session) with `originOrderId` set to the subscription you want to move. That puts the endpoint into **plan-change mode** and returns a `checkoutUrl` for the confirmation page. ```json theme={"system"} { "productId": "PROD_5xK2mNqR8vT1wY7zA3bC4d", "currency": "USD", "originOrderId": "ORD_2aUyqjCzEIiEcYMKj7TZtw" } ``` **2. Deliver it yourself** Email, in-app message, however you already reach the customer. The platform does not send this link. **3. Customer confirms** They review the comparison and confirm. Your system finds out by webhook. **Optional parameters** | Parameter | Effect | | - | - | | `changeTiming` | `immediate` or `next_period`. Omit to use the direction default above. Only valid alongside `originOrderId` | | `changeAmount` | Charge a specific amount this cycle, **tax-inclusive**. Exceeding the target plan's normal charge returns 400 — it never silently falls back to list price | | `withTrial` | `true` forces a trial and skips eligibility checks, `false` forces none. Omit to follow the product group's rules | **Guards checked when issuing the link** — these fail before the customer ever sees the page: | Condition | Status | | - | - | | Target plan uses a different currency | 400 | | Subscription is in a trial | 409 | | Subscription already has a **confirmed** change | 409 | | Target plan is the current plan | 400 | > [!TIP] > > An *unconfirmed* change does not block a new one. If the customer opened a link and never paid, just issue another. *** #### What your system should expect Three [webhook events](/api-reference/webhooks) cover the lifecycle: | Event | Fires when | | - | - | | `subscription.plan_change_scheduled` | Customer confirmed, switch set for the next period | | `subscription.plan_changed` | The switch took effect. `data.planChange` carries direction, both plan names and prices, and `chargedAmount` | | `subscription.plan_change_failed` | The payment channel reported it did not complete | An immediate change reaches its switch moment right after authorization, so it goes straight to `plan_changed` with no `scheduled` event first. > [!WARNING] > > **Two traps for access-control logic:** > > 1. `subscription.activated` and `subscription.canceled` are **not** sent for the two orders involved — deliberately, so a "revoke access on cancellation" handler does not fire on a plan change. > 2. Between confirmation and the switch moment the original subscription sits in `canceling` **while still entitled** — its paid period is still running. Treat `canceling` as active access, exactly as you would for a customer's own end-of-period cancellation. > [!NOTE] > > While a scheduled change is pending, the new subscription has **no billing period yet** (`currentPeriod` is `null`) — the first period is confirmed by the payment channel at the switch moment. **If it fails**, the new order closes and the original subscription carries on as before. A scheduled change that had already moved the original to `canceling` puts it **back to active**. You can then issue a new change. > [!NOTE] > > Cross-currency changes are not supported, and a subscription cannot change plan during a trial. ## Metrics ### MRR (Monthly Recurring Revenue) ``` Weekly subscription: $10 × 4.33 = $43.30 MRR Monthly subscription: $29 × 1 = $29 MRR Annual subscription: $290 ÷ 12 = $24.17 MRR ``` ### Key Metrics | Metric | What It Tells You | | - | - | | MRR | Monthly recurring revenue | | Churn | % subscriptions canceled | | LTV | Customer lifetime value | | ARPU | Average revenue per user | *** ## Webhooks Subscribe to subscription lifecycle events via webhooks. Configure webhook endpoints in **Settings --> Webhooks**. > [!WARNING] > > Specific webhook event names are not listed here as they may change. Refer to the webhook configuration in your Dashboard for the current list of available events. Webhook payloads use standard Waffo Pancake conventions: * IDs are UUID v4 format * Amounts as display format strings * Timestamps in ISO 8601 UTC * Billing frequency uses the `billingPeriod` field (e.g., `monthly`, `yearly`) *** ## Customer Portal Let customers manage their own subscriptions: * View details * Update payment method * Change plans * Cancel * Resume subscription * Download invoices > **[Customer Portal](/features/customer-portal)** > > Self-service subscription management. *** ## Best Practices > **Don't cut access immediately** > > A missed renewal charge does not need to mean instant cancellation. Give the customer time to recover the subscription. > **Send reminders** > > Trial ending. Upcoming charge. No surprises. # Test Mode Source: https://docs.waffo.ai/features/test-mode Break things. Risk-free. ## Test Everything. Break Nothing. Build and test your entire integration without real transactions. No real charges. No real payouts. Just safe experimentation. > **Safe** > > No real money moves. > **Full Features** > > Everything works like Live Mode. *** ## Test vs Live | | Test Mode | Live Mode | | - | - | - | | Transactions | Simulated | Real charges | | Money | Fake | Real funds | | Data | Isolated | Production | | Webhooks | Fully functional | Fully functional | | API Behavior | Identical | Identical | **Switch modes:** Dashboard header toggle or `X-Environment` header in API calls. | Header Value | Mode | | - | - | | `X-Environment: test` | Test Mode | | `X-Environment: prod` | Live Mode | > [!WARNING] > > Always verify you're in the correct mode before sharing payment links. *** ## API Keys by Environment API Keys are created for a specific environment (test or production). When creating an API key in the Dashboard, you select which environment the key belongs to. | Environment | Purpose | | - | - | | Test | Development and testing | | Production | Real payments | > [!NOTE] > > API Keys use key pair authentication, not prefixed secret keys. See [Authentication](/api-reference/authentication) for details. *** ## Test Cards ### Successful Payments | Card | Type | | - | - | | `4576 7500 0000 0110` | Visa Credit | | `2226 9000 0000 0110` | Mastercard Credit | | `4001 7000 0000 0110` | Visa Debit | | `2226 9300 0000 0110` | Mastercard Debit | ### Declined Payments | Card | Type | | - | - | | `4576 7500 0000 0220` | Visa Credit | | `2226 9000 0000 0220` | Mastercard Credit | | `4001 7000 0000 0220` | Visa Debit | | `2226 9300 0000 0220` | Mastercard Debit | > [!NOTE] > > Any future expiry date. Any 3-digit CVC. *** ## Test Payment Methods ### Digital Wallets Test Mode shows simulated UI: * **Apple Pay** -- Safari/iOS * **Google Pay** -- Chrome/Android *** ## Test Webhooks Webhooks fire normally in Test Mode. To test your webhook endpoints: 1. Register your webhook endpoint in Dashboard --> API & Development 2. Switch to Test Mode 3. Perform actions that trigger events (create orders, complete payments) 4. Your endpoint receives webhook events just like in Live Mode *** ## Test Subscriptions Test the full lifecycle: 1. **Create** -- Subscribe via test checkout 2. **Bill** -- Renewals bill on the real schedule. You can also advance one period yourself with the simulation buttons below 3. **Update** -- Change plans via the Customer Portal or API 4. **Cancel** -- Test cancellation flow 5. **Expire** -- Verify expired subscription behavior ### Simulate a Renewal Open a test subscription in Dashboard --> Subscriptions and use the two buttons in the detail drawer to advance one billing period without waiting for the real due date: * **Simulate renewal success** -- charges the next period as paid. A new successful payment appears, the next billing date moves forward one period, and your endpoint receives `subscription.payment_succeeded` (plus `subscription.renewed`). On a past due subscription the recovery also emits `subscription.recovered`. * **Simulate renewal failure** -- charges the next period as failed. An active subscription becomes past due and your endpoint receives `subscription.past_due`. > [!WARNING] > > Simulated failures accumulate: `active` --> `past_due` --> `canceled`. A second failure on an already past due subscription terminates it for good — the subscription becomes canceled, emits `subscription.canceled`, and cannot be restored. The Dashboard asks for confirmation before every simulated failure. > [!NOTE] > > Both buttons only exist in Test Mode, and the API rejects the request for live subscriptions regardless of what the UI shows. Each click advances exactly one period — there is no rewind, no reset and no "advance N periods". > > Results arrive asynchronously from the payment provider: a successful click means "triggered", not "already applied". Refresh the page after a moment to see the new payment, the new status and the webhook delivery. > [!NOTE] > > Expiry has no self-service equivalent: to exercise one without waiting a full cycle, send the test order ID to support and we advance the subscription for you. **Send Test Events** under Dashboard → Webhooks delivers one sample payload only; it is not tied to any of your real test orders. *** ## Test Data ### Isolation Test data is completely separate: * Test products don't appear in Live Mode * Test customers are separate * Test transactions don't affect live reports ### Environment Sync When ready to go live, sync your products from test to production: The example below uses API Key authentication — the three signature headers, not a Bearer token. See [API Key Authentication](/api-reference/authentication) for how `X-Signature` is computed, or let the SDK sign for you. ```bash theme={"system"} curl -X POST https://api.waffo.ai/v1/actions/onetime-product/publish-product \ -H "Content-Type: application/json" \ -H "X-Merchant-Id: MER_xxx" \ -H "X-Timestamp: 1705312200" \ -H "X-Signature: BASE64_RSA_SHA256_SIGNATURE" \ -d '{ "id": "product-uuid" }' ``` > [!NOTE] > > The publish-product endpoint is a one-way operation from test to production. It does not require an `X-Environment` header. *** ## Going Live Checklist Before accepting real payments: * [ ] Complete end-to-end testing in test mode * [ ] Test edge cases (declined cards, failures) * [ ] Verify webhook handling * [ ] Test checkout on mobile devices * [ ] Add a payout account (Payout Accounts) * [ ] Complete business details (Settings --> Business Details) * [ ] Review product pricing * [ ] Sync products from test to production using publish-product > **[Quickstart](/quickstart#going-live-checklist)** > > Full going-live checklist. # AI Product Billing Source: https://docs.waffo.ai/guides/ai-billing Set up flexible billing for AI products and API services ## Who Is This For? This guide is for developers building AI products, API services, or any usage-based business. Common examples: | Business Type | Examples | | - | - | | AI API Services | LLM API proxies, image generation, speech recognition | | AI SaaS | AI writing assistants, AI code completion, AI translation | | AI Agent Platforms | Automated workflows, data analysis agents | | API Services | Payment processing, messaging, data queries | *** ## How Billing Works with Waffo Pancake Waffo Pancake does not provide built-in usage metering, but you can model AI billing with two primary approaches: `subscriptions` and `on-demand purchases`. In many businesses, these two approaches work best together. ### Approach 1: Subscriptions Create subscription products at different tiers, each with a different token quota, request allowance, or task limit. > Prices below are examples only. Set them based on your actual business and costs. | Plan | Monthly | Token Quota | Best For | | - | - | - | - | | **Starter** | \$9/month | 100K tokens | Individual developers | | **Pro** | \$49/month | 1M tokens | Small teams | | **Scale** | \$199/month | 10M tokens | Enterprise | Best for: * recurring monthly or annual access * plans with included usage * upgrade paths that unlock higher quotas ### Approach 2: On-Demand Purchases Use one-time orders or dynamic pricing to charge based on additional usage, credits, or runtime-calculated amounts. Best for: * buying extra tokens or credits * charging for overage beyond the included plan * per-task, per-call, or quoted usage #### Dynamic Pricing via Checkout Session Pass dynamic pricing through `priceSnapshot` when creating a checkout session to charge based on actual usage. ```typescript theme={"system"} const session = await client.checkout.createSession({ storeId: "store_id", productId: "usage-product-id", productType: "onetime", currency: "USD", // replace with your currency priceSnapshot: { amount: calculatedAmount, // dynamically calculated based on usage taxIncluded: false, taxCategory: "saas", }, }); ``` ### External Metering Tools Use dedicated metering tools to track usage, combined with Waffo Pancake for billing. *** ## Recommended Metering Tools > **[New API](https://github.com/QuantumNous/new-api)** > > API aggregation and management platform with multi-model key distribution, usage tracking, and quota control. Waffo Pancake partner. *** ## Recommended Combination > [!NOTE] > > Most AI products do not need to choose only one billing model. The most common pattern is to combine subscriptions with on-demand purchases. ### Combined Pattern: Base Subscription + On-Demand Usage This is the most common and easiest billing model for customers to understand. **Setup:** 1. Create tiered subscription products such as Starter / Pro / Scale 2. Include a fixed quota of tokens, requests, or tasks in each plan 3. Track actual usage with an external metering system 4. When a user exceeds the included quota, charge extra through a one-time order or `priceSnapshot` **Fits well for:** * AI API services * AI SaaS * AI agent platforms **Dashboard workflow:** * Monitor active plans in **Subscriptions** * Review extra purchases or overage charges in **Payments** * Track subscription revenue and on-demand revenue together in **Analytics** *** ## Key Webhook Events | Event | Action | | - | - | | `subscription.activated` | Set initial token/request quota | | `subscription.plan_changed` | Adjust quota to match new plan | | `subscription.canceled` | Revoke API access or downgrade to free tier | | `subscription.past_due` | Reduce quota or throttle API calls | | `order.completed` | Grant additional token allowance (overage purchase) | For API details, see the [API Reference](/api-reference/introduction). *** ## Testing **1. Create Test Products** Set up both subscription products and on-demand products in test mode. **2. Subscribe with Test Card** Use `4576 7500 0000 0110` to subscribe to each tier. **3. Simulate Usage** Test your usage tracking and quota enforcement logic. **4. Test On-Demand Billing** Verify the dynamic pricing and on-demand billing flow. *** ## Launch Checklist * [ ] Subscription products created for each tier * [ ] On-demand or overage product created * [ ] Pricing and quotas clearly documented * [ ] Usage tracking/metering tool integrated * [ ] Quota enforcement working correctly * [ ] Upgrade/downgrade flows tested * [ ] On-demand billing flow verified * [ ] Products published to production *** ## Next Steps > **[Run SaaS Subscriptions](/guides/subscriptions)** > > Learn more about subscription management > **[Set Up Webhooks](/guides/webhooks)** > > Automate quota management with webhooks # Let Signed-In Customers Manage Orders Without Email Verification Source: https://docs.waffo.ai/guides/customer-portal-sso Send customers who are signed in on your site straight into your store's customer portal ## What You'll Build A **Manage orders** button on your site. When a signed-in customer clicks it, your server asks Waffo Pancake for a portal link and redirects the browser there. The customer lands in your store's customer portal, already signed in, with no email or verification code. ```mermaid theme={"system"} sequenceDiagram participant C as Customer Browser participant S as Your Server participant W as Waffo Pancake API participant P as Customer Portal C->>S: Click "Manage orders" S->>S: Read the customer from your own session S->>W: Create portal link (API Key) W->>S: portalUrl, expiresAt S->>C: 302 redirect to portalUrl C->>P: Portal for this customer, this store ``` In the portal the customer can: | Area | Available | | - | - | | Orders and payments | View | | Subscriptions | View, cancel, reactivate, change plan | | Invoices | View | | Refund tickets | View only — creating or resubmitting a refund request is not available in this version | > [!NOTE] > > Customers who arrive this way cannot request refunds from the portal. Handle refund requests through your own support channel, then refund from the Dashboard or with the [Create Refund Ticket](/api-reference/endpoints/refunds/create-refund-ticket) API. *** ## Prerequisites * An API Key (Dashboard → API & Development). Use a test key while you build * The Store ID (`STO_xxx`) of the store whose portal the customer should see * Orders created with [authenticated checkout](/integrate/sdks#authenticated-checkout-recommended), so they carry your `buyerIdentity` * Your own sign-in: this flow trusts your server's session, so the customer must already be authenticated on your site * If you use an SDK: `@waffo/pancake-ts` 0.26.0 or later, `@waffo/pancake-nextjs` 0.9.0 or later, or the [Go SDK](https://pkg.go.dev/github.com/waffo-com/waffo-pancake-sdk-go) v0.17.0 or later * Your store's **Website** set in [Store Settings](/settings/store-settings). When a portal session ends, the portal offers a **Return to merchant site** button that links only to this address; if no website is set, the button is hidden *** ## Step 1: Choose the Customer Identity The portal shows the orders whose `buyerIdentity` equals the value you pass here, in the store you name. Use **the same stable value you pass when creating orders**. * **Recommended:** your internal customer ID — stable, and never reassigned to another person * Avoid email addresses: a customer who changes email would lose sight of earlier orders, and a recycled address could expose them to someone else * Orders placed anonymously, or under a different identity, **do not appear**. Waffo Pancake does not merge identities; if you switch identifiers, earlier orders stay under the old value > [!WARNING] > > Take `buyerIdentity` and `storeId` from your server's own signed-in session — never from a query parameter, form field, header, or cookie value the browser can set. Whoever controls `buyerIdentity` gets that customer's portal. Waffo Pancake trusts your server and does not verify the customer's email. *** ## Step 2: Create the Link on Your Server Call the API from your backend only. The API Key must never reach the browser. * **Environment follows the API Key.** A test key opens the portal with test data; a production key opens it with production data. There is no environment parameter * **Create the link on every click**, right before redirecting. Do not cache it, store it, or send it by email * **Redirect with 302.** Add `Cache-Control: no-store` and `Referrer-Policy: no-referrer` to the redirect response, so the tokenized link is neither cached nor passed on as a referrer ```typescript Next.js (Route Handler) theme={"system"} // app/account/portal/route.ts import { NextResponse } from "next/server"; import { WaffoPancake } from "@waffo/pancake-ts"; import { getSignedInUser } from "@/lib/auth"; // your own session check const client = new WaffoPancake({ merchantId: process.env.WAFFO_MERCHANT_ID!, privateKey: process.env.WAFFO_PRIVATE_KEY!, }); export async function GET(request: Request) { const user = await getSignedInUser(request); if (!user) { return NextResponse.redirect(new URL("/login", request.url), 302); } try { // portalUrl already includes #token=... const { portalUrl } = await client.auth.createCustomerPortalLink({ storeId: process.env.WAFFO_STORE_ID!, buyerIdentity: user.id, // same value used at checkout }); const response = NextResponse.redirect(portalUrl, 302); response.headers.set("Cache-Control", "no-store"); response.headers.set("Referrer-Policy", "no-referrer"); return response; } catch (err) { // Log the error, never the portal URL console.error("customer portal link failed", err); return new NextResponse("The customer portal is unavailable. Please try again.", { status: 502 }); } } ``` ```typescript Next.js (SDK helper) theme={"system"} // app/account/portal/route.ts // Signature summary — see the @waffo/pancake-nextjs reference for the exact types import { createCustomerPortalRedirect } from "@waffo/pancake-nextjs/server"; import { getSignedInUser } from "@/lib/auth"; // your own session check export const GET = createCustomerPortalRedirect( { merchantId: process.env.WAFFO_MERCHANT_ID!, privateKey: process.env.WAFFO_PRIVATE_KEY!, }, { // Resolve the customer from YOUR session, never from the request body or query resolveAuthenticatedCustomer: async (request) => { const user = await getSignedInUser(request); return user ? { storeId: process.env.WAFFO_STORE_ID!, buyerIdentity: user.id } : null; }, // Fixed path you control; without loginUrl, signed-out visitors get a 401 loginUrl: "/login?returnTo=/account/portal", }, ); ``` ```typescript Node.js (Express) theme={"system"} import express from "express"; import { WaffoPancake } from "@waffo/pancake-ts"; const client = new WaffoPancake({ merchantId: process.env.WAFFO_MERCHANT_ID!, privateKey: process.env.WAFFO_PRIVATE_KEY!, }); const app = express(); // req.user is set by your own auth middleware; typed here for the example type SignedInRequest = express.Request & { user?: { id: string } }; app.get("/account/portal", async (req: SignedInRequest, res) => { const user = req.user; if (!user) return res.redirect(302, "/login"); try { const { portalUrl } = await client.auth.createCustomerPortalLink({ storeId: process.env.WAFFO_STORE_ID!, buyerIdentity: user.id, }); res.set("Cache-Control", "no-store"); res.set("Referrer-Policy", "no-referrer"); res.redirect(302, portalUrl); } catch (err) { // Log the error, never the portal URL console.error("customer portal link failed", err); res.status(502).send("The customer portal is unavailable. Please try again."); } }); ``` ```go Go theme={"system"} // Snippet, not a full program: mount portalHandler on your own server. // signedInUser is your own session lookup, e.g. // func signedInUser(r *http.Request) (user User, ok bool) // Exact types: https://pkg.go.dev/github.com/waffo-com/waffo-pancake-sdk-go import ( "log" "net/http" "os" pancake "github.com/waffo-com/waffo-pancake-sdk-go" ) func portalHandler(client *pancake.Client) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { user, ok := signedInUser(r) // your own session check if !ok { http.Redirect(w, r, "/login", http.StatusFound) return } link, err := client.Auth.CreateCustomerPortalLink(r.Context(), pancake.CreateCustomerPortalLinkParams{ StoreID: os.Getenv("WAFFO_STORE_ID"), BuyerIdentity: user.ID, // same value used at checkout }) if err != nil { log.Printf("customer portal link failed: %v", err) // never log link.PortalURL http.Error(w, "The customer portal is unavailable. Please try again.", http.StatusBadGateway) return } // link.PortalURL already includes #token=... w.Header().Set("Cache-Control", "no-store") w.Header().Set("Referrer-Policy", "no-referrer") http.Redirect(w, r, link.PortalURL, http.StatusFound) } } ``` The SDK helper `createCustomerPortalRedirect` takes these options: | Option | Required | Behavior | | - | - | - | | `resolveAuthenticatedCustomer` | Yes | Returns `{ storeId, buyerIdentity }` from your own session, or `null` when no one is signed in | | `loginUrl` | No | Where signed-out visitors are sent with a 302. Without it, they get a `401` JSON response | | `onError` | No | Handles a failed link creation. The default is a generic `502` JSON response; use it to log the error (never the portal URL) or return your own page | Every response the helper builds carries `Cache-Control: no-store` and `Referrer-Policy: no-referrer`. A response you return from `onError` is your own — set both headers on it as well. > [!WARNING] > > Set `loginUrl` to a path you control. Never build it by copying request parameters (such as a `returnTo` query value) verbatim — that turns your portal route into an open redirect. Not using an SDK? Call [Issue Session Token](/api-reference/endpoints/auth/issue-session-token) with `purpose: "portal"` and `storeId`, then redirect to `portalUrl + "#token=" + token`. *** ## Step 3: Add the Button Point the button at your own route, not at Waffo Pancake. The browser never sees the API Key, and the link is minted only when the customer clicks. ```tsx theme={"system"} // A plain , not next/link: prefetching would create portal links nobody clicked const PORTAL_ROUTE = "/account/portal"; // the route from Step 2 export function ManageOrdersButton() { return Manage orders; } ``` *** ## How the Session Behaves | Behavior | Detail | | - | - | | Lifetime | 15 minutes of inactivity. Each action in the portal extends it | | Expired session | The portal shows a re-entry page asking the customer to go back to your site, with a **Return to merchant site** button if your store's website is set. A new click on **Manage orders** creates a fresh link — no email code | | Reusing a link | The link is **not single-use**: it can be opened again while the session is alive. Treat it as a password | | One portal per browser | A browser holds one portal session at a time. Entering from your site replaces any earlier portal session in that browser, including one opened with an email Magic Link or for another store. An older tab of the replaced session shows **Session switched** and moves to the current session | | Scope | One store, one environment, one `buyerIdentity`. Other stores and the other environment are not visible | > [!WARNING] > > The `#token=` part of the link is a bearer credential. Do not write the link to logs, analytics, error trackers, or support tickets, and do not share it in email or chat. *** ## Test Before Going Live **1. Create a test order** With your test API Key, place an order through authenticated checkout using a test customer's `buyerIdentity`. **2. Open the portal** Sign in to your site as that customer and click **Manage orders**. The test order should be listed. **3. Check the identity boundary** Sign in as a different customer and confirm the first customer's order does not appear. Try adding another customer's ID to the request — your route must ignore it. **4. Switch to production** Deploy with your production API Key. Links now open production data. *** ## Troubleshooting > **The portal opens but shows no orders** > > 1. Check that the orders were created with the same `buyerIdentity` string (exact match, including case) > 2. Check that the orders belong to the `storeId` you passed > 3. Check the API Key's environment: a test key shows only test orders, a production key only production orders > 4. Orders from anonymous checkout carry no `buyerIdentity` and never appear here > **The portal says the session has ended** > > The portal shows **Please re-enter from the merchant's site** when the session was idle for more than 15 minutes, or when the portal was opened for a different store than the session in this browser, without a new link. Send the customer back through **Manage orders** on your site to get a new link. > **The portal says the session was switched** > > The customer entered the portal again in the same browser — from your site in another tab, from another store's portal, or with an email Magic Link. The newest entry becomes the browser's portal session; older tabs show **Session switched** and move to the current session. No action is needed. > **403 Environment mismatch from the Customer Portal API** > > You called the Customer Portal API with a portal token and an `X-Environment` that differs from the API Key's environment. Send the key's environment. *** ## Checklist * [ ] The link is created on your server; the API Key never reaches the browser * [ ] `buyerIdentity` comes from your own signed-in session and matches the value used at checkout * [ ] `storeId` comes from your server configuration, not the request * [ ] The route responds with a 302, `Cache-Control: no-store` and `Referrer-Policy: no-referrer` * [ ] Portal links and tokens are never logged or stored * [ ] Refund requests have a support path outside the portal *** ## Next Steps > **[Issue Session Token](/api-reference/endpoints/auth/issue-session-token)** > > Request and response fields for `purpose: "portal"`. > **[Customer Portal](/features/customer-portal)** > > What customers see in the portal. # Discounts & Promotions Source: https://docs.waffo.ai/guides/discounts Create coupons and promotion codes, and let customers use them at checkout ## What You Can Do * Create **coupons**: a percentage or a fixed amount off, limited to some products, a total number of uses and an expiry, with a code customers type at checkout * Hand out more **promotion codes** for the same coupon, each with its own customer restrictions — eligible emails, uses per customer, a minimum amount — one per influencer or campaign channel, or a batch of single-use codes * Let customers type a code on the checkout page, share a product link with a code already applied, or apply a coupon or pre-fill a promotion code from your server when you create a checkout session > [!NOTE] > > Discounts apply to **one-time products, new subscriptions and plan changes**. On a subscription, the coupon's duration decides how many billing periods are discounted — see [Subscriptions](#subscriptions). On a plan change, a new code replaces the subscription's discount, and without one the discount carries over while it can — see [Plan Changes](#plan-changes). *** ## Coupons and Promotion Codes A **coupon** defines the discount and has its own code customers can type — set it when you create the coupon, or let Pancake generate one. A coupon only limits its expiry and total uses, so its own code works for any customer within those limits. A **promotion code** is another code for the same coupon that carries customer restrictions: a coupon can have many, and a customer must pass the promotion code's restrictions as well as the coupon's expiry and total uses. You can create promotion codes together with the coupon, in the same request, or add them later. A coupon you apply from your server with `couponId` needs no code. | Rule | Set on | Description | | - | - | - | | Discount | Coupon | Percentage off, or a fixed amount per currency. A fixed amount does not apply to an order whose currency is not listed — there is no currency conversion | | Products | Coupon | Limit the coupon to some products, or leave it store-wide | | Expiry | Coupon, promotion code | After the expiry the code can no longer be used. A promotion code cannot outlive its coupon | | Total uses | Coupon, promotion code | Uses across all customers. The coupon's limit counts its own code and all its promotion codes; a promotion code's limit cannot exceed its coupon's | | Eligible customers | Promotion code | Only these customer emails (case-insensitive) | | Uses per customer | Promotion code | Lifetime uses of the code per customer | | Minimum amount | Promotion code | Minimum per currency, before discount and tax. Currencies not listed have no minimum | Coupons and their codes belong to one store and one environment: a code created in test mode does not work in live mode. Codes are case-insensitive — a customer can type `spring-20` for `SPRING-20`. *** ## Creating Coupons ### Via Dashboard Go to **Dashboard → Coupons** to create a coupon, add promotion codes, generate a batch of codes, and see how many times each code has been used — see [Coupons](/dashboard/discounts) in the Dashboard guide. ### Via API or SDK Create coupons and promotion codes from your server with the [Coupon](/api-reference/endpoints/coupons/overview) and [Promotion Code](/api-reference/endpoints/promotion-codes/overview) endpoints: ```typescript TypeScript theme={"system"} import { CouponDiscountType, WaffoPancake } from "@waffo/pancake-ts"; const client = new WaffoPancake({ merchantId: process.env.WAFFO_MERCHANT_ID!, privateKey: process.env.WAFFO_PRIVATE_KEY!, }); const { coupon } = await client.coupons.create( { storeId: "STO_xxx", name: "Spring sale", discount: { type: CouponDiscountType.Percentage, percentOff: 20 }, maxRedemptions: 500, code: "SPRING-20", // the coupon's own code; omit it for a random one // Promotion codes created together with the coupon (up to 20), each with its own restrictions promotionCodes: [{ code: "SPRING-NEW", restrictions: { perCustomerLimit: 1 } }], }, { idempotencyKey: "coupon-spring-2026" }, ); // A code for one influencer: 100 uses, at least $50 before tax await client.promotionCodes.create({ couponId: coupon.id, code: "KOL-ALICE", restrictions: { maxRedemptions: 100, minimumAmount: { USD: "50.00" } }, }); ``` ```go Go theme={"system"} res, err := client.Coupons.Create(ctx, pancake.CreateCouponParams{ StoreID: "STO_xxx", Name: "Spring sale", Discount: pancake.CouponDiscount{Type: pancake.CouponDiscountTypePercentage, PercentOff: pancake.Ptr(20.0)}, MaxRedemptions: pancake.Ptr(500), Code: pancake.Ptr("SPRING-20"), PromotionCodes: []pancake.CreateCouponPromotionCodeParams{{ Code: pancake.Ptr("SPRING-NEW"), Restrictions: &pancake.PromotionCodeRestrictions{PerCustomerLimit: pancake.Ptr(1)}, }}, }, pancake.WithIdempotencyKey("coupon-spring-2026")) ``` ## Common Campaigns What to set up for the promotions merchants run most often. Each one is a coupon, plus promotion codes where customers need different rules — set up in the [Dashboard](/dashboard/discounts) or with the SDK. > **Launch sale: a public code for a limited time** > > A 20% code everyone can use for two weeks, with a cap so the campaign cannot run away. > > * **Set up**: one coupon — percentage 20, expiry in two weeks, redemption limit (for example 500), all products or just the launch product. Its own code is the public code, for example `LAUNCH-20`. > * **Customers get it**: they type the code on the checkout page — your product link shows the code entry field as soon as the coupon exists. For ads and emails, put the code in the link so nothing has to be typed: `…/product/{productId}?discount_code=LAUNCH-20`. > * **Watch out**: the expiry is checked at the moment of entry and again at order time, so a customer who opens the page before the deadline and pays after it is charged the full price. A coupon's expiry also ends the discount on subscriptions it was applied to. > > ```typescript theme={"system"} > await client.coupons.create({ > storeId: "STO_xxx", > name: "Launch sale", > code: "LAUNCH-20", > discount: { type: CouponDiscountType.Percentage, percentOff: 20 }, > maxRedemptions: 500, > redeemBy: "2026-11-15T00:00:00.000Z", > }); > ``` > **Influencers and channels: one code per partner** > > The same discount, but you want to know which partner each order came from and cap each of them separately. > > * **Set up**: one coupon with the discount, then one promotion code per partner on it — `KOL-ALICE`, `KOL-BOB`, `PODCAST-10` — each with its own total uses and, if the deal needs it, a minimum order amount. The coupon's own code can stay unpublished. > * **Customers get it**: the partner shares their code or a product link with `?discount_code=KOL-ALICE`. > * **Track**: the coupon details list uses per code; export the codes as CSV for your partner report. Deactivate a partner's code on its own when the deal ends — the other codes keep working. > > ```typescript theme={"system"} > await client.promotionCodes.create({ > couponId: "CPN_xxx", > code: "KOL-ALICE", > restrictions: { maxRedemptions: 200, minimumAmount: { USD: "30.00" } }, > }); > ``` > **Newsletter or giveaway: one single-use code per person** > > Each recipient gets their own code that works once, so codes cannot be shared. > > * **Set up**: one coupon, then **Generate in bulk** on it — the number of codes you need (up to 500 per batch), a prefix such as `NEWS-`, and *each code can be used up to 1 time*. Download the CSV and merge it into your email tool. > * **Customers get it**: each email carries one code; the customer types it at checkout. > * **Watch out**: a code is used up by a paid order; an order left unpaid holds the use for 72 hours, then the code becomes usable again. Bulk codes are random, so there is no way to tell who used which code except by matching the CSV to the orders' emails. > > ```typescript theme={"system"} > const { promotionCodes } = await client.promotionCodes.generate({ > couponId: "CPN_xxx", > count: 500, > prefix: "NEWS-", > restrictions: { maxRedemptions: 1 }, > }); > ``` > **Win-back or VIP list: only certain customers** > > A discount only the customers on your list can use, even if the code leaks. > > * **Set up**: a promotion code with *Only specific customers can use it* — paste the emails — and *Each customer can use it up to 1 time*. > * **Customers get it**: they type the code at checkout. The code is matched against the email they enter on the checkout page, so the page asks for the email first when the code is applied before one is typed; a customer who is not on the list sees that the code is for specific customers. > * **Watch out**: the match is on the exact email (case-insensitive). A customer who checks out with a different email than the one you have is refused — tell them which address the offer was sent to. > > ```typescript theme={"system"} > await client.promotionCodes.create({ > couponId: "CPN_xxx", > code: "COMEBACK-30", > restrictions: { customerEmails: ["jane.doe@example.com"], perCustomerLimit: 1 }, > }); > ``` > **Loyalty tiers or partner pricing: you decide, no code shown** > > Your own system knows who gets the discount — a membership tier, a reseller, a quote you agreed on — and the customer should not see or share a code. > > * **Set up**: a coupon per tier (`Gold 15%`, `Partner 25%`), with no need to publish its code. > * **Customers get it**: your server creates the checkout session with `couponId` and sends the customer to its `checkoutUrl`. The checkout page shows the discount and the discounted total, no code and no code entry field; the customer cannot remove it. > * **Watch out**: `couponId` needs your API Key, so decide the eligibility in your server code — never from values the browser sends. With the Next.js SDK, `createCheckoutAction` strips `couponId`; call `@waffo/pancake-ts` from your own server code instead. To let the customer stack their own code on top, use a promotion code with `promotionCode` plus `allowPromotionCodes: true` instead — a coupon cannot be combined with code entry. > > ```typescript theme={"system"} > // In your server code, after checking the customer's tier > const session = await client.checkout.createSession({ > storeId: "STO_xxx", > productId: "PROD_xxx", > currency: "USD", > couponId: tier === "gold" ? "CPN_gold" : undefined, > buyerEmail: customer.email, > }); > redirect(session.checkoutUrl); > ``` > **Subscriptions: first months cheaper, or a reason to switch to annual** > > "25% off for 3 months" on a monthly plan, or a code that only works on the annual plan to move customers over. > > * **Set up**: for the first months, a coupon with duration *Multiple billing cycles* = 3. For the annual push, a coupon limited to the annual product, so the code is refused on the monthly plan with `PRODUCT_NOT_ELIGIBLE`. > * **Customers get it**: new subscribers type the code at checkout. Existing monthly subscribers switch from the Customer Portal: the plan change page shows the code entry field when a code can be used on the annual plan, or you create the plan change session yourself with `promotionCode` and send them the link. > * **Watch out**: a free trial does not use the discount — it starts with the first paid period. A paid trial does, and counts as the first period. On a plan change, a new code replaces the current discount; without one the current discount carries over with the periods already used. See [Subscriptions](#subscriptions) and [Plan Changes](#plan-changes). > > ```typescript theme={"system"} > await client.coupons.create({ > storeId: "STO_xxx", > name: "Annual upgrade", > code: "GO-ANNUAL", > discount: { type: CouponDiscountType.Percentage, percentOff: 25 }, > duration: CouponDuration.Repeating, > durationInPeriods: 3, > productIds: ["PROD_annual"], > }); > ``` > **Test first, then go live** > > Coupons belong to one environment, so a coupon built in test mode is not visible in live mode. > > * **Set up**: build the coupon and its codes in test mode and run a test checkout — the test checkout accepts test cards. > * **Go live**: open the coupon and choose **Copy to live** (products must be published to live first). The copy starts with 0 uses; active, unexpired promotion codes come along if you tick the option. With the API, create the coupon again with your live API Key. > * **Watch out**: a code already in use on live stops the copy — deactivate it there first, or copy without codes. *** ## Applying Discounts at Checkout A discount reaches the checkout page in one of four ways. The customer always sees the discounted, tax-inclusive total before paying. | Way | How | Can the customer change it? | | - | - | - | | Code entry field | The customer types a coupon code or promotion code on the checkout page | Yes — they can replace or remove it | | Product link with a code | Add `discount_code` to a product link | No — the code is applied and locked | | Coupon set by your server | Pass `couponId` when you create a checkout session with merchant credentials (API Key or JWT) | No — the discount is applied and locked | | Promotion code set by your server | Pass `promotionCode` when you create a checkout session with merchant credentials (API Key or JWT) | Only if you also pass `allowPromotionCodes: true` — then they can replace or remove it | ### Code Entry Field Product links and your store page show the code entry field when the store has a code that can be used on the product: an `active` coupon that covers the product, is not expired and is under its total usage limit, with its own code or a promotion code that is `active`, not expired and under its own usage limit. Rules that depend on the customer, such as eligible customers or a minimum amount, are checked only when the code is entered. A code that has just expired or reached its limit can keep the field showing for up to 5 minutes. Checkout sessions you create with your API Key follow the same rule when you leave out `allowPromotionCodes`; pass `true` to always show the field, or `false` to hide it: ```typescript theme={"system"} const session = await client.checkout.createSession({ productId: "PROD_xxx", currency: "USD", allowPromotionCodes: true, }); ``` #### Scenarios How the checkout page decides, and what to pass, in common situations: | Scenario | Code entry field | What to pass | | - | - | - | | You created a coupon in the Dashboard for all products; a customer opens a product link or your store page | Shown | Nothing — the page detects the coupon | | The coupon is limited to product A; the customer opens product B | Hidden on B, shown on A | Nothing | | The store's only coupon has expired, is used up, or was deactivated | Hidden (within 5 minutes) | Nothing — create a new coupon to show it again | | The coupon's only code is limited to specific customer emails | Shown — customer rules are not part of the check. Another customer's code is refused with `CUSTOMER_NOT_ELIGIBLE`; applied before an email is entered, the page asks for the email first | Nothing | | The only coupon is a fixed amount in USD; the customer checks out in EUR | Shown — currencies are not part of the check. The code is refused with `CURRENCY_MISMATCH` | Add a EUR amount to a new coupon, or leave it | | You create the session from your server with your API Key | Hidden, even when the store has codes | `allowPromotionCodes: true` to show it | | You create the session from your server and want a code pre-filled | Code shown as applied and locked | `promotionCode: "KOL-ALICE"`; add `allowPromotionCodes: true` to let the customer replace or remove it | | You decide the discount yourself (loyalty tier, partner deal) and do not want a code shown | Hidden; the discount is applied and locked, with no code | `couponId: "CPN_xxx"` — cannot be combined with `promotionCode` or `allowPromotionCodes` | | You send a campaign link with the code built in | Hidden; the code is applied and locked. A code that cannot be used is explained, with **Continue without discount** | `?discount_code=SPRING-20` on the product link | | Your own storefront creates the session with Store Slug (no merchant credentials) | Default detection, as for a product link | `allowPromotionCodes: true` or `false` to override the detection | | A customer changes plan from the Customer Portal | Shown when a code can be used on the new plan's product; without a code, the current discount carries over while it can | Nothing — or `couponId` / `promotionCode` on a plan change session you create | | You use the Next.js SDK's `createCheckoutAction` | Hidden unless the button passes `allowPromotionCodes` | `allowPromotionCodes` on ``; `couponId` and `promotionCode` are stripped there — set them in server code with `@waffo/pancake-ts` | ### Product Link with a Code Add `discount_code` to a [product link](/checkout/checkout-flow#product-purchase-links). The code is applied when the page opens, and the code entry field is hidden: ``` https://pancake.waffo.ai/store/{store-slug}/product/{productId}?currency=USD&discount_code=SPRING-20 ``` If the code cannot be used — it has expired, or it does not cover the product — the checkout page tells the customer why. ### Coupon Set by Your Server Pass `couponId` (the coupon's `CPN_` ID) when you create the checkout session. The customer sees the discount — its name, amount and duration — but not a code, even when the coupon has its own code; to show a code, pre-fill it with `promotionCode` instead. The coupon is checked right away: a coupon from another store or environment, a deactivated or expired coupon, a product the coupon does not cover, or a fixed amount with no value in the session currency is rejected with `409` — see [Create Checkout Session](/api-reference/endpoints/orders/create-checkout-session#discounts). ```typescript theme={"system"} const session = await client.checkout.authenticated.create({ productId: "PROD_xxx", currency: "USD", buyerIdentity: "userIdInYourSystem", couponId: "CPN_xxx", }); ``` `couponId` cannot be combined with `allowPromotionCodes` or `promotionCode` — sending both returns `400`. `couponId` is accepted only with merchant credentials (API Key or JWT): a Store Slug request or a customer session token gets `403`, and the [Next.js SDK](/integrate/nextjs#discounts) server action strips it, so customers cannot pick a coupon for themselves. ### Promotion Code Set by Your Server Pass `promotionCode` — the text of a coupon code or promotion code, case-insensitive — to apply it when the checkout page opens. It is checked right away against the same rules as `couponId`, and a code that cannot be used is rejected with `409`. Whether the customer can change it is up to `allowPromotionCodes`: | `allowPromotionCodes` | On the checkout page | | - | - | | `true` | The code is applied, and the customer can replace it with another code or remove it. After removing it they can enter a code again | | Omitted or `false` | The code is applied and locked | ```typescript theme={"system"} const session = await client.checkout.createSession({ productId: "PROD_xxx", currency: "USD", promotionCode: "KOL-ALICE", allowPromotionCodes: true, // let the customer replace or remove it }); ``` Like `couponId`, `promotionCode` is accepted only with merchant credentials (API Key or JWT) — a Store Slug request or a customer session token gets `403`, and the Next.js SDK server action strips it. *** ## When a Code Cannot Be Used Pancake checks the code when the customer enters it, and makes the final decision when they place the order. The check at entry is a preview, so a few rules are left to the order: * For a guest checkout, only paid orders count toward the code's total uses: the code is refused at entry only once its paid uses reach the limit. Unpaid orders and the per-customer limit are checked when the order is placed — if other customers' unpaid orders hold the remaining uses, the order is refused then. * For a signed-in customer, their own unpaid order with the same code does not count against the use limits — except an unpaid plan change that still holds the use: one already confirmed and waiting for its switch date, or one the current discount is being carried over to. * A customer who leaves the payment page without paying can come back and enter the same code again. When they place the new order, it takes over the use held by their unpaid order. The checkout page shows the reason in the customer's language: | Reason | Meaning | | - | - | | `CODE_NOT_FOUND` | No active code with this text in this store and environment. A deactivated code, or a code from another store, shows the same reason | | `CODE_INACTIVE` | The coupon or promotion code is no longer active — for example, it was deactivated after the customer applied it | | `CODE_EXPIRED` | The code has expired. A code within 60 seconds of its expiry already counts as expired — when the checkout session is created, when the code is entered and when the order is placed | | `MAX_REACHED` | The code has reached its total number of uses | | `USER_LIMIT_REACHED` | The customer has used the code as often as allowed | | `CUSTOMER_NOT_ELIGIBLE` | The customer's email is not on the code's list. A code limited to specific customers can only be checked against an email: when the customer applies it before entering one, the checkout page asks for the email first | | `PRODUCT_NOT_ELIGIBLE` | The code does not cover this product | | `CURRENCY_MISMATCH` | The fixed amount has no value in the checkout currency | | `MINIMUM_NOT_MET` | The order is below the code's minimum amount (before discount and tax); the minimum is shown | | `TEMPORARILY_UNAVAILABLE` | Reserved — not returned at present. A customer who enters codes too quickly gets HTTP `429` instead, and can try again shortly | If a rule fails only when the order is placed — for example, someone else took the last use a moment earlier — no order is created, nothing is charged and the checkout session stays usable. What the customer can do next depends on how the code was applied: | Applied by | What the customer can do | | - | - | | Code entry field | Remove the code and pay the full price, or try another code | | Product link with a code | The code is locked: reopen the product link without `discount_code`. When a link's code is rejected as the page opens, that page offers **Continue without discount** | | Coupon set by your server | The coupon is locked: create a new checkout session without `couponId` | | Promotion code set by your server | With `allowPromotionCodes: true`, as for the code entry field. Otherwise the code is locked: create a new checkout session without `promotionCode` | A customer who placed an order with a code but has not paid can place a new order with the same code. The new order takes over the use held by the earlier one; the earlier order stays payable, but if it is paid as well it is flagged for review and not counted as another use. An unpaid order holds its use for 72 hours. After that, the next order that uses the same coupon — with any of its promotion codes, placed by any customer — takes the use back. The unpaid order is not canceled: it keeps its status, and if it is paid later it is flagged for review and not counted as another use. *** ## Subscriptions New subscriptions take a discount the same ways as one-time products, with the same rules. Before paying, the customer sees the first charge and what each later period costs, with and without the discount. ### How Many Periods Are Discounted | `duration` | Discounted billing periods | | - | - | | `once` | One period | | `repeating` | `durationInPeriods` periods in a row | | `forever` | Every period, until the coupon's expiry | Only a period whose price before the discount is above zero uses up the discount. A 100% discount still uses up its period, even though nothing is charged. ### Trials | Trial | What is discounted | | - | - | | No trial | The first charge, then the following periods | | Free trial | Nothing during the trial: it costs nothing and uses no period. The discount starts with the first paid period | | Paid trial | The trial charge is discounted and counts as the first period — a `once` coupon is used up by the trial, and a `repeating` coupon counts its periods from the trial | A promotion code's minimum amount is checked against the first charge, before the discount and tax: the trial price for a paid trial, the regular price otherwise. Renewals are not checked again. For example, at $10 a month with a 20% coupon for 3 periods (`repeating`), periods 1 to 3 charge $8 and period 4 onward $10. With a 7-day free trial and a `once` coupon, the trial costs $0, the first paid month is discounted and later months are full price. ### When a Use Is Counted * A use is counted once, when the first discounted charge succeeds: the first paid charge, or the trial charge for a paid trial. Renewals do not count again. * Until then the subscription holds the use. If the subscription ends before that charge — canceled during a free trial, or its first payment never succeeds — the use is given back and the customer can use the code again. A subscription order left unpaid for more than 72 hours is not canceled, but it no longer holds the use: the next order that uses the same coupon, with any of its promotion codes, takes it back. * If the coupon expires before that charge and the customer is charged the full price, the use is given back as well. * A new order by the same customer with the same code takes over the use only from an earlier order that was never paid. An active subscription in its free trial keeps its hold: the new order does not take it over, and the held use counts toward the code's limits. ### When the Discount Ends * When the duration runs out, renewals are charged the full price. * **The coupon's expiry also ends discounts already on subscriptions**: renewals after it are charged the full price, even with `forever`. A promotion code's own expiry only stops new uses. * Deactivating a coupon does not end discounts already on subscriptions until their next plan change — see [Plan Changes](#plan-changes). * Canceling a subscription ends its discount for good. Undoing the cancellation before the period ends keeps the discount. * A plan change ends the discount, unless it carries over to the new plan — see [Plan Changes](#plan-changes). ### Plan Changes A plan change replaces the subscription with a new one on the new plan. The plan change page shows a code entry field when the plan change session allows it, and you can set `couponId` or `promotionCode` on a plan change session the same way as on a new purchase — see [Create Checkout Session](/api-reference/endpoints/orders/create-checkout-session#discounts). A product link's `discount_code` does not apply to plan changes. The plan change page does not ask for an email, so a promotion code's eligible-customer list is matched against the original subscription's customer email — both when the code is entered and when the plan change is submitted. | The plan change | The discount on the new subscription | | - | - | | Comes with a code — entered on the plan change page, or set with `couponId` or `promotionCode` | The new discount replaces the current one, and what is left of the current discount is dropped. It is a new use of the code: every rule is checked again when the change is submitted, it holds a use and is counted once, and its periods count from the new subscription. Entering the code the subscription already has is a new use as well | | Comes without a code, and the current discount can continue | The current discount carries over. Periods already used are not reset — the remaining periods continue on the new plan. Carrying over is not a new use: no use is held or counted | | Comes without a code, and the current discount cannot continue | The new subscription has no discount. A discount cannot continue once its periods are used up, once the coupon has expired or expires within 60 seconds, or once the coupon has been deactivated. | So **deactivating a coupon ends the discounts on subscriptions at their next plan change.** * **The first period.** On a change that takes effect immediately, the new subscription's first period costs the new plan's price minus the credit for the unused part of the current period — or the amount you set with `changeAmount` or `changeCreditAmount`. When that is above zero, the discount applies to it and it uses up one period. **The discount is worked out on the new plan's full price, and then the credit is taken off**: a percentage coupon takes its percentage of the new plan's price, a fixed amount stays the same, and the discount is capped at the first period's price, so the customer pays the first period's price minus the discount, never below zero. A first period whose discount covers it in full still uses up one period. When it is zero — usually a downgrade whose credit covers the new plan — it takes no discount and uses no period, and the discount starts with the second period. A change that takes effect next period starts with a regular-price period, and a change that grants a trial follows the trial rules above. * **The credit is based on what the customer pays.** The credit for the unused part of the current period is worked out from what that period costs the customer: the discounted amount when the period is discounted, the list price otherwise. * **A promotion code's minimum amount** is checked against the new plan's regular price, before the discount and tax. The credit is not taken off. * **When a use is counted.** A new code is counted when the first discounted charge of the new subscription succeeds — the first period, or the second period when the first is zero. If the change does not go through — the customer does not finish it, the payment channel reports it failed, or the change scheduled for next period is canceled — the use is given back. A change that is started but never completes stops holding its use after 72 hours, and the next order that uses the same coupon, with any of its promotion codes, takes it back — the same goes for a use being carried over to it from a subscription that has since ended. When the current subscription's own code is still waiting for its first discounted charge, a discount that carries over takes that held use along to the new subscription; a new code or no code gives it back. For example, at $5 a month with $1 off for 3 periods (`repeating`), 1 of them used, the customer upgrades to $10 a month halfway through the period without a code. The credit is $2 — half of the $4 they paid — so the first period is $8 before the discount and $7 to pay, the next period is $9, and later periods are $10. If they enter a new 20% `once` code instead, the discount is $2 — 20% of the $10 plan — so the first period is $8 before the discount and $6 to pay, and later periods are $10: the old discount's remaining period is dropped. ### Amounts on Subscription Payments * The subscription order keeps the list price. Each payment records what Pancake expects for that period: the original price, the discount and the amount to pay. The [`subscription.payment_succeeded`](/api-reference/webhooks) webhook carries them in `listPrice` (`listTotal`, `discountAmount`, `total`). * A charge that does not match the expected discount — the discount ended early, or the customer paid more or less — is reconciled by Pancake internally. The payment keeps the expected amounts; what was actually taken is in `chargedAmount` on the webhook. * The first receipt — for the trial charge of a paid trial, or for the first charge without a trial — lists the original price, the discount, the subtotal, the tax and the amount paid when that charge is discounted. A free trial's first receipt is for \$0 and shows no breakdown. * Each renewal receipt shows the same breakdown when its period is discounted. The first charge after a trial sends no renewal receipt — with a free trial, that is the first discounted period. The customer sees its expected amount in the upcoming-charge reminder. * The next charge shown in emails includes the discount only when that period is still discounted. * After a plan change, the new subscription's first payment expects the first period's amounts (see [Plan Changes](#plan-changes)), but no receipt is sent for it. When the first period is zero, this first payment is a \$0 payment; later payments expect the regular-period amounts. The customer gets a plan-changed email instead, which shows the new plan's regular price before any discount, the next billing date, and the next charge amount — discounted when that period still gets the discount. It doesn't show the first period's amount or a discount breakdown. The payment record keeps the first period's amounts. Later renewals get receipts as described above. *** ## Amounts, Receipts and Usage * **The discount applies to the tax-inclusive price.** A percentage discount is rounded down to the currency's smallest unit; a fixed amount never takes the total below zero, and a 100% discount produces a free order. * **Orders, payments, receipts and the Dashboard show three amounts**: the original price, the discount, and what the customer paid. Refunds are capped at what the customer paid. * **An order's price snapshot keeps the list price.** Its `total` is the tax-inclusive price before the discount, for one-time and subscription orders alike. The discounted amount of each charge is on the payment (`snapshotAmountDetails.total`). * **A discounted receipt** lists the original price, the discount, the subtotal (after the discount, excluding tax), the tax and the amount paid. The subtotal and tax lines appear only when tax applies. * **A use is counted when the payment succeeds** — for a subscription, the first discounted charge (see [Subscriptions](#subscriptions)). A canceled or expired order gives the use back, so the customer can use the code again. A refund does not give the use back. *** ## Next Steps > **[Coupon Endpoints](/api-reference/endpoints/coupons/overview)** > > Create, rename and deactivate coupons > **[Create Checkout Session](/api-reference/endpoints/orders/create-checkout-session#discounts)** > > Apply a coupon or show the code entry field # Guide Source: https://docs.waffo.ai/guides/introduction Step-by-step guides for common business scenarios, from product setup to daily operations ## Find the Right Guide for Your Business Whether you're selling digital products, running a SaaS subscription, or managing day-to-day operations, these guides walk you through the entire process — from setting up in the Dashboard to going live. *** ## Business Scenarios > **[Sell Digital Products](/guides/one-time-payments)** > > Courses, templates, ebooks, software licenses. Set up one-time purchases and start selling in minutes. > **[Run SaaS Subscriptions](/guides/subscriptions)** > > Monthly/yearly plans with trials and cancellation handling. Manage recurring revenue with ease. > **[AI Product Billing](/guides/ai-billing)** > > Billing for AI products and API services. Subscription tiers with token quotas, dynamic pricing, and metering tools. *** ## Operations > **[Set Up Webhooks](/guides/webhooks)** > > Get notified when payments succeed, subscriptions renew, or refunds are processed. Configure notifications in Dashboard. > **[Manage Refunds](/guides/refunds)** > > Handle refund requests, set refund policies, and track refund status from your Dashboard. *** ## Quick Decision Guide | I want to... | Guide | | - | - | | Sell a course, ebook, or template | [Sell Digital Products](/guides/one-time-payments) | | Launch a SaaS with monthly/yearly plans | [Run SaaS Subscriptions](/guides/subscriptions) | | Bill for AI products or API usage | [AI Product Billing](/guides/ai-billing) | | Get notified on payment events | [Set Up Webhooks](/guides/webhooks) | | Handle customer refund requests | [Manage Refunds](/guides/refunds) | *** ## Before You Start Make sure you have: 1. **A Waffo Pancake account** — [Sign up here](https://pancake.waffo.ai/merchant/auth/signin) 2. **A store created** — You'll be guided through this during onboarding 3. **Test mode enabled** — All guides use test mode by default, so you can safely experiment > [!TIP] > > You can do everything from the Dashboard without writing any code. When you're ready for deeper integration, check the [API Reference](/api-reference/introduction). *** ## No-Code vs Code ### No-Code (Recommended to start) 1. Create products in Dashboard 2. Copy the checkout link 3. Share anywhere — your website, email, social media **Best for:** Quick launches, validating ideas, non-technical merchants. ### Code Integration 1. Create checkout sessions via API 2. Handle webhooks for automated fulfillment 3. Build custom flows **Best for:** Custom experiences, automated delivery, advanced tracking. > [!NOTE] > > All guides start with the no-code approach. Code integration is introduced where it adds value, with links to the API Reference for details. # Sell Digital Products Source: https://docs.waffo.ai/guides/one-time-payments Set up one-time purchases for courses, templates, ebooks, and software licenses ## Who Is This For? This guide is for merchants who sell digital products with a single payment — no recurring billing. Common examples include: | Product Type | Examples | | - | - | | Digital Downloads | Ebooks, templates, design assets, stock photos | | Online Courses | Video courses, tutorials, workshops | | Software Licenses | Desktop apps, plugins, browser extensions | | Digital Services | One-time consultations, audits, reports | *** ## Step 1: Create Your Product **1. Go to Products** In your Dashboard, navigate to **Products** from the sidebar. ![Products list page](https://mintcdn.com/waffo/5dRlk76Jm-9Zm6Tj/images/guides/products-list.png?fit=max\&auto=format\&n=5dRlk76Jm-9Zm6Tj\&q=85\&s=2644c3ec77acc0f3c7769bdd91553232) **2. Click Create Product** Click the **Create Product** button in the top right corner. Select **One-Time** as the product type. ![Create one-time product form](https://mintcdn.com/waffo/5dRlk76Jm-9Zm6Tj/images/guides/create-onetime-product.png?fit=max\&auto=format\&n=5dRlk76Jm-9Zm6Tj\&q=85\&s=179269c9ed799df90a5669e216660de4) **3. Fill in Product Details** * **Name**: Your product name * **Price**: Set the price and currency * **Description**: What the customer gets * **Image**: Upload a product image (optional but recommended) **4. Save and Activate** Click **Save** to create the product. The product starts in **test mode** — only visible to test checkouts. When you're ready to sell, switch the product status to **Active** in the product detail page. *** ## Step 2: Share Your Checkout Link Once your product is created, you'll get a checkout link that you can share anywhere. ### Get the Link On the product detail page, copy the checkout link: ``` https://checkout.waffo.ai/your-store/my-product ``` ### Where to Share * **Your website** — Add a "Buy Now" button linking to the checkout URL * **Email campaigns** — Include the link in newsletters or launch emails * **Social media** — Share directly on Twitter, Instagram, or other platforms * **Landing pages** — Embed the link in your marketing pages > [!NOTE] > > This is all you need to start selling. No code required. Customers click the link, pay, and receive a confirmation email automatically. *** ## Step 3: Track Orders After customers purchase, you can track everything from the Dashboard. ### Orders Page Navigate to **Payments** in the sidebar to see all completed orders. ![Payments list page](https://mintcdn.com/waffo/5dRlk76Jm-9Zm6Tj/images/guides/payments-list.png?fit=max\&auto=format\&n=5dRlk76Jm-9Zm6Tj\&q=85\&s=5924bf80d62d8704770780f32f353276) Each order shows: * Customer email * Amount paid * Payment method * Order status * Date and time ### Email Notifications By default, both you and the customer receive email notifications on purchase. You can customize notification settings in **Settings → Notifications**. *** ## Step 4: Manage Your Products ### Update Product Details You can update the product name, description, price, or image at any time from the product detail page. > [!WARNING] > > When you update a product, Waffo Pancake creates a new version. Existing customers who already purchased are not affected. ### Publish to Production Products you create in test mode need to be published before real customers can purchase them: 1. Go to the product detail page 2. Click **Publish to Production** 3. The product is now live and available for real payments *** ## Business Scenarios > [!NOTE] > > The following are example scenarios. Adjust them to match your actual business. ### Scenario 1: Selling an Online Course 1. **Create product**: Enter your course name and set a price of \$49 (example) 2. **Share link**: Add the checkout link to your course landing page 3. **Customer purchases**: They pay and receive an order confirmation email 4. **Deliver content**: Use webhooks to automatically grant course access, or manually send access details ### Scenario 2: Selling Design Templates 1. **Create product**: Upload your template bundle with preview images 2. **Set pricing tiers**: Create separate products for different bundles (e.g., Basic $19, Pro $49, Complete \$99) (example) 3. **Share links**: Each product has its own checkout link 4. **Delivery**: Configure webhooks to send download links after purchase ### Scenario 3: Software Licenses 1. **Create product**: Set up your software as a one-time purchase 2. **Customer purchases**: Payment is processed automatically 3. **Generate license**: Use webhooks to trigger license key generation in your system 4. **Deliver**: Customer receives their license key via email *** ## Going Further: Code Integration For automated delivery or custom checkout flows, you can integrate with the Waffo Pancake API. ### When You Need Code * **Automated delivery**: Send download links or license keys automatically after payment * **Custom tracking**: Pass metadata (user ID, campaign source) to track conversions * **Dynamic pricing**: Create checkout sessions with custom amounts ### How It Works ``` Customer clicks "Buy" → Checkout Session → Payment → Webhook → Your server delivers the product ``` For API details, see the [API Reference](/api-reference/introduction). *** ## Testing Before Launch Use test mode to verify your entire flow before accepting real payments. **1. Enable Test Mode** Toggle the **Test/Production** switch in the top navigation bar of your Dashboard. **2. Create a Test Purchase** Open your checkout link and complete a purchase using a test card: | Scenario | Card Number | | - | - | | Successful payment (Visa) | `4576 7500 0000 0110` | | Successful payment (Mastercard) | `2226 9000 0000 0110` | | Declined | `4576 7500 0000 0220` | **3. Verify in Dashboard** Check that the test order appears in your **Payments** page and that notification emails were sent. *** ## Launch Checklist Before going live: * [ ] Product created with correct name, description, and price * [ ] Checkout link tested in test mode * [ ] Order confirmation email looks good * [ ] Product published to production * [ ] Checkout link shared on your website / social media *** ## Next Steps > **[Set Up Webhooks](/guides/webhooks)** > > Automate delivery by receiving payment notifications > **[Manage Refunds](/guides/refunds)** > > Handle refund requests from customers # Manage Refunds Source: https://docs.waffo.ai/guides/refunds Issue refunds, set refund policies, and track refund status ## What You'll Learn How to manage the refund process from your Dashboard: * Issue full and partial refunds * Understand refund types and policies * Track refund status * Handle subscription cancellations with refunds *** ## Refund Types | Type | Description | When to Use | | - | - | - | | **Full Refund** | Refund the entire payment amount | Customer dissatisfied, product not as described | | **Partial Refund** | Refund part of the payment | Partial service delivered, goodwill gesture | *** ## Step 1: Find the Payment Customers can't submit refunds themselves. When a customer asks for one through your support channel, find the payment in your Dashboard and issue the refund from there. **1. Go to Payments** Navigate to **Payments** in the sidebar to see all payments. ![Payments page](https://mintcdn.com/waffo/5dRlk76Jm-9Zm6Tj/images/guides/payments-refund.png?fit=max\&auto=format\&n=5dRlk76Jm-9Zm6Tj\&q=85\&s=a593df3123cbab1999990d9e394e6d73) **2. Open the Payment** Click on a payment to see its details (amount, date, product) and confirm it is the one the customer is asking about. *** ## Step 2: Issue the Refund From the payment details, issue a full refund or enter a partial amount. ![Refund dialog](https://mintcdn.com/waffo/5dRlk76Jm-9Zm6Tj/images/guides/refund-action.png?fit=max\&auto=format\&n=5dRlk76Jm-9Zm6Tj\&q=85\&s=ab5370c8d9875942e812d1ea36f2b498) ### What Happens After You Refund 1. The refund amount is deducted from your balance 2. The customer receives a refund confirmation email 3. Funds are returned to the customer's original payment method 4. The payment status updates to reflect the refund > [!WARNING] > > Refunds are permanent. Once issued, they cannot be reversed. Check the payment and amount carefully before you confirm. *** ## Step 3: Track Refund Status Refund tickets go through these statuses: | Status | Meaning | | - | - | | `pending` | Ticket created, awaiting review | | `processing` | Refund approved, being processed by payment provider | | `succeeded` | Refund completed, funds returned to customer | | `rejected` | Ticket rejected | | `failed` | Refund failed during processing (rare) | You can filter and track all refunds in the **Payments** section of your Dashboard. *** ## Refund Policies ### Setting Expectations We recommend establishing clear refund policies and communicating them to customers: | Policy Element | Recommendation | | - | - | | **Time window** | 7–30 days after purchase | | **Conditions** | Product not as described, technical issues | | **Exclusions** | Consumed services, customized products | | **Process time** | 5–10 business days for funds to appear | > [!TIP] > > Display your refund policy clearly on your checkout page and product pages. Clear policies reduce disputes and build customer trust. *** ## Subscription Refunds ### When a Subscriber Requests a Refund For subscription products, consider these options: 1. **Refund + Cancel**: Refund the current period and cancel the subscription 2. **Refund only**: Refund the current period but keep the subscription active 3. **Cancel only**: Cancel the subscription without a refund (customer keeps access until period ends) ### Recommended Approach For most cases, **refund + cancel** is the cleanest approach. The customer gets their money back, and the subscription is terminated. *** ## Business Scenarios ### Scenario 1: Digital Product Refund **Customer says:** "The course didn't cover what was advertised." **Recommended action:** 1. Find the payment in Dashboard 2. If it fits your refund policy, issue a full refund (Waffo sets no time limit on refunds) 3. Customer receives confirmation and funds are returned ### Scenario 2: Subscription First-Month Refund **Customer says:** "I didn't realize I'd be charged after the trial." **Recommended action:** 1. Refund the first payment 2. Cancel the subscription 3. Consider improving trial-to-paid communication ### Scenario 3: Partial Refund for Service Issue **Customer says:** "The service was down for a week." **Recommended action:** 1. Calculate the proportional refund (e.g., 25% for 1 week of a month) 2. Issue a partial refund 3. Optionally extend the current period as a goodwill gesture *** ## Going Further: Code Integration ### Webhooks for Refunds If you use webhooks, you can automate post-refund actions: | Event | Automated Action | | - | - | | `refund.succeeded` | Revoke product access, update database | | Refund approved | Send internal notification to support team | ### API Refunds For programmatic refund processing, see the [API Reference — Refunds](/api-reference/endpoints/refunds). *** ## Best Practices 1. **Respond quickly**: Reply to refund requests within 24–48 hours 2. **Be fair**: When in doubt, lean toward the customer's side 3. **Keep records**: Document the reason for each refund decision 4. **Learn from patterns**: If many refunds cite the same reason, fix the underlying issue 5. **Communicate clearly**: Always explain refund decisions to customers *** ## Checklist * [ ] Refund policy established and communicated * [ ] Support channel in place for customers to ask for refunds * [ ] Refund review process in place for your team * [ ] Webhook events configured for refund notifications (if using code integration) * [ ] Refund policy displayed on checkout/product pages *** ## Next Steps > **[Set Up Webhooks](/guides/webhooks)** > > Automate post-refund actions > **[Sell Digital Products](/guides/one-time-payments)** > > Set up products with clear refund expectations # Run SaaS Subscriptions Source: https://docs.waffo.ai/guides/subscriptions Set up recurring billing with monthly/yearly plans, trials, and cancellation handling ## Who Is This For? This guide is for merchants who sell subscription-based services or products with recurring billing. Common examples include: | Business Type | Examples | | - | - | | SaaS Products | Project management tools, CRM, analytics platforms | | Content Platforms | Online learning, premium newsletters, media access | | Digital Services | Cloud hosting, API access, design tools | | Membership | Community access, premium support, exclusive content | *** ## Subscription Lifecycle Before setting up, it helps to understand how subscriptions flow: ``` Trial → Active → (Renew each period) → Canceled → Expired ↑ ↓ └───── Reactivate ────┘ ``` | Status | What It Means | | - | - | | `trialing` | Customer is in a trial period (free or paid) | | `active` | Paying customer, subscription is active | | `past_due` | Renewal charge failed; the payment channel retries once (typically the next day). Success restores `active`, a second failure cancels the subscription | | `canceling` | Customer canceled, but still has access until period ends | | `canceled` | Subscription has fully ended | *** ## Step 1: Create Subscription Products You'll typically create multiple products for different pricing tiers (e.g., Free, Pro, Enterprise). **1. Go to Products** In your Dashboard, navigate to **Products** from the sidebar. ![Products list page](https://mintcdn.com/waffo/5dRlk76Jm-9Zm6Tj/images/guides/products-list.png?fit=max\&auto=format\&n=5dRlk76Jm-9Zm6Tj\&q=85\&s=2644c3ec77acc0f3c7769bdd91553232) **2. Create a Subscription Product** Click **Create Product** and select **Subscription** as the product type. ![Create subscription product form](https://mintcdn.com/waffo/5dRlk76Jm-9Zm6Tj/images/guides/create-subscription-product.png?fit=max\&auto=format\&n=5dRlk76Jm-9Zm6Tj\&q=85\&s=93bbcb12bcebb09ce92d5e961981986a) **3. Configure Pricing** * **Name**: Your plan name (e.g., "Basic Plan", "Pro Plan") * **Billing Period**: Choose monthly, quarterly, or yearly * **Price**: Set the recurring price * **Description**: What's included in this plan > [!TIP] > > Create separate products for each billing period. For example, create both a monthly and yearly version of the same plan. **4. Save and Activate** Click **Save**. The product starts in test mode. Activate it when ready. *** ## Step 2: Organize Plans with Product Groups If you have multiple tiers (Free, Pro, Enterprise), use **Product Groups** to organize them. Groups are managed on the **product edit page** — create, rename, dissolve, and adjust members from the group card. Every action takes effect immediately; there is no separate save step. **1. Create a Product Group** Open any subscription product and create a new group from its group card (e.g., "Pricing Plans"). **2. Add Products to the Group** Select the subscription products that belong together. This helps manage pricing tiers as a unit. A single plan can also leave the group in one click. **3. Configure Group Settings** * **Shared Trial**: If enabled, a customer who used a trial on one plan can't get another trial on a different plan in the same group. * **Self-service plan changes**: Controls whether subscribers can switch between plans in this group from the [Customer Portal](/features/customer-portal). The group is what scopes the change — customers can move between its members, not to unrelated products. > [!NOTE] > > Product groups are optional but recommended if you offer multiple pricing tiers. They prevent trial abuse, define the self-service upgrade path, and simplify management. *** ## Step 3: Share and Start Selling Just like one-time products, subscription products get a checkout link. ### Share the Checkout Link Copy the checkout link from the product detail page: ``` https://checkout.waffo.ai/your-store/my-product ``` ### Build a Pricing Page Create a pricing page on your website that links to each plan's checkout URL: > Prices below are examples only. Set them based on your actual business. | Plan | Price | Checkout Link | | - | - | - | | Basic | \$9/month | `https://checkout.waffo.ai/your-store/basic-plan` | | Pro | \$29/month | `https://checkout.waffo.ai/your-store/pro-plan` | | Enterprise | \$99/month | `https://checkout.waffo.ai/your-store/enterprise-plan` | *** ## Step 4: Monitor Subscriptions ### Subscriptions Dashboard Navigate to **Subscriptions** in the sidebar to see all active, trialing, and canceled subscriptions. ![Subscriptions list page](https://mintcdn.com/waffo/5dRlk76Jm-9Zm6Tj/images/guides/subscriptions-list.png?fit=max\&auto=format\&n=5dRlk76Jm-9Zm6Tj\&q=85\&s=b096a5c0a55a9a70ae469be890dd431e) Each subscription shows: * Customer email * Current plan * Status (active, trialing, past\_due, etc.) * Current period start and end dates * Next billing date ### Subscription Detail Click on any subscription to view details: * Payment history * Plan changes * Cancellation details (if applicable) *** ## Step 5: Handle Cancellations When a customer cancels, the subscription enters a **canceling** state. The customer keeps access until the current billing period ends, then it becomes **canceled**. ### What Happens Automatically * Customer receives a cancellation confirmation email * You receive a notification * Access continues until the period ends * No further charges are made ### View Cancellations in Dashboard Filter subscriptions by **Canceling** or **Canceled** status to see who has left. *** ## Business Scenarios > [!NOTE] > > The following are example scenarios. Adjust them to match your actual business. ### Scenario 1: SaaS with Monthly and Yearly Plans 1. **Create products**: Create both monthly and yearly versions of the same plan 2. **Group them**: Create a product group to link them together 3. **Pricing page**: Link each option on your website 4. **Monitor**: Track MRR and churn in the Analytics page ### Scenario 2: Content Platform with Free Trial 1. **Create product**: Set up your subscription plan and price 2. **Enable trial**: Set a 14-day free trial period 3. **Share link**: Customer signs up and starts trial immediately 4. **After trial**: Automatically converts to paid subscription, or expires if they don't add payment ### Scenario 3: API Service with Tiered Plans 1. **Create products**: Create a subscription product for each tier with different API call quotas and prices 2. **Group them**: Create a product group with shared trial 3. **Integrate webhooks**: Grant appropriate API limits based on which plan the customer subscribes to *** ## Going Further: Code Integration ### When You Need Code * **Access control**: Check subscription status in your app to gate features * **Automated provisioning**: Use webhooks to automatically create accounts or adjust limits * **Custom cancellation flows**: Build in-app cancellation with feedback collection ### Key Webhook Events | Event | When It Fires | | - | - | | `subscription.activated` | First payment succeeded and the subscription started — the first billing period begins here | | `subscription.payment_succeeded` | Every successful charge, first and renewals alike. A payment event: it carries the charge, not the new period dates | | `subscription.renewed` | The billing period rolled forward — carries `currentPeriodStart` / `currentPeriodEnd`. Extend access on this one | | `subscription.recovered` | An overdue subscription was brought back to active by a successful retry | | `subscription.past_due` | A renewal charge failed and the subscription is overdue | | `subscription.plan_changed` | A plan change took effect — only on plan changes, never on ordinary renewals | | `subscription.canceling` / `subscription.canceled` | Cancellation requested / subscription ended at the period end | `order.completed` is for one-time orders only and never fires for subscriptions. For webhook setup, see the [Webhooks guide](/guides/webhooks). For API details, see the [API Reference](/api-reference/introduction). *** ## Testing **1. Enable Test Mode** Toggle to test mode in your Dashboard. **2. Subscribe with Test Card** Use `4576 7500 0000 0110` to simulate a successful subscription. **3. Check Subscription** Verify the subscription appears in your Subscriptions page with the correct plan and status. **4. Test Cancellation** Cancel the test subscription and verify it transitions to canceling → canceled. *** ## Launch Checklist * [ ] Subscription products created for each plan/tier * [ ] Product group set up (if multiple tiers) * [ ] Pricing page links to correct checkout URLs * [ ] Test subscription flow works end-to-end * [ ] Cancellation flow tested * [ ] Notification emails look correct * [ ] Products published to production *** ## Next Steps > **[Set Up Webhooks](/guides/webhooks)** > > Automate access control with subscription event notifications > **[AI Product Billing](/guides/ai-billing)** > > Combine subscriptions with metered usage # Set Up Webhooks Source: https://docs.waffo.ai/guides/webhooks Get notified when payments succeed, subscriptions renew, or refunds are processed ## What Are Webhooks? Webhooks are automatic notifications that Waffo Pancake sends to your server when something happens — a payment succeeds, a subscription renews, a refund is processed, etc. **Why you need them:** * **Automate delivery**: Send download links or grant access immediately after payment * **Keep your system in sync**: Update your database when subscription status changes * **React to events**: Handle failed payments, cancellations, and refunds in real time *** ## Step 1: Add a Webhook in the Dashboard **1. Go to Settings** In your Dashboard, navigate to **Settings → Webhooks**. ![Webhooks settings page with Test Mode and Live Mode sections](https://mintcdn.com/waffo/MyxWRBeTICeW5ClC/images/guides/webhook-settings.png?fit=max\&auto=format\&n=MyxWRBeTICeW5ClC\&q=85\&s=ebf0fc610d7a43a1578dca3607e5f324) **2. Choose a Format** Select how the payload should be shaped for the destination — Raw JSON for your own backend, a chat-platform format (Slack / Discord / Feishu / Telegram) so messages render natively in that tool, or **OpenClaw / Hermes** (the self-hosted Pancake plugin) for custom routing and downstream logic. See [Choose a payload format](#choose-a-payload-format) below. ![Add Webhook modal with the Format dropdown open showing Raw, Feishu, Slack, Discord, Telegram, OpenClaw/Hermes](https://mintcdn.com/waffo/MyxWRBeTICeW5ClC/images/guides/webhook-add-format.png?fit=max\&auto=format\&n=MyxWRBeTICeW5ClC\&q=85\&s=69333c1c37cae6513c9574f502c69000) **3. Set Your Webhook URL** Enter the URL where Waffo Pancake should send event notifications. * **Test mode URL**: Your development/staging server (e.g., `https://staging.yoursite.com/webhooks/waffo`) * **Production URL**: Your production server (e.g., `https://yoursite.com/webhooks/waffo`) > [!TIP] > > You can set different URLs for test and production environments. This keeps test events separate from real ones. > [!NOTE] > > If you picked **Telegram** in the previous step, you'll fill in a **Bot Token** and a **Chat ID** instead of a URL. See [Telegram](#telegram) below for how to obtain them. **4. Pick the events** All events are subscribed by default. Untick the ones you don't want. **5. Save** Click **Save Webhook**. You can configure **up to 10 webhooks per environment**, so you can fan out the same events to multiple destinations (your backend, a Slack channel, an internal dashboard) without writing your own relay. The same URL cannot be added twice in the same environment. > [!NOTE] > > **Production note**: Live Mode webhooks only deliver after your store passes review. While the store is still under review, use Test Mode webhooks against staging code paths. *** ## Choose a payload format Waffo can deliver each event in the format your destination expects, so you don't have to write a translator. Pick the format when you add the webhook; you can re-add a webhook with a different format if you change your mind. | Format | Use when… | Endpoint | | - | - | - | | **Raw** (default) | You're calling your own backend and want the canonical, signed JSON payload. | Any HTTPS URL | | **Feishu / Lark** | You want events posted into a Feishu group via a custom bot. | `https://open.feishu.cn/open-apis/bot/v2/hook/` | | **Slack** | You want events posted into a Slack channel via an Incoming Webhook. | `https://hooks.slack.com/services/T.../B.../` | | **Discord** | You want events posted into a Discord channel via a channel webhook. | `https://discord.com/api/webhooks//` | | **Telegram** | You want events posted into a Telegram chat or group via a bot. | Bot Token + Chat ID (URL is built for you) | | **OpenClaw / Hermes** | You're routing events through the self-hosted **Pancake plugin** for custom downstream logic. | `https://relay.waffo.ai/webhook/` | Only **Raw** carries an RSA-SHA256 signature. The chat-platform formats authenticate via the URL-embedded token issued by the destination platform, so signature verification is not used for them. ### Raw 1. In your backend, expose an HTTPS endpoint that accepts `POST application/json`. 2. Paste the URL into the **Endpoint URL** field. 3. On the same **Settings → Webhooks** page, copy the **Webhook Public Key** for the environment you're integrating (Test or Production) — you'll use it to verify deliveries (see [API Reference — Webhooks](/api-reference/webhooks)). The key is platform-level, shared across all stores; it doesn't depend on the webhook you just added, and it stays the same whenever you add, edit, or delete webhook URLs. ### Feishu / Lark 1. In your Feishu group, add a **Custom Bot** and copy its webhook URL. 2. The URL looks like `https://open.feishu.cn/open-apis/bot/v2/hook/` (or `open.larksuite.com/...` outside China — both work). 3. Paste it into the **Endpoint URL** field. ### Slack 1. In your Slack workspace, install an **Incoming Webhook** for the destination channel. 2. Copy the webhook URL — it looks like `https://hooks.slack.com/services/T.../B.../`. 3. Paste it into the **Endpoint URL** field. ### Discord 1. In the destination channel, open **Edit Channel → Integrations → Webhooks → New Webhook** and copy the URL. 2. Format: `https://discord.com/api/webhooks//`. 3. Paste it into the **Endpoint URL** field. ### Telegram Telegram needs both a **Bot Token** and a **Chat ID** — Waffo builds the Telegram `sendMessage` URL for you. 1. Talk to [@BotFather](https://t.me/botfather) and create (or pick) a bot. Copy its token, e.g. `123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11`. 2. Add the bot to the destination chat or channel and grant it permission to send messages. 3. Get the chat ID. The easiest way: send a message in the chat, then visit `https://api.telegram.org/bot/getUpdates` and copy the `chat.id` from the response. 4. In the **Add Webhook** modal, choose **Telegram**, paste the **Bot Token** and **Chat ID**, and save. Behind the scenes Waffo posts to `https://api.telegram.org/bot/sendMessage` with `chat_id` set to the value you provided. ### OpenClaw / Hermes (Pancake plugin) The Pancake plugin is Waffo's self-hosted relay. It receives events from Waffo, runs your custom logic (templating, rate-limiting, multi-fan-out), and forwards messages to wherever you want. **OpenClaw** and **Hermes** are two ready-to-run flavors of the plugin; pick whichever matches your stack. 1. Install the plugin with the matching setup command: ```bash theme={"system"} # OpenClaw npx -p @waffo/pancake-plugin openclaw-setup # Hermes npx -p @waffo/pancake-plugin hermes-setup ``` Full setup guide: [github.com/waffo-com/waffo-pancake-plugin](https://github.com/waffo-com/waffo-pancake-plugin). 2. After install, the plugin gives you a relay URL of the form `https://relay.waffo.ai/webhook/`. 3. In the **Add Webhook** modal, choose **OpenClaw / Hermes**, paste the relay URL, and save. *** ## Step 2: Understand Event Types Waffo Pancake sends these webhook events: ### Order Events | Event | When It Fires | Common Action | | - | - | - | | `order.completed` | Order completed successfully | Deliver product, grant access | ### Subscription Events | Event | When It Fires | Common Action | | - | - | - | | `subscription.activated` | Subscription activated | Create account, set limits | | `subscription.payment_succeeded` | Subscription charge succeeded (pure payment event) | Record the receipt, issue the invoice | | `subscription.renewed` | Billing period rolled forward | Extend access period | | `subscription.recovered` | Overdue subscription recovered | Restore full access | | `subscription.plan_changed` | Plan change took effect | Update access level | | `subscription.canceling` | Cancellation requested | Notify team, send retention offer | | `subscription.uncanceled` | Subscription reactivated | Restore full access | | `subscription.canceled` | Subscription fully ended | Revoke access | | `subscription.past_due` | Payment failed | Notify customer, retry | ### Refund Events | Event | When It Fires | Common Action | | - | - | - | | `refund.succeeded` | Refund processed | Revoke access, update records | | `refund.failed` | Refund processing failed | Notify merchant, investigate | *** ## Step 3: Set Up Email Notifications In addition to webhook events, you can configure email notifications for both you and your customers. ### Merchant Notifications Go to **Settings → Notifications** to choose which events trigger email alerts to you: * New orders * New subscriptions * Failed payments * Refund requests ![Notification settings](https://mintcdn.com/waffo/5dRlk76Jm-9Zm6Tj/images/guides/notification-settings.png?fit=max\&auto=format\&n=5dRlk76Jm-9Zm6Tj\&q=85\&s=c1e650a73ceae7f9ee34289cc7efb9c4) ### Customer Notifications Customers automatically receive emails for: * Order confirmation * Subscription confirmation * Subscription renewal * Subscription cancellation * Payment failure You can toggle these in the notification settings. *** ## How Webhooks Work ``` Event occurs (e.g., payment succeeds) ↓ Waffo Pancake sends POST request to your webhook URL ↓ Your server receives the event ↓ Your server processes it (deliver product, update database, etc.) ↓ Your server responds with 200 OK ``` ### Retry Policy If your server doesn't return a 2xx status code, or doesn't respond within the timeout window, the delivery is retried automatically: * Up to **3 retries** (4 attempts in total), scheduled by the delivery queue with its default exponential backoff — Waffo does not configure the intervals. * After the last retry fails, the event is marked `failed`. There is no manual resend; reconcile from the Dashboard delivery logs or by querying orders and payments through GraphQL. See [Retry Policy](/api-reference/webhooks#retry-policy) in the API Reference for details. *** ## For Developers: Code Integration If you're integrating webhooks with your server, here's how the flow works: ### 1. Create a Webhook Endpoint Your server needs a POST endpoint to receive events. The specific implementation depends on your tech stack. ### 2. Verify the Signature Every webhook request includes a signature header for security. Verify it to ensure the request came from Waffo Pancake, not a malicious third party. ### 3. Process Events Parse the event type and data, then take the appropriate action (deliver product, update subscription status, etc.). ### 4. Respond Quickly Return a 200 status code as fast as possible. If you need to do heavy processing, do it asynchronously after responding. > [!NOTE] > > For detailed code examples and signature verification, see the [API Reference — Webhooks](/api-reference/webhooks). *** ## Testing Webhooks **1. Set Test Webhook URL** In Dashboard → Settings → Webhooks, enter your test server URL. **2. Make a Test Purchase** Use test mode to create a purchase. This triggers webhook events to your test URL. **3. Verify Receipt** Check your server logs to confirm the webhook was received and processed correctly. *** ## Local development with ngrok When you're building your webhook handler locally, Pancake's servers can't reach `http://localhost:3000` directly. You need a **public HTTPS tunnel** that forwards inbound requests to your local port. We recommend [ngrok](https://ngrok.com) — it's free for development and preserves all custom headers (including `X-Waffo-Signature`). ### Why a tunnel is required Webhook delivery is **inbound to your server**: Pancake POSTs to whatever URL you configure. A localhost URL is only reachable from your own machine, so without a tunnel the requests never arrive. The tunnel gives your local server a public HTTPS hostname for the duration of your dev session. ### Install and start ngrok **1. Install** * **macOS**: `brew install ngrok` * **Windows / Linux**: download from [ngrok.com/download](https://ngrok.com/download) **2. Authenticate (free tier is fine)** Sign up at [ngrok.com](https://ngrok.com), grab your authtoken from the dashboard, then run: ```bash theme={"system"} ngrok config add-authtoken ``` **3. Start the tunnel** Point ngrok at your local server's port. If your webhook handler runs on `localhost:3000`: ```bash theme={"system"} ngrok http 3000 ``` ngrok prints a forwarding URL like: ``` Forwarding https://abc-123-456-789.ngrok-free.app -> http://localhost:3000 ``` Copy the `https://...ngrok-free.app` URL — that's your public webhook endpoint. ### Wire it into Pancake **1. Configure the Test Webhook URL** In the Merchant Dashboard, open your store and go to **Settings → Webhooks**. Paste the ngrok URL (with your handler path appended, e.g. `https://abc-123.ngrok-free.app/api/webhooks/waffo`) into **Test Webhook URL** and select the events you want to receive. Save. > [!WARNING] > > Only configure Test environment with the ngrok URL. Never put a temporary tunnel URL into the Production webhook — production traffic must hit a stable, deployed endpoint. **2. Trigger an event** Either click **Send test event** in the Dashboard, or perform a real action in test mode (e.g., create a checkout and complete it with a [test card](/api-reference/webhooks#testing)). **3. Inspect the request** Open ngrok's local web inspector at [http://127.0.0.1:4040](http://127.0.0.1:4040) — it shows every request that came through, including headers and body. Confirm the `X-Waffo-Signature` header is present. **4. Verify in your handler** Check your local server logs. You should see the webhook POST landing and `verifyWebhook()` succeeding. If verification fails, see the pitfalls below. ### Common pitfalls | Issue | Why it happens | Fix | | - | - | - | | **`localtunnel` always returns 401 on signature verification** | localtunnel strips custom HTTP headers, so `X-Waffo-Signature` never reaches your handler | Use ngrok or cloudflared instead — both preserve all headers | | **The ngrok URL changed after restart** | The free tier issues a new random subdomain on every `ngrok http` run | Update the Test Webhook URL in the Dashboard each time. For frequent dev, ngrok's paid tier offers reserved subdomains | | **Events stop arriving after a while** | Free ngrok sessions expire after a few hours | Restart `ngrok http 3000` and re-paste the new URL | | **Pancake retried the event multiple times** | Your handler returned a non-2xx response and the delivery was retried with exponential backoff | Fix the handler and wait for the next retry. Manual **Resend** is not available yet — the button in the delivery log is disabled | ### Cloudflared as an alternative If you prefer a no-account option, [cloudflared](https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/downloads/) works similarly: ```bash theme={"system"} cloudflared tunnel --url http://localhost:3000 ``` It preserves headers, requires no signup for ad-hoc tunnels, and prints a `*.trycloudflare.com` URL you can paste into the Dashboard. The trade-off is no built-in request inspector UI — you'll rely on your own server logs. ### Quick verification checklist * [ ] Local server is running and listening on the expected port * [ ] `ngrok http ` is running, forwarding URL captured * [ ] Test Webhook URL in Dashboard matches the **current** ngrok URL (with handler path) * [ ] Inbound request visible at [http://127.0.0.1:4040](http://127.0.0.1:4040) with `X-Waffo-Signature` header * [ ] Local logs show `verifyWebhook` returning success and your event handler running *** ## Best Practices 1. **Respond quickly**: Return 200 immediately, process asynchronously 2. **Handle duplicates**: Events may be sent more than once — make your processing idempotent 3. **Verify signatures**: Always verify the webhook signature before processing 4. **Log everything**: Keep logs of received webhooks for debugging 5. **Monitor failures**: Check your Dashboard for failed webhook deliveries *** ## Checklist * [ ] Webhook URLs configured for test and production * [ ] Email notifications configured for your team * [ ] Customer notification preferences set * [ ] Test webhook received and processed successfully * [ ] Signature verification implemented (if using code integration) *** ## Next Steps > **[Manage Refunds](/guides/refunds)** > > Handle refund requests and track refund status > **[API Reference — Webhooks](/api-reference/webhooks)** > > Detailed webhook payload format and code examples # Introduction Source: https://docs.waffo.ai/index Accept payments globally — we handle taxes, compliance, and payouts so you don't have to. ## Turn Your Software into a Business You built something people want. Now you need to get paid — globally, compliantly, without the headache. **Waffo Pancake handles everything between your product and your bank account:** payments, taxes, compliance, and payouts worldwide. > **Global Card Payments** > > Accept Visa, Mastercard, Apple Pay & Google Pay for faster checkout. > **No LLC? No Problem.** > > Get paid directly to your bank account. We're your Merchant of Record. *** ## What's Blocking Your Revenue? You want to ship, not fight compliance. Here's what we solve for you: > **I don't have a company. Can I still get paid?** > > Traditional MoR services require you to register a legal entity first — that takes weeks and thousands of dollars. > > **Waffo Pancake's Solution:** We act as your Merchant of Record. You get paid directly to your bank account without needing an LLC. > **Building a billing system is too complex** > > Subscription management, tax calculation, dunning emails, failed payment retries... that's months of engineering work. > > **Waffo Pancake's Solution:** Complete infrastructure out of the box — subscriptions, one-time payments, all handled. > **Global tax compliance gives me a headache** > > The US has 10,000+ tax jurisdictions, the EU has 27 countries each with VAT rules, plus constantly changing regulations... > > **Waffo Pancake's Solution:** We're the legal seller. Tax calculation, collection, and reporting are handled automatically. > **Poor checkout experience is losing customers** > > Complex checkout forms, no Apple Pay/Google Pay, no multi-language support — every step loses customers. > > **Waffo Pancake's Solution:** Optimized two-step checkout flow, Apple Pay & Google Pay support, built-in 19 languages. *** ## How Waffo Pancake Helps You > **We're the Legal Seller** > > Taxes, compliance, risk — all handled by us. You focus on your product. > **All Major Card Networks** > > Visa, Mastercard, Apple Pay, and Google Pay. > **Flexible Billing Models** > > One-time or subscription — your business model, your choice. Weekly, monthly, quarterly, or annual billing. > **Optimized Checkout** > > Two-step checkout flow, 19 languages supported, mobile-first design. > **Real-time Insights** > > Revenue, customers, subscription metrics — no SQL needed, everything at a glance. > **Complete Order Management** > > Refunds, customer portal, subscription management — all in one dashboard. *** ## Who Is This For? > **Solo Founders** > > No company? No problem. Get paid directly to your bank account. We handle all compliance. > **SaaS Startups** > > Subscriptions, trials, seat-based billing, usage metering — complete solution designed for SaaS. > **Vibe Coders** > > AI-friendly integration via SDK, MCP Skill, and CLI — ship payments with natural language prompts. *** ## Start Getting Paid in 5 Minutes **1. Create an Account** Sign up at [Merchant Dashboard](https://pancake.waffo.ai/merchant/auth/signin). No credit card required. **2. Add a Product** Create a product and set pricing. Done in 2 minutes. **3. Share Your Link** Get your checkout link and add it to your website. **4. Get Paid** Funds go directly to your bank account. > **[Quickstart](/quickstart)** > > Set up your first payment in 5 minutes. > **[Feature Overview](/feature-list)** > > Browse everything Waffo Pancake offers. > **[Test Mode](/features/test-mode)** > > Safely test the complete flow before going live. *** ## Built for Developers Install the official TypeScript SDK and start accepting payments in a few lines: ```bash theme={"system"} npm install @waffo/pancake-ts ``` ```typescript theme={"system"} import { WaffoPancake } from "@waffo/pancake-ts"; const client = new WaffoPancake({ merchantId: process.env.WAFFO_MERCHANT_ID!, privateKey: process.env.WAFFO_PRIVATE_KEY!, }); // Create a checkout session — redirect consumer to checkoutUrl const session = await client.checkout.createSession({ storeId: "store_xxx", productId: "prod_xxx", productType: "onetime", currency: "USD", }); // => session.checkoutUrl ``` Or call the REST API directly: ```bash theme={"system"} curl -X POST https://api.waffo.ai/v1/actions/checkout/create-session \ -H "Content-Type: application/json" \ -H "X-Store-Slug: your-store-slug" \ -H "X-Environment: test" \ -d '{ "productId": "your-product-uuid", "productType": "onetime", "currency": "USD" }' ``` > **[TypeScript SDK](/integrate/sdks)** > > Official SDK with built-in signing and webhook verification. > **[API Reference](/api-reference/introduction)** > > REST + GraphQL API with full endpoint documentation. > **[Webhooks](/api-reference/webhooks)** > > Real-time event notifications. Seamless backend integration. *** ## Start Your Global Revenue Journey Don't let complex compliance slow down your product momentum. > **[Sign Up Now](https://pancake.waffo.ai/merchant/auth/signin)** > > Start accepting payments in minutes. Built for developers. # AI Integration Source: https://docs.waffo.ai/integrate/ai-integration Complete reference for the @waffo/pancake-ts SDK — covers store setup, products, checkout, webhooks, subscriptions, and GraphQL queries ### The Simple Version Tell your AI assistant: ```text theme={"system"} Read https://docs.waffo.ai/llms-full.txt, load the official Waffo Pancake skill from https://docs.waffo.ai/integrate/skill, and integrate Waffo Pancake payments into the current project. ``` That's it. Use this page as the AI integration entry point, then open the official skill file below when you need the exact `SKILL.md`. ### The Full Version For a complete integration with end-to-end tests: ```text theme={"system"} Read https://docs.waffo.ai/llms-full.txt, load the official Waffo Pancake skill from https://docs.waffo.ai/integrate/skill, and use Waffo Pancake SDK to integrate Waffo Pancake payments into the current project and run through the full checkout flow: 1. Get Merchant ID from Dashboard → API & Development → "Create an API Key" section → first row above the key list → copy button (use this as `WAFFO_MERCHANT_ID`, not `storeId`) 2. Create an API Key from Dashboard → API & Development → API Keys 3. Use only `WAFFO_MERCHANT_ID` and `WAFFO_PRIVATE_KEY` as required env vars for the first working integration 4. Install @waffo/pancake-ts SDK 5. Create checkout and webhook endpoints 6. Test with card 4576750000000110 7. Verify webhook receives order.completed event Use test environment. ``` > **[Official Waffo Pancake Skill](/integrate/skill)** > > Open the official skill file from the AI Integration page to view, copy, or download the exact `SKILL.md` used by the team. *** The `@waffo/pancake-ts` SDK is the official server-side TypeScript client for the Waffo Pancake API. It handles request signing, checkout session creation, webhook verification, and GraphQL queries. ## AI Coding Workflow AI coding agents are most useful when you already understand the business model but want help turning it into a clean Waffo catalog and implementation plan. Typical tasks: * Convert a pricing page into Waffo products and product groups * Decide which offers should be subscription products vs one-time charges * Design dynamic pricing flows with `priceSnapshot` * Batch-generate product definitions, metadata, and rollout checklists * Review an existing catalog for naming, plan structure, and production readiness ### Recommended Workflow **1. Describe the business model** Explain what you sell, how customers are charged, and which parts are fixed-price versus usage-based. **2. Ask for a catalog plan** Have the agent map your offers into one-time products, subscription products, product groups, and optional dynamic pricing flows. **3. Review the output** Confirm naming, billing periods, tax categories, and whether any add-ons should remain one-time charges. **4. Implement** Use the output to create products in the Dashboard or to generate SDK/API integration code. ### Prompt Templates #### 1. Turn a Pricing Page into Waffo Products ```text theme={"system"} Read https://docs.waffo.ai/llms-full.txt. I need you to turn this pricing model into a Waffo Pancake catalog: - Starter: $19/month - Pro: $59/month - Scale: custom annual contract - Overage: $0.20 per extra credit - Optional onboarding fee: $499 one time Please output: 1. Which items should be subscription products 2. Which items should be one-time products 3. Which subscription products should be grouped together 4. Which flows require dynamic pricing via priceSnapshot 5. Recommended product names, tax categories, and environment rollout order ``` #### 2. Plan Dynamic Pricing ```text theme={"system"} Read https://docs.waffo.ai/llms-full.txt. I already have a subscription business in Waffo Pancake. I need to add dynamic pricing for overage billing. Please design: 1. The base one-time product I should create 2. When to use priceSnapshot 3. What data should be calculated on my server before checkout 4. How to explain this clearly to my team so they do not confuse it with subscription billing ``` #### 3. Review an Existing Catalog ```text theme={"system"} Read https://docs.waffo.ai/llms-full.txt. Review this Waffo product catalog and tell me: 1. Which names are unclear 2. Which subscription products should be grouped 3. Where dynamic pricing should replace fixed pricing 4. Which products should stay one-time even though the business is subscription-led 5. What should be published to production first ``` ### Practical Rules | Situation | Recommended model | | - | - | | Fixed public price | Product price stored on the product | | Runtime-calculated amount | Checkout session with `priceSnapshot` | | Recurring plan | Subscription product | | Multiple subscription tiers | One subscription product per tier + product group | | Setup fee or credits top-up | One-time product | | Overage charge for a subscription customer | One-time product with dynamic pricing | > [!NOTE] > > It is normal for a subscription-led business to create both subscription products and one-time charges. The charging model should match the business event, not the company label. ### What To Avoid * Do not paste private keys or production secrets into prompts * Do not let an AI agent publish products to production without review * Do not model every pricing variation as a separate product if the final amount is computed at runtime * Do not force overage billing into subscription products when the charge is event-based ## Gotchas — Read This First These are the mistakes that break integrations. Read before writing any code. | Gotcha | Why It Breaks | Fix | | - | - | - | | Reading webhook body as JSON | `request.json()` re-serializes the body, changing whitespace. Signature verification compares against the **original raw bytes**. | Always use `request.text()` (App Router / Hono) or `express.raw()` (Express). | | Using localtunnel for webhooks | localtunnel strips custom HTTP headers. `X-Waffo-Signature` never reaches your handler. | Use `cloudflared tunnel --url http://localhost:3000` instead. | | Forgetting `.publish()` | Products are created in `test` environment by default. Production checkout sessions for unpublished products will fail silently. | Call `client.onetimeProducts.publish({ id })` or `client.subscriptionProducts.publish({ id })` before going live. | | Accessing `result` instead of `result.data` in GraphQL | The GraphQL client returns `{ data: T \| null, errors?: [...] }`. Fields are nested under `.data`. | Always destructure: `const stores = result.data?.stores ?? []`. | | Using `$id: ID!` in GraphQL variables | Backend uses `$id: String!`, not `$id: ID!`. Using the wrong type silently returns `null`. | Always declare ID variables as `String!`. | | `productIds` in group update is full replacement | Calling `subscriptionProductGroups.update({ productIds: [...] })` replaces the entire list — it does not append. | Always pass the complete desired list, not just new additions. | *** ## Use Cases Waffo Pancake is a merchant-of-record payment platform. The SDK fits projects that need: * **SaaS subscription billing** — monthly/yearly plans with upgrade/downgrade (e.g., Free/Pro/Team tiers) * **Digital product sales** — one-time purchases for e-books, templates, courses, licenses * **Per-usage payments** — charge per download, API call, or generated report * **Hybrid models** — subscriptions + one-time purchases combined | Project Type | Payment Model | Products to Create | | - | - | - | | AI Skills marketplace | Per-download + Pro subscription | 1 one-time (\$0.99/download) + 2 subscriptions (monthly/yearly) | | Online course platform | One-time per course | 1 one-time per course ($29–$199) | | SaaS (Starter/Pro/Enterprise) | Subscription tiers | 3 subscriptions + 1 product group for plan switching | | Template shop | One-time per template | 1 one-time per template, or 1 shared product with `priceSnapshot` override | | API credits | Credit packs + subscription | 1 one-time per pack + subscription for monthly quota | *** ## Installation & Setup ```bash theme={"system"} npm install @waffo/pancake-ts ``` Server-side only. Node.js 18+. Zero dependencies. ```typescript theme={"system"} import { WaffoPancake } from "@waffo/pancake-ts"; const client = new WaffoPancake({ merchantId: process.env.WAFFO_MERCHANT_ID!, privateKey: process.env.WAFFO_PRIVATE_KEY!, }); ``` Two env vars are required — provided at signup: ``` WAFFO_MERCHANT_ID= WAFFO_PRIVATE_KEY= ``` `WAFFO_MERCHANT_ID` means your **Merchant ID**, not `storeId` and not a store identifier from a URL. `storeId` is still part of the current API model for store and product management flows, so do not confuse the two. For the first working integration, only these two env vars need to exist: `WAFFO_MERCHANT_ID` and `WAFFO_PRIVATE_KEY`. Store IDs and Product IDs are runtime values you can keep in code, app config, or your own database. ### PEM Key Handling **Escaped newlines** (simplest): ``` WAFFO_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\nMIIEv...\n-----END PRIVATE KEY-----" ``` **Base64** (recommended for CI/CD): ```bash theme={"system"} cat private.pem | base64 | tr -d '\n' ``` ```typescript theme={"system"} const privateKey = Buffer.from(process.env.WAFFO_PRIVATE_KEY_BASE64!, "base64").toString("utf-8"); ``` **File path** (local dev): ```typescript theme={"system"} import { readFileSync } from "fs"; const privateKey = readFileSync("./keys/private.pem", "utf-8"); ``` *** ## Quick Start: Path A ```typescript theme={"system"} // 1. Create a store const { store } = await client.stores.create({ name: "My SaaS" }); // 2. Create products const { product: monthly } = await client.subscriptionProducts.create({ storeId: store.id, name: "Pro Monthly", billingPeriod: "monthly", prices: { USD: { amount: "9.99", taxIncluded: true, taxCategory: "saas" } }, }); const { product: yearly } = await client.subscriptionProducts.create({ storeId: store.id, name: "Pro Yearly", billingPeriod: "yearly", prices: { USD: { amount: "99.00", taxIncluded: true, taxCategory: "saas" } }, }); // 3. Create a checkout session const session = await client.checkout.createSession({ productId: monthly.id, productType: "subscription", currency: "USD", }); // Redirect customer to session.checkoutUrl ``` Store IDs and Product IDs are follow-up values. Save them wherever your app keeps runtime configuration; they do not need to be env vars unless you want that convention. If a merchant has multiple stores, confirm which store should own the product before creating it. Do not guess the target store. ## Quick Start: Path B If products already exist in the Dashboard, copy the Product ID and go straight to checkout. In this flow, you still only need the same two env vars above: ```typescript theme={"system"} const session = await client.checkout.createSession({ productId: "PROD_xxx_from_dashboard", productType: "subscription", currency: "USD", buyerEmail: "customer@example.com", successUrl: "https://myapp.com/welcome", }); // Redirect customer to session.checkoutUrl ``` *** ## API Reference ### Stores ```typescript theme={"system"} // Create const { store } = await client.stores.create({ name: "My Store" }); // Update (partial — only provided fields change) const { store } = await client.stores.update({ id: "store_id", name: "New Name", supportEmail: "help@example.com", website: "https://example.com", }); // Soft-delete const { store } = await client.stores.delete({ id: "store_id" }); ``` ### One-Time Products ```typescript theme={"system"} const { product } = await client.onetimeProducts.create({ storeId: "store_id", name: "E-Book", description: "A great e-book", prices: { USD: { amount: 29.00, taxIncluded: false, taxCategory: "digital_goods" }, }, successUrl: "https://example.com/thanks", metadata: { sku: "EB-001" }, }); // Update (creates new immutable version) const { product } = await client.onetimeProducts.update({ id: "product_id", name: "E-Book v2", prices: { USD: { amount: 39.00, taxIncluded: false, taxCategory: "digital_goods" } }, }); // Publish test → production (required before going live) const { product } = await client.onetimeProducts.publish({ id: "product_id" }); // Activate / deactivate const { product } = await client.onetimeProducts.updateStatus({ id: "product_id", status: "inactive", // or "active" }); ``` **taxCategory options:** `digital_goods` | `saas` | `software` | `ebook` | `online_course` | `consulting` | `professional_service` ### Subscription Products ```typescript theme={"system"} const { product } = await client.subscriptionProducts.create({ storeId: "store_id", name: "Pro Monthly", billingPeriod: "monthly", // "weekly" | "monthly" | "quarterly" | "yearly" prices: { USD: { amount: 9.99, taxIncluded: true, taxCategory: "saas" } }, }); // update, publish, updateStatus — same pattern as one-time products ``` ### Subscription Product Groups Groups enable shared trials and plan switching between subscription products. ```typescript theme={"system"} const { group } = await client.subscriptionProductGroups.create({ storeId: "store_id", name: "Pro Plans", rules: { sharedTrial: true }, productIds: ["monthly_product_id", "yearly_product_id"], }); // Update (productIds is FULL REPLACEMENT, not append) await client.subscriptionProductGroups.update({ id: "group_id", productIds: ["monthly_id", "quarterly_id", "yearly_id"], }); // Publish to production await client.subscriptionProductGroups.publish({ id: "group_id" }); // Delete (physical delete, not soft-delete) await client.subscriptionProductGroups.delete({ id: "group_id" }); ``` ### Checkout Sessions ```typescript theme={"system"} const session = await client.checkout.createSession({ productId: "product_id", productType: "onetime", // "onetime" | "subscription" currency: "USD", buyerEmail: "buyer@example.com", // optional, pre-fills email successUrl: "https://example.com/thanks", // redirect after payment metadata: { orderId: "internal-123" }, // custom key-value pairs // Optional overrides: priceSnapshot: { amount: 19.99, taxIncluded: true, taxCategory: "saas" }, billingDetail: { country: "US", isBusiness: false }, expiresInSeconds: 3600, // default: 86400 (24 hours), recommended: 60–604800 }); // session.checkoutUrl — redirect customer here // session.sessionId — for tracking // session.expiresAt — ISO 8601 expiry ``` ### Order-Level Parameters & Priority Parameters passed to `createSession` can override product-level settings. Understanding the priority hierarchy is essential for AI integrations: | Parameter | Purpose | Priority | | - | - | - | | `priceSnapshot` | Override product price (dynamic pricing) | **Highest** — ignores the product's set price | | `currency` | Specify checkout currency | Required — selects the matching currency from product prices | | `buyerEmail` | Pre-fill consumer email | Optional — skips the email input step on the checkout page | | `billingDetail` | Pre-fill billing info (country, tax ID, etc.) | Optional — skips the address input on the checkout page | | `successUrl` | Redirect URL after successful payment | Overrides product-level successUrl | | `metadata` | Custom key-value pairs (internal order ID, etc.) | Passed through to webhook event.data | | `withTrial` | Enable trial period | Overrides product-level trial settings | | `expiresInSeconds` | Session expiration time | Default 24 hours, recommended 1 minute to 7 days | | `darkMode` | Checkout page dark mode | `true`=dark / `false`=light / omit=store default | > [!WARNING] > > **`priceSnapshot` is the key parameter for dynamic pricing.** When `priceSnapshot` is provided, the price set on the product is completely ignored. Use cases include: usage-based tiered pricing, A/B testing different price points, and more. Do not use it for discounts — create a coupon and apply it with `couponId`, `promotionCode` or `allowPromotionCodes`, so uses and limits are tracked and the customer sees the discount (see [Discounts & Promotions](/guides/discounts)). ```typescript theme={"system"} // Dynamic pricing example: override price based on usage tier const session = await client.checkout.createSession({ storeId: "store_id", productId: "api-credits-product-id", productType: "onetime", currency: "USD", priceSnapshot: { amount: 49.00, taxIncluded: true, taxCategory: "saas" }, // overrides product price buyerEmail: "user@example.com", metadata: { internalOrderId: "ORD-2024-001", tier: "growth" }, successUrl: "https://myapp.com/purchase/success", }); ``` ### Webhook Integration Notes Key points to keep in mind when integrating webhooks: | Point | Description | | - | - | | **Raw body** | Must use `request.text()` to read the body, not `.json()` — signature verification relies on raw bytes | | **Idempotent handling** | Use `event.id` (delivery ID) for deduplication — the same event may be retried multiple times | | **Return 200 immediately** | Return 200 OK first, then process business logic asynchronously. Timeouts trigger retries | | **Environment distinction** | `event.mode` is `"test"` or `"prod"` — ensure test events don't trigger production logic | | **Retry mechanism** | Non-2xx or timeout triggers retries (default 3 times, exponential backoff) | **Typical webhook handler pattern:** ```typescript theme={"system"} import { verifyWebhook } from "@waffo/pancake-ts"; export async function POST(request: Request) { const body = await request.text(); const sig = request.headers.get("x-waffo-signature"); try { const event = verifyWebhook(body, sig); // Idempotency check if (await isDuplicate(event.id)) return new Response("OK"); await markProcessed(event.id); // Dispatch by event type switch (event.eventType) { case "order.completed": await handleOrderCompleted(event.data); break; case "subscription.activated": await handleSubscriptionActivated(event.data); break; case "subscription.canceled": await handleSubscriptionCanceled(event.data); break; case "subscription.past_due": await handlePastDue(event.data); break; } return new Response("OK"); } catch { return new Response("Invalid signature", { status: 401 }); } } ``` ### Cancel Subscription ```typescript theme={"system"} const { orderId, status } = await client.orders.cancelSubscription({ orderId: "order_id", }); // status: "canceled" (was pending) or "canceling" (active → ends at period end) ``` ### GraphQL Queries Read-only. Use `String!` for ID variables (not `ID!`). ```typescript theme={"system"} const result = await client.graphql.query<{ stores: Array<{ id: string; name: string; status: string }>; }>({ query: `query { stores { id name status } }`, }); const stores = result.data?.stores ?? []; // With variables — note String!, not ID! const result = await client.graphql.query<{ onetimeProduct: { id: string; name: string; prices: unknown }; }>({ query: `query ($id: String!) { onetimeProduct(id: $id) { id name prices } }`, variables: { id: "product_id" }, }); const product = result.data?.onetimeProduct; ``` *** ## Webhook Verification The SDK embeds public keys for both environments. Verification is one function call. ### Next.js App Router ```typescript theme={"system"} import { verifyWebhook } from "@waffo/pancake-ts"; export async function POST(request: Request) { const body = await request.text(); // MUST be raw text, not .json() const sig = request.headers.get("x-waffo-signature"); try { const event = verifyWebhook(body, sig); // event.eventType, event.data, event.storeId, event.mode return new Response("OK"); } catch { return new Response("Invalid signature", { status: 401 }); } } ``` ### Express ```typescript theme={"system"} import express from "express"; import { verifyWebhook } from "@waffo/pancake-ts"; // MUST use express.raw(), not express.json() app.post("/webhooks", express.raw({ type: "application/json" }), (req, res) => { try { const event = verifyWebhook( req.body.toString("utf-8"), req.headers["x-waffo-signature"] as string, ); res.status(200).send("OK"); } catch { res.status(401).send("Invalid signature"); } }); ``` ### Hono ```typescript theme={"system"} import { verifyWebhook } from "@waffo/pancake-ts"; app.post("/webhooks", async (c) => { const body = await c.req.text(); // raw text const sig = c.req.header("x-waffo-signature"); try { const event = verifyWebhook(body, sig); return c.text("OK"); } catch { return c.text("Invalid signature", 401); } }); ``` ### Verification Options ```typescript theme={"system"} // Explicit environment (skip auto-detection) const event = verifyWebhook(body, sig, { environment: "prod" }); // Custom replay tolerance (default: 5 minutes) const event = verifyWebhook(body, sig, { toleranceMs: 600000 }); // Disable replay protection (not recommended in production) const event = verifyWebhook(body, sig, { toleranceMs: 0 }); ``` ### Event Types | Event | Trigger | | - | - | | `order.completed` | One-time payment succeeded | | `subscription.activated` | First subscription payment succeeded | | `subscription.payment_succeeded` | Renewal payment succeeded | | `subscription.canceling` | Cancel initiated (active until period end) | | `subscription.uncanceled` | Cancellation withdrawn | | `subscription.plan_changed` | Plan changed (upgrade/downgrade) | | `subscription.canceled` | Subscription fully terminated | | `subscription.past_due` | Renewal payment failed | | `refund.succeeded` | Refund completed | | `refund.failed` | Refund failed | ### Event Shape ```typescript theme={"system"} interface WebhookEvent { id: string; // Delivery ID (use for idempotent dedup) timestamp: string; // ISO 8601 UTC eventType: string; // e.g. "order.completed" eventId: string; // Business event ID (payment/order ID) storeId: string; mode: "test" | "prod"; data: { orderId: string; buyerEmail: string; currency: string; amount: number; // USD dollar amount (e.g. 9.99) taxAmount: number; productName: string; }; } ``` ### Configuring Webhook URLs A store can have multiple webhooks, each delivering to a different channel (`http`, `feishu`, `discord`, `telegram`, `slack`). Register one entry per channel and environment: ```typescript theme={"system"} // HTTP — Test environment await client.webhooks.add({ storeId: "store_id", channel: "http", url: "https://your-domain.com/api/webhooks", events: [ "order.completed", "subscription.activated", "subscription.canceled", "subscription.past_due", ], testMode: true, }); // HTTP — Production environment await client.webhooks.add({ storeId: "store_id", channel: "http", url: "https://your-domain.com/api/webhooks", events: [ "order.completed", "subscription.activated", "subscription.canceled", "subscription.past_due", ], testMode: false, }); // Update an existing webhook (events / url) await client.webhooks.update({ id: "WBH_xxx", events: ["order.completed"], }); // Remove a webhook (hard delete) await client.webhooks.remove({ id: "WBH_xxx" }); ``` To list webhooks, use the GraphQL `Store.storeWebhooks` field — it is the only query entry point. *** ## Error Handling ```typescript theme={"system"} import { WaffoPancakeError } from "@waffo/pancake-ts"; try { await client.stores.create({ name: "My Store" }); } catch (err) { if (err instanceof WaffoPancakeError) { console.log(err.status); // HTTP status code console.log(err.errors); // Array of { message, layer } console.log(err.errors[0].layer); // "store" | "product" | "order" | ... } } ``` Errors are ordered by call stack depth: `errors[0]` is the root cause (deepest layer), `errors[n]` is the outermost caller. *** ## Development Tips 1. **Webhook tunneling** — use `cloudflared`, not localtunnel (see Gotchas). ```bash theme={"system"} brew install cloudflare/cloudflare/cloudflared cloudflared tunnel --url http://localhost:3000 ``` 2. **Idempotency is opt-in** — the SDK sends no key unless you pass `{ idempotencyKey }` on the call. Without one a retried write executes again; with one the platform replays the first response for 24h. 3. **Test → Prod workflow** — products default to test. Use `.publish()` to promote. Webhook events include `mode: "test" | "prod"` so your handler can distinguish. *** ## Dashboard UI Glossary The Dashboard supports English, Chinese, and Japanese. When docs reference a Dashboard location (e.g. "go to Integration"), the label may differ by language. Use this table to find the right menu item. ### Navigation | English | 中文 | 日本語 | | - | - | - | | Home | 首页 | ホーム | | Products | 产品 | 商品 | | Customers | 客户 | 顧客 | | Analytics | 分析 | 分析 | | Payments | 付款 | 支払い | | Subscriptions | 订阅 | サブスクリプション | | Revenue | 收入 | 収益 | | API & Development | API 与开发 | API と開発 | | Settings | 设置 | 設定 | ### Key Fields | English | 中文 | 日本語 | | - | - | - | | Merchant ID | 商户 ID | マーチャントID | | Store ID | 店铺 ID | ストアID | | API Key | API 密钥 | APIキー | | Private Key | 私钥 | 秘密鍵 | ### Modes & Actions | English | 中文 | 日本語 | | - | - | - | | Test Mode | 测试模式 | テストモード | | Live Mode | 生产模式 | 本番モード | | Create | 创建 | 作成 | | Edit | 编辑 | 編集 | | Delete | 删除 | 削除 | | Copy | 复制 | コピー | | Save | 保存 | 保存 | ### Product & Billing | English | 中文 | 日本語 | | - | - | - | | One-time | 一次性 | 単発 | | Subscription | 订阅 | サブスクリプション | | Weekly | 每周 | 週間 | | Monthly | 每月 | 月間 | | Quarterly | 每季度 | 四半期 | | Yearly | 每年 | 年間 | ### Statuses | English | 中文 | 日本語 | | - | - | - | | Active | 生效中 | 有効 | | Awaiting Payment | 待支付 | 支払い待ち | | Completed | 已完成 | 完了 | | Canceled | 已取消 | キャンセル済み | | Expired | 已过期 | 期限切れ | ### Where to Find IDs | Value | Location in Dashboard | | - | - | | `WAFFO_MERCHANT_ID` | API & Development (API 与开发) → "Create an API Key" section → first row above the key list → copy button | | `Store ID` | Settings (设置) → Store Profile (店铺资料) | | `Product ID` | Products (产品) → click a product → shown in URL and detail page | | `API Key` | API & Development (API 与开发) → "Create an API Key" section → Create Key | *** ## Quick Start Checklist 1. `npm install @waffo/pancake-ts` 2. Set `WAFFO_MERCHANT_ID` and `WAFFO_PRIVATE_KEY` env vars (see "Where to Find IDs" above) 3. Initialize `new WaffoPancake({ merchantId, privateKey })` 4. Create or reference a store 5. If the merchant has multiple stores, confirm which store should own the product(s) 6. Create or reference product(s) 7. Create checkout: `client.checkout.createSession(...)` → redirect to `checkoutUrl` 8. Test with card `4576750000000110` (success) or `4576750000000220` (declined) in sandbox 9. Handle webhooks: `verifyWebhook(rawBody, sig)` — **must use `request.text()`** 10. Configure webhook URL: `client.webhooks.add({ storeId, channel: "http", url, events, testMode })` # Migrate to Waffo Pancake Source: https://docs.waffo.ai/integrate/migrate Move your products, prices, webhooks, and branding to Waffo Pancake with the pancake-migrate CLI Already running on Stripe or Creem? The [`@waffo/pancake-migrate`](https://www.npmjs.com/package/@waffo/pancake-migrate) CLI copies your products, prices, webhooks, and branding into a Waffo Pancake store — no manual re-entry. > [!NOTE] > > Migration moves your **catalog and settings**, not live billing. Active subscriptions, customers, and payment methods stay where they are — see [What does *not* migrate](#what-does-not-migrate) for why and what to do. > [!NOTE] > > On a different platform? We currently support migrating from **Stripe** and **Creem**, with more on the way. [Contact us](mailto:support@waffo.ai) and let us know what you're moving from — we'll prioritize it. ## How concepts map Before you run anything, here's how your existing setup lines up with Waffo Pancake. The CLI handles this mapping for you — this table is just so you know what to expect. | Stripe / Creem | Waffo Pancake | Notes | | - | - | - | | Product + Price | One product (with `prices`) | Pancake folds price into the product. Stripe multi-currency prices are preserved; Creem is single-currency. | | Recurring interval | `billingPeriod` | `week`→`weekly`, `month`→`monthly`, every 3 months→`quarterly`, `year`→`yearly`. | | Webhook endpoint | Store webhook | Stripe endpoints migrate with URL + event-type mapping. (Creem webhooks are not read by the CLI.) | | Account branding | Store branding | Stripe support email + website migrate. | | Tax behavior | `taxCategory` | Creem categories map automatically; for Stripe you pass one default via `--tax-category`. | | Test / live keys | `test` / `production` | Auto-detected from your key prefix (`sk_test_`→test, `sk_live_`→production). | ## Before you start You need three things: 1. **Node.js 18+** 2. **A Waffo Pancake API key** — your Merchant ID (`MER_...`) and RSA private key. Create one in [Dashboard → API & Development](https://pancake.waffo.ai/merchant/dashboard/integration). See [the SDK guide](/integrate/skill) for key handling. 3. **Your source platform key** — a Stripe Secret Key (`sk_test_...` / `sk_live_...`) or a Creem API Key (`creem_test_...` / `creem_...`). > [!WARNING] > > The migration **creates** products in the target environment that your key implies (test vs. live). Always do a `--dry-run` first to preview exactly what will be created. ## Quickest path: interactive mode ```bash theme={"system"} npx @waffo/pancake-migrate ``` It walks you through it step by step: **1. Choose source** Stripe or Creem. **2. Choose target store** Pick an existing store, or create a new one on the spot. **3. Preview** See exactly what will be migrated before anything is created. **4. Migrate** Products, prices, images, webhooks, and branding are created in your store. ## Scripted migration If you'd rather pass everything as flags (for CI, or to repeat the run), use the per-source subcommands. ### From Stripe ```bash theme={"system"} # Full migration (products + webhooks + branding) npx @waffo/pancake-migrate stripe \ --stripe-key sk_test_xxx \ --merchant-id MER_xxx \ --private-key ./private.pem \ --store-id STO_xxx \ --tax-category saas ``` Preview first with `--dry-run`: ```bash theme={"system"} npx @waffo/pancake-migrate stripe \ --stripe-key sk_test_xxx \ --merchant-id MER_xxx \ --private-key ./private.pem \ --store-id STO_xxx \ --tax-category saas \ --dry-run ``` Don't have a store yet? Pass `--store-id new` to create one during migration: ```bash theme={"system"} npx @waffo/pancake-migrate stripe \ --stripe-key sk_test_xxx \ --merchant-id MER_xxx \ --private-key ./private.pem \ --store-id new \ --tax-category saas ``` Skip steps you don't want with `--skip-products`, `--skip-webhooks`, or `--skip-branding`: ```bash theme={"system"} npx @waffo/pancake-migrate stripe ... --skip-webhooks --skip-branding ``` **Stripe flags** | Flag | Description | | - | - | | `--stripe-key ` | Stripe Secret Key (`sk_test_...` or `sk_live_...`) | | `--merchant-id ` | Pancake Merchant ID (`MER_...`) | | `--private-key ` | Path to your Pancake API private key file, or the raw key content | | `--store-id ` | Target Store ID (`STO_...`), or `new` to create one | | `--tax-category ` | Default tax category: `saas`, `digital_goods`, `software`, `ebook`, `online_course`, `consulting`, `professional_service` | | `--dry-run` | Preview without creating anything | | `--yes` | Skip the confirmation prompt | | `--skip-products` | Skip product migration | | `--skip-webhooks` | Skip webhook migration | | `--skip-branding` | Skip branding migration | ### From Creem ```bash theme={"system"} npx @waffo/pancake-migrate creem \ --api-key creem_test_xxx \ --merchant-id MER_xxx \ --private-key ./private.pem \ --store-id STO_xxx ``` Preview first: ```bash theme={"system"} npx @waffo/pancake-migrate creem \ --api-key creem_test_xxx \ --merchant-id MER_xxx \ --private-key ./private.pem \ --store-id STO_xxx \ --dry-run ``` **Creem flags** | Flag | Description | | - | - | | `--api-key ` | Creem API Key (`creem_test_...` or `creem_...`) | | `--merchant-id ` | Pancake Merchant ID (`MER_...`) | | `--private-key ` | Path to your Pancake API private key file, or the raw key content | | `--store-id ` | Target Store ID (`STO_...`), or `new` to create one | | `--dry-run` | Preview without creating anything | | `--yes` | Skip the confirmation prompt | ## What gets migrated ### From Stripe | Data | Migrated | | - | - | | Products + Prices | Yes — multi-currency, images, descriptions | | Billing periods | Yes — `week`→`weekly`, `month`→`monthly`, every 3 months→`quarterly`, `year`→`yearly` | | Webhook endpoints | Yes — URL + event-type mapping | | Store branding | Yes — support email + website | | Environment | Auto-detected — `sk_test_`→test, `sk_live_`→production | ### From Creem | Data | Migrated | | - | - | | Products + Prices | Yes — single-currency, images, descriptions | | Billing periods | Yes — every-month→`monthly`, every-three-months→`quarterly`, every-year→`yearly` | | Tax categories | Yes — `saas`→`saas`, `digital-goods-service`→`digital_goods`, `ebooks`→`ebook` | ## What does *not* migrate These are intentional — here's what to do about each: | Not migrated | Why | What to do | | - | - | - | | Active subscriptions | A subscription is a live billing authorization with the customer's bank; it can't be copied between processors | Existing subscribers re-subscribe through Waffo Pancake [checkout](/guides/checkout-session). Run the old and new processor in parallel during the transition. | | Customer data | Created automatically on first purchase | Nothing — customers are created on their first Pancake payment | | Payment methods | PCI compliance — card data never leaves the original processor | Customers re-enter payment details at checkout | | Coupons / promotion codes | Not copied by the migration — Pancake supports coupons and promotion codes natively | Recreate them in Pancake — see [Discounts & Promotions](/guides/discounts) | | Checkout theme colors | Stripe doesn't expose these via API | Set them in [Dashboard → Settings → Checkout](https://pancake.waffo.ai/merchant/dashboard) | ## After migrating **1. Verify your catalog** Open **Dashboard → Products** and confirm prices, billing periods, and images came across correctly. **2. Publish to production** Products land in the environment your key implied. If you migrated into test, [publish](/integrate/skill) each product to go live. **3. Wire up checkout** Point your app at Waffo Pancake [checkout sessions](/guides/checkout-session) and [webhooks](/guides/webhooks). **4. Run in parallel, then cut over** Keep your old processor active while existing subscribers migrate at their own renewal. Stop new sign-ups on the old processor once Pancake checkout is live. > [!TIP] > > Building the integration after migrating? The [Waffo Pancake Skill](/integrate/skill) gives AI coding agents the exact `@waffo/pancake-ts` workflow for checkout, webhooks, and subscriptions. # Next.js Integration Source: https://docs.waffo.ai/integrate/nextjs Build a complete payment flow with Next.js App Router > **✨ Install with AI** > > Copy this prompt to your AI code editor (Cursor, Copilot, Claude Code, etc.) to set up the integration automatically: > > ```text theme={"system"} > Integrate Waffo Pancake payments into my Next.js app using the official TypeScript SDK. > > npm install @waffo/pancake-ts > > Requirements: > 1. Create /app/api/checkout/route.ts — use WaffoPancake client with client.checkout.createSession() > 2. Create /app/api/webhooks/waffo/route.ts — use verifyWebhook() from SDK to verify x-waffo-signature > 3. Add environment variables: WAFFO_MERCHANT_ID, WAFFO_PRIVATE_KEY, NEXT_PUBLIC_APP_URL > > Read https://waffo.mintlify.app/llms-full.txt for full API reference. > ``` *** ## What You'll Build A complete checkout integration in Next.js including: * Server-side checkout session creation * Client-side redirect to hosted checkout * Webhook handling for payment confirmation * Protected routes based on payment status *** ## Prerequisites * Next.js 13+ with App Router * Waffo Pancake account with API keys * A product created in Dashboard *** ## Project Setup ### 1. Install Dependencies ```bash theme={"system"} npm install @waffo/pancake-ts ``` ### 2. Environment Variables ```bash theme={"system"} # .env.local WAFFO_MERCHANT_ID=your-merchant-id WAFFO_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\nMIIE..." NEXT_PUBLIC_APP_URL=http://localhost:3000 ``` > [!TIP] > > The SDK accepts private keys in multiple formats: PEM, base64, or raw — it auto-normalizes at construction time. Literal `\n` in `.env` files works too. *** ## Create Checkout API Route Create an API route to generate checkout sessions using the SDK: ```typescript theme={"system"} // app/api/checkout/route.ts import { NextRequest, NextResponse } from "next/server"; import { WaffoPancake, CheckoutSessionProductType, WaffoPancakeError } from "@waffo/pancake-ts"; const client = new WaffoPancake({ merchantId: process.env.WAFFO_MERCHANT_ID!, privateKey: process.env.WAFFO_PRIVATE_KEY!, }); export async function POST(req: NextRequest) { try { const { productId, email, metadata } = await req.json(); const session = await client.checkout.createSession({ storeId: "store_xxx", productId, productType: CheckoutSessionProductType.Onetime, currency: "USD", buyerEmail: email || undefined, metadata, successUrl: `${process.env.NEXT_PUBLIC_APP_URL}/success`, }); return NextResponse.json({ checkoutUrl: session.checkoutUrl }); } catch (error) { if (error instanceof WaffoPancakeError) { return NextResponse.json({ error: error.errors[0]?.message }, { status: error.status }); } return NextResponse.json({ error: "Failed to create checkout" }, { status: 500 }); } } ``` > [!NOTE] > > The SDK automatically handles request signing -- no manual header setup needed. Idempotency is opt-in: pass `{ idempotencyKey }` as the last argument of a write (or of a server action) when a retry must not create a second record; nothing is sent, and nothing deduplicated, if you omit it. *** ## Discounts Discounts apply to one-time products, new subscriptions and plan changes. There are three settings on a checkout session; `couponId` cannot be combined with either of the others (sending both returns `400`): * `couponId` applies a coupon the customer cannot change or remove * `promotionCode` pre-fills a code the customer can see — locked, unless you also pass `allowPromotionCodes: true` * `allowPromotionCodes: true` shows a code entry field on the checkout page (without it, the field is shown only when the store has a code that can be used on the product; `false` hides it) **Never take `couponId` or `promotionCode` from the request body.** The route above signs with your API Key, so whatever the browser sends would be applied with your authority — a customer could apply any of your coupons to their own purchase. Decide the discount on the server: ```typescript theme={"system"} // app/api/checkout/route.ts — decide the discount on the server const session = await client.checkout.createSession({ productId, currency: "USD", // Apply a coupon only after your own check, e.g. the signed-in user is a VIP ...(user?.isVip ? { couponId: "CPN_xxx" } : { allowPromotionCodes: true }), successUrl: `${process.env.NEXT_PUBLIC_APP_URL}/success`, }); ``` If you use the [`@waffo/pancake-nextjs`](https://www.npmjs.com/package/@waffo/pancake-nextjs) components, link checkout takes a `discountCode` (sent to the product page as `discount_code`, applied and locked), and the server action from `createCheckoutAction()` forwards `allowPromotionCodes` but **strips `couponId` and `promotionCode`** for the same reason. To apply a coupon or pre-fill a code, call `@waffo/pancake-ts` from your own server code as above. ```tsx theme={"system"} import { CheckoutButton } from "@waffo/pancake-nextjs"; import { checkout } from "./lib/waffo"; // createCheckoutAction(config) // Product link with a locked code — no server action needed Buy Now — 20% off // Session created by the server action, with a code entry field on the checkout page Buy Now ``` See [Discounts & Promotions](/guides/discounts) for the rules and the reasons a code can be rejected. *** ## Pricing Page Component Create a pricing page with checkout buttons: ```tsx theme={"system"} // app/pricing/page.tsx 'use client'; import { useState } from 'react'; const plans = [ { name: 'Starter', price: '$9', period: 'month', productId: 'prod_starter', features: ['5 projects', '10GB storage', 'Email support'], }, { name: 'Pro', price: '$29', period: 'month', productId: 'prod_pro', features: ['Unlimited projects', '100GB storage', 'Priority support', 'API access'], popular: true, }, { name: 'Enterprise', price: '$99', period: 'month', productId: 'prod_enterprise', features: ['Everything in Pro', 'Custom integrations', 'Dedicated support', 'SLA'], }, ]; export default function PricingPage() { const [loading, setLoading] = useState(null); async function handleCheckout(productId: string) { setLoading(productId); try { const response = await fetch('/api/checkout', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ productId }), }); const { checkoutUrl, error } = await response.json(); if (error) { alert(error); return; } // Redirect to Waffo Pancake checkout window.location.href = checkoutUrl; } catch (error) { alert('Something went wrong'); } finally { setLoading(null); } } return (

Choose Your Plan

{plans.map((plan) => (
{plan.popular && ( Most Popular )}

{plan.name}

{plan.price} /{plan.period}

    {plan.features.map((feature) => (
  • {feature}
  • ))}
))}
); } function CheckIcon({ className }: { className: string }) { return ( ); } ``` *** ## Webhook Handler Handle payment confirmations using the SDK's built-in `verifyWebhook()` -- it has embedded public keys for both test and production environments, so you don't need to manage webhook secrets: ```typescript theme={"system"} // app/api/webhooks/waffo/route.ts import { NextResponse } from "next/server"; import { verifyWebhook, WebhookEventType } from "@waffo/pancake-ts"; export async function POST(request: Request) { const body = await request.text(); const signature = request.headers.get("x-waffo-signature"); try { const event = verifyWebhook(body, signature); // Respond immediately, process asynchronously switch (event.eventType) { case WebhookEventType.OrderCompleted: console.log(`Order completed: ${event.data.orderId}`); // Update your database, grant access, etc. break; case WebhookEventType.SubscriptionActivated: console.log(`Subscription activated: ${event.data.buyerEmail}`); break; case WebhookEventType.SubscriptionCanceling: console.log(`Subscription canceling: ${event.data.orderId}`); break; case WebhookEventType.SubscriptionCanceled: console.log(`Subscription canceled: ${event.data.orderId}`); break; case WebhookEventType.RefundSucceeded: console.log(`Refund succeeded: ${event.data.amount} ${event.data.currency}`); break; } return NextResponse.json({ received: true }); } catch { return new Response("Invalid signature", { status: 401 }); } } ``` > [!NOTE] > > The SDK's `verifyWebhook()` uses embedded public keys -- no `WAFFO_WEBHOOK_SECRET` environment variable needed. It also includes replay protection by default. *** ## Success Page Show confirmation after successful payment: ```tsx theme={"system"} // app/success/page.tsx import { Suspense } from 'react'; export default function SuccessPage() { return ( Loading...}> ); } async function SuccessContent() { return (

Payment Successful!

Thank you for your purchase. You now have access to all features.

Go to Dashboard
); } ``` *** ## Protected Routes Middleware Protect routes based on subscription status: ```typescript theme={"system"} // middleware.ts import { NextResponse } from 'next/server'; import type { NextRequest } from 'next/server'; export function middleware(request: NextRequest) { // Get user session (implement your auth logic) const session = request.cookies.get('session'); // Protected routes const protectedPaths = ['/dashboard', '/settings', '/projects']; const isProtectedPath = protectedPaths.some(path => request.nextUrl.pathname.startsWith(path) ); if (isProtectedPath && !session) { return NextResponse.redirect(new URL('/login', request.url)); } return NextResponse.next(); } export const config = { matcher: ['/dashboard/:path*', '/settings/:path*', '/projects/:path*'], }; ``` *** ## Server Component: Check Subscription ```tsx theme={"system"} // app/dashboard/page.tsx import { redirect } from 'next/navigation'; import { getServerSession } from 'your-auth-library'; export default async function DashboardPage() { const session = await getServerSession(); if (!session) { redirect('/login'); } // Get user's subscription from database const user = await prisma.user.findUnique({ where: { id: session.user.id }, select: { plan: true, subscriptionActive: true, subscriptionEndsAt: true, }, }); if (!user?.subscriptionActive) { redirect('/pricing'); } return (

Welcome to your Dashboard

Your current plan: {user.plan}

{/* Dashboard content */}
); } ``` *** ## Customer Portal Link Let signed-in users manage their orders and subscriptions without an email code. A Route Handler on your server creates the portal link and redirects: ```typescript theme={"system"} // app/account/portal/route.ts // Signature summary — see the @waffo/pancake-nextjs reference for the exact types import { createCustomerPortalRedirect } from "@waffo/pancake-nextjs/server"; import { auth } from "@/lib/auth"; // your own session check export const GET = createCustomerPortalRedirect( { merchantId: process.env.WAFFO_MERCHANT_ID!, privateKey: process.env.WAFFO_PRIVATE_KEY!, }, { // Take the identity from your session — the same buyerIdentity used at checkout resolveAuthenticatedCustomer: async () => { const session = await auth(); return session?.user ? { storeId: process.env.WAFFO_STORE_ID!, buyerIdentity: session.user.id } : null; }, // Fixed path you control; without loginUrl, signed-out visitors get a 401 loginUrl: "/login?returnTo=/account/portal", }, ); ``` ```tsx theme={"system"} // components/ManageSubscription.tsx // A plain , not next/link: prefetching would create portal links nobody clicked const PORTAL_ROUTE = "/account/portal"; export function ManageSubscriptionButton() { return ( Manage Subscription ); } ``` See [Let Signed-In Customers Manage Orders](/guides/customer-portal-sso) for identity rules, session lifetime, and a version without the helper. *** ## Complete File Structure ``` app/ ├── api/ │ ├── checkout/ │ │ └── route.ts # Create checkout sessions │ └── webhooks/ │ └── waffo/ │ └── route.ts # Handle webhooks ├── pricing/ │ └── page.tsx # Pricing page ├── success/ │ └── page.tsx # Success page ├── dashboard/ │ └── page.tsx # Protected dashboard └── layout.tsx middleware.ts # Route protection .env.local # Environment variables ``` *** ## Testing Checklist Before going live: * [ ] Test checkout flow with test card `4576 7500 0000 0110` * [ ] Verify webhooks are received (check Dashboard logs) * [ ] Test declined payment with `4576 7500 0000 0220` * [ ] Confirm success page displays correctly * [ ] Switch to live API keys * [ ] Update webhook URL to production endpoint *** ## Next Steps > **[Handle Webhooks](/guides/webhooks)** > > Deep dive into webhook handling > **[Subscription Management](/guides/subscriptions)** > > Advanced subscription features # SDKs Source: https://docs.waffo.ai/integrate/sdks Client libraries and framework integrations ## SDKs & Libraries Waffo Pancake provides official SDKs for TypeScript and Next.js, plus direct API access. ### Choose Your Integration Level > **Next.js SDK** > > **Fastest** — Drop-in components, hooks, and server actions. Handles checkout UI, webhook routing, and buyer self-service out of the box. > > `npm install @waffo/pancake-nextjs` > **TypeScript SDK** > > **Flexible** — Full API coverage with automatic signing, typed responses, and webhook verification. Use with any Node.js framework. > > `npm install @waffo/pancake-ts` > **Direct API** > > **Full control** — REST endpoints for writes, GraphQL for reads. Implement signing and verification yourself. Any language. > [!TIP] > > **Next.js projects**: Start with `@waffo/pancake-nextjs` — it wraps `@waffo/pancake-ts` and adds React components and server actions. You can always drop down to the TypeScript SDK or raw API calls for advanced use cases. *** ## TypeScript SDK > **[@waffo/pancake-ts](https://www.npmjs.com/package/@waffo/pancake-ts)** > > Official TypeScript SDK on npm ### Installation ```bash theme={"system"} npm install @waffo/pancake-ts ``` ### Features * Zero runtime dependencies, ESM + CJS, Node >= 20 * Automatic request signing; opt-in idempotency keys per call * Full TypeScript type definitions (15 enums, 40+ interfaces) * Webhook verification with embedded public keys (test/prod) * Plan change links for existing subscriptions — merchant-issued, or customer-issued from a session token (same product group + `selfServicePlanChange` on) — and the product group switch itself ### Quick Start ```typescript theme={"system"} import { WaffoPancake } from "@waffo/pancake-ts"; const client = new WaffoPancake({ merchantId: process.env.WAFFO_MERCHANT_ID!, privateKey: process.env.WAFFO_PRIVATE_KEY!, }); // Create a store const { store } = await client.stores.create({ name: "My Store" }); // Create a one-time product const { product } = await client.onetimeProducts.create({ storeId: store.id, name: "E-Book: TypeScript Handbook", prices: { USD: { amount: "29.00", taxIncluded: false, taxCategory: "digital_goods" }, }, }); // Create a checkout session const session = await client.checkout.createSession({ productId: product.id, currency: "USD", }); // => redirect consumer to session.checkoutUrl ``` ### Configuration | Parameter | Type | Required | Description | | - | - | - | - | | `merchantId` | `string` | Yes | Your Merchant ID | | `privateKey` | `string` | Yes | RSA private key (PEM, base64, or raw — auto-normalized) | | `baseUrl` | `string` | No | API base URL (default: production) | | `fetch` | `typeof fetch` | No | Custom fetch implementation | ### Available Resources | Namespace | Methods | Description | | - | - | - | | `client.stores` | `create()` `update()` `delete()` | Store management | | `client.onetimeProducts` | `create()` `update()` `publish()` `updateStatus()` | One-time product CRUD | | `client.subscriptionProducts` | `create()` `update()` `publish()` `updateStatus()` | Subscription product CRUD | | `client.subscriptionProductGroups` | `create()` `update()` `delete()` `publish()` | Product groups — shared trial and the `selfServicePlanChange` switch | | `client.orders` | `cancelSubscription()` | Order management | | `client.checkout` | `createSession()` `createPlanChangeSession()` | Create checkout sessions and plan change links | | `client.customer(token)` | `cancelSubscription()` `createRefundTicket()` `createPlanChangeSession()` … | Customer self-service, including customer-initiated plan change | | `client.graphql` | `query()` | Typed GraphQL queries | | `client.auth` | `issueSessionToken()` `createCustomerPortalLink()` | Issue buyer session token for checkout; create a [signed-in customer portal link](/guides/customer-portal-sso) | | `client.webhooks` | `verify()` | Webhook signature verification | ### Checkout Modes The SDK supports two checkout modes based on whether you know the buyer's identity: | Mode | Method | Buyer Identity | Form | Use Case | | - | - | - | - | - | | **Authenticated** | `checkout.authenticated.create()` | Merchant provides | Pre-filled | Sites with user accounts | | **Anonymous** | `checkout.anonymous.create()` | Not provided | Empty | Template stores, shared links | > [!WARNING] > > **Always use authenticated checkout when you know the buyer.** Authenticated checkout binds orders to the `buyerIdentity` you provide — a stable, merchant-controlled identifier. Without it: > > * **Trial abuse**: buyers can claim unlimited free trials by changing their email > * **Order unlinking**: different emails are treated as different users > * **No self-service**: buyers cannot manage orders in Customer Portal #### Authenticated Checkout (Recommended) ```typescript theme={"system"} const result = await client.checkout.authenticated.create({ productId: "PROD_xxx", currency: "USD", buyerIdentity: "userIdInYourSystem", }); // Redirect: res.redirect(result.checkoutUrl) or window.location.href = result.checkoutUrl ``` > [!NOTE] > > `buyerIdentity` is for order attribution and trial tracking only — it is not rendered on the checkout page. To pre-fill the email field on the checkout form, pass `buyerEmail` explicitly. With dynamic pricing and trial control: ```typescript theme={"system"} const result = await client.checkout.authenticated.create({ productId: "PROD_xxx", currency: "USD", buyerIdentity: "userIdInYourSystem", buyerEmail: "customer@example.com", priceSnapshot: { amount: "19.99", taxCategory: "digital_goods" }, withTrial: true, billingDetail: { country: "US", isBusiness: false }, successUrl: "https://example.com/thank-you", }); ``` #### Anonymous Checkout ```typescript theme={"system"} const result = await client.checkout.anonymous.create({ productId: "PROD_xxx", currency: "USD", }); // Also supports priceSnapshot and withTrial ``` ### Webhook Verification ```typescript theme={"system"} import { verifyWebhook, WebhookEventType } from "@waffo/pancake-ts"; // Express (use raw body — parsed JSON breaks signature verification) app.post("/webhooks", express.raw({ type: "application/json" }), (req, res) => { try { const event = verifyWebhook( req.body.toString("utf-8"), req.headers["x-waffo-signature"] as string, ); res.status(200).send("OK"); switch (event.eventType) { case WebhookEventType.OrderCompleted: // handle order completion break; case WebhookEventType.SubscriptionActivated: // handle subscription activation break; } } catch { res.status(401).send("Invalid signature"); } }); // Next.js App Router export async function POST(request: Request) { const body = await request.text(); const sig = request.headers.get("x-waffo-signature"); try { const event = verifyWebhook(body, sig); // handle event ... return new Response("OK"); } catch { return new Response("Invalid signature", { status: 401 }); } } ``` ### Error Handling ```typescript theme={"system"} import { WaffoPancakeError } from "@waffo/pancake-ts"; try { await client.stores.create({ name: "" }); } catch (err) { if (err instanceof WaffoPancakeError) { console.log(err.status); // 400 console.log(err.errors); // [{ message: "...", layer: "store" }, ...] } } ``` *** ## Next.js SDK > **[@waffo/pancake-nextjs](https://www.npmjs.com/package/@waffo/pancake-nextjs)** > > Official Next.js SDK — components, hooks, and server actions ### Installation ```bash theme={"system"} npm install @waffo/pancake-nextjs ``` Requires `@waffo/pancake-ts` as a peer dependency. Works with Next.js 14+ App Router. ### Client Exports | Export | Type | Description | | - | - | - | | `CheckoutButton` | Component | Three-mode checkout button (link / anonymous / authenticated) | | `WaffoPancakeProvider` | Component | Buyer self-service context with automatic token lifecycle | | `useCheckout()` | Hook | Programmatic checkout control | | `useBuyer()` | Hook | Buyer self-service actions (cancel, refund, reactivate, query) | | `useBuyerOrders()` | Hook | Fetch buyer's orders | | `useBuyerPayments()` | Hook | Fetch buyer's payment records | | `useBuyerRefundTickets()` | Hook | Fetch buyer's refund tickets | | `useMerchantOrders()` | Hook | Merchant dashboard orders | | `useMerchantSales()` | Hook | Merchant sales overview | | `useMerchantSubscriptions()` | Hook | Merchant subscription overview | | `Webhook` | Route Handler | Auto-verify signatures and dispatch events | ### Server Exports (`@waffo/pancake-nextjs/server`) | Export | Description | | - | - | | `createCheckoutAction(config)` | Server Action: create checkout sessions and plan change links (`type: "planChange"`) | | `createBuyerTokenAction(config)` | Server Action: issue buyer session tokens | | `createBuyerSessionAction(config)` | Server Action: buyer self-service operations | | `createMerchantQueryAction(config)` | Server Action: merchant GraphQL queries | | `createCustomerPortalRedirect(config, { resolveAuthenticatedCustomer, loginUrl?, onError? })` | Route Handler: 302 a signed-in customer into your store's customer portal. Without `loginUrl`, signed-out visitors get a 401; `onError` replaces the default 502 ([guide](/guides/customer-portal-sso)) | ### Quick Example ```typescript theme={"system"} // app/lib/actions.ts "use server"; import { createCheckoutAction, createBuyerTokenAction } from "@waffo/pancake-nextjs/server"; const config = { merchantId: process.env.WAFFO_MERCHANT_ID!, privateKey: process.env.WAFFO_PRIVATE_KEY!, }; export const checkoutAction = createCheckoutAction(config); export const issueBuyerToken = createBuyerTokenAction(config); ``` ```tsx theme={"system"} // app/components/BuyButton.tsx "use client"; import { CheckoutButton } from "@waffo/pancake-nextjs"; import { checkoutAction } from "@/app/lib/actions"; export function BuyButton({ productId }: { productId: string }) { return ( Subscribe Now ); } ``` ### Webhook Route Handler ```typescript theme={"system"} // app/api/webhooks/waffo/route.ts import { Webhook } from "@waffo/pancake-nextjs"; export const POST = Webhook({ onOrderCompleted: async (event) => { // Deliver digital goods }, onSubscriptionActivated: async (event) => { // Provision access }, onSubscriptionCanceled: async (event) => { // Revoke access }, }); ``` > **[Next.js Guide](/integrate/nextjs)** > > Full step-by-step Next.js integration guide. *** ## Direct API Access You can also use the REST and GraphQL API directly. API Key authentication is handled automatically by the SDK -- no manual header setup is needed. ```typescript theme={"system"} // Create a product const { product } = await client.onetimeProducts.create({ storeId: "your-store-uuid", name: "My Product", prices: { USD: { amount: "29.00", taxIncluded: false, taxCategory: "saas" }, }, }); // Query data via GraphQL const data = await client.graphql.query<{ stores: Array<{ id: string; name: string; status: string }> }>( `{ stores { id name status } }` ); ``` *** ## SDK Roadmap | Language | Status | | - | - | | **Node.js / TypeScript** | Available — [`@waffo/pancake-ts`](https://www.npmjs.com/package/@waffo/pancake-ts) | | **Next.js** | Available — [`@waffo/pancake-nextjs`](https://www.npmjs.com/package/@waffo/pancake-nextjs) | | **Go** | Available — [`github.com/waffo-com/waffo-pancake-sdk-go`](https://pkg.go.dev/github.com/waffo-com/waffo-pancake-sdk-go) | | **Python** | Planned | | **PHP** | Planned | *** ## Framework Guides > **[Next.js](/integrate/nextjs)** > > Build with Next.js and Server Actions. > **[Checkout Sessions](/guides/checkout-session)** > > Create checkout flows programmatically. > **[Subscriptions](/guides/subscriptions)** > > Implement recurring billing. > **[Webhooks](/integrate/webhooks)** > > Receive real-time event notifications. *** ## API Reference For complete endpoint documentation: > **[API Reference](/api-reference/introduction)** > > Full REST and GraphQL API documentation. # Waffo Pancake Skill Source: https://docs.waffo.ai/integrate/skill Copy or download the exact Waffo Pancake skill file used for AI-assisted integration Portable, machine-readable guidance that gives AI coding agents the exact Waffo Pancake integration workflow. > [!NOTE] > > This is the official Waffo Pancake Skill file. The content stays aligned with the team-managed source skill and is distributed as a standard English `SKILL.md`. ## Available Files | File | Purpose | | - | - | | `SKILL.md` | Complete Waffo Pancake integration guide for AI agents | | `llms-full.txt` | Full AI-readable documentation snapshot | ## SKILL.md: The Complete Guide This is the main skill file for AI-assisted Pancake integrations. It includes: * Merchant authentication and required environment variables * Store setup and product creation guidance * Product creation for one-time and subscription products * Checkout session creation * Webhook verification, event handling, and local `ngrok` testing * GraphQL queries, error handling, and integration rules ### Quick Reference Save the standard `SKILL.md` locally after copying or downloading it from this page. > **SKILL.md Preview** > > Inspect the complete standard `SKILL.md` source directly on this page before downloading it. > > [↓ View Full SKILL.md Below](#full-skill-content) > **Waffo Pancake Skill** > > Use the complete skill file in your AI coding workflow. You can copy the full skill content or download it directly as a standard `SKILL.md` file. > > ↓ Download SKILL.md ## What's Inside * Platform overview and supported billing models * SDK-first setup flow and direct dashboard-to-checkout flow * Merchant authentication and environment setup * Product, checkout, and webhook implementation examples * Test cards, common gotchas, and critical integration rules ## Installation ```bash theme={"system"} mkdir -p ~/.waffo/skills ``` Then copy or download the standard `SKILL.md` file from this page. ## For AI Agents 1. Save `SKILL.md` locally so you can reference it without re-fetching every conversation. 2. Use the Skill first when the human asks about Pancake products, checkout, subscriptions, webhooks, or merchant setup. 3. Follow the product, checkout, and webhook flows exactly as written in the Skill file. ## Full Documentation For a full documentation snapshot beyond the skill file itself: ```bash theme={"system"} curl -s https://docs.waffo.ai/llms-full.txt ``` ## Full SKILL.md Content Use the built-in copy control on the code block to copy the full Skill. ````md theme={"system"} --- name: waffo-pancake description: "Step-by-step guide for integrating @waffo/pancake-ts into any TypeScript/Node.js project — covers store setup, products, checkout, webhooks, subscriptions, and GraphQL queries. Use when implementing payment processing, checkout flows, subscriptions, webhooks, product management, or any Waffo Pancake API integration." user-invokable: true args: "[scenario]" --- # Waffo Pancake SDK Integration You are integrating the `@waffo/pancake-ts` payment SDK into a TypeScript project. Follow these steps exactly. The SDK uses Merchant API Key authentication — all requests are signed automatically. **Trigger when:** code imports `@waffo/pancake-ts`, user asks about Waffo Pancake payments, checkout integration, webhook verification, or product/order management. **Do NOT trigger when:** general payment concepts, other payment SDKs (Stripe, PayPal), or frontend-only UI work unrelated to payment logic. --- ## When to Use This SDK Waffo Pancake is a merchant-of-record payment platform. Use it when your project needs: - **SaaS subscription billing** — monthly/yearly plans with upgrade/downgrade, cancellation, and renewal handling - **Digital product sales** — one-time purchases for e-books, templates, courses, software licenses - **Per-usage or per-download payments** — charge users per action like downloading a file or API call credits - **Hybrid models** — combine subscriptions with one-time purchases ### Example Use Cases | Project Type | Payment Model | Products to Create | |---|---|---| | AI Skills marketplace | Per-download + Pro subscription | 1 one-time product ($0.99/download) + 2 subscription products (monthly/yearly) | | Online course platform | One-time purchase per course | 1 one-time product per course ($29–$199) | | SaaS tool (Starter/Pro/Enterprise) | Subscription tiers | 3 subscription products with a product group for plan switching | | Design template shop | One-time per template | 1 one-time product per template | | API service with usage credits | Credit packs + subscription | 1 one-time product per credit pack + subscription for monthly quota | | Newsletter / community | Membership subscription | 1 monthly + 1 yearly subscription product | --- ## Installation ```bash npm install @waffo/pancake-ts ``` Zero dependencies. Works in Node.js 18+. Server-side only — never expose the private key to the browser. --- ## Getting Started You only need **two values** to start: ```bash WAFFO_MERCHANT_ID= WAFFO_PRIVATE_KEY= ``` Both live on Dashboard → API & Development (API 与开发), inside the \"Create an API Key\" section. `WAFFO_MERCHANT_ID` means your **Merchant ID**, not `storeId` and not a store identifier from a URL. `storeId` is still part of the current API model for store and product management flows, so do not confuse the two. For the first working integration, only these two env vars need to exist: `WAFFO_MERCHANT_ID` and `WAFFO_PRIVATE_KEY`. Store IDs and Product IDs are runtime values you can keep in code, app config, or your own database. ### Store Selection Rule When creating products, first determine whether the merchant already has one or more stores: - If the merchant has no store yet, create a store first. - If the merchant has exactly one store, use that store automatically. - If the merchant has multiple stores, ask which store the product should be created in before calling any product creation API. Do not guess the target store when multiple stores exist. ### Path A: Create Everything via SDK (Starting Fresh) ```typescript import { WaffoPancake } from "@waffo/pancake-ts"; const client = new WaffoPancake({ merchantId: process.env.WAFFO_MERCHANT_ID!, privateKey: process.env.WAFFO_PRIVATE_KEY!, }); // 1. Create a store const { store } = await client.stores.create({ name: "My SaaS" }); console.log("Store ID:", store.id); // Save this // 2. Create products const { product: monthly } = await client.subscriptionProducts.create({ storeId: store.id, name: "Pro Monthly", billingPeriod: "monthly", prices: { USD: { amount: "9.99", taxCategory: "saas" } }, }); const { product: yearly } = await client.subscriptionProducts.create({ storeId: store.id, name: "Pro Yearly", billingPeriod: "yearly", prices: { USD: { amount: "99.00", taxCategory: "saas" } }, }); console.log("Monthly Product ID:", monthly.id); // Save this console.log("Yearly Product ID:", yearly.id); // Save this // 3. Create a checkout session const session = await client.checkout.createSession({ productId: monthly.id, currency: "USD", }); // Redirect customer to session.checkoutUrl ``` ### Path B: Use Existing Products from Dashboard If you've already created products in the Dashboard, copy the Product ID and go straight to checkout. In this flow, you still only need the same two env vars above: ```typescript const client = new WaffoPancake({ merchantId: process.env.WAFFO_MERCHANT_ID!, privateKey: process.env.WAFFO_PRIVATE_KEY!, }); const session = await client.checkout.createSession({ productId: "PROD_xxx_from_dashboard", currency: "USD", buyerEmail: "customer@example.com", successUrl: "https://myapp.com/welcome", }); // Redirect customer to session.checkoutUrl ``` --- ## PEM Key Handling The private key is RSA PEM format. Multiple approaches for environment variables: **Option A: Escaped newlines** ``` WAFFO_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\nMIIEv...\n-----END PRIVATE KEY-----" ``` **Option B: Base64 encode the entire PEM (recommended for CI/CD)** ```bash # Encode cat private.pem | base64 | tr -d '\n' # Set env var WAFFO_PRIVATE_KEY_BASE64=LS0tLS1CRUdJTi... ``` ```typescript const privateKey = Buffer.from(process.env.WAFFO_PRIVATE_KEY_BASE64!, "base64").toString("utf-8"); const client = new WaffoPancake({ merchantId, privateKey }); ``` **Option C: File path (local development)** ```typescript import { readFileSync } from "fs"; const privateKey = readFileSync("./keys/private.pem", "utf-8"); const client = new WaffoPancake({ merchantId, privateKey }); ``` The SDK auto-normalizes all formats (PEM headers, raw base64, literal `\n`, Windows line endings). The constructor throws immediately if the key is invalid. --- ## Available Resources | Namespace | Methods | Description | |-----------|---------|-------------| | `client.auth` | `issueSessionToken()` | Issue buyer session token for checkout | | `client.stores` | `create()` `update()` `delete()` | Store management (webhook, notification, checkout settings) | | `client.onetimeProducts` | `create()` `update()` `publish()` `updateStatus()` | One-time product CRUD with multi-currency pricing | | `client.subscriptionProducts` | `create()` `update()` `publish()` `updateStatus()` | Subscription product CRUD with billing period | | `client.subscriptionProductGroups` | `create()` `update()` `delete()` `publish()` | Product groups for shared trial and plan switching | | `client.orders` | `cancelSubscription()` | Cancel subscription (pending→canceled, active→canceling) | | `client.checkout` | `createSession()` | Create checkout session, returns `checkoutUrl` | | `client.graphql` | `query()` | Typed GraphQL queries (read-only) | | `client.webhooks` | `verify()` | Webhook signature verification | --- ## Full API Reference ### Stores ```typescript // Create const { store } = await client.stores.create({ name: "My Store" }); // Update (partial — only provided fields change) const { store } = await client.stores.update({ id: "store_id", name: "New Name", }); // Soft-delete const { store } = await client.stores.delete({ id: "store_id" }); ``` ### One-Time Products Prices use the **display amount** for the selected currency. For USD, pass `"29.00"` instead of cents. ```typescript // Create const { product } = await client.onetimeProducts.create({ storeId: "store_id", name: "E-Book", description: "A great e-book", prices: { USD: { amount: "29.00", taxCategory: "digital_goods" }, }, successUrl: "https://example.com/thanks", metadata: { sku: "EB-001" }, }); // Update (creates new version; no-op if unchanged) const { product } = await client.onetimeProducts.update({ id: "product_id", name: "E-Book v2", prices: { USD: { amount: "39.00", taxCategory: "digital_goods" } }, }); // Publish test version to production (one-way) const { product } = await client.onetimeProducts.publish({ id: "product_id" }); // Activate / deactivate const { product } = await client.onetimeProducts.updateStatus({ id: "product_id", status: "inactive", // or "active" }); ``` **taxCategory options:** `digital_goods` | `saas` | `software` | `ebook` | `online_course` | `consulting` | `professional_service` ### Subscription Products ```typescript // Create const { product } = await client.subscriptionProducts.create({ storeId: "store_id", name: "Pro Monthly", billingPeriod: "monthly", // "weekly" | "monthly" | "quarterly" | "yearly" prices: { USD: { amount: "9.99", taxCategory: "saas" }, }, metadata: { trialDays: 14 }, // optional trial }); // Update, publish, updateStatus — same pattern as one-time products ``` ### Subscription Product Groups Groups enable shared trials and plan switching between subscription products. ```typescript // Create group const { group } = await client.subscriptionProductGroups.create({ storeId: "store_id", name: "Pro Plans", rules: { sharedTrial: true }, productIds: ["monthly_product_id", "yearly_product_id"], }); // Update (productIds is a full replacement) await client.subscriptionProductGroups.update({ id: "group_id", productIds: ["monthly_id", "quarterly_id", "yearly_id"], }); // Publish to production (supports repeated UPSERT) await client.subscriptionProductGroups.publish({ id: "group_id" }); // Delete (physical delete, not soft) await client.subscriptionProductGroups.delete({ id: "group_id" }); ``` ### Checkout Sessions Creates a payment page. Redirect the customer to `checkoutUrl`. ```typescript const session = await client.checkout.createSession({ productId: "product_id", currency: "USD", buyerEmail: "buyer@example.com", // optional, pre-fills email successUrl: "https://example.com/thanks", // redirect after payment metadata: { orderId: "internal-123" }, // custom key-value pairs // Optional overrides: priceSnapshot: { amount: "19.99", taxCategory: "saas" }, // dynamic pricing billingDetail: { country: "US", isBusiness: false }, expiresInSeconds: 3600, // default: 86400 (24 hours), recommended: 60–604800 withTrial: true, // for subscriptions with trial darkMode: true, // true=dark / false=light / omit=store default }); // session.checkoutUrl — redirect customer here // session.sessionId — for tracking // session.expiresAt — ISO 8601 expiry ``` **Parameter priority:** | Parameter | Purpose | Notes | |-----------|---------|-------| | `priceSnapshot` | Override product price (dynamic pricing) | Highest priority — ignores product's set price | | `currency` | Specify checkout currency | Required | | `buyerEmail` | Pre-fill consumer email | Optional | | `billingDetail` | Pre-fill billing info | Optional | | `successUrl` | Redirect after payment | Overrides product-level successUrl | | `metadata` | Custom key-value pairs | Passed through to webhook `event.data` | | `withTrial` | Enable trial period | Overrides product-level trial settings | | `expiresInSeconds` | Session expiration | Default 86400 (24 h), recommended 60–604800 (1 min to 7 days) | | `darkMode` | Checkout dark mode | `true`=dark / `false`=light / omit=store default | ### Cancel Subscription ```typescript const { orderId, status } = await client.orders.cancelSubscription({ orderId: "order_id", }); // status: "canceled" (was pending) or "canceling" (was active, ends at period end) ``` ### GraphQL Queries Read-only queries. Return type is `{ data: T | null, errors?: [...] }` — access via `result.data`. ```typescript const result = await client.graphql.query<{ stores: Array<{ id: string; name: string; status: string }>; }>({ query: `query { stores { id name status } }`, }); const stores = result.data?.stores ?? []; // With variables const result = await client.graphql.query<{ onetimeProduct: { id: string; name: string; prices: unknown }; }>({ query: `query ($id: String!) { onetimeProduct(id: $id) { id name prices } }`, variables: { id: "product_id" }, }); ``` --- ## Webhook Verification Webhooks use RSA-SHA256 signatures. The SDK embeds public keys for both test and prod environments. **Critical:** Read the request body as **raw text**, not parsed JSON. Parsing first breaks signature verification. ### Next.js App Router ```typescript import { verifyWebhook, WebhookEventType } from "@waffo/pancake-ts"; export async function POST(request: Request) { const body = await request.text(); // MUST be raw text const sig = request.headers.get("x-waffo-signature")!; try { const event = verifyWebhook(body, sig); // Idempotent dedup — use event.id (delivery ID) if (await isDuplicate(event.id)) return new Response("OK"); await markProcessed(event.id); switch (event.eventType) { case WebhookEventType.OrderCompleted: // fulfill order break; case WebhookEventType.SubscriptionActivated: // activate access break; case WebhookEventType.SubscriptionCanceled: // revoke access at period end break; } return new Response("OK"); } catch { return new Response("Invalid signature", { status: 401 }); } } ``` ### Express ```typescript import express from "express"; import { verifyWebhook } from "@waffo/pancake-ts"; app.post("/webhooks", express.raw({ type: "application/json" }), (req, res) => { try { const event = verifyWebhook( req.body.toString("utf-8"), req.headers["x-waffo-signature"] as string, ); res.status(200).send("OK"); // handle event async... } catch { res.status(401).send("Invalid signature"); } }); ``` ### Hono ```typescript import { verifyWebhook } from "@waffo/pancake-ts"; app.post("/webhooks", async (c) => { const body = await c.req.text(); const sig = c.req.header("x-waffo-signature"); try { const event = verifyWebhook(body, sig); return c.text("OK"); } catch { return c.text("Invalid signature", 401); } }); ``` ### Verification Options ```typescript // Specify environment explicitly verifyWebhook(body, sig, { environment: "prod" }); // Disable replay protection (not recommended for production) verifyWebhook(body, sig, { toleranceMs: 0 }); // Custom tolerance (default: 5 minutes) verifyWebhook(body, sig, { toleranceMs: 600000 }); ``` ### Webhook Event Types | Event | Trigger | |-------|---------| | `order.completed` | One-time payment succeeded | | `subscription.activated` | First subscription payment succeeded | | `subscription.payment_succeeded` | Renewal payment succeeded | | `subscription.canceling` | Buyer initiated cancel (active until period end) | | `subscription.uncanceled` | Buyer withdrew cancellation | | `subscription.plan_changed` | Plan changed (upgrade/downgrade) | | `subscription.canceled` | Subscription fully terminated | | `subscription.past_due` | Renewal payment failed | | `refund.succeeded` | Refund completed | | `refund.failed` | Refund failed | ### Webhook Event Shape ```typescript interface WebhookEvent { id: string; // Delivery ID (use for idempotent dedup) timestamp: string; // ISO 8601 UTC eventType: string; eventId: string; // Business event ID (payment/order ID) storeId: string; mode: "test" | "prod"; data: { orderId: string; buyerEmail: string; currency: string; amount: string; // display amount string (for example "9.99" for USD) taxAmount: string; productName: string; }; } ``` ### Configuring Webhook URLs via SDK A store can have multiple webhooks, each delivering to a different channel (`http`, `feishu`, `discord`, `telegram`, `slack`). Register one entry per channel and environment: ```typescript // HTTP — Test environment await client.webhooks.add({ storeId: "store_id", channel: \"http\", url: "https://your-domain.com/api/webhooks", events: ["order.completed", "subscription.activated", "subscription.canceled"], testMode: true, }); // HTTP — Production environment await client.webhooks.add({ storeId: "store_id", channel: \"http\", url: "https://your-domain.com/api/webhooks", events: ["order.completed", "subscription.activated", "subscription.canceled"], testMode: false, }); // Update / remove await client.webhooks.update({ id: "WBH_xxx", events: ["order.completed"] }); await client.webhooks.remove({ id: "WBH_xxx" }); ``` To list webhooks, use the GraphQL `Store.storeWebhooks` field — it is the only query entry point. --- ## Common Gotchas | Gotcha | Why it breaks | Fix | |--------|---------------|-----| | Reading webhook body as JSON | `request.json()` re-serializes; signature fails | Use `request.text()` (App Router/Hono) or `express.raw()` (Express) | | Using localtunnel for webhooks | Strips custom HTTP headers; `X-Waffo-Signature` never arrives | Use `ngrok http 3000` | | Forgetting `.publish()` | Products created in test env by default; prod checkout sessions fail silently | Call `.publish()` before going live | | Accessing `result` instead of `result.data` in GraphQL | GraphQL returns `{ data: T, errors?: [...] }` | Destructure: `const stores = result.data?.stores ?? []` | | Using `$id: ID!` in GraphQL variables | Backend uses `String!` not `ID!`; wrong type silently returns null | Always declare ID variables as `$id: String!` | | `productIds` in group update is full replacement | Replaces entire list, does not append | Pass complete desired list every time | --- ## Error Handling ```typescript import { WaffoPancakeError } from "@waffo/pancake-ts"; try { await client.stores.create({ name: "" }); } catch (err) { if (err instanceof WaffoPancakeError) { console.log(err.status); // HTTP status code console.log(err.errors); // [{ message, layer }] console.log(err.errors[0].layer); // "store" | "product" | "order" | ... } } ``` Errors ordered by call stack depth: `errors[0]` = deepest layer (root cause), `errors[n]` = outermost. | Status | Cause | Fix | |--------|-------|-----| | 400 | Invalid request body | Check required fields and types | | 401 | Bad signature or expired token | Verify API key and private key match | | 403 | `prodEnabled=false` | Complete KYB review in dashboard | | 403 | Product not found or not accessible | Check the product belongs to the current merchant and environment | | 409 | Idempotency conflict or duplicate nickname | Wait and retry, or use unique nickname | | 429 | Rate limited | Back off and retry | --- ## Critical Rules ### ALWAYS DO - **Raw body for webhooks**: `express.raw()` or `request.text()`. Parsed JSON breaks signatures. - **Redirect synchronously in the click handler**: `window.location.href = checkoutUrl` (same tab; `successUrl` brings the buyer back) or `window.open(url, "_blank")` called directly in the handler. Server-side, use `res.redirect(checkoutUrl)`. - **Built-in verification**: `verifyWebhook()` has embedded public keys for test and prod. - **Use display amounts**: pass `"29.00"` for USD instead of cents-based integers. - **Env vars for secrets**: `WAFFO_MERCHANT_ID` and `WAFFO_PRIVATE_KEY` in `.env`. - **Separate API keys**: Different keys for test and production environments. - **Respond 200 immediately**: In webhook handlers, respond before async processing. - **Use `ngrok` for local tunneling**: It preserves custom HTTP headers. localtunnel strips them. ### NEVER DO - **Never** use `express.json()` on webhook routes. - **Never** call `window.open()` from an async callback (after `await`) — Safari and mobile browsers block the popup. - **Never** implement RSA-SHA256 signing manually — the SDK handles it. - **Never** hardcode private keys in source code. - **Never** use the same API key for test and production. - **Never** mix cents-based integers with display amounts in the same integration. --- ## Data Conventions | Type | Format | Example | |------|--------|---------| | Amounts | Display amount string | `"29.00"` for USD | | Currency | ISO 4217 | `USD`, `EUR`, `JPY` | | Timestamps | ISO 8601 UTC | `2026-01-23T00:00:00.000Z` | | IDs | `{PREFIX}_{base62}` | `STO_xxx`, `PROD_xxx`, `ORD_xxx` | | Checkout Session ID | `cs_` + UUID | `cs_550e8400-...` | --- ## Dashboard UI Glossary (EN → ZH → JA) The Dashboard supports English, Chinese, and Japanese. When referencing a Dashboard location, use this mapping. | English | 中文 | 日本語 | |---------|------|--------| | Home | 首页 | ホーム | | Products | 产品 | 商品 | | Customers | 客户 | 顧客 | | Analytics | 分析 | 分析 | | Payments | 付款 | 支払い | | Subscriptions | 订阅 | サブスクリプション | | Revenue | 收入 | 収益 | | API & Development | API 与开发 | API と開発 | | Settings | 设置 | 設定 | | Merchant ID | 商户 ID | マーチャントID | | Store ID | 店铺 ID | ストアID | | API Key | API 密钥 | APIキー | | Private Key | 私钥 | 秘密鍵 | | Test Mode | 测试模式 | テストモード | | Live Mode | 生产模式 | 本番モード | | One-time | 一次性 | 単発 | | Subscription | 订阅 | サブスクリプション | | Active | 生效中 | 有効 | | Canceled | 已取消 | キャンセル済み | | Completed | 已完成 | 完了 | **Where to find IDs:** - `WAFFO_MERCHANT_ID` → Dashboard → API & Development (API 与开发) → the \"Create an API Key\" section → first row above the key list, with a copy button. It is **not** at the top of the page and the section heading does not mention it - `Store ID` → Dashboard → Settings (设置) → Store Profile (店铺资料) - `Product ID` → Dashboard → Products (产品) → click product → shown in URL and detail page - `API Key` → Dashboard → API & Development (API 与开发) → \"Create an API Key\" section → Create Key --- ## Test Cards ### Successful Payments | Card | Type | |------|------| | `4576 7500 0000 0110` | Visa Credit | | `2226 9000 0000 0110` | Mastercard Credit | | `4001 7000 0000 0110` | Visa Debit | | `2226 9300 0000 0110` | Mastercard Debit | ### Declined Payments | Card | Type | |------|------| | `4576 7500 0000 0220` | Visa Credit | | `2226 9000 0000 0220` | Mastercard Credit | | `4001 7000 0000 0220` | Visa Debit | | `2226 9300 0000 0220` | Mastercard Debit | Any future expiry. Any CVC. --- ## Local Development Tips 1. **Use `ngrok` for webhook tunneling** — preserves all custom HTTP headers including `X-Waffo-Signature`. localtunnel strips custom headers. ngrok preserves them. ```bash # Install: brew install ngrok/ngrok/ngrok (or https://ngrok.com/download) ngrok http 3000 ``` 2. **Idempotency** — opt-in. No `X-Idempotency-Key` is sent unless you pass one: `client.stores.create(params, { idempotencyKey: myKey })`. Without a key a retried write executes again; with one the platform replays the first response for 24h (and answers 409 while the original is still in flight). You own the key's uniqueness. 3. **Test vs Prod** — Products created in test environment by default. Use `.publish()` to promote to production. Webhook events include `mode: "test" | "prod"`. --- ## Product Model Decision Table | Situation | Model | |-----------|-------| | Fixed public price | Product price set on the product | | Runtime-calculated amount (overage, credits) | Checkout session with `priceSnapshot` | | Recurring plan | Subscription product | | Multiple subscription tiers | One subscription product per tier + product group | | Setup fee or credits top-up | One-time product | | Overage charge for a subscription customer | One-time product with dynamic `priceSnapshot` | --- ## Quick Start Checklist 1. `npm install @waffo/pancake-ts` 2. Set only `WAFFO_MERCHANT_ID` and `WAFFO_PRIVATE_KEY` env vars (see "Where to find IDs" above) 3. Initialize `new WaffoPancake({ merchantId, privateKey })` 4. Create store: `client.stores.create({ name })` — or use an existing store from Dashboard 5. Before creating product(s), confirm which store should own them when the merchant has multiple stores 6. Create product(s): `client.onetimeProducts.create(...)` or `client.subscriptionProducts.create(...)` — or copy existing Product IDs from Dashboard 7. Create checkout: `client.checkout.createSession(...)` → redirect to `checkoutUrl` 8. Test with card `4576750000000110` (success) or `4576750000000220` (declined) in sandbox 9. Handle webhooks: `verifyWebhook(rawBody, signatureHeader)` — use `request.text()` not `.json()` 10. Configure webhook URL: `client.webhooks.add({ storeId, channel: \"http\", url, events, testMode })` --- ## Documentation - Full docs: https://docs.waffo.ai/ - AI-readable full reference: https://docs.waffo.ai/llms-full.txt - SDK integration: https://docs.waffo.ai/integrate/sdks - AI Skills guide: https://docs.waffo.ai/integrate/ai-integration - npm: https://www.npmjs.com/package/@waffo/pancake-ts - Dashboard: https://pancake.waffo.ai/merchant/dashboard/integration ```` # Consumer Portal Source: https://docs.waffo.ai/merchant/customer-portal Access and configure the self-service portal for your customers ## Overview The Consumer Portal is a merchant-level feature that gives your customers a self-service interface to manage their orders, subscriptions, and billing details. It operates across all your stores. Access it from the **user menu → Consumer Portal**. *** ## What Customers Can Do | Feature | Description | | - | - | | View orders | Browse all past orders and payment history | | Download invoices | PDF invoices with multi-language support | | Manage subscriptions | View status, next billing date, and cancel | | Reactivate subscriptions | Resume a canceling subscription before it expires | | Update billing details | Edit invoice address and tax information | *** ## Accessing the Portal There are two ways customers reach the portal: > **Magic Link (Email)** > > Customers log in via a one-time magic link sent to their email. No password required. > **Direct Link** > > Share your store's portal URL directly. Customers enter their email to receive a login link. > **[From Your Site](/guides/customer-portal-sso)** > > Your server creates a portal link for a customer who is signed in on your site. No email step. > [!NOTE] > > A portal opened from your site shows one store and one environment, matched by the `buyerIdentity` you used at checkout. Refund tickets are view-only there. To manage subscriptions from inside your own pages instead, use the [Customer Portal API](/api-reference/endpoints/auth/customer-endpoints) with a customer session token. *** ## Portal URL The portal is a single sign-in page shared across all stores: ``` https://pancake.waffo.ai/consumer/portal/login ``` Customers sign in with the email they used at checkout and see their orders from every Waffo Pancake store in one place — the portal is not scoped to one store, so there is no per-store sign-in URL. Links created by your server for [signed-in customers](/guides/customer-portal-sso) are the exception: they open a portal scoped to your store. > [!NOTE] > > `pancake.waffo.ai/store/{store-slug}` is your **public storefront**, a different page. See [Store Settings](/settings/store-settings) for your slug. *** ## Merchant View From the user menu, clicking **Consumer Portal** opens a preview of the portal as it appears to your customers. Use this to verify the experience before sharing the link. > [!NOTE] > > The portal always renders in dark mode and does **not** follow your checkout theme. Because one portal spans every store a customer buys from, it cannot take on any single store's colors. # Merchant Finance Source: https://docs.waffo.ai/merchant/finance Pooled balance and payouts across all your stores ## Overview Open **Merchant Finance** from the user menu (top-right avatar) or at `/merchant/dashboard/finance`. This is your merchant-level view — all your stores' settled revenue flows here, and you request payouts from here. ![Merchant Finance page](https://mintcdn.com/waffo/ufjGfSwGi0IBOUvV/images/dashboard/merchant-finance.png?fit=max\&auto=format\&n=ufjGfSwGi0IBOUvV\&q=85\&s=a5b2bb4125eda58f6da8144e96714111) *** ## Balance Indicators Three KPI cards at the top of the page summarize your funds: | Indicator | Meaning | | - | - | | **Available to withdraw** | Net amount that has fully settled and is ready to pay out | | **Processing** | Withdrawals you have already requested that haven't landed in your account yet | | **Total withdrawals** | Cumulative amount you have paid out so far | *** ## Tabs | Tab | Content | | - | - | | **Pay out** | Request a payout from your available balance | | **Withdrawal records** | Historical payouts and their statuses | If you haven't bound a payout account yet, a banner at the top links to **Payout Accounts**. *** ## Payout Accounts Payout accounts live at the merchant level — all your stores share the same set. Manage them under [Payout Accounts](/merchant/payout-accounts). > [!NOTE] > > **Current coverage:** mainland China, Hong Kong, United States, Japan, South Korea and Singapore, all currently settled in USD. Methods and required fields per region are listed under [Payout Accounts](/merchant/payout-accounts). *** ## Fees Two kinds of fees apply to the amount that lands in your account: * **Transaction fee** — deducted from each successful payment at the time of settlement. The Net column reflects what you actually receive after this. * **Payout fee** — charged when you initiate a payout from your merchant balance. See [Fee Details](/mor/fees) for the full breakdown with worked examples. # Identity Verification Source: https://docs.waffo.ai/merchant/identity-kyc Verify your identity to receive payouts Verify your identity before you add a payout account. Every payout is sent to a holder name derived from your verified identity — getting that name exactly right is how we make sure your funds arrive. This page covers **individual identity verification**, used when you pay out to a personal bank account or Alipay. If you pay out to a **company account**, see [Paying out to a company account](#paying-out-to-a-company-account) below. > [!NOTE] > > Identity verification is required before you can add a payout account and request payouts. ## What you'll provide ![Identity form on Profile — first name, last name, legal full name, country, ID type, ID number](https://mintcdn.com/waffo/ufjGfSwGi0IBOUvV/images/dashboard/identity-kyc.png?fit=max\&auto=format\&n=ufjGfSwGi0IBOUvV\&q=85\&s=336c0011b822ba196c54064421766a9e) | Field | Format | Notes | | - | - | - | | **First name** | Latin characters, 1–64 chars | Romanized given name | | **Last name** | Latin characters, 1–64 chars | Romanized family name | | **Legal full name** | Local script (e.g. 张三), 1–128 chars | The most important field. Must match your ID exactly — this becomes the holder name on every payout | | **Nationality** | ISO 3166-1 alpha-2 (e.g. CN) | Country of citizenship | | **ID type** | National ID **or** Passport | National ID for mainland China, passport for others | | **ID number** | 18 digits (National ID) or 7–13 alphanumeric (Passport) | Must match the ID type | > [!TIP] > > Legal full name is the field people most often get wrong. Compare it to your ID character-by-character — including spaces and punctuation — before you save. ## When you can edit your identity Whether the core fields are editable depends on your payout history: * **No payout activity yet** — legal name, ID number, nationality, and ID type can all be edited freely. Previously empty fields can also be filled in any time. * **A payout is in progress, or you have one or more successful payouts on record** — the core fields are locked from self-edit. Contact support if you legitimately need to update one (for example, a legal name change with supporting documentation). Sensitive fields (ID number, bank account number, Alipay account) are stored encrypted. The dashboard only shows the last few characters. ## Paying out to a company account If you'll receive payouts on a **company bank account** instead of a personal one, the identity used for the holder-name match is your **company**, not you as an individual. The fields you provide are different — they describe your legal entity rather than your personal ID. > [!NOTE] > > **Coming soon.** Company-entity identity verification is being finalized. Until it's released, all payouts use the individual identity on your account. Watch this page for updates. ## Where to find it The identity form lives on the **Profile** page. Open it from the user menu (top-right avatar) → **Profile**. # Merchant Overview Source: https://docs.waffo.ai/merchant/overview How merchant-level features fit together ## Merchant vs Store Waffo Pancake organizes your account into two levels: > **Store** > > Each store has its own products, orders, customers, and revenue. Manage store-level data from the sidebar inside a store. > **Merchant** > > Your merchant account sits above all stores. It owns your identity, your payout accounts, and the pooled balance across every store you run. Access merchant tools from the top-right avatar menu. ## Merchant-Level Pages Open from the user menu (top-right avatar): | Page | What it's for | | - | - | | **Profile** | Your personal identity used for payout holder-name matching. See [Identity Verification](/merchant/identity-kyc). | | **Merchant Finance** | Pooled balance across all your stores. Initiate payouts and view withdrawal history. See [Merchant Finance](/merchant/finance). | | **Payout Accounts** | Bank card or Alipay accounts that receive your payouts. Shared across all your stores. See [Payout Accounts](/merchant/payout-accounts). | # Payout Accounts Source: https://docs.waffo.ai/merchant/payout-accounts Add and manage the accounts that receive your payouts Payout accounts are where your payouts arrive. They are managed per merchant and shared by every store you own. You can keep several on file and pick the destination each time you request a payout. ![Payout Accounts page — basic identity summary and saved accounts](https://mintcdn.com/waffo/ufjGfSwGi0IBOUvV/images/dashboard/payout-accounts.png?fit=max\&auto=format\&n=ufjGfSwGi0IBOUvV\&q=85\&s=d77a203c5679b86469a24811e3e2457b) > [!NOTE] > > Alipay on this page is an account **you receive money into** — it is not a payment method for your buyers. ## Adding a Payout Account **1. Verify your identity first** The holder name on every payout comes from your legal name, so you can't add an account without a verified identity. See [Identity Verification](/merchant/identity-kyc). **2. Open Payout Accounts** Click your avatar in the top-right and select **Payout Accounts**. **3. Pick the region and method, enter the account** Choose the receiving account's **country / region**, **currency** and **payout method**, then fill in the fields that method needs. The holder name comes from your identity — you don't type it. **4. Save** On the first payout to a new account the bank checks the holder name against your legal name; once it matches, the account is marked **Verified**. ID numbers, bank account numbers and Alipay accounts show only their last few characters after saving. ## Supported Regions and Payout Methods | Region | Methods | Fields required | | - | - | - | | 🇨🇳 Mainland China | Bank card / Alipay | Bank card: bank (from the list), card number, plus the branch for cards not starting with 62; Alipay: registered mobile number or email | | 🇭🇰 Hong Kong | Bank transfer | Bank (from the list), account number | | 🇺🇸 United States | Bank transfer | ABA routing number, account number, account type (Checking / Savings), the address registered on the account | | 🇯🇵 Japan | Bank transfer | Bank (from the list), 3-digit branch code, 7-digit account number, contact phone | | 🇰🇷 South Korea | Bank transfer | Bank (from the list), account number | | 🇸🇬 Singapore | Bank transfer / PayNow | Bank transfer: bank (from the list), account number; PayNow: registered mobile number (+65-XXXXXXXX) | * **Settlement currency:** every region is currently settled in **USD**. If the receiving bank credits you in local currency, it converts at its rate on the day of arrival; Hong Kong accounts are credited in USD as-is, with HKD accounts opening later. * **Bank list:** the list is the set of banks the payout channel supports today; banks outside it can't receive payouts yet. * **Japanese accounts:** enter only the 7-digit account number, with the branch code in its own field. Japanese banks match the katakana name registered on the account; if it differs from the Latin name in your identity, the payout may bounce — contact support. * **Alipay limits:** RMB 50,000 per payout and RMB 300,000 per recipient per year; use a bank card for larger amounts. > **[Need another region or method?](https://forms.gle/xKPbT3ZSTVy1sbBNA)** > > Tell us which region, currency or payout method you need — submissions feed directly into roadmap prioritization. ## Managing Accounts * **Add:** within one region and currency, the same card or Alipay account can be added only once. * **Delete:** allowed when no payout to that account is in progress. * **Change:** accounts can't be edited — delete and add again. * **Choosing the destination:** there is no default account; you pick one on every payout. Payouts are irreversible, so one extra click beats sending to the wrong account. ## Common Issues > **Why can't I add a payout account?** > > Usually an incomplete identity. Fill in the missing fields on **Profile** and try again — see [Identity Verification](/merchant/identity-kyc). > **Why can't I change the holder name?** > > It comes from your verified legal name, which prevents typos from bouncing a payout. Change the legal name on **Profile**; if it's locked, contact support. > **Can I add the same card twice?** > > Not within the same region and currency. Hong Kong is the exception: one card can be added once for HKD and once for USD (HKD opens later). > **My bank isn't on the list.** > > Banks outside the list can't receive payouts yet. Use an account at a listed bank, Alipay (mainland China) or PayNow (Singapore), or contact support. > **My payout failed with A0016: Bank code is not supported** > > The account's bank code isn't on the channel's supported list — usually an account entered by hand before the bank picker existed. Delete it and add it again, choosing the bank from the list. # Payouts Source: https://docs.waffo.ai/merchant/payout-flow How payouts work How payouts work. Every sale on your store goes through a short waiting period, then auto-settles into your merchant balance. From there, you request a payout whenever you want — funds land in your bank account, Alipay or PayNow a few business days later. (Alipay here is a payout destination for you, the merchant — buyers cannot pay with Alipay yet.) **1. Store earns revenue** A customer pays. The amount lands in that store's balance and waits about **10 business days** so any refunds or chargebacks can settle first. Business days follow the **Hong Kong public-holiday calendar**, so around a long holiday the wait can run past two calendar weeks. **2. Auto-settle to your merchant balance** After the waiting period, funds move automatically into your **merchant balance** — pooled across all of your stores. Nothing for you to do. View it in **Finance** at the top of the dashboard. **3. You request a payout** Once your balance clears the minimum, you initiate a payout from Finance. Bank-card payouts requested before **15:00 Beijing time on a business day** arrive the same day; later requests arrive the next business day, and nothing is paid out on weekends or holidays. Alipay payouts are not tied to business days and usually arrive the same day. ## Fees and Payout Schedule | | | | - | - | | **Minimum payout** | **More than \$10 USD** — converted to your local currency at the rate when you submit | | **Settlement hold** | \~10 business days from sale before funds clear — business days per the Hong Kong holiday calendar, so long holidays stretch the calendar time | | **Arrival time** | **Bank card:** same day if requested before 15:00 Beijing time on a business day, otherwise the next business day; no payouts on weekends or holidays. **Alipay:** no business-day restriction, usually the same day; large payouts may trigger Alipay's risk review and a request for transaction-background documents. **Other regions (Hong Kong, United States, Japan, South Korea, Singapore):** usually 1–3 business days | | **Payout schedule** | On-demand — no fixed cycle; request manually once your balance clears the minimum | | **Payout fee** | **1% per payout, \$10 minimum** — deducted from the amount before arrival | | **Taxes** | Local taxes may also apply, depending on your jurisdiction. Contact support if you need a breakdown | > [!NOTE] > > **Current coverage:** mainland China, Hong Kong, United States, Japan, South Korea and Singapore. Methods, arrival currencies and required fields per region are listed under [Payout Accounts](/merchant/payout-accounts). > [!NOTE] > > Test mode doesn't affect payouts. Finance and Payout History always show real data, and you can't simulate a payout. ## Requesting a Payout ![Merchant Finance — balance, available amount, and request payout](https://mintcdn.com/waffo/ufjGfSwGi0IBOUvV/images/dashboard/merchant-finance.png?fit=max\&auto=format\&n=ufjGfSwGi0IBOUvV\&q=85\&s=a5b2bb4125eda58f6da8144e96714111) **1. Open Finance** Click **Finance** in the top navigation. You'll see your merchant balance and the amount available to withdraw. **2. Enter an amount** Type the amount you want. The amount must be **more than \$10 USD** — the threshold is set in USD, and the local-currency amount arriving in your account is calculated at the rate the moment you submit. **3. Pick the destination** Choose which payout account receives the money — there is no default, so this is an explicit choice every time. The holder name comes from your verified identity and isn't editable here. **4. Submit** Click **Request Payout**, then confirm in the dialog — it restates the amount and destination before anything moves. The payout enters **pending** and is tracked under **Payout History**. ## Debit Note Download a formal **Debit Note** PDF for any payout from its entry in **Payout History** — a settlement document for your accountant or your books. Each note carries: * Legal entity name and registration number * Contact details * The Merchant-of-Record disclaimer Laid out to the conventions accounting software and auditors expect. ## Failed Payouts Most payouts land without issue. If yours doesn't, work through this list: * **Name mismatch.** The bank returned a holder name that doesn't match your legal name on file. Open **Profile**, compare your legal name to your ID character-by-character (including spaces and punctuation), correct it, and retry. If the field is locked, contact support. * **Identity incomplete.** You can't request a payout — or even add a payout account — without a verified identity. See [Identity Verification](/merchant/identity-kyc). * **Below the minimum.** Payouts of \$10 USD equivalent or less are rejected. Wait until your balance clears the threshold, or contact support for an exception. * **Pending longer than 5 business days.** The bank may be running extra checks on a large amount or a brand-new account. If it doesn't clear within a week, contact support with your payout ID. * **Holder name doesn't match your identity.** Each payout account must belong to the same legal person whose identity you've verified. If the names don't match exactly — even a punctuation or spacing difference — the payout fails. Open **Profile**, verify your legal name matches your ID exactly, and retry. See [Identity Verification](/merchant/identity-kyc). * **`C0001: System error`.** An error on the payout channel's side, unrelated to your account details. Request the payout again; if it keeps failing, contact support with the payout ID. * **Alipay account doesn't match its real-name profile.** The email or mobile number you entered must match the Alipay account's real-name registration exactly — a single mistyped character fails the payout. And while your identity verification is still incomplete, no payout account can pass the channel's check. * **`A0016: Bank code is not supported`.** The account's bank code isn't on the payout channel's supported list — usually an account entered by hand before the bank picker existed. Delete the account and add it again, choosing the bank from the list. * **Japanese account returns `INVALID-BENEFICIARY`.** Usually the branch code was prefixed to the account number, or the holder name doesn't match the katakana name registered on the account. Enter only the 7-digit account number with the branch code in its own field; for name mismatches, contact support. > [!TIP] > > When contacting support, include your merchant ID, the payout ID, the timestamp, and a screenshot. That's enough for us to find the record and respond fast. ## Managing Your Payout Account You can add or remove payout accounts at any time, and you choose the destination each time you request a payout. See [Payout Accounts](/merchant/payout-accounts) for the setup walkthrough and supported methods. > **[Payout Accounts](/merchant/payout-accounts)** > > Add or remove a bank card or Alipay account > **[Identity Verification](/merchant/identity-kyc)** > > Verify your identity before you can receive a payout ## FAQ > **When can I start receiving payouts?** > > As soon as your identity is verified and you've added a payout account. The first sale on your store starts a \~10 business day waiting period before funds clear into your merchant balance — once they do, you can request a payout whenever your balance clears the \$10 USD minimum. > **Which countries and currencies do you support?** > > We pay out to accounts in **mainland China, Hong Kong, the United States, Japan, South Korea and Singapore**: bank card or Alipay in mainland China, bank transfer in Hong Kong / the US / Japan / Korea, and bank transfer or PayNow in Singapore. Every region is currently settled in **USD**; if the receiving bank credits your account in local currency, it converts at its rate on the day of arrival. Field requirements per region are under [Payout Accounts](/merchant/payout-accounts). > **Can I simulate a payout in test mode?** > > No. Finance and Payout History always read live data, and there's no way to simulate a payout. Anything you submit moves real money. > **How do I change my payout account?** > > Open **Payout Accounts** from the user menu (or **Finance → Payout Account**) and add the new account. There is no edit action — to change an existing account's details, delete it and add it again. The holder name is taken from your identity and isn't editable here. See [Payout Accounts](/merchant/payout-accounts). > **My payout is stuck in pending — is something wrong?** > > Pending is normal for the first 3–5 business days while the bank processes it. Only worry if it stays pending past 5 business days — at that point, contact support with your payout ID. > **My payout failed with a name mismatch. What do I do?** > > The bank returned a holder name that doesn't match your legal name on file. Open **Profile**, compare your legal name field to your ID character-by-character (including spaces and punctuation), save the correction, and retry. If the field is locked, contact support. > **Alipay is asking me to submit extra documents. Why, and what do I provide?** > > For larger payouts, Alipay's risk team may ask you to supply documents proving the background of your transactions. This is a routine check on cross-border settlements — it does **not** mean anything is wrong with your account. You'll typically be asked for: > > * **Terms of service (TNC)** — proof that Waffo acts as your merchant of record, collecting, invoicing and settling on your behalf. See the [Developer Terms](https://www.waffo.ai/developer-terms). > * **Transaction / settlement details** — download an export from the corresponding page in your dashboard and submit it as an Excel/CSV file. > * **Invoices** — the receipts issued to your customers. Go to the Payments page, open a transaction to see its detail, and you'll find the invoice link there. > * **Website / product info** — a screenshot of your own pricing page, so the products and prices match your transaction records. > > A few tips: > > * You can upload **up to 10 files**. A good mix is your terms + one transaction export + your top invoices. > * **Prioritize your largest transactions** — they carry the most weight. > * Submit **within 24 hours**, or the request is returned. > * For the **service type** field, we recommend selecting **software service** (数字产品 / SaaS / 订阅), and keep it consistent with your website and invoices. > **Alipay keeps rejecting my documents. Is there another way to get paid?** > > Yes. Alipay isn't your only option — you can switch to a **bank card**. Open **Payout Accounts**, add a Bank Transfer account, set it as your payout account, and request your payout through it. This bypasses the Alipay document review entirely. Contact support if you'd like help deciding. > **Is there a limit on Alipay payouts?** > > Yes. Alipay payouts go to **personal Alipay accounts in mainland China**, and two limits apply: each payout is capped at **RMB 50,000**, and each recipient can receive a cumulative **RMB 300,000 per year** via Alipay. If you need to receive more than that, use a **bank card** instead — see [Payout Accounts](/merchant/payout-accounts). > **When should I contact support?** > > Reach out if your payout has been pending for more than 5 business days, you see a failure reason you don't recognize, you need to change a locked identity field, or you need a country or currency we don't support yet. Include your merchant ID, the payout ID, the timestamp, and a screenshot. # Preferences Source: https://docs.waffo.ai/merchant/preferences Manage display currency, language, and appearance for your dashboard ## Overview Preferences are personal settings that affect how the dashboard displays for you. They are not store-specific and apply across all stores in your merchant account. Access preferences from the **user menu** (click your avatar in the top-right corner). *** ## Available Preferences ### Display Currency The currency used to display amounts throughout the dashboard. * Default: **USD** * You can switch to any supported currency for display purposes * This does **not** affect your actual settlement currency or payout currency > [!NOTE] > > USD is the official settlement currency. Other display currencies are for reference only and use live exchange rates. ### Language The dashboard interface language. | Option | Language | | - | - | | English | English | | 简体中文 | Simplified Chinese | | 日本語 | Japanese | ### Appearance The dashboard color theme. | Option | Description | | - | - | | **Light** | Light background theme | | **Dark** | Dark background theme | | **System** | Follows your device's system setting | # Account Reviews Source: https://docs.waffo.ai/mor/account-reviews What we review before enabling live payments, and how to pass it As a Merchant of Record, Waffo Pancake processes payments and handles tax on your behalf. Before a store can accept **live payments**, we review it once to confirm it's a legitimate business that complies with our terms. This protects you, your customers, and the payment network. > [!NOTE] > > You can build products and take **test payments** at any time without a review. The review only gates **live payments** on a store. ## What gets reviewed The review applies to a **store** (the Store Business Review). You submit your business information from the store's [Business Details](/merchant/business-details) page, and our team reviews it. Identity information for [payouts](/merchant/payout-accounts) is **not** part of this review and has no separate approval step. ## Information you provide When you submit a store for review, you provide: * **Legal name** — the individual or business entity behind the store * **Business description** — what your business does and how it operates * **Product website URL** — a live, publicly reachable page describing what you sell * **Contact email** — a real, monitored support address * **Business type and tax residence** — for correct tax handling * Confirmation that your product complies with our terms (prohibited products, pricing visibility, no trademark conflicts) ## Approval checklist Go through every item below before you submit. Most "changes requested" outcomes come from missing one of these — fixing them upfront gets you approved on the first pass. * [ ] **Website is reachable** — The product website URL you submit opens normally, and our reviewers can see the page describing what you sell without a password or invite. Whether the product has officially launched, or whether users must sign up or log in to use it, does not affect the review; products still in development can be submitted too, and can take live payments as soon as the review is approved. * [ ] **Product is clearly visible** — We can understand what you're selling from your website or landing page. The product, its purpose, and how it works are obvious to a first-time visitor. * [ ] **Pricing page is complete** — A dedicated pricing page, viewable without logging in, shows every plan's name, price, billing cycle (one-time or subscription, and whether it auto-renews), and included features — before customers reach checkout. A blank page, an "under construction" page, or "contact us for pricing" alone does not count. * [ ] **Terms of Service & Privacy Policy are complete** — Both documents cover the [minimum legal content](#legal-terms-minimum) below. Need a starting point? Use our [Terms of Service template](/mor/account-reviews/tos) and [Privacy Policy template](/mor/account-reviews/privacy-policy). * [ ] **Legal links are in the footer** — Links to your Terms of Service, Privacy Policy, and other legal pages sit in your site footer and open without logging in. Each link leads to real, complete content — not an empty link, and not a redirect to an unrelated third-party site. * [ ] **Customer support email** — A real, monitored support email is set up and shown on your website, and it matches the contact email you submit for review. The same address should appear on customer receipts. * [ ] **No false information** — No fake reviews, testimonials, or inflated user/customer counts. Everything on your site is truthful. * [ ] **No trademark conflicts** — Your product and store name don't infringe an existing trademark or cause confusion with another brand. * [ ] **Acceptable use** — No high-risk, deceptive, or illegitimate use cases. * [ ] **Not on the prohibited list** — Your product isn't on our [prohibited products](/mor/prohibited-products) list. > [!NOTE] > > Does your product generate images or video with AI? It also has to meet the additional requirements in [AIGC Compliance](/mor/account-reviews/aigc-compliance). ### Minimum legal content Your **Terms of Service** must include: * A clear description of the product or service * Pricing and billing cycles * Refund and cancellation policy * Disclaimers, plus terms on user breach and account suspension Your **Privacy Policy** must include: * What data you collect * How you use and store it * Whether and how you share it with third parties * Users' data rights ## Review outcomes Review typically takes **1–3 business days**. You can track the status from the Business Details page. There are two outcomes: | Outcome | What it means | What to do | | - | - | - | | **Approved** | The store can now accept live payments (`prodEnabled`). | Start selling. | | **Changes requested** | Something needs fixing before approval. | Address the feedback and resubmit — see [Resubmitting after changes requested](#resubmitting-after-changes-requested). | ## Resubmitting after changes requested If the review comes back with changes requested, you don't start over — fix the flagged items and resubmit the same store. Common reasons and fixes: | Reason | Fix | | - | - | | Website inaccessible | Remove password protection or bot walls so the page loads for anyone. | | Missing or gated legal pages | Add a Terms of Service and Privacy Policy reachable without login, linked from the footer. | | Incomplete pricing | Add a pricing page anyone can view without logging in, listing each plan's name, price, billing cycle, and features. | | Support email mismatch | Make the email in your store settings match the one on your website. | | Inaccurate information | Correct anything misleading — descriptions, reviews, or claims must be truthful. | **1. Fix the flagged items** Work through the feedback on the Business Details page. **2. Update your business details** Edit the submission with the corrected information. **3. Resubmit for review** Submit again from the Business Details page. The status resets and the store re-enters review (typically another 1–3 business days). ## Frequently asked questions > **How long does the review take?** > > Typically 1–3 business days after submission. Track the status from the Business Details page. > **Can I accept payments before the review passes?** > > You can test the full flow in test mode anytime. Live payments require the store review to pass. > **What if changes are requested?** > > Fix the flagged items and resubmit the same store. The status resets and it goes through review again. # AIGC Compliance Source: https://docs.waffo.ai/mor/account-reviews/aigc-compliance Review requirements for AI image / video generation products — branding, model disclosure, content moderation, content policy, and what counts as a deepfake If your product lets users generate images or videos from text prompts, account review checks it against every requirement on this page, on top of the general [account review](/mor/account-reviews) checklist. Fix everything here before you submit — these items decide whether an AI generation product is approved. > [!NOTE] > > This page applies to products with AI **image or video generation** capability. If your product builds on top of an AI model (an "AI wrapper"), these requirements are how review distinguishes a legitimate product from a repackaged model. ## What review checks > **Independent branding** > > **Required:** your own product name and identity. **Not allowed:** marketing yourself *as* an AI model brand (e.g., "the official GPT app") or using a model's name/logo as your own. > **Honest marketing** > > **Required:** describe what your product actually does. **Not allowed:** overstating capabilities, implying endorsement by a model provider, or hiding that output is AI-generated. > **Moderation in place** > > **Required:** integrate [Prompt Sift](#moderation-api) to screen user prompts, and run a moderation step on generated outputs. **Not allowed:** shipping an unmoderated raw-model passthrough. > **Published content policy** > > **Required:** a public AUP covering prohibited content, reporting, and enforcement — use the [AUP template](/mor/account-reviews/aup). **Not allowed:** no policy, or one that doesn't match your actual product. > **Deepfakes** > > **Required:** if users can upload photos or voice of real people, your terms [restrict where that material comes from](#real-person-uploads). **Not allowed:** face swap, "nudify," intimate-scene compositing, or any other [deepfake](#deepfake) feature — whether or not the people involved consent. ## Underlying model disclosure You must clearly disclose the underlying AI models your platform actually uses. Either form of disclosure is accepted: * **Document-based**: list the model names on your About, Pricing, or Terms page, or on a dedicated page; * **Interface-based**: in the image/video generation UI, users can directly see and select different underlying models (e.g., a dropdown, model switcher, or model cards), with each option clearly labeled with the model name. The disclosure must meet all of the following: * Model names are **real and specific** — vague phrasing such as "AI technology," "advanced models," or "30+ models" is not acceptable; * The models used are **industry-mainstream** (e.g., Flux, Seedream, Nano Banana/Gemini, GPT Image, Veo, Kling, Seedance, Wan); * **No repackaging or misrepresentation**: no free-riding on official brands, no inflated version numbers, no models of unknown origin without safety guardrails; * If multiple models are offered, **every selectable model must meet the requirements above**, and switching models must not bypass content-safety filtering. > [!NOTE] > > Truthful model disclosure does not conflict with the independent-branding requirement: listing "images/videos on this product are generated with Flux and Kling" in your docs or UI is compliant disclosure; marketing yourself *as* the model's brand (e.g., "the official GPT app") is the violation. ## Content moderation API — Waffo Prompt Sift A platform-side moderation step is a hard requirement (see [content policy requirements](#content-policy-requirements) below). Every AI application — not only image and video generation — must integrate **Prompt Sift**, Waffo's content-safety check for AI generation, to screen user prompts before generation; output moderation after generation can be your own. ### How to set up moderation **1. Deploy scanning at more than one stage.** * **Before generation** — scan user prompts in real time (Prompt Sift is required here). * **After generation, before display** — scan the AI output before showing it to the user. * **After publication** — if your product has a public gallery or feed, scan published images/videos asynchronously. Cover at least the first two; add the third whenever user works are publicly visible. **2. Maintain an actively updated blocklist of prohibited terms and prompts.** It should cover at minimum: pornography/NSFW terms; CSAM-related vocabulary; copyrighted characters, brands, and trademark names; violence, hate speech, and self-harm; deepfake / celebrity / political-figure terms. "Actively updated" is part of the requirement — a static list shipped once doesn't count. **3. Keep moderation logs.** Retain both the AI moderation model's outputs and human-review decisions. Review may ask you to produce them. ### What Prompt Sift is Before you hand a user's text prompt to your generation model, send it to Waffo for a safety check. Prompt Sift primarily intercepts requests involving child-unsafe content — standard practice across the industry (OpenAI, Google, Civitai, and other major AI generation platforms run equivalent checks). It protects your users and your product, and helps you meet the compliance requirements on this page. ### How it works **1. Your user enters a generation prompt** Any text description the user submits for image or video generation. **2. Your product calls Prompt Sift before generating** Send the prompt to the check endpoint at `https://api.waffo.ai/v1/actions/verification/scan-prompt`. **3. Act on the verdict** * **Pass** → call your generation model as normal; the flow is unaffected. * **Block** → don't generate; show the user a friendly message (e.g., "This content doesn't meet our usage guidelines"). * **Pending review** → hold briefly (usually resolved within 1 hour); our human review team makes the final call. ### What you get A simple API: pass us the user's text prompt, and we return a clear verdict — with minimal impact on your product flow. > **[Content safety API reference](/api-reference/endpoints/content-safety/scan-prompt)** > > Endpoint reference, request/response format, and integration examples. Prefer an SDK? The official Waffo SDKs (TypeScript / Go) expose this as `client.contentSafety.scanPrompt(...)` — the fastest way to integrate. > **[SDK integration guide](/integrate/sdks)** > > Install and authenticate the TypeScript or Go SDK, then call content safety with a single method. > [!TIP] > > If your product is an AI application that takes text input from users — to generate images, video, or text, or to hold a conversation — you must integrate Prompt Sift to screen that input. ## Content policy requirements You must publish a **standalone AUP page**, or a **dedicated chapter** in your Terms of Service, covering all of the following. **Six prohibited-generation categories (listed one by one — no vague catch-alls):** * Pornography / NSFW * Violence / gore * Hate speech * Child-unsafe content (CSAM) * Deepfakes / impersonation — see [what counts as a deepfake](#deepfake) * Copyright / trademark infringement **Supporting mechanisms:** * **Enforcement actions** — account bans, credit forfeiture, content removal, etc. * **A user reporting channel** — users can report violating generated content, and you describe how reports are handled. * **A description of platform-side content moderation** — your moderation workflow (automated filtering, human review, etc.). > **[AUP template](/mor/account-reviews/aup)** > > A complete Acceptable Use Policy covering everything above — the six prohibited categories listed one by one, plus enforcement, reporting, and moderation sections. Replace the placeholders and publish. ## Real-person uploads If your product lets users upload photos or voice recordings of real people, your Terms of Service or AUP must explicitly restrict **where uploaded material comes from**. Either approach works: * Your terms explicitly prohibit uploading another person's photos or voice without their consent; or * At upload, users must actively confirm "This is my own material, or I have permission from the people in it." Section 2.4 of the [AUP template](/mor/account-reviews/aup) provides ready-to-use wording. > [!WARNING] > > Permission does not make a deepfake feature compliant. The four forms below count whether or not the people involved consent. ## What counts as a deepfake Products whose core business is deepfaking real people are a [prohibited category](/mor/prohibited-products) and cannot be accepted on any payment channel. This goes beyond the content your policy bans users from generating — if the product itself offers these features, it will not pass review. **Definition:** the output replaces or disguises one real person's identity or face as another real person's, or composites two real people into a fabricated intimate scene — whether or not the people involved consent. ### The four forms **1. Face swap** Putting A's face onto B's photo or video, or "turning" A's photo into another specific real person — swaps between celebrities, public figures, and ordinary users all count. **Any face-swap entry point or menu item on your site is enough to count.** Real case: Indian actress Rashmika Mandanna's face was swapped onto someone else's body in a video that went viral and drew public attention to deepfake technology ([NewsBytes](https://newsbytesapp.com/news/entertainment/mandanna-warns-about-deepfake-after-viral-face-swap-with-patel/tldr); for more cases, see [HyperVerge: 20+ real deepfake examples](https://hyperverge.co/blog/examples-of-deepfakes/)). ![Screenshot of a deepfake video from the Unreal Keanu Reeves TikTok account](https://mintcdn.com/waffo/xtfHZ84AcIkOjK_r/images/deepfake/face-swap-keanu-reeves.jpg?fit=max\&auto=format\&n=xtfHZ84AcIkOjK_r\&q=85\&s=2e7fc97d8e4ffe8885902ad5337caa4b) A deepfake video from the “Unreal Keanu Reeves” TikTok account — the person on screen is not Keanu Reeves **2. Deep nude / "nudify"** Applied to photos of real people to produce nude or sexualized content. Real case: a CBS News investigation found large numbers of ads for "nudify" AI tools on Meta's Instagram and Facebook ([CBS News](https://www.cbsnews.com/news/meta-instagram-facebook-ads-nudify-deepfake-ai-tools-cbs-news-investigation/)), and several jurisdictions have begun passing laws aimed specifically at these apps ([Minnesota legislation](https://19thnews.org/2026/04/minnesota-nudification-ban-ai-deepfake/)). **3. Two-person intimate scene synthesis (kiss / hug)** Compositing two real people into the same kissing, hugging, or other intimate scene — whether from one existing photo of the two of them or from two separately uploaded single-person photos. Real case: an AI-generated video of Italian Prime Minister Giorgia Meloni and Elon Musk "kissing" spread widely on social media, prompting ethical debate over deepfake misuse ([OECD.AI incident record](https://oecd.ai/en/incidents/2024-12-10-1ce9); [Euronews](https://www.euronews.com/2024/12/20/viral-video-of-musk-and-meloni-kissing-is-ai-generated)). ![Screenshot of the AI-generated video of Meloni and Musk kissing](https://mintcdn.com/waffo/xtfHZ84AcIkOjK_r/images/deepfake/intimate-scene-meloni-musk.jpg?fit=max\&auto=format\&n=xtfHZ84AcIkOjK_r\&q=85\&s=07bb55ec4eea9c85746c39477ea4d367) AI-generated video of Meloni and Musk “kissing.” Source: Euronews **4. Fabricated statements or actions** Making a real person "say" or "do" something they never said or did — not limited to video; still images count too. Any output that places a real person (especially a public figure or celebrity) in a fabricated scene, action, or event that never actually happened falls into this category. Real case: in 2022, hackers inserted a deepfake video into a live TV broadcast in which Ukrainian President Zelenskyy appeared to call on Ukrainian troops to surrender — words he never said ([Britannica: Deepfake](https://www.britannica.com/technology/deepfake)). ![Deepfake video of Zelenskyy compared with the real Zelenskyy](https://mintcdn.com/waffo/xtfHZ84AcIkOjK_r/images/deepfake/fabricated-speech-zelensky.jpg?fit=max\&auto=format\&n=xtfHZ84AcIkOjK_r\&q=85\&s=b0f205425984b960c2a0f1a7bf4bdeaa) Left: the deepfake video. Right: the real Zelenskyy. Source: UVA Today ## Before you request review 🔴 items decide whether an AI generation product is approved. 🟡 items strengthen the case. **1. 🔴 Must be done** * Product uses **independent branding** — not an AI model's name or logo as your own * Marketing is accurate — no overstated capabilities, no implied provider endorsement * **Underlying models are disclosed** truthfully and specifically, and are industry-mainstream ([model disclosure](#model-disclosure)) * **[Prompt Sift](#moderation-api) is integrated** to screen prompts, and a moderation step runs on outputs * A public **AUP page or ToS chapter** lists the six prohibited categories one by one ([content policy](#content-policy-requirements)) * At least one real, monitored **user reporting channel** exists * The product has **no [deepfake](#deepfake) features** — including any face-swap entry point or menu item * If users can upload photos or voice of real people, your terms [restrict where that material comes from](#real-person-uploads) * Enforcement actions in your policy are ones you can actually carry out **2. 🟡 Strongly recommended** * Output is labeled or otherwise disclosed as AI-generated * An appeals path exists for wrongly-actioned users * Age verification in place if you allow any restricted content # Acceptable Use Policy (AUP) Template Source: https://docs.waffo.ai/mor/account-reviews/aup A content policy for AI products on Pancake — content standards, moderation, reporting, and enforcement A complete Acceptable Use Policy for AI-powered (AIGC) products on Pancake. It sets the content standards, moderation, reporting, and enforcement that keep an AI product in good standing — pick what applies, replace the placeholders, publish. > [!WARNING] > > This is a template, not legal advice. AI content rules vary by market and change fast — have a qualified AI-compliance professional review it before publishing if your model, content types, or jurisdiction are unusual. ## Why this matters for AI products If you resell or build on top of AI models, [account review](/mor/account-reviews) looks at how you handle the content your users generate. A published AUP plus real moderation is what keeps an AI product approved — and keeps it from being suspended later. The four things review cares about most: > **Independent branding** > > **Required:** your own product name and identity. **Not allowed:** marketing yourself *as* an AI model brand (e.g., "the official GPT app") or using a model's name/logo as your own. > **Honest marketing** > > **Required:** describe what your product actually does. **Not allowed:** overstating capabilities, implying endorsement by a model provider, or hiding that output is AI-generated. > **Moderation in place** > > **Required:** run a content-moderation step (a moderation API or equivalent) on inputs and outputs. **Not allowed:** shipping an unmoderated raw-model passthrough. > **Published content policy** > > **Required:** a public AUP (this template) covering prohibited content, reporting, and enforcement. **Not allowed:** no policy, or one that doesn't match your actual product. ## Before you publish or request review 🔴 items decide whether an AI product is approved. 🟡 items strengthen the case. **1. 🔴 Must be done** * Product uses **independent branding** — not an AI model's name or logo as your own * Marketing is accurate — no overstated capabilities, no implied provider endorsement * A **moderation step runs on inputs and outputs** (name the tool in Section 3.1) * The "Absolutely Prohibited" list (2.1) is published and enforced — CSAM, terrorism, WMD, deepfakes of real people (consent or not) * The **six prohibited-generation categories are listed one by one** (Section 2) — porn/NSFW, violence/gore, hate speech, CSAM, deepfakes/impersonation, copyright/trademark infringement * Prohibited and restricted categories match what your product can actually generate * At least one **real, monitored reporting channel** exists (Section 5) * If users can upload photos or voice of real people: **2.4 is kept**, restricting where that material comes from * Enforcement actions (Section 7) are ones you can actually carry out * Image/video generators: the **underlying models are disclosed truthfully and specifically**, and are industry-mainstream (see [AIGC Compliance](/mor/account-reviews/aigc-compliance#model-disclosure)) **2. 🟡 Strongly recommended** * Output is labeled or otherwise disclosed as AI-generated * Severity tiers (3.4) map to concrete response times (Section 6) * An appeals path exists for wrongly-actioned users (Section 8) * Age verification in place if you allow any restricted (e.g., adult) content **3. Final pass** * Every `[placeholder]` replaced with real text * "Last Updated" date filled in * Categories/channels that don't apply to your product are deleted, not left as stubs > [!NOTE] > > This AUP is the standalone content policy. It complements Section 10 (Acceptable Use) of the [Terms of Service template](/mor/account-reviews/tos) — the T\&C points users at your full content policy; this is that policy. > **[AIGC Compliance](/mor/account-reviews/aigc-compliance)** > > The full review requirements for AI image/video generation products — underlying model disclosure, the Prompt Sift moderation API, and the content policy requirements. This template fulfills the content-policy requirements in full. ## Template Copy the block below and replace every `[placeholder]` with your real text. Delete any category, channel, or action that doesn't apply to your product. > [!NOTE] > > The template is in English. Translate or localize as your market requires — the content standards should stay the same. ```text Acceptable Use Policy — AI-Generated Content (replace every [placeholder]) theme={"system"} [Platform / Company Name] Acceptable Use Policy — AI-Generated Content Last Updated: [DATE] [Platform / Company Name] ("Platform," "we," "us," or "our") is committed to providing safe, lawful, and responsible AI-generated content services. This Acceptable Use Policy ("Policy") applies to all content generated, published, distributed, or stored through the Platform, and sets out our content standards, moderation, reporting procedures, and enforcement actions. All users, developers, and merchants using the Platform must comply with this Policy. 1. Scope This Policy applies to all content types, including: - Text: AI-generated text, dialogue, code, articles, etc. - Images: AI-generated or edited images and illustrations. - Audio / Video (if applicable): AI-synthesized voice, music, and video. - User Inputs (Prompts): prompts and instructions submitted by users. - [Other content types supported by the Platform, if applicable.] 2. Content Standards & Prohibited Categories The Platform prohibits generating the following six categories of content: - Pornography / NSFW content. - Violence / gore. - Hate speech. - Child-unsafe content (CSAM). - Deepfakes / impersonation of real people. - Content infringing copyright or trademarks. The clauses below break these categories and other violations down further. 2.1 Absolutely Prohibited — Zero Tolerance The following will be actioned immediately and may be reported to authorities: - Child sexual abuse material (CSAM) or any sexual content involving minors. - Content that promotes or facilitates terrorism, extremism, or mass violence. - Technical instructions for weapons of mass destruction. - Content inciting genocide or ethnic hatred. - Deepfakes of real individuals, including face swaps, nudification, intimate-scene compositing, and fabricated statements or actions, whether or not the individuals consent. - [Add categories based on applicable local regulations.] 2.2 Restricted — Subject to Review - Adult content: only permitted on age-verified, compliant platforms. - Violent content: must have a clear creative or educational context. - Politically sensitive content: content that may be misleading. - Medical / legal / financial advice: must comply with local regulations. 2.3 Generally Prohibited Conduct - Generating or spreading misinformation or disproven claims. - Impersonating real individuals, brands, or organizations. - Infringing intellectual property, publicity, or privacy rights. - Deceiving users by passing AI-generated content off as human-created. - Bulk-generating spam or deceptive commercial content. - Jailbreak prompts designed to bypass Platform safety measures. 2.4 Source of Uploaded Material [keep if the Platform accepts uploads of real people's photos or voices] You may only upload your own photos or voice, or material for which you have explicit permission from the people depicted. Uploading another person's photos or voice without their consent is prohibited. Before uploading, you must confirm that the material is your own or that you have permission. Permission does not authorize generating the deepfake content prohibited under Section 2.1. 3. Content Moderation We operate a multi-layer moderation system: automated review, human review, and periodic audits. 3.1 Automated Review (real-time) All requests and generated content are scanned in real time by safety filters. - Input filtering: keyword, semantic, and intent detection on prompts. - Output filtering: real-time safety assessment of generated content. - Usage pattern analysis: monitoring for anomalous API usage. - Safety model used: [e.g., OpenAI Moderation API, or a proprietary model]. 3.2 Human Review - Auto-flagged content enters a human review queue. - User-reported content is reviewed manually by the trust & safety team. - Review team: [e.g., 24/7 on-call moderation team]. - Reviewers complete content-safety training and sign NDAs. 3.3 Periodic Audits - Random content sampling performed [specify frequency]. - Regular evaluation and improvement of classifier accuracy. - [Whether independent third-party audits are conducted, if applicable.] 3.4 Content Severity Levels | Level | Description | Review | Action | |---|---|---|---| | L1 — Critical | Child safety, terrorism | Auto-block + human confirmation | Immediate ban + report | | L2 — High | Severe violations | Auto-flag + priority review | Remove + suspend account | | L3 — Medium | General violations | Human review | Warning + removal | | L4 — Low | Minor violations | Report-triggered | Warning + edit required | 4. Reporting 4.1 When to Report - Content or behavior violating this Policy's content standards. - Critical violations involving child safety or terrorism. - AI impersonation or infringement of your own rights. - [Other situations the Platform deems reportable.] 4.2 Reporting Principles - Confidentiality: reporter identity is strictly protected. - Impartiality: all reports receive independent, objective review. - Anti-abuse: malicious or false reports are recorded and actioned. 5. Reporting Channels Retain the options that apply: - Dedicated report email: [report@yourplatform.com] - Online report form: [https://yourplatform.com/report] - In-product report button: [e.g., Content page → ··· → Report] - Customer support: [live chat or support email] - Emergency contact (critical): [hotline or instant-messaging channel, if applicable] 6. Response & Processing Timelines | Violation Type | Initial Response | Resolution | |---|---|---| | L1 — Critical | Within 2 hours | Within 24 hours | | L2 — High | Within 24 hours | Within 3 business days | | L3 — Medium | Within 3 business days | Within 7 business days | | L4 — Low | Within 5 business days | Within 15 business days | If extended processing is required, we will notify the reporter proactively with reasons. Processing workflow: received (auto-acknowledge) → triage (classify L1–L4) → review (auto + human) → decision → enforcement → notification. 7. Enforcement Actions | Action | Measure | Applies to | |---|---|---| | 1. Warning | Written notice requiring removal or edit | First-time minor violation | | 2. Content removal | Violating content taken down | Confirmed L3–L4 | | 3. Feature restriction | Reduced quota or model access | Repeat minor or single L3 | | 4. Account suspension | Temporary suspension pending review | L2 or cumulative violations | | 5. Permanent ban | Permanent termination of access | L1 or repeat L2 | | 6. Legal action | Report to authorities; cooperate with investigation | Criminal-level L1 | 8. Appeals You may appeal an enforcement decision within [specify days] of receiving notice: - Appeal channel: [appeal@yourplatform.com] - Timeline: [e.g., reviewed within 10 business days]. - Review method: reviewed by a reviewer independent of the original decision. 9. Transparency & Policy Updates - We publish a content-safety transparency report every [specify period]. - Material changes are notified at least [e.g., 15] days in advance. - Continued use of the Platform constitutes acceptance of updates. 10. Contact Us - Safety Email: [safety@yourplatform.com] - Report Email: [report@yourplatform.com] - Appeal Email: [appeal@yourplatform.com] - Company Name: [full legal name] - Address: [registered address] This Policy is for general reference only and does not constitute legal advice. We recommend having it reviewed by a qualified AI-compliance attorney before publication. ``` ## Section-by-section reference Each section below shows its **tier** (🔴 load-bearing · 🟡 strongly recommended · ⚪ optional), a one-line summary, and the matching **template snippet** so you can read the guidance and copy that block together. ### 1. Scope **🔴 load-bearing** Names every content type you generate. A code assistant doesn't need the image/audio lines; an image generator does. Prompts count as content too — keep that line. ```text Section 1 theme={"system"} 1. Scope This Policy applies to all content types, including: - Text: AI-generated text, dialogue, code, articles, etc. - Images: AI-generated or edited images and illustrations. - Audio / Video (if applicable): AI-synthesized voice, music, and video. - User Inputs (Prompts): prompts and instructions submitted by users. - [Other content types supported by the Platform, if applicable.] ``` ### 2. Content Standards & Prohibited Categories **🔴 load-bearing** The six prohibited-generation categories at the top map to the hard requirements in [AIGC Compliance](/mor/account-reviews/aigc-compliance#content-policy-requirements) — list them one by one, no vague catch-alls, keep all of them. The 2.1 zero-tolerance list is the floor, not a menu — keep all of it and add local-law items. 2.2 is "allowed with conditions" (age-gating, context, local rules); for image/video generators going through Pancake review, pornography/NSFW is a prohibited category — delete the adult-content line from 2.2 rather than keeping it as restricted. 2.3's "passing AI off as human" and "jailbreak" lines are AI-specific and matter for review. Keep 2.4 only if your product accepts uploads of real people's photos or voices — it covers the [AIGC Compliance](/mor/account-reviews/aigc-compliance#real-person-uploads) requirement. ```text Section 2 theme={"system"} 2. Content Standards & Prohibited Categories The Platform prohibits generating the following six categories of content: - Pornography / NSFW content. - Violence / gore. - Hate speech. - Child-unsafe content (CSAM). - Deepfakes / impersonation of real people. - Content infringing copyright or trademarks. The clauses below break these categories and other violations down further. 2.1 Absolutely Prohibited — Zero Tolerance The following will be actioned immediately and may be reported to authorities: - Child sexual abuse material (CSAM) or any sexual content involving minors. - Content that promotes or facilitates terrorism, extremism, or mass violence. - Technical instructions for weapons of mass destruction. - Content inciting genocide or ethnic hatred. - Deepfakes of real individuals, including face swaps, nudification, intimate-scene compositing, and fabricated statements or actions, whether or not the individuals consent. - [Add categories based on applicable local regulations.] 2.2 Restricted — Subject to Review - Adult content: only permitted on age-verified, compliant platforms. - Violent content: must have a clear creative or educational context. - Politically sensitive content: content that may be misleading. - Medical / legal / financial advice: must comply with local regulations. 2.3 Generally Prohibited Conduct - Generating or spreading misinformation or disproven claims. - Impersonating real individuals, brands, or organizations. - Infringing intellectual property, publicity, or privacy rights. - Deceiving users by passing AI-generated content off as human-created. - Bulk-generating spam or deceptive commercial content. - Jailbreak prompts designed to bypass Platform safety measures. 2.4 Source of Uploaded Material [keep if the Platform accepts uploads of real people's photos or voices] You may only upload your own photos or voice, or material for which you have explicit permission from the people depicted. Uploading another person's photos or voice without their consent is prohibited. Before uploading, you must confirm that the material is your own or that you have permission. Permission does not authorize generating the deepfake content prohibited under Section 2.1. ``` ### 3. Content Moderation **🔴 load-bearing** How you actually catch violations — review expects a real moderation step, not a promise. Name a real tool in 3.1 (`[OpenAI Moderation API]` or your own); a step on inputs **and** outputs is the single thing review most wants to see. The L1–L4 tiers in 3.4 drive response times and enforcement. ```text Section 3 theme={"system"} 3. Content Moderation We operate a multi-layer moderation system: automated review, human review, and periodic audits. 3.1 Automated Review (real-time) All requests and generated content are scanned in real time by safety filters. - Input filtering: keyword, semantic, and intent detection on prompts. - Output filtering: real-time safety assessment of generated content. - Usage pattern analysis: monitoring for anomalous API usage. - Safety model used: [e.g., OpenAI Moderation API, or a proprietary model]. 3.2 Human Review - Auto-flagged content enters a human review queue. - User-reported content is reviewed manually by the trust & safety team. - Review team: [e.g., 24/7 on-call moderation team]. - Reviewers complete content-safety training and sign NDAs. 3.3 Periodic Audits - Random content sampling performed [specify frequency]. - Regular evaluation and improvement of classifier accuracy. - [Whether independent third-party audits are conducted, if applicable.] 3.4 Content Severity Levels | Level | Description | Review | Action | |---|---|---|---| | L1 — Critical | Child safety, terrorism | Auto-block + human confirmation | Immediate ban + report | | L2 — High | Severe violations | Auto-flag + priority review | Remove + suspend account | | L3 — Medium | General violations | Human review | Warning + removal | | L4 — Low | Minor violations | Report-triggered | Warning + edit required | ``` ### 4. Reporting **🔴 load-bearing** When and how users flag content, plus confidentiality and anti-abuse. The "independent, objective review" and "false reports actioned" lines keep the process credible. ```text Section 4 theme={"system"} 4. Reporting 4.1 When to Report - Content or behavior violating this Policy's content standards. - Critical violations involving child safety or terrorism. - AI impersonation or infringement of your own rights. - [Other situations the Platform deems reportable.] 4.2 Reporting Principles - Confidentiality: reporter identity is strictly protected. - Impartiality: all reports receive independent, objective review. - Anti-abuse: malicious or false reports are recorded and actioned. ``` ### 5. Reporting Channels **🔴 load-bearing** At least one real, monitored channel — list only what you can staff. One real channel beats five unstaffed ones. ```text Section 5 theme={"system"} 5. Reporting Channels Retain the options that apply: - Dedicated report email: [report@yourplatform.com] - Online report form: [https://yourplatform.com/report] - In-product report button: [e.g., Content page → ··· → Report] - Customer support: [live chat or support email] - Emergency contact (critical): [hotline or instant-messaging channel, if applicable] ``` ### 6. Response & Processing Timelines **🟡 strongly recommended** Response/resolution windows by severity. Be realistic — you'll be held to them. Keep L1 fast (hours, not days); child-safety and terrorism content can't sit in a queue. ```text Section 6 theme={"system"} 6. Response & Processing Timelines | Violation Type | Initial Response | Resolution | |---|---|---| | L1 — Critical | Within 2 hours | Within 24 hours | | L2 — High | Within 24 hours | Within 3 business days | | L3 — Medium | Within 3 business days | Within 7 business days | | L4 — Low | Within 5 business days | Within 15 business days | If extended processing is required, we will notify the reporter proactively with reasons. Processing workflow: received (auto-acknowledge) → triage (classify L1–L4) → review (auto + human) → decision → enforcement → notification. ``` ### 7. Enforcement Actions **🔴 load-bearing** The escalation ladder from warning to permanent ban to legal referral. List only actions you can actually take — if you can't suspend at the account level, describe what you can do instead. ```text Section 7 theme={"system"} 7. Enforcement Actions | Action | Measure | Applies to | |---|---|---| | 1. Warning | Written notice requiring removal or edit | First-time minor violation | | 2. Content removal | Violating content taken down | Confirmed L3–L4 | | 3. Feature restriction | Reduced quota or model access | Repeat minor or single L3 | | 4. Account suspension | Temporary suspension pending review | L2 or cumulative violations | | 5. Permanent ban | Permanent termination of access | L1 or repeat L2 | | 6. Legal action | Report to authorities; cooperate with investigation | Criminal-level L1 | ``` ### 8. Appeals **🟡 strongly recommended** A second look by someone uninvolved in the original decision. The "independent reviewer" line is the point — appeals reviewed by the same person who made the call aren't appeals. ```text Section 8 theme={"system"} 8. Appeals You may appeal an enforcement decision within [specify days] of receiving notice: - Appeal channel: [appeal@yourplatform.com] - Timeline: [e.g., reviewed within 10 business days]. - Review method: reviewed by a reviewer independent of the original decision. ``` ### 9. Transparency & Policy Updates **⚪ optional** Optional reporting cadence plus a change-notice window. The transparency report is optional; the change-notice window is good practice. ```text Section 9 theme={"system"} 9. Transparency & Policy Updates - We publish a content-safety transparency report every [specify period]. - Material changes are notified at least [e.g., 15] days in advance. - Continued use of the Platform constitutes acceptance of updates. ``` ### 10. Contact Us **🔴 load-bearing** Real safety/report/appeal inboxes. Every channel you list is one you're committing to monitor. ```text Section 10 theme={"system"} 10. Contact Us - Safety Email: [safety@yourplatform.com] - Report Email: [report@yourplatform.com] - Appeal Email: [appeal@yourplatform.com] - Company Name: [full legal name] - Address: [registered address] ``` > [!TIP] > > Publish the AUP at a stable URL and link it from your product (footer, signup, and the report button). Reference it from Section 10 of your [Terms of Service](/mor/account-reviews/tos) so the two documents point at each other. # Privacy Policy Template Source: https://docs.waffo.ai/mor/account-reviews/privacy-policy A drop-in privacy policy for Pancake merchants — GDPR/CCPA-aware, ready to localize A complete, regulation-aware privacy policy for Pancake merchants. Fill in your details, replace the bracketed placeholders, publish — and link it from your checkout and your Terms of Service. > [!WARNING] > > This is a template, not legal advice. Privacy law varies by market — have a qualified professional review it before publishing if your jurisdiction or data practices are unusual. ## Before you publish 🔴 items are legally load-bearing. 🟡 items materially reduce your privacy risk. **1. 🔴 Must be done** * Data controller filled in — legal company name, registered address, privacy contact email * Every category of data you actually collect is listed (delete rows you don't use; add ones you do) * Payment processor named: **`Waffo Pancake`** — card data is processed by Pancake, not stored on your servers * "We do not sell your personal information" kept if true (it's true for most Pancake merchants) * Retention periods filled in with real numbers * Children's minimum age set to match your market (13 / 16 / 18) * The policy is linked from checkout and referenced by your Terms of Service `[privacy policy URL]` **2. 🟡 Strongly recommended** * Analytics tools named, each linked to its own privacy policy * International-transfer safeguards declared if your servers or vendors are cross-border (SCCs, adequacy, BCRs) * A real opt-out path for marketing (unsubscribe link + account toggle), separate from essential service notices * Breach-notification timeframe stated (e.g., 72 hours) **3. Final pass** * Every `[placeholder]` replaced with real text * "Last Updated" date filled in * Optional blocks (location, third-party login, platform/API data sharing) kept only if they apply > [!NOTE] > > **Keep it in sync with your T\&C.** Section 11 of the [Terms of Service template](/mor/account-reviews/tos) links to this policy by URL — publish this one first, then paste its URL into the T\&C. ## Template Copy the block below and replace every `[placeholder]` with your real text. Delete any row or section that doesn't apply to your product. > [!NOTE] > > The template is in English. Translate or localize as your market requires — the legal substance should stay the same. ```text Privacy Policy (replace every [placeholder]) theme={"system"} [Legal Name] Privacy Policy Last Updated: [DATE] [Legal Name] ("we," "us," or "our") is committed to protecting your privacy. This Privacy Policy ("Policy") explains how we collect, use, store, and share your personal information when you use [Product / Service Name] (the "Service"), and the rights available to you. Please read this Policy carefully before using the Service. By using the Service, you agree to this Policy. We may update this Policy periodically and will notify you of material changes via [notification method, e.g., email or in-product notice]. 1. Data Controller The data controller for this Service is: - Company Name: [full legal company name] - Registered Address: [business registration address] - Privacy Email: [privacy@yourcompany.com] - Data Protection Officer (DPO): [name / contact, or "Not applicable"] 2. Personal Information We Collect 2.1 Information You Provide Directly - Account Info: name, email, password (stored encrypted), [other registration fields]. - Payment Info: transaction amount and payment status. Full card numbers are not stored by us — card data is processed by our payment processor (see Section 5). - Communications: emails, support tickets, and feedback you send us. - [Other business-specific fields, e.g., delivery address, business license.] 2.2 Information We Collect Automatically - Device & Network: IP address, device model, operating system, browser type, time zone. - Usage Data: pages visited, feature usage, activity logs, session duration. - Log Data: request timestamps, error logs, performance metrics. - [Other business-specific data, e.g., search history, playback records.] [Optional] - Location: collected with your authorization, for [describe purpose]. - Third-Party Login: basic profile information shared by [WeChat / Google / etc.] when you sign in through them. 3. How We Use Your Information | Purpose | Legal Basis | |---|---| | Service delivery & maintenance | Contract performance | | Billing & payment processing | Contract performance | | Customer support | Contract / Legitimate interests | | Service notifications (billing, security, policy) | Legitimate interests | | Security & fraud prevention | Legitimate interests | | Product analytics & improvement | Legitimate interests | | Legal compliance | Legal obligation | | Marketing — [describe content] (optional) | Your consent | We may aggregate or anonymize data for statistical purposes. Such data cannot be linked to any individual. 4. Cookies & Tracking Technologies | Type | Purpose | Disableable | |---|---|---| | Strictly necessary | Login sessions, core functionality | No | | Functional | Language preferences, personalization | Yes | | Analytics | Anonymous usage stats, product optimization | Yes | | Marketing (optional) | Targeted ads and effectiveness measurement | Yes | Analytics tools in use: [list tools and link to their privacy policies, e.g., Google Analytics]. You can manage your preferences via your browser settings or our Cookie Preference Center. 5. Sharing & Disclosure We do not sell your personal information, including as defined under applicable laws such as the CCPA. We share your information only in the following circumstances: - Service Providers: cloud, payment, support, and analytics vendors, bound by confidentiality. Payment card data is processed exclusively by our PCI-DSS certified payment processor, [Waffo Pancake], and is not stored on our servers. - Business Partners: [if applicable, describe partner type and data scope; otherwise delete]. - Legal Requirements: where required by law, court order, or a lawful regulatory request. - Business Transactions: in a merger, acquisition, or similar event, with advance notice and continued protections. - With Your Consent: for any other purpose, with your explicit prior consent. [Optional: For platform businesses, add a note on data sharing with counterparties. For third-party API integrations, describe the data flow to those providers.] 6. Data Security - Encryption in transit: TLS / HTTPS. - Secure storage: passwords and sensitive data are encrypted or hashed. - Access controls: least-privilege principle; staff sign confidentiality agreements. - Regular security audits and vulnerability assessments. - [Additional measures, e.g., ISO 27001, SOC 2.] In the event of a security incident affecting your rights, we will notify you and the relevant authorities within [timeframe, e.g., 72 hours of discovery] as required by law. Please keep your credentials secure and do not share them. 7. Data Retention | Data Type | Retention Period | Upon Expiry | |---|---|---| | Account information | While active; [X] years after deletion | Delete or anonymize | | Transaction records | Per regulations, typically [X] years | Delete or archive | | Support records | [X] years | Secure deletion | | Security audit logs | [X] months | Secure deletion | | [Other data type] | [period] | [method] | 8. Your Data Rights To exercise any right below, contact us; we respond within [e.g., 30 calendar days]. | Right | Description | |---|---| | Right to be informed | Know what data we collect and how we use it | | Right of access | Obtain a copy of your personal information | | Right to rectification | Correct inaccurate or incomplete data | | Right to erasure | Request deletion under certain conditions | | Right to restrict processing | Temporarily suspend processing in certain cases | | Right to data portability | Receive your data in a machine-readable format | | Right to object | Object to processing based on legitimate interests or marketing | | Right to withdraw consent | Withdraw consent for consent-based processing | You may also lodge a complaint with your local data protection authority. 9. Marketing & Opt-Out With your consent, we may send marketing communications about [describe content types] via email, SMS, or in-app notifications. You can opt out at any time: click "Unsubscribe" in any email, disable marketing in your account settings, or contact us. Opting out does not affect essential service notifications (e.g., billing, security alerts). 10. International Data Transfers Our servers and partners may be located in [list regions, e.g., Singapore, the United States]. For international transfers, we safeguard your data through: - Data processing agreements incorporating EU Standard Contractual Clauses (SCCs). - Transfers only to recipients with an equivalent level of protection. - [Other safeguards, e.g., adequacy decisions, BCRs.] 11. Children's Privacy The Service is intended for users aged [13 / 16 / 18] and above. We do not knowingly collect information from children below that age. If you believe your child has provided information, contact us immediately and we will promptly delete it. 12. Third-Party Links & Services The Service may include links to, or integrations with, third-party services. This Policy applies only to data we directly collect. We are not responsible for third-party privacy practices and encourage you to review their policies before use. 13. Policy Changes For material changes, we will provide at least [X, e.g., 15] days' advance notice via platform announcement or your registered email, and update the "Last Updated" date at the top of this page. Continued use after the effective date constitutes acceptance. 14. Contact Us - Privacy Email: [privacy@yourcompany.com] - Support Email: [support@yourcompany.com] - Company Name: [full legal name] - Mailing Address: [postal address] - Business Hours: [e.g., Mon–Fri, 09:00–18:00 UTC+8] This Privacy Policy is for general reference only and does not constitute legal advice. We strongly recommend having it reviewed by a qualified legal professional in your target market before publication. [Legal Name] · [Website URL] ``` ## Section-by-section reference Each section below shows its **tier** (🔴 load-bearing · 🟡 strongly recommended · ⚪ optional), a one-line summary, and the matching **template snippet** so you can read the guidance and copy that block together. ### 1. Data Controller **🔴 load-bearing** Names the legal entity responsible for the data — a brand name alone won't do. Fill `[full legal company name]`, `[registered address]`, `[privacy@yourcompany.com]`. DPO only applies to large-scale or sensitive processing; otherwise write "Not applicable." ```text Section 1 theme={"system"} 1. Data Controller The data controller for this Service is: - Company Name: [full legal company name] - Registered Address: [business registration address] - Privacy Email: [privacy@yourcompany.com] - Data Protection Officer (DPO): [name / contact, or "Not applicable"] ``` ### 2. Personal Information We Collect **🔴 load-bearing** List only what you actually collect — over-claiming creates obligations you can't meet. Delete categories you don't use, add ones you do. Keep the line that card numbers are **not** stored by you. Drop the optional block unless location or third-party login apply. ```text Section 2 theme={"system"} 2. Personal Information We Collect 2.1 Information You Provide Directly - Account Info: name, email, password (stored encrypted), [other registration fields]. - Payment Info: transaction amount and payment status. Full card numbers are not stored by us — card data is processed by our payment processor (see Section 5). - Communications: emails, support tickets, and feedback you send us. - [Other business-specific fields, e.g., delivery address, business license.] 2.2 Information We Collect Automatically - Device & Network: IP address, device model, operating system, browser type, time zone. - Usage Data: pages visited, feature usage, activity logs, session duration. - Log Data: request timestamps, error logs, performance metrics. - [Other business-specific data, e.g., search history, playback records.] [Optional] - Location: collected with your authorization, for [describe purpose]. - Third-Party Login: basic profile information shared by [WeChat / Google / etc.] when you sign in through them. ``` ### 3. How We Use Your Information **🔴 load-bearing** Each purpose is paired with a legal basis (GDPR Art. 6) — keep the pairing, it's what regulators check. If you do marketing, "Your consent" is the basis, which means a real opt-in. ```text Section 3 theme={"system"} 3. How We Use Your Information | Purpose | Legal Basis | |---|---| | Service delivery & maintenance | Contract performance | | Billing & payment processing | Contract performance | | Customer support | Contract / Legitimate interests | | Service notifications (billing, security, policy) | Legitimate interests | | Security & fraud prevention | Legitimate interests | | Product analytics & improvement | Legitimate interests | | Legal compliance | Legal obligation | | Marketing — [describe content] (optional) | Your consent | We may aggregate or anonymize data for statistical purposes. Such data cannot be linked to any individual. ``` ### 4. Cookies & Tracking Technologies **🟡 strongly recommended** Disclose tracking. Strictly-necessary cookies can't be disabled; everything else must be. Name your analytics tools and link each to its own policy; marketing pixels go in the "Marketing" row. ```text Section 4 theme={"system"} 4. Cookies & Tracking Technologies | Type | Purpose | Disableable | |---|---|---| | Strictly necessary | Login sessions, core functionality | No | | Functional | Language preferences, personalization | Yes | | Analytics | Anonymous usage stats, product optimization | Yes | | Marketing (optional) | Targeted ads and effectiveness measurement | Yes | Analytics tools in use: [list tools and link to their privacy policies, e.g., Google Analytics]. You can manage your preferences via your browser settings or our Cookie Preference Center. ``` ### 5. Sharing & Disclosure **🔴 load-bearing** "We don't sell" plus a named processor. For Pancake merchants the payment-processor line is the important one: **`Waffo Pancake`** is your PCI-DSS processor and card data never touches your servers. Keep "we do not sell" only if it's true. ```text Section 5 theme={"system"} 5. Sharing & Disclosure We do not sell your personal information, including as defined under applicable laws such as the CCPA. We share your information only in the following circumstances: - Service Providers: cloud, payment, support, and analytics vendors, bound by confidentiality. Payment card data is processed exclusively by our PCI-DSS certified payment processor, [Waffo Pancake], and is not stored on our servers. - Business Partners: [if applicable, describe partner type and data scope; otherwise delete]. - Legal Requirements: where required by law, court order, or a lawful regulatory request. - Business Transactions: in a merger, acquisition, or similar event, with advance notice and continued protections. - With Your Consent: for any other purpose, with your explicit prior consent. [Optional: For platform businesses, add a note on data sharing with counterparties. For third-party API integrations, describe the data flow to those providers.] ``` ### 6. Data Security **🔴 load-bearing** Concrete measures plus a breach-notification window. List what you actually do; the 72-hour window (the GDPR reference point) signals you have an incident process. ```text Section 6 theme={"system"} 6. Data Security - Encryption in transit: TLS / HTTPS. - Secure storage: passwords and sensitive data are encrypted or hashed. - Access controls: least-privilege principle; staff sign confidentiality agreements. - Regular security audits and vulnerability assessments. - [Additional measures, e.g., ISO 27001, SOC 2.] In the event of a security incident affecting your rights, we will notify you and the relevant authorities within [timeframe, e.g., 72 hours of discovery] as required by law. Please keep your credentials secure and do not share them. ``` ### 7. Data Retention **🔴 load-bearing** How long, then what happens. Vague "as long as necessary" is weak — give numbers. Tie transaction-record retention to your tax/accounting obligations, not a guess. ```text Section 7 theme={"system"} 7. Data Retention | Data Type | Retention Period | Upon Expiry | |---|---|---| | Account information | While active; [X] years after deletion | Delete or anonymize | | Transaction records | Per regulations, typically [X] years | Delete or archive | | Support records | [X] years | Secure deletion | | Security audit logs | [X] months | Secure deletion | | [Other data type] | [period] | [method] | ``` ### 8. Your Data Rights **🔴 load-bearing** The eight GDPR rights, how to exercise them, and the DPA complaint route. Fill the response window (`[30 calendar days]` is the GDPR default) and make sure the privacy email in Section 14 routes these requests to someone. ```text Section 8 theme={"system"} 8. Your Data Rights To exercise any right below, contact us; we respond within [e.g., 30 calendar days]. | Right | Description | |---|---| | Right to be informed | Know what data we collect and how we use it | | Right of access | Obtain a copy of your personal information | | Right to rectification | Correct inaccurate or incomplete data | | Right to erasure | Request deletion under certain conditions | | Right to restrict processing | Temporarily suspend processing in certain cases | | Right to data portability | Receive your data in a machine-readable format | | Right to object | Object to processing based on legitimate interests or marketing | | Right to withdraw consent | Withdraw consent for consent-based processing | You may also lodge a complaint with your local data protection authority. ``` ### 9. Marketing & Opt-Out **🟡 strongly recommended** Consent in, easy opt-out, and a clear line between marketing and essential notices. Keep billing and security notices outside the opt-out. ```text Section 9 theme={"system"} 9. Marketing & Opt-Out With your consent, we may send marketing communications about [describe content types] via email, SMS, or in-app notifications. You can opt out at any time: click "Unsubscribe" in any email, disable marketing in your account settings, or contact us. Opting out does not affect essential service notifications (e.g., billing, security alerts). ``` ### 10. International Data Transfers **🟡 strongly recommended** Only needed if data crosses borders. Name the safeguard — SCCs cover most cases. ```text Section 10 theme={"system"} 10. International Data Transfers Our servers and partners may be located in [list regions, e.g., Singapore, the United States]. For international transfers, we safeguard your data through: - Data processing agreements incorporating EU Standard Contractual Clauses (SCCs). - Transfers only to recipients with an equivalent level of protection. - [Other safeguards, e.g., adequacy decisions, BCRs.] ``` ### 11. Children's Privacy **🔴 load-bearing** Set the minimum age for your market and don't knowingly collect below it (13 US/COPPA, 16 default GDPR, varies by member state). ```text Section 11 theme={"system"} 11. Children's Privacy The Service is intended for users aged [13 / 16 / 18] and above. We do not knowingly collect information from children below that age. If you believe your child has provided information, contact us immediately and we will promptly delete it. ``` ### 12. Third-Party Links & Services **⚪ optional** Disclaims responsibility for sites and services you don't control. ```text Section 12 theme={"system"} 12. Third-Party Links & Services The Service may include links to, or integrations with, third-party services. This Policy applies only to data we directly collect. We are not responsible for third-party privacy practices and encourage you to review their policies before use. ``` ### 13. Policy Changes **🔴 load-bearing** Advance-notice window plus updating the date. 15 days is a reasonable default. ```text Section 13 theme={"system"} 13. Policy Changes For material changes, we will provide at least [X, e.g., 15] days' advance notice via platform announcement or your registered email, and update the "Last Updated" date at the top of this page. Continued use after the effective date constitutes acceptance. ``` ### 14. Contact Us **🔴 load-bearing** Real, monitored channels. The privacy email here is where rights requests land — make sure someone reads it. ```text Section 14 theme={"system"} 14. Contact Us - Privacy Email: [privacy@yourcompany.com] - Support Email: [support@yourcompany.com] - Company Name: [full legal name] - Mailing Address: [postal address] - Business Hours: [e.g., Mon–Fri, 09:00–18:00 UTC+8] ``` > [!TIP] > > Publish the privacy policy at a stable URL, then paste that URL into Section 11 of your [Terms of Service](/mor/account-reviews/tos) and into your checkout. Keep a version log with effective dates so you can prove what was live at any past point. # Terms of Service Template Source: https://docs.waffo.ai/mor/account-reviews/tos A drop-in T&C for Pancake merchants — covers Subscription, Credits, and Hybrid billing A complete, card-network-compliant Terms of Service for Pancake merchants. Pick your billing model, replace the bracketed placeholders, publish. > [!WARNING] > > This is a template, not legal advice. Have a lawyer review before publishing if your jurisdiction or business model is unusual. ## Pick your billing model Each model maps to its own billing-specific block (sections 4–7) further down. Pick the card that matches how you charge — it jumps straight to the matching block. > **[V1 — Subscription](#v1-subscription-sections-4-7)** > > Monthly or yearly recurring. Auto-renews until canceled. > **[V2 — Credits](#v2-credits-sections-4-7)** > > Buy credit packs and spend them. Optional auto top-up. > **[V3 — Hybrid](#v3-hybrid-sections-4-7)** > > A plan with credits **and** extra packs sold separately. ## Before you publish 🔴 items are what wins or loses disputes. 🟡 items materially strengthen your defense. **1. 🔴 Must be done** * Legal name filled in (company: legal entity + registered address; individual / sole trader: legal name only — no business address needed) * Recurring / auto-top-up authorization in place (if you charge automatically) * In-product cancel flow exists (not email-only) * Refund policy filled in **and** shown at checkout * Third-party AI providers declared (if you use them) * Prohibited-uses list matches your actual product * Payment processor named: **`Waffo Pancake`** * Every contact channel listed is real and monitored **2. 🟡 Strongly recommended** * Billing descriptor set so customers recognize the name on their card statement — the #1 chargeback cause is "I don't recognize this charge" * Annual subscribers get a renewal reminder \~7 days out * Free-trial users get a "trial converting" reminder \~7 days out * V2/V3 — credits-about-to-expire reminder **3. Final pass** * Every `[placeholder]` is replaced with real text * Version number and effective date filled in * V3 — picked one option from each of the three refund choices * Deleted the sections that don't apply (V1 users remove V2/V3 blocks, etc.) > [!NOTE] > > **On the refund policy display:** in Pancake, save the refund policy in your store settings — the checkout picks it up automatically. You don't need to keep two copies in sync. ## Template Copy the **common sections** below, then pick the **billing-specific block** that matches your model and slot it in between Section 3 and Section 8. Replace every `[placeholder]` with your real text. > [!NOTE] > > The template is in English. Translate or localize as your market requires. ### Common — sections 1–3 and 8–16 ```text Sections 1–3 & 8–16 (use in every version) theme={"system"} [LEGAL NAME] Terms of Service — AI-Powered Services 1. Introduction & Acceptance of Terms Welcome to [Legal Name] ("[Legal Name]" / "we" / "us" / "our"). [Pick the line that fits you and delete the other:] [If a company:] a company incorporated under the laws of [Country/Region] with its registered address at [Legal Registered Address]. [If an individual / sole trader:] an individual / sole trader operating under the laws of [Country/Region]. These Terms of Service ("Terms") govern your access to and use of our AI-powered services, including [Brief service description], available at [Website URL] (the "Service"). By creating an account, subscribing to any plan, purchasing credits, or otherwise using the Service, you confirm that you: (a) are at least 18 years of age; (b) have read, understood, and agree to be bound by these Terms; (c) agree to our Privacy Policy; and (d) are authorized to enter into this agreement on behalf of yourself or any organization you represent. ⚠️ Important: If you do not agree to these Terms, you may not use the Service. Continued use after any update constitutes acceptance of the revised Terms. 2. Service Description 2.1 What We Provide [Legal Name] provides an AI-powered platform that enables users to [describe core functionality]. The Service is a digital software-as-a-service (SaaS) product delivered via the internet. 2.2 Nature of the Service The Service is a digital, intangible product. Upon confirmed payment, access is granted immediately. Due to the immediate digital delivery, specific limitations apply to refunds as described in Section 7. 2.3 AI Model Dependency (optional) [Optional: Our Service utilizes third-party AI model providers including [e.g., OpenAI, Anthropic, Google]. Service performance and availability may be affected by the operational status of these providers. We will endeavor to communicate significant disruptions in a timely manner.] 3. Account Registration & Eligibility 3.1 Account Creation To use the Service, you must create an account with accurate and complete information. You are responsible for maintaining the confidentiality of your login credentials and for all activities under your account. 3.2 Account Security - Notify us immediately of any unauthorized use at [security@company.com]. - Do not share your credentials with any third party. - Keep your billing email address up to date. 3.3 Business Accounts If you register on behalf of a company or organization, you represent that you have authority to bind that entity to these Terms. [INSERT SECTIONS 4–7 FROM THE V1 / V2 / V3 BLOCK MATCHING YOUR BILLING MODEL] 8. Billing Disputes If you believe there is an error in a charge, please contact us at [billing@company.com] before disputing with your bank. We commit to responding within 2 business days and resolving confirmed billing errors within 5 business days. 9. AI Output & Intellectual Property 9.1 Ownership of Outputs Subject to these Terms, AI-generated content produced in response to your inputs ("Outputs") is owned by you. You may use Outputs for any lawful purpose consistent with Section 10. 9.2 Input License By submitting content to the Service ("Inputs"), you grant [Legal Name] a limited, non-exclusive license to process your Inputs solely to deliver the Service. We do not use your Inputs to train AI models without your explicit consent. 9.3 Third-party AI Model Dependency (if applicable) [Include if applicable] Our Service uses third-party AI model providers including [e.g., OpenAI, Anthropic, Google]. Outputs may be influenced by these providers' models. We do not guarantee specific output quality and accept no liability for outputs generated by third-party models. 9.4 Accuracy of AI Outputs AI-generated content may contain errors or inaccuracies. You are solely responsible for reviewing and verifying Outputs before relying on them. 10. Acceptable Use Policy 10.1 Permitted Uses You may use the Service only for lawful purposes in accordance with these Terms. 10.2 Prohibited Uses You agree NOT to use the Service to: - Generate content that is illegal, defamatory, harassing, or fraudulent. - Generate, distribute, or facilitate deepfake content — including AI-synthesized audio, video, or images — that impersonates real individuals or is intended to deceive viewers about its origin or authenticity. - Generate content that sexualizes minors or violates child protection laws. - Produce malware, phishing content, or cyberattack tools. - Infringe the intellectual property or privacy rights of any third party. - Circumvent or interfere with security features of the Service. - Resell or sub-license access to the Service without prior written approval. - Violate any applicable law, regulation, or card network rule. 10.3 AI-Specific Prohibitions In addition to the general prohibitions above, given the AI-powered nature of the Service, you specifically agree NOT to: - Use Service inputs, outputs, model responses, or any derivative thereof to train, fine-tune, benchmark, distil, or otherwise develop any artificial intelligence or machine learning model that competes, directly or indirectly, with the Service or [Legal Name]'s products. - Systematically scrape, extract, or harvest model outputs at scale for purposes other than your own authorised use of the Service. - Represent AI-generated outputs as the work of a human professional (e.g., a licensed doctor, lawyer, or financial adviser) in contexts where such misrepresentation could cause harm. 11. Data, Privacy & Security Your use of the Service is governed by our Privacy Policy at [privacy policy URL]. Payment card data is processed exclusively by our PCI-DSS certified payment processor (Waffo Pancake) and is not stored on our servers. Account data is retained for [90] days following cancellation, then deleted. 12. Disclaimers & Limitation of Liability 12.1 Disclaimer of Warranties THE SERVICE IS PROVIDED "AS IS" AND "AS AVAILABLE" WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR ACCURACY OF AI OUTPUTS. 12.2 AI-Generated Content Disclaimer ⚠️ AI GENERATED CONTENT DISCLAIMER Outputs may be inaccurate, incomplete, or outdated. Do not rely on them for legal, medical, financial, or other professional advice. Always verify AI-generated content with a qualified professional before acting on it. 12.3 Limitation of Liability TO THE MAXIMUM EXTENT PERMITTED BY LAW, [LEGAL NAME] SHALL NOT BE LIABLE FOR ANY INDIRECT, INCIDENTAL, CONSEQUENTIAL, OR PUNITIVE DAMAGES. OUR TOTAL LIABILITY SHALL NOT EXCEED THE AMOUNT YOU PAID IN THE [12] MONTHS PRECEDING THE EVENT GIVING RISE TO THE CLAIM. 13. Term & Termination These Terms remain effective while you use the Service. We may suspend or terminate your account if you materially breach these Terms, we suspect fraudulent activity, or as required by law. If we terminate for reasons other than your breach, we will provide a pro-rated refund for any unused prepaid period. You may delete your account at any time by contacting [support@company.com]. 14. Governing Law & Dispute Resolution These Terms are governed by the laws of [Country / State / Region]. Before initiating any formal proceedings, please contact us at [legal@company.com] to attempt informal resolution. [Optional: Any unresolved dispute shall be submitted to binding arbitration in [City] under the rules of [Arbitration Body].] 15. General Provisions We may update these Terms at any time. Material changes will be notified by email at least [14] days before the effective date. Continued use constitutes acceptance. If any provision is found unenforceable, the remainder continues in full effect. 16. Contact Information For any questions about these Terms or billing, please contact us: - General Support: [support@company.com] - Billing: [billing@company.com] - Refunds: [refunds@company.com] - Cancel Subscription: [cancel@company.com] or Account Settings - Legal & Privacy: [legal@company.com] - Security: [security@company.com] - Phone: [+X-XXX-XXX-XXXX] - Mailing Address: [Legal Name], [Street Address], [City, Country] By using the Service or checking "I agree" at checkout, you acknowledge and agree to these Terms. Last Updated: [DATE] · [Legal Name] · [Website URL] ``` ### Billing-specific — sections 4–7 Pick the one block that matches your billing model and slot it between Section 3 and Section 8. Delete the other two. #### V1 — Subscription ```text V1 — Subscription (sections 4–7) theme={"system"} 4. Subscription Plans (V1) We offer subscription plans for access to the Service. [Describe subscription plans briefly, e.g.: We offer monthly and annual subscription plans.] For current plan details and pricing, please visit [pricing URL]. We reserve the right to modify plan features or introduce new plans at any time. Price changes are governed by Section 5.1. 5. Billing & Payment (V1) 5.1 Recurring Billing Authorization By providing your payment method and subscribing to a paid plan, you expressly authorize [Legal Name] to charge your payment method on a recurring basis for the applicable subscription fee. This recurring authorization remains in effect until you cancel in accordance with Section 6. Your subscription renews automatically at the end of each billing period unless cancelled. We will send you advance notice before the renewal of any annual subscription. 5.2 Taxes Prices are exclusive of applicable taxes (including VAT, GST, sales tax, or similar) unless otherwise stated. Where required by applicable law, we will collect and remit such taxes. 6. Cancellation Policy (V1) 6.1 How to Cancel You may cancel your subscription at any time through: - Online (recommended): Account Settings → Subscription → Cancel Subscription - Email: Send a cancellation request from your registered email to [cancel@company.com] Cancellation takes effect immediately. A confirmation email will be sent within [10] minutes. 6.2 Effect of Cancellation - Your subscription remains active until the end of the current billing period. - You will not be charged for subsequent billing periods. - Account data is retained for [90] days after cancellation, then deleted per our Privacy Policy. 7. Refund Policy (V1) 7.1 General Policy Due to the immediate and intangible nature of our digital services, subscription fees are generally non-refundable, except as expressly stated below. 7.2 Eligible Refunds - New subscriber 7-day guarantee: A full refund is available to first-time subscribers within 7 days of the initial charge, provided usage has not exceeded [X]% of the plan quota. - Duplicate charge: A full refund for any billing error resulting in a duplicate charge. - Verified service outage (≥72 hrs): A pro-rated credit or refund for extended outages within our control. - Statutory rights: If applicable law grants withdrawal or refund rights (e.g., 14-day withdrawal right in EU/UK), those rights are preserved. 7.3 How to Request a Refund To request a refund, contact us at [refunds@company.com] with your account email, transaction ID, and reason. We will acknowledge within 2 business days and process eligible refunds within 5–10 business days. 7.4 Non-Refundable Items - Fees for subscription periods already used (except as noted in 7.2). - Annual subscription fees requested after [30] days from initial purchase. - Accounts terminated for violation of these Terms or the Acceptable Use Policy. ``` #### V2 — Credits / Top-up ```text V2 — Credits / Top-up (sections 4–7) theme={"system"} 4. Credits & Top-up Plans (V2) The Service operates on a credit-based system. [Describe credit plans briefly, e.g.: Users may purchase credit packages at any time.] Credits are used to access Service features. For available credit packages and current pricing, please visit [pricing URL]. 5. Billing & Payment (V2) 5.1 Single Purchase Authorization Each credit purchase is a one-time transaction. By completing a purchase, you authorize [Legal Name] to charge your payment method for the amount displayed at checkout. 5.2 Auto Top-up Authorization (if enabled) [Optional — include ONLY if your product offers automatic top-up] If you choose to enable the Auto Top-up feature, you authorize [Legal Name] to automatically charge your saved payment method when your credit balance falls below the threshold you have set, at the amount you have configured in your Account Settings. You may disable Auto Top-up at any time. 5.3 Taxes Prices are exclusive of applicable taxes unless otherwise stated. Where required by law, applicable taxes will be collected at checkout. 6. Credits Validity & Account Termination (V2) 6.1 Credits Validity Purchased credits are valid for [X] months/years from the date of purchase, unless otherwise stated at the time of purchase. We will send you a reminder notification before your credits expire. 6.2 Termination of Account If your account is terminated (by you or by us), unused credits will be retained for [X] days following termination. After this period, unused credits expire without refund unless otherwise required by applicable law. 7. Refund Policy (V2) All credit purchases are generally non-refundable after credits have been consumed. The following exceptions apply: - Unused credits within 7 days of purchase: A full refund may be requested within 7 days of purchase if credits have not been used. - Duplicate charge: Full refund for any billing error. - Statutory rights (EU/UK/AU): 14-day withdrawal right for first-time purchasers is preserved, waived upon first use. To request a refund, contact [refunds@company.com] with your account email and transaction ID. ``` #### V3 — Hybrid ```text V3 — Hybrid (sections 4–7) theme={"system"} 4. Plans & Credits (V3) We offer both subscription plans and credit packages. [Describe subscription plans briefly.] [Describe credit packages briefly.] For current plan details and pricing, please visit [pricing URL]. 5. Billing & Payment (V3) 5.1 Subscription Recurring Billing Authorization By subscribing to a paid plan, you expressly authorize [Legal Name] to charge your payment method on a recurring basis for the applicable subscription fee until you cancel per Section 6. 5.2 Credit Purchase Authorization Each credit purchase is a one-time transaction authorized at checkout. 5.3 Auto Top-up Authorization (if enabled) [Optional — include ONLY if your product offers auto top-up] If you enable Auto Top-up, you authorize [Legal Name] to automatically charge your payment method when your credit balance falls below your configured threshold, at the amount configured in your Account Settings. You may disable this at any time. 5.4 Taxes Prices are exclusive of applicable taxes unless otherwise stated. 6. Cancellation Policy (V3) You may cancel your subscription at any time via Account Settings → Subscription → Cancel, or by emailing [cancel@company.com]. Cancellation takes effect at the end of the current billing period. Credits purchased separately are not cancelled and remain subject to their validity period. 7. Refund Policy (V3) 7.1 Subscription Refunds - 7-day guarantee for first-time subscribers: Full refund if usage has not exceeded [X]% of plan quota. - Duplicate charge or service failure (≥72 hrs): Eligible for refund or credit. 7.2 Credits Refunds - Unused credits within 7 days of purchase: Eligible for full refund. - Used credits are non-refundable. 7.3 Subscription Plan Credits — Rollover Policy (pick one, delete the other) [Option A1 — No rollover] Credits included in a subscription plan expire at the end of each billing period and do not carry over to the next period. [Option A2 — Rollover] Credits included in a subscription plan accumulate across billing periods and do not expire as long as your subscription remains active (subject to a maximum balance limit specified in your plan). 7.4 Credits After Subscription Cancellation (pick one, delete the others) [Option B1] Separately purchased credits retain their original validity period regardless of subscription status. [Option B2] After subscription cancellation, separately purchased credits remain usable for [X] days. [Option B3] After subscription cancellation, separately purchased credits become immediately unavailable; a refund will be issued for any unused balance in accordance with Section 7.2. 7.5 Credit Consumption Order (pick one, delete the other) [Option C1] When both subscription plan credits and separately purchased credits are available, subscription plan credits are consumed first. [Option C2] When both subscription plan credits and separately purchased credits are available, separately purchased credits are consumed first. ``` ## Section-by-section reference Each section shows its **tier** (🔴 load-bearing · 🟡 strongly recommended · ⚪ optional), a one-line summary, and the matching **template snippet**. Sections 4–7 vary by billing model — pick the one block (V1, V2, or V3) that matches how you charge. ### 1. Introduction & Acceptance **🔴 load-bearing** Names the seller — a company gives its legal entity + registered address; a sole trader / individual gives their legal name only, no business address needed. A brand name alone won't do. Fill `[Legal Name]`, `[Country/Region]`, `[Brief service description]`, `[Website URL]`; companies also fill `[Legal Registered Address]`. ```text Section 1 (common) theme={"system"} [LEGAL NAME] Terms of Service — AI-Powered Services 1. Introduction & Acceptance of Terms Welcome to [Legal Name] ("[Legal Name]" / "we" / "us" / "our"). [Pick the line that fits you and delete the other:] [If a company:] a company incorporated under the laws of [Country/Region] with its registered address at [Legal Registered Address]. [If an individual / sole trader:] an individual / sole trader operating under the laws of [Country/Region]. These Terms of Service ("Terms") govern your access to and use of our AI-powered services, including [Brief service description], available at [Website URL] (the "Service"). By creating an account, subscribing to any plan, purchasing credits, or otherwise using the Service, you confirm that you: (a) are at least 18 years of age; (b) have read, understood, and agree to be bound by these Terms; (c) agree to our Privacy Policy; and (d) are authorized to enter into this agreement on behalf of yourself or any organization you represent. ⚠️ Important: If you do not agree to these Terms, you may not use the Service. Continued use after any update constitutes acceptance of the revised Terms. ``` ### 2. Service Description **🔴 load-bearing** "Digital SaaS, delivered immediately on payment" — the line that pushes back when customers claim non-delivery. Fill `[Legal Name]`, `[describe core functionality]`. Keep 2.3 only if you depend on third-party AI providers. ```text Section 2 (common) theme={"system"} 2. Service Description 2.1 What We Provide [Legal Name] provides an AI-powered platform that enables users to [describe core functionality]. The Service is a digital software-as-a-service (SaaS) product delivered via the internet. 2.2 Nature of the Service The Service is a digital, intangible product. Upon confirmed payment, access is granted immediately. Due to the immediate digital delivery, specific limitations apply to refunds as described in Section 7. 2.3 AI Model Dependency (optional) [Optional: Our Service utilizes third-party AI model providers including [e.g., OpenAI, Anthropic, Google]. Service performance and availability may be affected by the operational status of these providers. We will endeavor to communicate significant disruptions in a timely manner.] ``` ### 3. Account Registration & Eligibility **🔴 load-bearing** Establishes that the account holder is responsible — blocks "someone else used my login." Fill `[security@company.com]`. ```text Section 3 (common) theme={"system"} 3. Account Registration & Eligibility 3.1 Account Creation To use the Service, you must create an account with accurate and complete information. You are responsible for maintaining the confidentiality of your login credentials and for all activities under your account. 3.2 Account Security - Notify us immediately of any unauthorized use at [security@company.com]. - Do not share your credentials with any third party. - Keep your billing email address up to date. 3.3 Business Accounts If you register on behalf of a company or organization, you represent that you have authority to bind that entity to these Terms. ``` ### 4–7. Billing block — V1 Subscription **🔴 load-bearing** Plans, recurring authorization, in-product cancel, and refund policy for recurring subscriptions. Section 5.1 is the clause card networks care about most — the customer must **explicitly** authorize recurring charges. Don't go with "no refunds"; at minimum give first-time buyers 7 days. Prices stay on your pricing page, not here. ```text V1 — Subscription (sections 4–7) theme={"system"} 4. Subscription Plans (V1) We offer subscription plans for access to the Service. [Describe subscription plans briefly, e.g.: We offer monthly and annual subscription plans.] For current plan details and pricing, please visit [pricing URL]. We reserve the right to modify plan features or introduce new plans at any time. Price changes are governed by Section 5.1. 5. Billing & Payment (V1) 5.1 Recurring Billing Authorization By providing your payment method and subscribing to a paid plan, you expressly authorize [Legal Name] to charge your payment method on a recurring basis for the applicable subscription fee. This recurring authorization remains in effect until you cancel in accordance with Section 6. Your subscription renews automatically at the end of each billing period unless cancelled. We will send you advance notice before the renewal of any annual subscription. 5.2 Taxes Prices are exclusive of applicable taxes (including VAT, GST, sales tax, or similar) unless otherwise stated. Where required by applicable law, we will collect and remit such taxes. 6. Cancellation Policy (V1) 6.1 How to Cancel You may cancel your subscription at any time through: - Online (recommended): Account Settings → Subscription → Cancel Subscription - Email: Send a cancellation request from your registered email to [cancel@company.com] Cancellation takes effect immediately. A confirmation email will be sent within [10] minutes. 6.2 Effect of Cancellation - Your subscription remains active until the end of the current billing period. - You will not be charged for subsequent billing periods. - Account data is retained for [90] days after cancellation, then deleted per our Privacy Policy. 7. Refund Policy (V1) 7.1 General Policy Due to the immediate and intangible nature of our digital services, subscription fees are generally non-refundable, except as expressly stated below. 7.2 Eligible Refunds - New subscriber 7-day guarantee: A full refund is available to first-time subscribers within 7 days of the initial charge, provided usage has not exceeded [X]% of the plan quota. - Duplicate charge: A full refund for any billing error resulting in a duplicate charge. - Verified service outage (≥72 hrs): A pro-rated credit or refund for extended outages within our control. - Statutory rights: If applicable law grants withdrawal or refund rights (e.g., 14-day withdrawal right in EU/UK), those rights are preserved. 7.3 How to Request a Refund To request a refund, contact us at [refunds@company.com] with your account email, transaction ID, and reason. We will acknowledge within 2 business days and process eligible refunds within 5–10 business days. 7.4 Non-Refundable Items - Fees for subscription periods already used (except as noted in 7.2). - Annual subscription fees requested after [30] days from initial purchase. - Accounts terminated for violation of these Terms or the Acceptable Use Policy. ``` ### 4–7. Billing block — V2 Credits / Top-up **🔴 load-bearing** Credit packs, one-time purchase authorization, validity, and refunds. Include 5.2 only if you offer auto top-up. State explicitly that consumed credits are non-refundable; allow a 7-day refund on untouched credits. ```text V2 — Credits / Top-up (sections 4–7) theme={"system"} 4. Credits & Top-up Plans (V2) The Service operates on a credit-based system. [Describe credit plans briefly, e.g.: Users may purchase credit packages at any time.] Credits are used to access Service features. For available credit packages and current pricing, please visit [pricing URL]. 5. Billing & Payment (V2) 5.1 Single Purchase Authorization Each credit purchase is a one-time transaction. By completing a purchase, you authorize [Legal Name] to charge your payment method for the amount displayed at checkout. 5.2 Auto Top-up Authorization (if enabled) [Optional — include ONLY if your product offers automatic top-up] If you choose to enable the Auto Top-up feature, you authorize [Legal Name] to automatically charge your saved payment method when your credit balance falls below the threshold you have set, at the amount you have configured in your Account Settings. You may disable Auto Top-up at any time. 5.3 Taxes Prices are exclusive of applicable taxes unless otherwise stated. Where required by law, applicable taxes will be collected at checkout. 6. Credits Validity & Account Termination (V2) 6.1 Credits Validity Purchased credits are valid for [X] months/years from the date of purchase, unless otherwise stated at the time of purchase. We will send you a reminder notification before your credits expire. 6.2 Termination of Account If your account is terminated (by you or by us), unused credits will be retained for [X] days following termination. After this period, unused credits expire without refund unless otherwise required by applicable law. 7. Refund Policy (V2) All credit purchases are generally non-refundable after credits have been consumed. The following exceptions apply: - Unused credits within 7 days of purchase: A full refund may be requested within 7 days of purchase if credits have not been used. - Duplicate charge: Full refund for any billing error. - Statutory rights (EU/UK/AU): 14-day withdrawal right for first-time purchasers is preserved, waived upon first use. To request a refund, contact [refunds@company.com] with your account email and transaction ID. ``` ### 4–7. Billing block — V3 Hybrid **🔴 load-bearing** Subscription **plus** separately-sold credits. Combines recurring and one-time authorization. Refund section 7.3/7.4/7.5 has three picks (rollover, post-cancellation validity, consumption order) — choose one option each and delete the rest. Explain your choice on your help center too. ```text V3 — Hybrid (sections 4–7) theme={"system"} 4. Plans & Credits (V3) We offer both subscription plans and credit packages. [Describe subscription plans briefly.] [Describe credit packages briefly.] For current plan details and pricing, please visit [pricing URL]. 5. Billing & Payment (V3) 5.1 Subscription Recurring Billing Authorization By subscribing to a paid plan, you expressly authorize [Legal Name] to charge your payment method on a recurring basis for the applicable subscription fee until you cancel per Section 6. 5.2 Credit Purchase Authorization Each credit purchase is a one-time transaction authorized at checkout. 5.3 Auto Top-up Authorization (if enabled) [Optional — include ONLY if your product offers auto top-up] If you enable Auto Top-up, you authorize [Legal Name] to automatically charge your payment method when your credit balance falls below your configured threshold, at the amount configured in your Account Settings. You may disable this at any time. 5.4 Taxes Prices are exclusive of applicable taxes unless otherwise stated. 6. Cancellation Policy (V3) You may cancel your subscription at any time via Account Settings → Subscription → Cancel, or by emailing [cancel@company.com]. Cancellation takes effect at the end of the current billing period. Credits purchased separately are not cancelled and remain subject to their validity period. 7. Refund Policy (V3) 7.1 Subscription Refunds - 7-day guarantee for first-time subscribers: Full refund if usage has not exceeded [X]% of plan quota. - Duplicate charge or service failure (≥72 hrs): Eligible for refund or credit. 7.2 Credits Refunds - Unused credits within 7 days of purchase: Eligible for full refund. - Used credits are non-refundable. 7.3 Subscription Plan Credits — Rollover Policy (pick one, delete the other) [Option A1 — No rollover] Credits included in a subscription plan expire at the end of each billing period and do not carry over to the next period. [Option A2 — Rollover] Credits included in a subscription plan accumulate across billing periods and do not expire as long as your subscription remains active (subject to a maximum balance limit specified in your plan). 7.4 Credits After Subscription Cancellation (pick one, delete the others) [Option B1] Separately purchased credits retain their original validity period regardless of subscription status. [Option B2] After subscription cancellation, separately purchased credits remain usable for [X] days. [Option B3] After subscription cancellation, separately purchased credits become immediately unavailable; a refund will be issued for any unused balance in accordance with Section 7.2. 7.5 Credit Consumption Order (pick one, delete the other) [Option C1] When both subscription plan credits and separately purchased credits are available, subscription plan credits are consumed first. [Option C2] When both subscription plan credits and separately purchased credits are available, separately purchased credits are consumed first. ``` ### 8. Billing Disputes **🔴 load-bearing** Where customers reach you before going to their bank. Fill `[billing@company.com]`. ```text Section 8 (common) theme={"system"} 8. Billing Disputes If you believe there is an error in a charge, please contact us at [billing@company.com] before disputing with your bank. We commit to responding within 2 business days and resolving confirmed billing errors within 5 business days. ``` ### 9. AI Output & Intellectual Property (if you ship AI) **🔴 load-bearing** Customer owns outputs; you have a limited license to process inputs; you don't train on inputs without consent. Fill `[Legal Name]` in 9.2; add 9.3 if you use OpenAI / Anthropic / Google or similar. ```text Section 9 (common) theme={"system"} 9. AI Output & Intellectual Property 9.1 Ownership of Outputs Subject to these Terms, AI-generated content produced in response to your inputs ("Outputs") is owned by you. You may use Outputs for any lawful purpose consistent with Section 10. 9.2 Input License By submitting content to the Service ("Inputs"), you grant [Legal Name] a limited, non-exclusive license to process your Inputs solely to deliver the Service. We do not use your Inputs to train AI models without your explicit consent. 9.3 Third-party AI Model Dependency (if applicable) [Include if applicable] Our Service uses third-party AI model providers including [e.g., OpenAI, Anthropic, Google]. Outputs may be influenced by these providers' models. We do not guarantee specific output quality and accept no liability for outputs generated by third-party models. 9.4 Accuracy of AI Outputs AI-generated content may contain errors or inaccuracies. You are solely responsible for reviewing and verifying Outputs before relying on them. ``` ### 10. Acceptable Use Policy **🔴 load-bearing** What customers can't do, including AI-specific prohibitions (no competing models, no deepfakes, no impersonating professionals). No placeholders — read the list and make sure it covers your product. For a fuller content policy, pair this with the [AUP template](/mor/account-reviews/aup). ```text Section 10 (common) theme={"system"} 10. Acceptable Use Policy 10.1 Permitted Uses You may use the Service only for lawful purposes in accordance with these Terms. 10.2 Prohibited Uses You agree NOT to use the Service to: - Generate content that is illegal, defamatory, harassing, or fraudulent. - Generate, distribute, or facilitate deepfake content — including AI-synthesized audio, video, or images — that impersonates real individuals or is intended to deceive viewers about its origin or authenticity. - Generate content that sexualizes minors or violates child protection laws. - Produce malware, phishing content, or cyberattack tools. - Infringe the intellectual property or privacy rights of any third party. - Circumvent or interfere with security features of the Service. - Resell or sub-license access to the Service without prior written approval. - Violate any applicable law, regulation, or card network rule. 10.3 AI-Specific Prohibitions In addition to the general prohibitions above, given the AI-powered nature of the Service, you specifically agree NOT to: - Use Service inputs, outputs, model responses, or any derivative thereof to train, fine-tune, benchmark, distil, or otherwise develop any artificial intelligence or machine learning model that competes, directly or indirectly, with the Service or [Legal Name]'s products. - Systematically scrape, extract, or harvest model outputs at scale for purposes other than your own authorised use of the Service. - Represent AI-generated outputs as the work of a human professional (e.g., a licensed doctor, lawyer, or financial adviser) in contexts where such misrepresentation could cause harm. ``` ### 11. Data, Privacy & Security **🔴 load-bearing** PCI-DSS handling plus a privacy-policy link. **Pancake merchants: name `Waffo Pancake` as the processor.** Fill `[privacy policy URL]` (point it at your published [privacy policy](/mor/account-reviews/privacy-policy)) and `[90] days`. ```text Section 11 (common) theme={"system"} 11. Data, Privacy & Security Your use of the Service is governed by our Privacy Policy at [privacy policy URL]. Payment card data is processed exclusively by our PCI-DSS certified payment processor (Waffo Pancake) and is not stored on our servers. Account data is retained for [90] days following cancellation, then deleted. ``` ### 12. Disclaimers & Limitation of Liability **🔴 load-bearing** As-is disclaimer + AI-output disclaimer + a 12-month liability cap. Fill `[LEGAL NAME]` (all caps) and `[12] months`. Keep §12.2 — it's the clause that protects you when customers act on AI output and lose money. ```text Section 12 (common) theme={"system"} 12. Disclaimers & Limitation of Liability 12.1 Disclaimer of Warranties THE SERVICE IS PROVIDED "AS IS" AND "AS AVAILABLE" WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR ACCURACY OF AI OUTPUTS. 12.2 AI-Generated Content Disclaimer ⚠️ AI GENERATED CONTENT DISCLAIMER Outputs may be inaccurate, incomplete, or outdated. Do not rely on them for legal, medical, financial, or other professional advice. Always verify AI-generated content with a qualified professional before acting on it. 12.3 Limitation of Liability TO THE MAXIMUM EXTENT PERMITTED BY LAW, [LEGAL NAME] SHALL NOT BE LIABLE FOR ANY INDIRECT, INCIDENTAL, CONSEQUENTIAL, OR PUNITIVE DAMAGES. OUR TOTAL LIABILITY SHALL NOT EXCEED THE AMOUNT YOU PAID IN THE [12] MONTHS PRECEDING THE EVENT GIVING RISE TO THE CLAIM. ``` ### 13. Term & Termination **🔴 load-bearing** When you can suspend, and how customers delete their account. Fill `[support@company.com]`. ```text Section 13 (common) theme={"system"} 13. Term & Termination These Terms remain effective while you use the Service. We may suspend or terminate your account if you materially breach these Terms, we suspect fraudulent activity, or as required by law. If we terminate for reasons other than your breach, we will provide a pro-rated refund for any unused prepaid period. You may delete your account at any time by contacting [support@company.com]. ``` ### 14. Governing Law & Dispute Resolution **⚪ optional** Jurisdiction + an optional arbitration clause. Fill `[Country / State / Region]` and `[legal@company.com]`. The arbitration sentence is optional — confirm with a lawyer if unsure. ```text Section 14 (common) theme={"system"} 14. Governing Law & Dispute Resolution These Terms are governed by the laws of [Country / State / Region]. Before initiating any formal proceedings, please contact us at [legal@company.com] to attempt informal resolution. [Optional: Any unresolved dispute shall be submitted to binding arbitration in [City] under the rules of [Arbitration Body].] ``` ### 15. General Provisions **🔴 load-bearing** Boilerplate with a 14-day minimum notice for terms changes. Fill `[14] days` (30 is friendlier). ```text Section 15 (common) theme={"system"} 15. General Provisions We may update these Terms at any time. Material changes will be notified by email at least [14] days before the effective date. Continued use constitutes acceptance. If any provision is found unenforceable, the remainder continues in full effect. ``` ### 16. Contact Information **🔴 load-bearing** Six channels by default. Better to list fewer real ones than six unmonitored — every channel here is checked during dispute handling. If you can only commit to one reliably, use it for every row. ```text Section 16 (common) theme={"system"} 16. Contact Information For any questions about these Terms or billing, please contact us: - General Support: [support@company.com] - Billing: [billing@company.com] - Refunds: [refunds@company.com] - Cancel Subscription: [cancel@company.com] or Account Settings - Legal & Privacy: [legal@company.com] - Security: [security@company.com] - Phone: [+X-XXX-XXX-XXXX] - Mailing Address: [Legal Name], [Street Address], [City, Country] By using the Service or checking "I agree" at checkout, you acknowledge and agree to these Terms. Last Updated: [DATE] · [Legal Name] · [Website URL] ``` > [!TIP] > > After publishing, store the T\&C URL, version number, and effective date together. When you change terms, notify existing users at least 14 days in advance — and keep a version log so you can prove what was active at any past point in time. # Chargebacks Source: https://docs.waffo.ai/mor/chargebacks What a chargeback is, how the money moves, and what you must do before the response deadline. > **A chargeback is not a refund** > > A refund is something you initiate. A chargeback is the cardholder going around you, straight to their bank — the funds are pulled from your balance whether you agree or not. *** ## What Is a Chargeback? A cardholder contacts their issuing bank and asks for their money back. The bank reverses the charge through the card network. You are not part of that conversation, and the funds move before anyone asks for your side of the story. | | Refund | Chargeback | | - | - | - | | Who starts it | You (or the customer, through you) | The cardholder, via their bank | | Your involvement | Full control | None until you are notified | | Cost | Principal only | Principal **plus** a \$25 chargeback fee | | Counts toward your chargeback rate | No | Yes | > [!NOTE] > > The \$25 chargeback fee is incurred the moment the issuer files the chargeback, regardless of how the case turns out. This fee is payable to the card networks, issuing banks, and acquirers. Waffo Pancake does not profit from such fees. We always do our best to avoid such occurrences. ### Why Cardholders File | Category | What happened | | - | - | | **True fraud** | The card was stolen or the number leaked. The cardholder genuinely never made the purchase. | | **Friendly fraud** | They did buy it, then regretted it — and told the bank they never bought anything. | | **Product issue** | Not delivered, delivered broken, or a subscription they tried and failed to cancel. | | **System error** | Double charge, or an amount that does not match what they agreed to. | *** ## Responding to a Chargeback **1. You are notified** Waffo Pancake notifies you by email. Case correspondence goes through [chargebacks@waffo.ai](mailto:chargebacks@waffo.ai). **2. Review the case and respond before the deadline** The notification email carries the case details. Confirm the case status and, above all, the **Expire Date** — accept or contest before that date. There is no extension. ### Your two options | | Accept the chargeback | Contest it | | - | - | - | | How | Reply to the chargeback notification email stating that you accept | Reply to the chargeback notification email with your evidence attached | | What you provide | Nothing | Transaction and order records, account usage logs, customer correspondence | | Extra cost | None | \$10.00 representment fee | | What Waffo Pancake does | Handles the downstream refund flow for you | Compiles your evidence and files it with the card network | | Outcome | Immediate — case closed against you | Decision in **75–180 days** | > [!WARNING] > > Do not process a refund yourself to "settle" a chargeback. The chargeback has already returned the money to the cardholder — a refund on top pays them twice and you absorb double the order value. Accepting is done by replying to the notification email. > [!WARNING] > > If a case passes its Expire Date with no action, it is automatically treated as forfeited. The funds are deducted from your settlement and there is no route to appeal. ### After you submit a defense Once your evidence reaches Waffo Pancake, we carry the case from there. You wait for the outcome. **1. We build the defense package** Waffo Pancake assembles your evidence and writes the rebuttal letter, formatted and argued the way the card network expects. **2. We file it with the channel** The package goes to the acquiring channel, which passes it to the issuer. **3. The issuer reviews** This is the slow step — a decision typically takes **75–180 days**. **Win** — the case closes and the \$100.00 principal returns to your balance. The \$35.00 in chargeback and representment fees does not, leaving a net of **−\$35.00**. **Lose** — the case escalates to pre-arbitration. **4. Pre-arbitration** Waffo Pancake keeps working the case with the channel. This stage adds a further \$25.00 pre-arbitration fee. **Win** — the case closes and the \$100.00 principal returns to your balance. The \$60.00 in chargeback, representment, and pre-arbitration fees does not, leaving a net of **−\$60.00**. Waffo Pancake updates you. **Lose, and you accept it** — the case ends here. It does not escalate, no arbitration fee is incurred, and your net is **−\$160.00**. **Lose, and you press on** — the case escalates to arbitration. Escalating is your decision, not a forced step. **5. Arbitration** The card network makes the final ruling. Waffo Pancake works this stage with the channel from start to finish and updates you when the case closes. The arbitration fee is **\$500.00, paid by the losing side** — deducted from your settlement if you lose. The network's ruling is final. There is no further appeal. > [!NOTE] > > The overwhelming majority of cases end at the issuer review step. Pre-arbitration and arbitration are reached by a small minority of disputes. None of the escalation requires action from you, but it does stretch the timeline considerably. *** ## How the Money Moves Take a \$100 order. > **Before the dispute** > > ``` > Customer pays +$100.00 > Processing fee −$4.40 > You receive ≈ $95.60 > ``` > > The processing fee is 3.9% + \$0.50. > **The moment it lands** > > ``` > Principal reversed −$100.00 > Chargeback fee −$25.00 > Net movement −$125.00 > ``` > > The bank pulls both out of your balance before any review. ### Then one of three endings Contesting adds a \$10.00 representment fee on top. Accepting does not. > **You accept** > > Principal: **−\$100.00** > > Chargeback fee: **−\$25.00** > > Representment fee: **—** > > **Net: −\$125.00** > > No contest, no representment fee. > **You contest and win** > > Principal returned: **+\$100.00** > > Chargeback fee: **−\$25.00** > > Representment fee: **−\$10.00** > > **Net: −\$35.00** > > You get the revenue back. Neither fee comes back. > **You contest and lose** > > Principal: **−\$100.00** > > Chargeback fee: **−\$25.00** > > Representment fee: **−\$10.00** > > Pre-arbitration fee: **−\$25.00** > > **Net: −\$160.00** > > Losing escalates the case to pre-arbitration, which carries its own fee. > [!NOTE] > > The \$25 chargeback fee is charged per case and is never refunded, regardless of outcome; a failed representment escalates the case to pre-arbitration, which adds a further \$25. Both of those and the \$500 arbitration fee are payable to the card networks, issuing banks, and acquirers. Waffo Pancake does not profit from such fees. The \$10 representment fee, by contrast, covers our own work: assembling your evidence, writing the rebuttal letter, and filing it with the channel. We always do our best to avoid such occurrences. *** ## Excessive Chargebacks > [!WARNING] > > To maintain the integrity of our platform and protect all users, Waffo Pancake may take action, including account suspension, if a store experiences an excessive number of chargebacks. *** ## FAQ > **How do I improve my win rate at the chargeback stage?** > > Your win rate depends on the quality and compliance of the evidence. The Waffo Pancake platform provides a structured evidence checklist based on the reason code. Make sure your evidence is clear, complete, and targeted (for example, signed proof of delivery and explicit transaction authorization records) so that it meets the issuer's review standard. A systematic process also avoids technical losses caused by missing the deadline or submitting the wrong format. > **Can chargeback fees be avoided?** > > Once the formal chargeback process starts, the fees charged by the issuer and the card network are generally non-refundable. The most effective cost control strategy is therefore proactive defense. > **How do I lower my chargeback rate?** > > Most chargebacks can be prevented before they happen. The goal is to make an unhappy customer **reach you before they reach their bank**. > > * **An obvious support contact** — put it on the checkout page, in the order confirmation email, and inside the product. Not buried in the footer. > * **A clear way to ask for a refund** — if a customer cannot find how to ask you for a refund, their next call is to the issuer. Tell them where to ask, somewhere they will actually find it. > * **A billing descriptor customers recognize** — the number one cause of chargebacks is "I don't recognize this charge." Use the brand name they remember, not your registered company name. > * **Product descriptions that match what is delivered** — a gap between the two turns into a "not as described" dispute. > * **Renewal reminders and a cancellation path that works** — tell subscribers before you charge them, and do not put obstacles in the cancellation flow. > * **Respond faster than the bank** — answer a complaint quickly and most problems resolve before a chargeback is ever filed. *** ## Platform Disputes (Not Chargebacks) Not every complaint goes through the card network. A customer can also raise a dispute **with Waffo Pancake directly** — through the Consumer Portal's **Report Issue** button or by writing to support. These are handled by our support team, not by the issuing bank, and they follow different rules: | | Platform dispute | Chargeback | | - | - | - | | Who opens it | Customer, via Consumer Portal or support email | Cardholder, via their bank | | How you are notified | Email from Waffo support with the customer's complaint | Chargeback notification email | | How you respond | **Reply All** to the notification email with your explanation and evidence | See [Responding to a Chargeback](#responding-to-a-chargeback) | | If the customer stops replying | The dispute is **closed automatically** after our follow-up goes unanswered | Deadline-driven; silence is a loss | | Fees | None | Chargeback fee applies even if you win | After you reply, nothing further is required on your side — we relay your response to the customer and close the case once it is resolved or the customer does not respond. If the customer rejects the outcome they may open a new dispute, or escalate to a chargeback with their bank. > [!NOTE] > > Disputes raised through **WeChat Pay** are handled inside WeChat's own dispute process. We forward the outcome to you; there is no separate response to file with Waffo Pancake. *** ## Related > **[Fees](/mor/fees)** > > Chargeback, representment, and pre-arbitration fees in full. > **[Payments](/dashboard/payments)** > > Where chargeback cases appear in your dashboard. # Fees Source: https://docs.waffo.ai/mor/fees 3.9% + $0.50 per successful transaction. > **3.9% + \$0.50 per successful transaction** > > No monthly fees. No setup costs. Pay only when you make sales. *** ## Fee Schedule ### Successful Transactions The rate depends on the payment method: | Payment method | Percentage | Fixed | | - | - | - | | Cards & digital wallets | 3.9% | \$0.50 | | WeChat Pay | 3.9% | — (no fixed fee) | **Example (card):** ``` Sale (tax inclusive): $100 Fee: $100 × 3.9% + $0.50 = $4.40 You receive: $95.60 ``` **Example (WeChat Pay):** ``` Sale (tax inclusive): $100 Fee: $100 × 3.9% = $3.90 You receive: $96.10 ``` *** ### Failed Transactions Failed transaction fees apply only to specific failure types. They are not cumulative. | Failure Type | Fee | Notes | | - | - | - | | Failed authentication (3DS) | \$0.30 / attempt | Card declined at the 3DS authentication stage | | Authentication passed but authorization failed | \$0.30 / attempt | Cleared 3DS but declined at authorization | | Did not reach authentication | \$0 | 3DS was never initiated — no fee charged | > [!NOTE] > > Failed transaction fees are charged per attempt, not per checkout session. Sessions that never trigger 3DS authentication are free. The fee shows up on the store's [Revenue](/dashboard/revenue) page as a **Failed transaction fee** row. *** ### Refunds The refund processing fee depends on the original order's payment method: | Payment method | Refund processing fee | | - | - | | Cards and digital wallets | \$1.00 per refund | | WeChat Pay | \$0 (free) | Refunds on card and digital wallet orders are charged \$1.00 per refund request. Refunds on WeChat Pay orders are free. For every payment method, the original transaction fee is not returned regardless of whether the refund is full or partial. *** ### Payouts | Item | Fee | | - | - | | Payout fee | 1% of payout amount | | Minimum fee | \$10.00 per payout request | Payout fees are charged per payout request, not per transaction. The minimum \$10.00 applies even if 1% of the payout amount is less than \$10. **Example:** ``` Payout: $500 Fee: $500 × 1% = $5.00 → minimum applies → $10.00 Pancake sends: $490.00 Payout: $2,000 Fee: $2,000 × 1% = $20.00 Pancake sends: $1,980.00 ``` > [!NOTE] > > The amount that actually lands in your account is determined by your receiving bank. Intermediary bank fees, FX conversion, and bank posting rules can create differences. *** ### Chargebacks | Event | Fee | | - | - | | First chargeback | \$25.00 | | Representment fee (contesting a chargeback) | \$10.00 | | Pre-arbitration | \$25.00 | > [!NOTE] > > The representment fee of \$10.00 is only charged if you opt in to contest the chargeback **and** we actually file on your behalf. See [Chargebacks](/mor/chargebacks) for the full flow and worked examples. > [!NOTE] > > The \$25.00 first chargeback fee and the \$25.00 pre-arbitration fee are payable to the card networks, issuing banks, and acquirers. Waffo Pancake does not profit from such fees. We always do our best to avoid such occurrences. The \$10.00 representment fee covers our own work assembling your evidence and filing the defense. *** ## What's Included All of the following are included at no additional charge: | Feature | Included | | - | - | | Payment processing | ✓ | | Global tax compliance | ✓ | | Tax calculation & collection | ✓ | | Tax remittance | ✓ | | All major card networks | ✓ | | Dashboard | ✓ | | Consumer Portal | ✓ | | Webhooks & API | ✓ | | Fraud protection | ✓ | *** ## Subscriptions with Trial Periods For 7-day trial subscriptions, the first billing cycle may result in a net loss of approximately \$0.50 — this covers the cost of a \$0 authorization check performed at trial start. *** ## vs Alternatives > [!NOTE] > > Competitor pricing is based on publicly available information and may change. FastSpring does not publish rates — pricing is negotiated directly. Always verify on their official pricing pages. | Provider | Transaction Fee | Monthly | | - | - | - | | **Waffo Pancake** | 3.9% + \$0.50 | \$0 | | Paddle | 5% + \$0.50 | \$0 | | Lemon Squeezy | 5% + \$0.50 | \$0 | | Gumroad | \~10% | \$0 | | FastSpring | Not published (contact sales) | \$0 | *** ## FAQ > **Are there minimum fees?** > > No monthly minimum. You only pay fees when transactions occur. > **What counts as a failed transaction fee?** > > Once 3DS authentication is triggered, \$0.30 / attempt applies — whether authentication itself fails or the card clears 3DS and then fails at authorization. Sessions that never reach authentication (customer leaves before 3DS) are free. > **Is the original transaction fee refunded when I issue a refund?** > > No. The original transaction fee is non-refundable. Refunds on card and digital wallet orders also incur a \$1.00 processing fee per refund request. Refunds on WeChat Pay orders are free. > **Subscription billing fees?** > > Same 3.9% + \$0.50 per successful renewal. No extra subscription management charges. # Prohibited & Restricted Products Source: https://docs.waffo.ai/mor/prohibited-products Categories that require additional review or are not permitted on Waffo Pancake. As a Merchant of Record, Waffo Pancake is responsible for every transaction processed through our platform. To maintain compliance with payment networks, financial regulations, and applicable laws, certain product and service categories are either restricted (accepted only under specific conditions) or prohibited entirely. > [!WARNING] > > Selling prohibited products will result in immediate account suspension and potential fund withholding. If you are unsure whether your product qualifies, contact support before listing. *** ## Digital delivery only Waffo Pancake supports **digitally delivered products and services only**. Two business models are outside what we can process, regardless of what is being sold: * Anything that requires shipping or other physical fulfillment * Anything whose substance is a person doing the work, including remotely Both are covered in [Prohibited Categories](#prohibited-categories) below, together with the exceptions that still qualify. *** ## Prohibited Categories The following categories are not permitted on Waffo Pancake under any circumstances, on any payment channel. An application rejected for a prohibited category cannot be appealed, and fixing the issue does not reopen it for resubmission. > **Child Sexual Abuse Material (Absolute Red Line)** > > * Any child sexual abuse or exploitation material (CSAM), including AI-generated or synthetic material > * Any product or service that sexualizes minors > > This is an absolute red line with no exceptions. > **Physical Goods & Logistics Fulfillment** > > We do not process payments for products that require shipping or any other physical fulfillment. This applies whatever the item is, and includes categories that were previously accepted under additional review: > > * Any product delivered by post, courier, or freight > * General e-commerce and online retail storefronts selling physical inventory > * Food, beverages, alcohol, and tobacco > * Luxury goods, jewelry, and collectibles > * Corrective contact lenses and other physical medical devices > * Live animals > * Printed books, physical media, and merchandise > > **Exception:** purely digital delivery is unaffected. Downloads, license keys, hosted software, and digital media remain eligible. > **Human-Delivered Services** > > Services whose substance is a person doing the work are not supported, whether delivered on site or remotely: > > * Video consultations, remote advisory, and paid one-to-one calls > * Online tutoring, live lessons, and remote coaching > * Tele-medicine and remote clinical services > * On-site services of any kind, including repairs, cleaning, and events > > **Exception:** software that only matches, books, or schedules human services is unaffected. The test is whether the buyer is paying for a person's time or for the software itself. > **Digital Top-Up & Resale Platforms** > > * Third-party game-card, game-currency, virtual-goods, and account top-up, recharge, or proxy-purchase services > * Opening or topping up official accounts and memberships for third-party AI services on someone else's behalf > * Prepaid code and gift-card resale > * Sale or loading of stored value cards > * Marketplaces that collect payments on behalf of third-party sellers > * eSIM and mobile data-plan sales or reseller services > **Live Social Audio & Streaming** > > * Multi-user live voice chat rooms > * One-to-one random voice or video matching with real people > * Live-streaming platforms with tipping, gifting, or paid interaction > > **Exception:** AI character chat products with no real people involved are unaffected — see the restricted categories below. > **Real-Person Deepfakes** > > Products whose core business is deepfaking real people — face swapping, "nudify" tools, compositing real people into intimate scenes, or making real people appear to say or do things they never said or did. These are not accepted whether or not the people involved consent. > > The four forms that count, and how each is judged, are in [AIGC Compliance: what counts as a deepfake](/mor/account-reviews/aigc-compliance#deepfake). > **Illegal Products & Services** > > Products or services that are illegal, facilitate illegal activity, or promote harm: > > * Controlled substances, narcotics, and drug paraphernalia > * Counterfeit identity documents, fake IDs, fraudulent credentials, and forged official or corporate seals and stamps > * Counterfeit currency > * Sale of bank accounts, payment credentials, or verified identities > * Telecommunications manipulation equipment (e.g., SIM cloners, call spoofing services) > * Content that promotes, glorifies, or incites violence or hatred, or that discriminates on the basis of race, sex, religion, national origin, physical ability, sexual orientation, or age > * Illegal political publications and programs, information that endangers national security or involves state secrets, and products or services that facilitate unlawful public gatherings > * Essay writing, plagiarism, and examination fraud services > * Human trafficking, organ trading, or any services facilitating the exploitation of persons > * Prescription drugs and medical devices sold without the required licensing or a valid prescription process > * Endangered species and products made from them > * Smuggled goods and unauthorized sales of duty-free goods > * Charities, political organizations, and religious organizations (payment collection via MoR is not appropriate for these entities) > * Debt collection services > * Selling, moving, or cashing out the proceeds of crime > **Attack Tooling & Intrusion Services** > > * Hacking services, intrusion for hire, and account takeover offerings > * Malware, ransomware, spyware, and exploit kits > * Stress-testing or "booter" services aimed at third-party infrastructure > * Reverse face search, covert people-tracing, and OSINT identity dossiers > **Intellectual Property Infringement** > > Products or services that violate intellectual property rights: > > * Unauthorized distribution of copyrighted media (films, music, books, software) > * Counterfeit goods — replicas or imitations misrepresenting brand or origin > * Illegal imports or exports of goods prohibited from cross-border trade > **Fraudulent Products & Services** > > Products or services designed to deceive consumers or exploit participants: > > * Pyramid schemes, multi-level marketing structured around recruitment fees > * Illegal fundraising and unlicensed deposit-taking > * Get-rich-quick schemes, guaranteed investment returns, or unrealistic income claims > * Predatory lending products with deceptive terms > * Services that sell or artificially inflate social media engagement (fake likes, followers, views, or reviews) > **Adult Content & Services** > > * Pornographic or sexually explicit content of any kind > * Prostitution, escort services, or any form of commercial sexual services > **Firearms & Dangerous Materials** > > * Firearms, handguns, rifles, and replica firearms, plus related accessories and modification parts > * Controlled knives and bladed weapons > * Ammunition, explosives, and the materials used to make them > * Toxic, hazardous, radioactive, or biological materials > * Any items regulated under arms control or export control laws > **Gambling** > > * Online casinos, poker, and all other forms of gambling, including gambling with cryptocurrency stakes > * Sports betting and betting agents, sports forecasting competitions with cash prizes > * Lotteries and sweepstakes where purchase is required for entry > **Crypto & Financial Services** > > * Any cryptocurrency business, including exchanges (licensed or not), market-data products, wallets, custody, and key-management products > * NFT marketplaces, mints, and NFT-based projects > * Initial Coin Offerings (ICOs) > * Mining hardware and mining equipment sales > * Stocks and securities, mutual funds, insurance, foreign exchange, and gold investment > * Investment, wealth management, and financial advisory services > * Lending, credit, and P2P lending > * Payment by instalments > * Money transfer and e-money services > * Financial trading software > * Crowdfunding platforms > **Misuse of Waffo Pancake** > > The following behaviors violate our platform policies and will result in immediate termination: > > * Creating accounts under a false identity or impersonating another individual or business > * Processing payments on behalf of an undisclosed third-party merchant > * Structuring transactions to avoid chargebacks, fraud detection, or reporting thresholds > * Distributing malware, ransomware, spyware, or any malicious software through the platform *** ## Restricted Categories These categories are accepted on Waffo Pancake, but require additional review and must meet specific conditions before you can begin selling. Contact our team to discuss your use case. Some of them also cannot be onboarded to certain payment methods — see [Payment Method Eligibility](#payment-method-eligibility). Whatever the category, if you sell subscriptions you must clearly disclose cancellation terms and get explicit customer consent for auto-renewal. | Category | Conditions & Notes | | - | - | | **Games** | **Skill Games**: Prizes must be disclosed clearly; age verification required where applicable **In-Game Virtual Items**: You must be the publisher or an authorized distributor. Third-party top-up and game-card resale platforms are prohibited. Must not facilitate unauthorized secondary markets **Digital Games (Vietnam)**: Must hold valid licensing approval from Vietnamese authorities; subject to additional review for Vietnam sales | | **AI Applications** | **AIGC (AI-Generated Content)**: Content must not infringe third-party IP; must include clear disclosure that content is AI-generated **AI Chat & Companion Apps**: Users must be talking to an AI character, with no live interaction with real people — see Live Social Audio & Streaming above Every AI application must integrate the Waffo content moderation API to screen user prompts — see [Content moderation API (Prompt Sift)](/mor/account-reviews/aigc-compliance#moderation-api) | | **Streaming & IPTV** | **Streaming Services**: Content must not include unauthorized copyrighted material; must comply with digital rights management obligations **IPTV**: Only licensed content distribution is permitted; unauthorized rebroadcasting of copyrighted channels is prohibited | | **Online Course Platforms** | Pre-recorded or otherwise digitally delivered course content only — live tutoring and coaching are not supported, see Human-Delivered Services above. Credentials and qualifications claimed must be accurate; refund policies must be clearly stated | | **Software Stores & VPN / VPS** | **Computer Software Stores**: All software sold must be properly licensed; no cracked, pirated, or key-reselling operations **VPN / VPS Services**: Must not be marketed for bypassing legal restrictions; acceptable use policies must be published | | **Advertising Networks & Ad Tech** | Applies when ad placement or brokerage is your core business — a site that merely displays ads alongside its own product is not affected | | **Divination & Fortune-Telling** | Astrology, Chinese astrology (BaZi, Zi Wei Dou Shu), tarot, name selection, fortune-telling, and feng shui services. Must be delivered as digital content, not as a live reading by a person | > [!NOTE] > > Approval for a restricted category does not guarantee ongoing eligibility. Waffo Pancake reserves the right to reassess accounts if business practices change or regulatory requirements are updated. *** ## Payment Method Eligibility Waffo Pancake settles through the following payment methods: | Payment method | Covers | | - | - | | **Card networks** | Visa and Mastercard | | **WeChat Pay** | One-time orders priced in USD or CNY — see [Payment methods](/payments/methods#wechat-pay) | | **Alipay** | One-time orders priced in USD or CNY — see [Payment methods](/payments/methods) | The card networks accept every category this page allows. Local payment methods have their own eligibility rules: if your business falls under a list below, your account can still go live — that payment method simply will not be enabled, and your customers pay another way instead. ### WeChat Pay In addition to the Prohibited Categories above, WeChat Pay does not onboard the following, however the product is presented: * **Skill games with any element of chance** — games that combine skill with chance, a draw, or a loot mechanic; purely skill-based games are unaffected * **AI chat and companion products built on real or photorealistic human likenesses** — fictional and anime characters are unaffected * **Divination, fortune-telling, and feng shui** — including tarot, Chinese astrology (BaZi, Zi Wei Dou Shu), astrology, name selection, and feng shui * **Advertising networks and ad tech** — where ad placement or brokerage is your core business ### Alipay Alipay eligibility follows the Alipay prohibited and restricted list. In addition to the Prohibited Categories above, Alipay does not onboard the following: * **Skill games with any element of chance** — games that combine skill with chance, a draw, or a loot mechanic; purely skill-based games are unaffected * **Rebate and cashback services** * **Lucky draws and auctions** — lucky-draw mechanics, and auction sites and services * **Online medical services** — medical consultation, hypnotherapy, plastic surgery, and the like, even when delivered digitally * **Video chat services** * **Religion and ancestor worship** — all religious websites, publications, and articles, as well as online cemeteries and ancestor-worship services * **Privacy and communications security** — decryption and descrambler products and services, devices that jam communications, products that infringe personal privacy or corporate data (such as monitoring online activity), sale of personal information, and espionage equipment * **Cashing out Alipay balances** — using an Alipay account to extract cash * **Invoice trading** — buying or selling invoices issued in mainland China * **Wallet and payment account top-ups** — transactions that fund an e-wallet or other payment account (POI funding) * **Other** — unlicensed event ticket sales, pawn services, real estate, mail-order spouse services, and airlines and air carriers *** ## Questions & Compliance This list is not exhaustive. Waffo Pancake may restrict additional categories based on evolving regulations, payment network requirements, or risk assessments. For the complete and legally binding terms, refer to the [Waffo Terms of Service](https://waffo.com/terms). > **[Account Reviews](/mor/account-reviews)** > > Learn about our merchant verification process. # Supported Countries Source: https://docs.waffo.ai/mor/supported-countries What payment methods buyers can use, and how merchants receive payouts ## Sell Globally Waffo Pancake handles tax, compliance, and refunds as your Merchant of Record across most countries. The lists below describe **what's live today** — additional payment methods and payout corridors are on the roadmap. *** ## Buyer Payment Methods The following payment methods are live for buyers worldwide. Available options at checkout depend on the buyer's device, region, and currency. | Method | Notes | | - | - | | Cards (Visa / Mastercard) | Available worldwide | | Apple Pay | iOS / macOS Safari, regions where Apple Pay is enabled | | Google Pay | Android / Chrome, regions where Google Pay is enabled | > **[Request a payment method](https://docs.google.com/forms/d/e/1FAIpQLSdJY9RDcUsUQ83bkUNWB_irQ0uFl4D_BhznFQ9p9cOhrKxK6A/viewform)** > > Need a regional method we don't list yet? Tell us which one and where you sell — submissions feed directly into our roadmap prioritization. *** ## Receive Payouts Waffo Pancake pays out to accounts in **mainland China, Hong Kong, the United States, Japan, South Korea and Singapore**, all currently settled in **USD**; if the receiving bank credits you in local currency, it converts at its rate on the day of arrival. > **Bank transfer** > > Bank accounts in mainland China, Hong Kong, the US, Japan, South Korea and Singapore — pick the bank from the channel's supported list. > **Alipay / PayNow** > > Alipay accounts in mainland China, and PayNow mobile numbers in Singapore. > [!TIP] > > Need another region or currency? Contact support and let us know which corridor you need so we can prioritize it. Field requirements per region are under [Payout Accounts](/merchant/payout-accounts). > **[Request a payout method](https://forms.gle/xKPbT3ZSTVy1sbBNA)** > > Need a payout channel or currency we don't list yet? Tell us which one and where you're based — submissions feed directly into our roadmap prioritization. *** ## Tax Compliance by Region We register and remit on behalf of merchants where required. Coverage depends on where you sell. ### United States * Sales tax in 45+ states * Nexus management * Automatic rate updates ### European Union * VAT registered * One-Stop Shop (OSS) * Digital services rules ### United Kingdom * UK VAT registered * Post-Brexit compliance ### Rest of World * Local compliance where required * Automatic threshold monitoring *** ## Unsupported Countries Due to international sanctions and compliance requirements, Waffo Pancake cannot process payments involving the following countries: | Code | Country | | - | - | | AFG | Afghanistan | | BDI | Burundi | | BLR | Belarus | | CAF | Central African Republic | | COD | Democratic Republic of the Congo | | CUB | Cuba | | GNB | Guinea-Bissau | | HTI | Haiti | | IRN | Iran | | IRQ | Iraq | | LBN | Lebanon | | LBY | Libya | | MLI | Mali | | MMR | Myanmar | | NIC | Nicaragua | | PRK | North Korea | | RUS | Russia | | SDN | Sudan | | SOM | Somalia | | SSD | South Sudan | | SYR | Syria | | YEM | Yemen | | ZWE | Zimbabwe | > [!WARNING] > > Transactions involving these countries — whether the consumer or merchant is located there — will be blocked. This list is subject to change based on evolving sanctions and compliance requirements. > [!NOTE] > > **Ukraine (Non-occupied Area)** is supported. Sanctions apply only to Russian-occupied territories within Ukraine, which are blocked at the territory level. *** ## Need Something Specific? > **[Request a Country or Payment Method](mailto:support@waffo.ai)** > > Tell us which corridor or local payment method matters to you and we'll prioritize it. # What is MoR? Source: https://docs.waffo.ai/mor/what-is-mor We're the seller. You focus on building. ## Merchant of Record = We Handle Everything A **Merchant of Record (MoR)** is the legal entity that sells to your customers. When you use Waffo Pancake, we become your MoR. > **We're the Seller** > > Legally, we sell to your customers. > **You Get Paid** > > Revenue goes to you. Minus fees. *** ## How It Works ``` Customer pays → Waffo Pancake → We handle taxes → You receive payout ↓ We're the legal seller We issue invoices We remit taxes ``` *** ## Without MoR vs With MoR ### Without MoR (DIY) **You're responsible for:** * Registering for taxes in every country * Calculating correct tax rates * Filing tax returns everywhere * Staying compliant with changing regulations * Handling audits and disputes ### With MoR (Waffo Pancake) **We handle:** * Global tax registration * Tax calculation and collection * Tax remittance * Regulatory updates * Audits and disputes **You focus on:** Building your product. *** ## Global Tax Complexity | Country | Tax | Rate | Complexity | | - | - | - | - | | USA | Sales Tax | 0-10%+ | 10,000+ jurisdictions | | EU | VAT | 17-27% | 27 countries, different rules | | UK | VAT | 20% | Post-Brexit rules | | Canada | GST/HST | 5-15% | Federal + provincial | | Australia | GST | 10% | Digital services rules | Without an MoR, you'd need to register, track, file, and manage compliance in every jurisdiction you sell to. *** ## Real Cost Comparison | Approach | Monthly Cost | Time | | - | - | - | | DIY Global Tax | \$2,000-15,000+ | 20+ hours/month | | Hire Tax Consultants | \$2,000-10,000 | 5-10 hours/month | | **Waffo Pancake** | Included in fees | 0 hours | *** ## What We Handle > **Tax Calculation** > > Real-time calculation based on: > > * Customer location > * Product type > * Local tax rules > * Exemptions and thresholds > **Tax Collection** > > Correct tax at checkout: > > * Inclusive or exclusive pricing > * Real-time rate updates > **Tax Remittance** > > We pay to authorities: > > * On-time filing > * Correct jurisdictions > * Proper documentation > **Payment Processing** > > * All major card networks + digital wallets > * Chargebacks and disputes > * Refunds > * Currency conversion *** ## MoR vs Payment Processor | Feature | Payment Processor | MoR | | - | - | - | | Processes payments | Yes | Yes | | Tax calculation | No | Yes | | Tax collection | No | Yes | | Tax remittance | No | Yes | | Legal seller | You | MoR | | Tax liability | You | MoR | > [!NOTE] > > Using just Stripe? You're still responsible for all tax obligations. With us, we handle everything. *** ## Benefits ### Solo Founders > **No LLC Required** > > Traditional MoRs require a legal entity. We don't. Get paid directly to your personal bank account. ### Startups > **Focus on Product** > > Don't spend engineering time on billing. Ship features instead. ### Growing Companies > **Scale Globally** > > Expand to new markets instantly. We're already compliant in 173 countries. *** ## FAQ > **Do customers see Waffo Pancake?** > > Customers see your brand on checkout. Invoices show us as legal seller (required for tax compliance), but feature your branding prominently. > **Can I use my own payment processor?** > > No. MoR model requires us to process payments. This is how we legally handle your tax obligations. > **Which countries do you support?** > > 173 countries. See the full list. > **[Supported Countries](/mor/supported-countries)** > > Full list of countries where you can sell. # Quickstart Source: https://docs.waffo.ai/quickstart Ship your first payment in 5 minutes ## Choose Your Starting Point > **AI Integration** > > **Fastest to ship** > > Best for teams with an existing codebase that want Claude Code or another coding agent to plan the model, implement the integration, and drive validation. > **API / SDK** > > **Most control** > > Best when you need custom checkout flows, server-side orchestration, dynamic pricing, or tighter control over integration behavior. > **Hosted Checkout** > > **Simplest** > > Best when you want to launch a payment link quickly first and deepen the integration later. *** ## Understand the Product Model In Waffo Pancake, a **product** is the billing object used for checkout and tax handling. It is not just a storefront card or SKU. | If you sell | Create in Waffo | Why | | - | - | - | | Fixed-price download, template, license | **One-time product** | Customer pays once for a predefined price | | Monthly or annual plan | **Subscription product** | Customer is billed on a recurring schedule | | Starter / Pro / Enterprise plans | **Multiple subscription products** | Each plan option is its own billable product | | Usage overage, credits top-up, negotiated quote | **One-time checkout with `priceSnapshot`** | The final amount is calculated at checkout time, so pricing stays dynamic | > [!NOTE] > > If your business is subscription-based, you may still create **one-time charges** for setup fees, add-ons, overage billing, or credit packs. That is expected behavior. *** ## Integrate with AI ### The Simple Version Tell your AI assistant: ```text theme={"system"} Read https://docs.waffo.ai/llms-full.txt, load the official Waffo Pancake skill from https://docs.waffo.ai/integrate/skill, and integrate Waffo Pancake payments into the current project. ``` That's it. The skill file contains everything your AI needs — API endpoints, SDK patterns, webhook handling, and best practices. ### The Full Version You can also describe your stack for a tailored integration: ```text theme={"system"} Read https://docs.waffo.ai/llms-full.txt, load the official Waffo Pancake skill from https://docs.waffo.ai/integrate/skill, and use Waffo Pancake SDK to integrate Waffo Pancake payments into the current project and run through the full checkout flow: 1. Get Merchant ID from Dashboard → API & Development → the "Create an API Key" section → first row above the key list → copy button (it is not at the top of the page) 2. Create an API Key from Dashboard → API & Development → the same section → Create Key 3. Use only `WAFFO_MERCHANT_ID` and `WAFFO_PRIVATE_KEY` as required env vars for the first working integration 4. Install @waffo/pancake-ts SDK 5. Create checkout and webhook endpoints 6. Test with card 4576750000000110 7. Verify webhook receives order.completed event Use test environment. My stack: [your stack — e.g., "Next.js with TypeScript"] ``` > **[AI Integration Guide](/integrate/ai-integration)** > > View the unified AI integration entry point for skill context, SDK patterns, code examples, catalog design, and dynamic pricing workflows. *** ## Ship Revenue in 5 Minutes No credit card required. No LLC needed. Just sign up and start selling. ![Get Started Steps](https://mintcdn.com/waffo/lzrM1_lBAlxHN0MS/images/get-started/get-started-steps.png?fit=max\&auto=format\&n=lzrM1_lBAlxHN0MS\&q=85\&s=4d471ca442ce1c7c13a3e554b933b789) *** ## 1. Create Account Visit [Merchant Dashboard](https://pancake.waffo.ai/merchant/auth/signin) and sign up with Google, GitHub, or Magic Link. > **[Merchant Dashboard](https://pancake.waffo.ai/merchant/auth/signin)** > > Sign up with Google, GitHub, or Magic Link — no credit card required. Three options: * **Google OAuth** — One click. Done. * **GitHub OAuth** — For developers. Quick and easy. * **Magic Link** — Email. Click link. In. *** ## 2. Create Store First login triggers store setup: | Field | What It Does | | - | - | | Store Name | Your brand name | > [!NOTE] > > No business registration required. Solo founders welcome. *** ## 3. Create Your First Product Dashboard → Products → **Create Product** ![Create Product Form](https://mintcdn.com/waffo/5dRlk76Jm-9Zm6Tj/images/get-started/create-product-form.png?fit=max\&auto=format\&n=5dRlk76Jm-9Zm6Tj\&q=85\&s=18e4852d38c241d836b9f344b005feb9) ```json theme={"system"} { "name": "Pro Monthly", "prices": { "USD": { "amount": "29.00", "taxIncluded": false, "taxCategory": "saas" } } } ``` For subscriptions, also set `billingPeriod` (`weekly`, `monthly`, `quarterly`, `yearly`). If your merchant account has multiple stores, confirm which store this product should belong to before creating it. If you offer multiple plans such as Starter / Pro / Enterprise: * Create **one subscription product per plan** * Start by defining the pricing and billing period for each plan clearly If you need dynamic pricing: * Create a base one-time product such as `Usage Overage` * Calculate the final amount on your server * Pass `priceSnapshot` when creating the checkout session > [!TIP] > > Think of the product catalog as your billing model: fixed-price products for standard offers, subscription products for recurring access, and `priceSnapshot` for runtime pricing. *** ## 4. Integrate Payments Product created? You get a checkout link to add to your website: ``` https://pancake.waffo.ai/store/{store-slug}/product/{productId} ``` Add it to your website's product page. Done. > [!NOTE] > > This link is permanent — it never expires and stays valid even when you update the product. Just click "Copy Link" in the Dashboard. *** ## 5. Get Paid Customer pays → We handle taxes → You receive payout. Funds go directly to your bank account. No intermediary. No delays. ![Merchant Finance — balance and payouts](https://mintcdn.com/waffo/ufjGfSwGi0IBOUvV/images/dashboard/merchant-finance.png?fit=max\&auto=format\&n=ufjGfSwGi0IBOUvV\&q=85\&s=a5b2bb4125eda58f6da8144e96714111) *** ## Test vs Live > **Test Mode** > > * No real charges > * Safe to experiment > * Separate test data > **Live Mode** > > * Real payments > * Real payouts > * Toggle when ready **Switch in Dashboard header.** Toggle via `X-Environment` header in API. Always test first. *** ## Test Cards ### Successful Payments | Card | Type | | - | - | | `4576 7500 0000 0110` | Visa Credit | | `2226 9000 0000 0110` | Mastercard Credit | | `4001 7000 0000 0110` | Visa Debit | | `2226 9300 0000 0110` | Mastercard Debit | ### Declined Payments | Card | Type | | - | - | | `4576 7500 0000 0220` | Visa Credit | | `2226 9000 0000 0220` | Mastercard Credit | | `4001 7000 0000 0220` | Visa Debit | | `2226 9300 0000 0220` | Mastercard Debit | Any future expiry. Any CVC. *** ## Going Live Checklist Before flipping to Live Mode: * [ ] Test checkout flow end-to-end * [ ] Verify webhook endpoints (if using) * [ ] Add a payout account (Payout Accounts page) * [ ] Complete business details (Settings → Business Details) * [ ] Review product pricing * [ ] Sync products from test to production * [ ] Switch your API Key to the production key * [ ] Switch your webhook signature public key to the production key > [!NOTE] > > Product IDs are identical in test and production, so the IDs in your code stay as they are. The two things that must change are the API Key and the webhook signature public key. *** ## What's Next? > **[Products](/features/products)** > > Pricing models. Trials. Intervals. > **[Subscriptions](/features/subscriptions)** > > Recurring billing. Dunning. Lifecycle. > **[Checkout](/features/checkout)** > > Your brand. Your colors. Our infra. > **[Integrations](/features/integrations)** > > API keys. Webhooks. Your backend. *** ## Need Help? > **[Join Discord](https://discord.gg/b7vw2NrKNa)** > > Community support. Fast answers. # Business Details Source: https://docs.waffo.ai/settings/business-details Complete the KYB review to enable production payments ## Why submit business details? As your Merchant of Record, Waffo Pancake needs a quick read on what you're selling so we can meet compliance requirements. Once reviewed, you unlock: * **Production payments** — accept real charges, not just test mode. * **Payouts** — funds settle into your bank account. * **Compliant invoices** — receipts carry the correct merchant information. > [!NOTE] > > You can build, test, and integrate everything in test mode without submitting business details. Submit only when you're ready to go live. *** ## Review flow **1. Fill in your details** In the dashboard, go to **Settings → Business Details** and complete the form. **2. Submit for review** Once everything looks right, submit. We run an automated risk check and queue it for review. **3. Wait for the result** Review usually completes within 1–3 business days. **4. Production unlocked** Once approved, the store flips to production mode automatically and you can accept real payments. *** ## What you'll fill in ### Product description | Field | Required | Notes | | - | - | - | | About your product | Yes | A short description of what you sell. | | Product website | Yes | The public URL where buyers see your product. | | Contact email | Yes | Used for review communication and as your store's support email. | ### Seller type Pick whichever fits — both pass review on the same merit. | Type | Notes | | - | - | | Individual / Solo developer | No company registration needed; operating as yourself. | | Registered business | A formally registered company or trade name. | > [!TIP] > > Both paths are fully supported and reviewed on the same merits. Pick whichever matches your current setup — solo developers and registered businesses both pass review when the rest of the submission checks out. ### Product status | Field | Required | Notes | | - | - | - | | Product readiness | Yes | Where the product is today — building, launched, etc. | | Existing customers | Yes | Whether you already have paying users. | ### Compliance acknowledgements You confirm that: * Your product is not in a [prohibited category](/mor/prohibited-products). * You've read and agreed to the account review policy. * Your pricing page is publicly accessible. * Your product doesn't infringe trademarks. *** ## Review outcomes | Status | Meaning | | - | - | | **Pending** | Submitted, waiting in queue. | | **In review** | Reviewer is looking at your submission. | | **Approved** | Production mode is now enabled. | | **Returned** | Some information needs adjustment — resubmit when corrected. | | **Rejected** | Doesn't meet requirements — the rejection reason is included. | > [!NOTE] > > On approval, your contact email becomes the store's support email and your product website becomes the store URL — both are written back automatically. *** ## FAQ > **Do I need a registered company to use Waffo Pancake?** > > No — both individuals and registered businesses are supported. Pick whichever fits your current setup; the review applies the same criteria to both. > **How long does review take?** > > 1–3 business days for typical submissions. More complex cases may take longer. > **What if my submission gets returned?** > > Read the return reason, adjust the relevant fields, and resubmit. You can resubmit as many times as you need. > **Will changing my details trigger another review?** > > Yes — edits after approval go through review again. Existing production functionality keeps working during the re-review. # Domain Verification Source: https://docs.waffo.ai/settings/domain-verification Prove ownership of your product website before submitting KYB ## Why we verify your domain Your website is the public face of your product. Before we approve KYB and enable production payments, we need to confirm that the domain you list as `Product website` actually belongs to you. Domain verification is a one-time step per store, and the binding stays in place after KYB approval. There are two entry points — both write to the same backend state, so verifying once is enough: * **Settings → General** — verify (or re-verify) your product domain at any time, independent of KYB. * **Settings → Business Details → Step 8 (Website URL)** — inline during KYB submission. The "Submit for review" button stays disabled until the domain on this step is verified. ## Verification methods Pancake offers four ways to verify a domain. Pick whichever your stack already supports — they are equivalent. | Method | Typical setup time | Best for | | - | - | - | | Email domain auto-match | Instant | Sites where the support email already lives on the same domain | | DNS TXT record | 5–30 min (DNS propagation) | Most websites; works on any host | | HTML `` tag | 1–2 min (deploy required) | Single-page apps and statically generated sites | | `.well-known` file | 1–2 min (deploy required) | Anything that can serve a static file | > [!NOTE] > > Pick **one** method. Once any method succeeds, the others stop being relevant for this domain. ## Method 1 — Email domain auto-match (recommended) If your support email is already verified in **Step 7 (Contact Email)** and lives on the same domain as your website, Pancake automatically detects this and shows a one-click **Verify domain** button. **Example.** Support email `support@acme.com` (verified) + Product website `https://acme.com` → auto-match available. 1. Click **Verify domain**. 2. Pancake validates the email/domain pair on the server. Verification completes immediately. If the support email is on a different domain (e.g. `team@gmail.com` while the site is `acme.com`), this option is hidden — use one of the manual methods below. ## Method 2 — DNS TXT record The most reliable method. You add a TXT record to the DNS zone for your domain. 1. In the dashboard, click **Use another method** → **DNS TXT**. 2. Pancake shows three values: * **Type**: `TXT` * **Host / Name**: `_waffo-challenge` (the dashboard strips the `.your-domain.com` suffix automatically — most providers prepend it for you) * **Value**: a one-time challenge string starting with `waffo-domain-verify=…` 3. Open your DNS provider's dashboard and add the record exactly as shown. Leave TTL at the default. 4. Wait for propagation. Most providers publish within minutes; some (Cloudflare, Route 53) are nearly instant. 5. Back in Pancake, click **I've added the record**. We query the public DNS for the TXT value and complete verification on success. > [!NOTE] > > You can leave the TXT record in place after verification. It does no harm. If you remove it, the existing binding is unaffected — we only re-check at verification time. ### Provider-specific notes | Provider | Where to add TXT records | | - | - | | Cloudflare | DNS → Records → Add record | | GoDaddy | My Products → DNS → Add → TXT | | Namecheap | Domain List → Manage → Advanced DNS → Add new record | | Route 53 | Hosted zones → your zone → Create record (Type = TXT) | | Google Domains | DNS → Custom records | If your provider expects a fully-qualified record name, use `_waffo-challenge.your-domain.com` instead of just `_waffo-challenge`. ## Method 3 — HTML `` tag Useful when you can't change DNS but you can deploy site code. 1. In the dashboard, click **Use another method** → **HTML meta tag**. 2. Pancake shows the snippet: ```html theme={"system"} ``` 3. Add it to the `` of your site's homepage (`https://your-domain.com/`). 4. Deploy. Verify the tag is present in the rendered HTML — view-source must include it; tags injected only after JS execution can fail if our crawler hits before hydration. If you're on a fully client-rendered SPA, prefer Method 2 or 4. 5. Back in Pancake, click **I've added the tag**. ## Method 4 — `.well-known` file Drop a static file under a fixed path. Works on any host that serves static assets. 1. In the dashboard, click **Use another method** → **.well-known file**. 2. Pancake shows: * **File URL**: `https://your-domain.com/.well-known/waffo-verify.txt` * **File contents**: a single line starting with `waffo-domain-verify=…` 3. Create the file at exactly that path. Make sure the response is `200 OK`, `Content-Type: text/plain` (or any text-like type), and the body is the challenge value with no extra whitespace. 4. Confirm in a browser that the URL returns the expected content. 5. Back in Pancake, click **I've uploaded the file**. > [!NOTE] > > Common mistake: deploying the file at `/.well-known/waffo-verify` (no extension) or returning a 301 redirect to `www.your-domain.com`. Both fail. Use the exact URL Pancake shows, served from the apex / canonical host you typed into the website field. ## Troubleshooting ### "Could not find the record / tag / file" Recheck the value. The challenge is generated per attempt; if you hit **Refresh** in Pancake, the previous value is invalidated. Make sure you copied the latest one. ### TXT record exists but verification still fails DNS caches. Try `dig TXT _waffo-challenge.your-domain.com` (Linux/macOS) or `nslookup -type=TXT _waffo-challenge.your-domain.com` (Windows). If the value isn't visible there yet, wait 5–10 minutes and retry. ### The challenge expired Each challenge has a short lifetime (the dashboard shows the exact time under the action button). If it expired, click **Refresh** in Pancake to issue a new one, then update your DNS / meta tag / file with the new value. ### I want to change my product website later Before KYB approval, you can revoke the current domain binding from **Step 8 (Website URL)** and re-verify a new one yourself. After KYB approval the domain is locked, because we reviewed your business against it: email support from your account email with your Merchant ID, the old domain and the new domain. We unbind the old one, and you then submit the new domain for review again. ## Programmatic / API access If you're verifying domains as part of an automated onboarding flow, the underlying endpoints are: | Endpoint | Purpose | | - | - | | `POST /v1/actions/verification/start-domain-verification` | Issues a challenge for one of the four methods | | `POST /v1/actions/verification/confirm-domain-verification` | Asks the server to check the record / tag / file | Both require the merchant JWT (or API key) and the standard `X-Environment` header. ## Next steps After domain verification succeeds, head back to Business Details and complete the remaining steps (Step 9 onward). The Submit for review button unlocks once **all** steps including domain verification turn green. # Support Email Verification Source: https://docs.waffo.ai/settings/email-verification Verify the support email merchants can reach you on, and unlock one-click domain verification ## Why we verify your support email Your **support email** is what buyers see on receipts, in failed-payment notifications, and in the customer portal. Pancake verifies it before KYB approval to make sure the address is reachable and that you control the inbox. A verified support email also unlocks a fast-path for [domain verification](/settings/domain-verification): if your support email is on the same domain as your product website (for example, `support@example.com` ↔ `https://example.com`), Pancake offers a one-click **Verify domain** button — no DNS records or HTML files needed. ## Two entry points Both entry points write to the same backend state, so verifying once is enough: * **Settings → General** — verify (or change) your support email at any time, independent of KYB. * **Settings → Business Details → Step 7 (Contact Email)** — inline during KYB submission. The "Submit for review" button stays disabled until the support email on this step is verified. ## How to verify **1. Enter your support email** Use an inbox you control. Free providers (Gmail, Outlook, etc.) are accepted, but Pancake recommends an address on the same domain as your product website so you can also use the one-click domain fast-path. **2. Click 'Send Code'** A 6-digit code is sent to the email. The button enters a 60-second cooldown before you can resend. **3. Enter the code** The code stays valid for 10 minutes. If it expires, click resend and use the new one. **4. Verified** The block flips to a green "Verified" state, and the support email is now bound to the store. You can change it later — re-verification is required after every change. ## Troubleshooting | Symptom | What to check | | - | - | | Code never arrives | Check spam / promotions. Wait for the cooldown to end, then resend. | | "Invalid or expired code" | Codes expire 10 minutes after sending. Resend and use the new code. | | Verified email shows the wrong address | Re-enter the correct address and verify again — the latest verified address replaces the old one. | | Domain fast-path didn't appear after verifying | The domain fast-path only triggers when the email host matches the website domain exactly. Public providers (gmail.com, outlook.com) never trigger it. | ## What happens after verification * The support email appears on receipts, refund notifications, and the customer portal. * If it shares a domain with your product website, the [domain verification](/settings/domain-verification) page shows a one-click **Verify domain** option. * KYB review can proceed — Step 7 (Contact Email) of Business Details turns green. # Store Settings Source: https://docs.waffo.ai/settings/store-settings Configure your store profile, checkout appearance, notifications, and webhooks; create and delete stores ## Overview Store Settings lets you manage all store-level configurations. Access it from **Settings** in the sidebar. There are five tabs: | Tab | Description | | - | - | | **General** | Store profile, branding, and verification | | **Team** | Invite teammates and manage access — see [Team](/settings/team) | | **Checkout** | Checkout page appearance | | **Notifications** | Email notifications for you and your customers | | **Webhooks** | Webhook endpoints and event subscriptions | *** ## General ### Store Profile | Field | Description | | - | - | | **Store Name** | Your store's display name (also updates the public store URL) | | **Store Slug** | URL-friendly identifier, auto-generated from store name | | **Store Logo** | Square image, at least 200×200px | | **Support Email** | Customer-facing contact email shown on receipts | | **Website** | Your product website | | **Checkout Return URL** | Redirect URL after checkout success or failure | > [!NOTE] > > Changing the store name will also update the public store URL automatically. ### Store Review Complete store verification to enable live payments. Status options: | Status | Description | | - | - | | **Not Started** | Verification not yet initiated | | **In Progress** | Partially filled, not yet submitted | | **Under Review** | Submitted, typically takes 1–3 business days | | **Verified** | Approved — live payments enabled | | **Verification Failed** | Not approved — update and resubmit | See [Business Details](/settings/business-details) for the full verification flow. ### Creating a New Store Each merchant account can have up to **100 stores**. Click your current store name in the top navigation bar and select **Create New Store**, then follow the setup flow. Each store is fully independent — with its own products, consumers, orders, and settings. ### Deleting a Store Permanently deletes the store and all associated data. This action cannot be undone. > [!WARNING] > > You must delete all products before deleting the store. *** ## Checkout Customize the appearance of your checkout page. Supports both light and dark themes. ### Branding * **Logo** — Shown in the checkout header. Synced with Store Logo in General Settings. ### Colors | Setting | Description | | - | - | | **Primary** | Button and highlight color | | **Background** | Page background | | **Card** | Card and panel backgrounds | | **Text** | Primary text color | ### Styling * **Border Radius** — Corner roundness for buttons, cards, and inputs ### Dual Theme (Light & Dark) Enable dual theme to configure separate color palettes for light and dark modes. Customers see the theme that matches their system preference, or you can set a default. > [!TIP] > > Use **Import from website** to automatically extract your brand colors from your website URL. *** ## Notifications ### Customer Emails Transactional email Waffo Pancake sends your customers automatically. All of them are **always on** except two reminders — the upcoming charge notice and the trial ending reminder — which you can switch off per store: | Email | Trigger | Configurable | | - | - | - | | Order confirmation | Customer completes a one-time purchase | Always on | | Subscription confirmation | Customer starts a new subscription | Always on | | Subscription cycled | Subscription automatically renews | Always on | | Subscription updated | Customer changes to a different subscription plan | Always on | | Subscription canceled | Customer cancels their subscription | Always on | | Subscription uncanceled | Customer reactivates a previously canceled subscription | Always on | | Subscription revoked | Canceled subscription permanently ends | Always on | | Subscription past due | Subscription payment fails | Always on | | Trial ending reminder | Sent before a paid trial ends | **Yes** — store update API | | Upcoming charge notice | Sent before a subscription renewal is charged | **Yes** — Settings → Notifications | | Refund processed | A refund on the customer's payment completes | Always on | > [!NOTE] > > Switching off **Upcoming charge notice** stops it for every subscription in that store, yearly plans included. Card networks expect buyers to get advance notice of an annual renewal, so if you turn it off, meeting that expectation is your responsibility. > [!NOTE] > > **Trial ending reminder** is on by default and switched per store through the store update API — set `notificationSettings.emailTrialEnding` to `false` on [`update-store`](/api-reference/endpoints/stores/update-store), and to `true` to start sending it again. Switching it off covers every buyer of that store; there is no per-buyer or per-product form of it. > > Clearing the whole object (`"notificationSettings": null`) switches it back on, along with every other setting you are allowed to write. Send a partial update carrying only the keys you want to change to keep the reminder off. > [!NOTE] > > Every other email above is a transactional record Waffo Pancake must send as Merchant of Record. ### Your Notifications Merchant notifications go to a **recipient list** — up to **5 addresses per store**, each subscribing to its own events. Add and configure them in the recipients card; changes save automatically. | Notification | Trigger | | - | - | | New Orders | A new one-time order is placed | | New Subscriptions | A new subscription is activated | | Subscription Canceled | A subscriber cancels while the access period is still running | | Subscription Renewed | A renewal is charged successfully | | Subscription Ended | A subscription fully ends and access is revoked | | Subscription Past Due | A renewal fails and the subscription is past due | | Subscription Uncanceled | A subscriber reverts a pending cancellation | | Refund Completed | A refund on a payment completes | > [!WARNING] > > Emptying the list **stops merchant notifications entirely** — there is no fallback address. > [!NOTE] > > Recipients are not environment-scoped: the same list applies in Test and Live. *** ## Webhooks Configure webhook endpoints to receive real-time event notifications. ### Endpoints You can configure separate endpoints for **Test** and **Live** environments. | Field | Description | | - | - | | **Endpoint URL** | HTTPS URL to receive webhook POST requests | | **Public Key** | Use to verify webhook signature authenticity | ### Event Types Select which events are delivered to each endpoint: | Group | Events | | - | - | | **Order** | `order.completed` | | **Subscription** | `subscription.activated`, `subscription.payment_succeeded`, `subscription.renewed`, `subscription.recovered`, `subscription.plan_changed`, `subscription.plan_change_scheduled`, `subscription.plan_change_failed`, `subscription.canceling`, `subscription.uncanceled`, `subscription.canceled`, `subscription.past_due` | | **Refund** | `refund.succeeded`, `refund.failed` | ### Event Logs View recent webhook delivery history — status (succeeded / pending / failed), response body, and retry attempts. Use **Send test event** to trigger a test delivery. > [!NOTE] > > Failed deliveries are retried up to 3 times with exponential backoff. # Team Source: https://docs.waffo.ai/settings/team Invite teammates to run your store with their own accounts, and manage who has access ## Overview The **Team** tab lets you give other people access to your store with their own Waffo Pancake accounts, so nobody has to share a login. Open it from **Settings → Team** in the sidebar. The team list shows everyone who has access to the store, plus invitations that have not been accepted yet: | Column | Description | | - | - | | **Member** | Name and email. A **You** badge marks your own row | | **Role** | Owner or Admin | | **Status** | **Active**, **Invited** (with time left), or **Invitation expired** | | **Joined** | When the person joined the store. Pending invitations show **—** | *** ## Roles Every store has exactly one **Owner** and any number of **Admins**. | | Owner | Admin | | - | :-: | :-: | | Run the store day to day (products, orders, customers, analytics, settings) | ✓ | ✓ | | Invite, revoke, and remove team members | ✓ | ✓ | | Delete the store | ✓ | — | | Receive the store's funds and withdraw them | ✓ | — | | Can be removed from the store | — | ✓ | * **Owner** — the person who created the store. The owner cannot be removed or changed to another role, and the store's balance belongs to them. Their **Merchant Finance** page totals every store they own. * **Admin** — everyone you invite. Admins work in the store with their own account but cannot delete it, and the store's funds never appear in their own finance page. > [!NOTE] > > **Finance**, **Developer**, and **View only** roles appear in the role menu as **Coming soon**. They cannot be selected yet. *** ## Inviting Members **1. Open the invite dialog** Go to **Settings → Team** and click **Invite member**. **2. Enter email addresses** Enter an email address and choose a role. Click **Add more** to invite up to **5 people at once**; use the delete button on a row to remove it. Empty rows are ignored. **3. Send** Click **Send invitation**. Each address gets an email with a link to join the store. Each address is sent separately, so one failure does not block the others. If some fail, the dialog stays open and shows the reason under each row — rows that were sent are locked, and clicking **Send invitation** again only retries the rest. *** ## Accepting an Invitation The invited person opens the link in the email and signs in to Waffo Pancake — or creates an account — **with the same email address the invitation was sent to**. They join the store as an Admin and can switch to it from the store menu. If they sign in without using the link, Waffo Pancake shows their pending invitations right after sign-in, where they can **Join** or **Decline** each one. If the link does not work, it has usually been used, revoked, or replaced, has expired, or was opened while signed in with a different email. Sign out, sign in with the invited address, and open the link again — or ask someone on the team to send a new invitation. *** ## Managing Invitations and Members Open the **⋯** menu at the end of a row: | Row | Available actions | | - | - | | Pending invitation | **Revoke invitation** — the link in the email stops working | | Expired invitation | **Resend invitation** — sends a new email with a fresh link; **Revoke invitation** | | Admin | **Remove from store** | | Owner | None — the owner cannot be removed | Pending invitations show how long they have left in the **Status** column. Once an invitation expires, resend it to give the person a new link. ### Removing a Member Removing a member takes away their access to this store immediately, including any API keys they use with it. Their notification recipient entry for this store is deleted too. Their own account and any other stores they belong to are not affected. You can invite them again later. > [!WARNING] > > Admins can remove other admins, including themselves. If you remove yourself, you lose access to the store right away. # Customer Portal API Overview Source: https://docs.waffo.ai/api-reference/endpoints/auth/customer-endpoints Endpoints the customer's browser calls with a session token minted via Issue Session Token The Customer Portal API is the customer-side surface of Waffo. The merchant's backend mints a short-lived session token via [Issue Session Token](/api-reference/endpoints/auth/issue-session-token), and the customer's browser (or your in-product UI) calls the endpoints below with that token in the `Authorization` header. The merchant API Key never leaves the server. > [!NOTE] > > Session tokens are scoped by `buyerIdentity` + `visitingStoreId` and only authorize operations on records that belong to that customer within that store. They cannot read merchant-wide state. ## Required headers on every call | Header | Value | | - | - | | `Authorization` | `Bearer ` (the JWT returned by Issue Session Token) | | `X-Environment` | `test` or `prod` (must match the environment the token was minted for) | A token issued with `purpose: "portal"` is bound to the environment of the API Key that issued it. Sending it with any other `X-Environment` value is rejected before the request reaches the endpoint (403 `Environment mismatch`). The gateway derives the customer identity and visiting store from the token; you do not pass them as separate headers. ## Endpoints > **[Cancel One-time Order](/api-reference/endpoints/orders/cancel-onetime-order)** > > Cancel a pending one-time order before payment completes > **[Cancel Subscription](/api-reference/endpoints/subscriptions/cancel-subscription-customer)** > > Cancel an active or pending subscription on behalf of the customer > **[Reactivate Subscription](/api-reference/endpoints/subscriptions/reactivate-order)** > > Reverse a pending cancellation while still in `canceling` > **[GraphQL](/api-reference/endpoints/graphql/overview)** > > Query the customer's own orders, payments, and refunds ## Token-path errors These errors are surfaced only on the session-token call path: | Status | `errors[0].message` | What it means | | - | - | - | | 400 | `Missing X-Context-Buyer-Identity header` | Token did not carry a customer identity (`buyerIdentity`) claim — re-mint the token | | 400 | `Missing X-Context-Visiting-Store-Id header` | Token was not scoped to a store — re-mint with `visitingStoreId` | | 401 | `Authentication failed` | Session token expired, malformed, or signed for a different merchant | | 403 | `Environment mismatch` | A portal token (`purpose: "portal"`) was sent with an `X-Environment` other than the one it was issued for — send the API Key's environment | # Analytics Source: https://docs.waffo.ai/api-reference/endpoints/graphql/analytics GraphQL query examples for revenue, payment, and customer analytics ## Overview Analytics queries return pre-aggregated statistics for a single store. Every analytics query takes: * A store identifier — `storeId` **or** `storeSlug` (top-level argument, at least one required). * A required `filter` of type `AnalyticsFilterInput!`. ```graphql theme={"system"} input AnalyticsFilterInput { timeRange: TimeRangeInput! # { startDate, endDate } as ISO 8601 strings — required currency: String # optional, ISO 4217 status: String # optional } ``` Many nested fields take their own arguments, most commonly `granularity` and `currency`. The time-bucket granularity uses the `TimePeriodGranularity` enum: `DAY`, `WEEK`, `MONTH`, `QUARTER`, `YEAR`, `ALL_TIME`. > [!NOTE] > > Each analytics query returns a **structured object**, not scalar totals. Amount fields are returned as display strings. Select the nested fields you need — the examples below show the available shape. *** ## Order Statistics Order counts, dual-source revenue, and buyer metrics. ```graphql theme={"system"} query($storeId: String!) { orderStatistics( storeId: $storeId filter: { timeRange: { startDate: "2026-01-01T00:00:00Z", endDate: "2026-02-01T00:00:00Z" } } ) { totalCount countsByStatus { status count } countsByPeriod(granularity: MONTH) { period count } revenueByCurrency { currency pspTotalAmount snapshotTotalAmount mismatchCount paymentCount } revenueByPeriod(granularity: MONTH, currency: "usd") { period currency pspTotalAmount snapshotTotalAmount paymentCount } buyerMetrics { totalBuyers newBuyers returningBuyers } ordersByCountry { country count } revenueByCountry(currency: "usd") { country totalAmount paymentCount } b2bVsB2cBreakdown(currency: "usd") { isBusiness label totalAmount orderCount } } } ``` > [!NOTE] > > `revenueByCurrency` / `revenueByPeriod` are **dual-source**: `pspTotalAmount` is the PSP actual amount, `snapshotTotalAmount` is the snapshot expected amount, and `mismatchCount` counts payments where the two disagree. **Variables:** ```json theme={"system"} { "storeId": "STO_3bVzrkD0FJjFdZNLk8Ualx" } ``` *** ## Payment Statistics Success rate, failure reasons, refunds, method distribution, and tax summary. ```graphql theme={"system"} query($storeId: String!) { paymentStatistics( storeId: $storeId filter: { timeRange: { startDate: "2026-01-01T00:00:00Z", endDate: "2026-02-01T00:00:00Z" } } ) { successRate { totalAttempts succeeded failed pending successRate } failedReasons { reason count percentage } refunds { totalCount succeededCount pendingCount failedCount amountByCurrency { currency totalAmount paymentCount } refundRate } methodDistribution(currency: "usd") { methodType count totalAmount percentage } cardBrandDistribution(currency: "usd") { brand count totalAmount percentage } successRateByMethod { methodType total succeeded failed successRate } taxSummary { currency totalTax totalPreTax totalAmount paymentCount } } } ``` > [!NOTE] > > `successRate` is an **object** (`{ totalAttempts, succeeded, failed, pending, successRate }`), not a scalar. *** ## Product Statistics Product counts, top sellers, and revenue contribution. ```graphql theme={"system"} query($storeId: String!) { productStatistics( storeId: $storeId filter: { timeRange: { startDate: "2026-01-01T00:00:00Z", endDate: "2026-02-01T00:00:00Z" } } ) { onetimeCountsByStatus { status count } subscriptionCountsByStatus { status count } onetimeTotalCount subscriptionTotalCount topByOrderCount(limit: 10) { productId productType productName orderCount totalRevenue currency } topByRevenue(limit: 10, currency: "usd") { productId productType productName orderCount totalRevenue currency } revenueContribution(currency: "usd") { productId productName revenue contributionPercentage cumulativePercentage } } } ``` *** ## Trend Analysis Period-over-period growth, cumulative revenue, and moving averages. ```graphql theme={"system"} query($storeId: String!) { trendAnalysis( storeId: $storeId filter: { timeRange: { startDate: "2026-01-01T00:00:00Z", endDate: "2026-02-01T00:00:00Z" } } ) { orderGrowth(granularity: MONTH) { period currentValue previousValue growthRate } revenueGrowth(granularity: MONTH, currency: "usd") { period currentValue previousValue growthRate } cumulativeRevenue(granularity: MONTH, currency: "usd") { period periodValue cumulativeValue } orderMovingAverage(windowDays: 7) { date dailyValue movingAverage } } } ``` *** ## Distribution Analysis Order amount percentiles, average-order-value trend, and amount buckets. ```graphql theme={"system"} query($storeId: String!) { distributionAnalysis( storeId: $storeId filter: { timeRange: { startDate: "2026-01-01T00:00:00Z", endDate: "2026-02-01T00:00:00Z" } } ) { orderAmountPercentiles(currency: "usd") { p10 p25 p50 p75 p90 p95 p99 min max avg stddev count } aovTrend(granularity: MONTH, currency: "usd") { period averageOrderValue orderCount totalRevenue } orderAmountBuckets(currency: "usd", bucketCount: 10) { rangeMin rangeMax count percentage } } } ``` *** ## Customer Analysis Cohort retention, LTV distribution, purchase frequency, and top customers. ```graphql theme={"system"} query($storeId: String!) { customerAnalysis( storeId: $storeId filter: { timeRange: { startDate: "2026-01-01T00:00:00Z", endDate: "2026-02-01T00:00:00Z" } } ) { cohortRetention(granularity: MONTH) { cohortPeriod cohortSize retention { periodOffset activeCustomers retentionRate } } ltvDistribution(currency: "usd") { averageLtv medianLtv percentiles { p50 p90 p99 min max } buckets { rangeMin rangeMax count percentage } } purchaseFrequency { purchaseCount customerCount percentage } topCustomers(limit: 10, currency: "usd") { buyerEmail totalSpent orderCount firstPurchaseDate lastPurchaseDate } } } ``` *** ## Tax Analysis Tax amounts by category, rate group, and country, plus B2B/B2C comparison. ```graphql theme={"system"} query($storeId: String!) { taxAnalysis( storeId: $storeId filter: { timeRange: { startDate: "2026-01-01T00:00:00Z", endDate: "2026-02-01T00:00:00Z" } } ) { byCategory(currency: "usd") { taxCategory totalTax totalAmount paymentCount } byRateGroup(currency: "usd") { taxRate totalTax totalAmount paymentCount } byCountry(currency: "usd") { country totalTax totalAmount paymentCount } b2bVsB2c(currency: "usd") { isBusiness label totalTax totalAmount orderCount } effectiveTaxRateTrend(granularity: MONTH, currency: "usd") { period avgTaxRate paymentCount } } } ``` *** ## Subscription Analysis Billing period distribution, cancellation stats, trial conversion, and churn. ```graphql theme={"system"} query($storeId: String!) { subscriptionAnalysis( storeId: $storeId filter: { timeRange: { startDate: "2026-01-01T00:00:00Z", endDate: "2026-02-01T00:00:00Z" } } ) { billingPeriodDistribution(currency: "usd") { billingPeriod count totalAmount percentage } activeCount cancellationStats { totalSubscriptions canceledCount cancellationRate avgLifetimeDays medianLifetimeDays } trialConversion { totalTrials convertedCount activeTrials conversionRate } churnRate(granularity: MONTH) { period startActive churned churnRate } } } ``` *** ## Refund Ticket Analysis Reason distribution, review efficiency, and approval rate. ```graphql theme={"system"} query($storeId: String!) { refundTicketAnalysis( storeId: $storeId filter: { timeRange: { startDate: "2026-01-01T00:00:00Z", endDate: "2026-02-01T00:00:00Z" } } ) { reasonDistribution(currency: "usd") { reason count totalAmount percentage } statusDistribution { status count percentage } reviewEfficiency { avgHours medianHours p90Hours totalReviewed } ticketTrend(granularity: MONTH) { period totalCreated resolvedCount approvedCount rejectedCount } approvalRate { approved rejected rate } } } ``` *** ## Settlement Analysis Actual settled amounts sourced from settlement files (post-fee, post-refund). This is the ground truth for reconciliation, distinct from `paymentStatistics.settlementRevenueByCurrency` (a PSP projection at payment time). ```graphql theme={"system"} query($storeId: String!) { settlementAnalysis( storeId: $storeId filter: { timeRange: { startDate: "2026-04-01T00:00:00Z", endDate: "2026-05-01T00:00:00Z" } } ) { countsByAccountingStatus { status count } netSettlementByCurrency { currency totalAmount paymentCount } netSettlementByPeriod(granularity: DAY, currency: "usd") { period currency totalAmount paymentCount } refundTotalByCurrency { currency totalAmount paymentCount } feeTotalByCurrency { currency totalAmount paymentCount } } } ``` > [!NOTE] > > `settlementAnalysis` time range is based on the settlement date, not `created_at`. Additional analytics queries are available depending on your role, including `deliveryAnalysis` (webhook/email delivery) and `payoutAnalysis` (payout tickets, scoped to the merchant). Use schema introspection to discover their full field sets. **Variables:** ```json theme={"system"} { "storeId": "STO_3bVzrkD0FJjFdZNLk8Ualx" } ``` # Orders & Payments Source: https://docs.waffo.ai/api-reference/endpoints/graphql/orders-and-payments GraphQL query examples for orders, payments, and refund tickets ## One-Time Orders ### List Completed Orders ```graphql theme={"system"} query($storeId: String!) { onetimeOrders( storeId: $storeId filter: { status: { eq: "completed" } } limit: 50 ) { id buyerEmail currency priceSnapshot { currency subtotal taxAmount total taxCategory } status metadata createdAt } onetimeOrdersCount(storeId: $storeId) } ``` **Variables:** ```json theme={"system"} { "storeId": "STO_3bVzrkD0FJjFdZNLk8Ualx" } ``` ### Filter by Date Range ```graphql theme={"system"} query($storeId: String!) { onetimeOrders( storeId: $storeId filter: { createdAt: { gte: "2026-01-01T00:00:00.000Z" lte: "2026-03-31T23:59:59.999Z" } } ) { id buyerEmail status createdAt } } ``` ### Look Up One-Time Order by Your Business Number (`orderMerchantExternalId`) Pass the same `orderMerchantExternalId` you attached at checkout creation. ```graphql theme={"system"} query($storeId: String!, $ref: String!) { onetimeOrders( storeId: $storeId filter: { orderMerchantExternalId: { eq: $ref } } ) { id buyerEmail status orderMerchantExternalId createdAt } } ``` **Variables:** ```json theme={"system"} { "storeId": "STO_3bVzrkD0FJjFdZNLk8Ualx", "ref": "ORDER-2026-00891" } ``` ### SDK Example ```typescript theme={"system"} const result = await client.graphql.query<{ onetimeOrders: Array<{ id: string; buyerEmail: string; priceSnapshot: { total: number; currency: string }; status: string; }>; }>({ query: `query($storeId: String!) { onetimeOrders(storeId: $storeId, filter: { status: { eq: "completed" } }) { id buyerEmail priceSnapshot { total currency } status } }`, variables: { storeId: "STO_3bVzrkD0FJjFdZNLk8Ualx" }, }); ``` *** ## Subscription Orders ### List Active Subscriptions ```graphql theme={"system"} query($storeId: String!) { subscriptionOrders( storeId: $storeId filter: { status: { in: ["active"] } } ) { id buyerEmail status billingPeriod createdAt } subscriptionOrdersCount(storeId: $storeId) } ``` ### Filter Canceling Subscriptions ```graphql theme={"system"} query($storeId: String!) { subscriptionOrders( storeId: $storeId filter: { status: { eq: "canceling" } } ) { id buyerEmail status createdAt } } ``` ### Look Up Subscription Order by Your Business Number (`orderMerchantExternalId`) Pass the same `orderMerchantExternalId` you attached at checkout creation. Every renewal payment that follows inherits the same value, so a single business reference resolves the whole subscription lifecycle. ```graphql theme={"system"} query($storeId: String!, $ref: String!) { subscriptionOrders( storeId: $storeId filter: { orderMerchantExternalId: { eq: $ref } } ) { id buyerEmail status billingPeriod orderMerchantExternalId createdAt } } ``` **Variables:** ```json theme={"system"} { "storeId": "STO_3bVzrkD0FJjFdZNLk8Ualx", "ref": "SUB-2026-01045" } ``` ### Which Billing Period a Subscription Is In The billing period this subscription is in **right now**, as reported by the payment channel and stored unchanged — Waffo never computes or infers it. `1` during the first period, `N` during the Nth. `0` means the channel authorized the subscription but has not charged it yet. A failed charge still advances it, so it is not a count of successful charges. Null until the first channel notification arrives, and on subscriptions created before this field shipped. Same concept as the webhook `data.periodNumber` and `Payment.periodNumber`, read at a different anchor — see [the field reference](/api-reference/webhooks#data-fields). This one moves as the subscription renews; `Payment.periodNumber` is frozen to the charge it belongs to. ```graphql theme={"system"} query($storeId: String!) { subscriptionOrders(storeId: $storeId, filter: { status: { in: ["active"] } }) { id orderMerchantExternalId currentPeriodStart currentPeriodEnd currentPeriodNumber } } ``` ### Discount on a Subscription A subscription bought with a coupon or promotion code keeps the list price on the order; each payment records the amounts expected for its own period. How periods are counted is in [Discounts](/guides/discounts#subscriptions), and what a plan change does to the discount in [Plan Changes](/guides/discounts#plan-changes). ```graphql theme={"system"} query($id: String!) { subscriptionOrder(id: $id) { id status priceSnapshot { currency specialPhaseDays specialPhase { total listTotal discountAmount discountedTaxAmount } regularPhase { total listTotal discountAmount discountedTaxAmount } firstPeriod { total listTotal discountAmount discountedTaxAmount } } discount { code appliedVia status listAmount { display } discountAmount { display } } activeDiscount { code couponId status duration durationInPeriods periodsUsed isActive endsAt } payments { id status periodNumber snapshotAmountDetails { currency listTotal discountAmount taxAmount total phase } } } } ``` **Variables:** ```json theme={"system"} { "id": "ORD_7cWxyzAbCdEfGhIjKlMnOp" } ``` | Field | Meaning | | - | - | | `discount` | The discount on this order: `code`, `appliedVia` (how it was applied: `coupon_id` — your `couponId`; `promotion_code` — your pre-filled `promotionCode`; `discount_code` — a product link's `discount_code`; `checkout` — typed by the customer; `null` for some discounts applied before this field existed), `status` (`reserved` until the first discounted charge succeeds, then `applied`), `listAmount` (price before the discount of the first discounted charge — the trial price for a paid trial) and `discountAmount` (confirmed by that payment; `null` before). `null` when the order has no discount or its use was given back. A discount carried over by a plan change is read from `activeDiscount` — except a carried discount that was still `reserved`: when the plan change succeeds it moves to the new order and shows in its `discount` too | | `activeDiscount` | How long the discount lasts and how far it has got. `duration`; `durationInPeriods` (`repeating` only); `periodsUsed` — succeeded charges whose price before the discount is above zero (a free trial does not count); `isActive` — whether the next charge is still expected to be discounted: the subscription is still billing, the coupon's expiry is later than the next charge date (the end of the current period) and the duration is not used up; `endsAt` — the coupon's expiry, `null` when it has none. `null` when the order has no discount of its own and none carried over from a plan change — so a carried-over discount shows here while `discount` is `null`. On a subscription created by a plan change, it shows the new code entered with the change or, without one, the discount carried over from the previous subscription, with `periodsUsed` counted across the plan changes. `code` is the code used, `couponId` the coupon (`CPN_xxx`) and `status` the state of that use of the code (`reserved`, `applied` or `needs_reconcile`, as for `discount`); for a carried-over discount they are those of the original use. When your customers query their own orders and subscriptions, `appliedVia`, `couponId` and `status` are not available, and `code` is `null` for a discount you applied with `couponId` (also when it was carried over) — they see the discount but not a code; otherwise `code` is the same as yours | | `specialPhase` / `regularPhase` → `total` | The phase's list price before the discount, tax included (the trial price for `specialPhase`). `listTotal` always equals it | | `specialPhase` / `regularPhase` → `discountAmount` / `discountedTaxAmount` | The discount and the tax for a charge of this phase that is discounted. A phase that can never be discounted shows `0` and `taxAmount`: no discount, a free trial, and the regular phase after a paid trial with `once` or `repeating` for 1 period. Whether a given period was discounted is on its payment | | `firstPeriod` | Only on a subscription created by a plan change that took effect immediately without a trial: the first period, priced apart from the regular phase. `total` is its price before the discount — the new plan's price minus the prorated credit, or the amount the merchant set — and `discountAmount` / `discountedTaxAmount` are as for the phases above, `0` and `taxAmount` when the first period is not discounted. `discountAmount` is worked out on the new plan's full price and capped at `total` (new plan 99.00, credit 8.90, 20% off → `total` 90.10, `discountAmount` 19.80, the customer pays 70.30). `total`, `discountAmount` and `discountedTaxAmount` are all `0` when the credit covers the whole first period. The new subscription's first payment records these amounts in `snapshotAmountDetails`, with `phase` `regular` — a \$0 payment when `total` is `0` — and later payments record the regular phase. `null` otherwise | | `snapshotAmountDetails` → `listTotal` / `discountAmount` / `total` | What this payment expects: the price before the discount (the phase's list price — the trial price for a trial charge), the discount for this period (`0` when it is not discounted) and the amount to pay, with `listTotal − discountAmount = total`. `taxAmount` is the tax in `total`. On a plan change scheduled for the next period, the \$0 card authorization made before the switch expects `0` for all of them, with `phase` `special`; the first charge after the switch records the regular phase | Payments recorded before these fields existed fall back to `listTotal = total` and `discountAmount = 0`. *** ## Payments ### List Successful Payments ```graphql theme={"system"} query { payments( filter: { status: { eq: "succeeded" } } limit: 100 ) { id orderId status refundStatus snapshotAmountDetails { subtotal listTotal discountAmount taxAmount total currency } createdAt } paymentsCount(filter: { status: { eq: "succeeded" } }) } ``` > [!NOTE] > > `snapshotAmountDetails.total` is the amount expected for the payment, after any discount. `listTotal` and `discountAmount` give the price before the discount and the discount, with `listTotal − discountAmount = total`; without a discount `discountAmount` is `0`. ### Filter by Date Range ```graphql theme={"system"} query { payments( filter: { status: { eq: "succeeded" } createdAt: { gte: "2026-01-01T00:00:00.000Z" lte: "2026-03-31T23:59:59.999Z" } } ) { id orderId snapshotAmountDetails { subtotal taxAmount total currency } createdAt } } ``` ### Look Up Payment by Waffo Payment ID ```graphql theme={"system"} query($paymentId: String!) { payment(id: $paymentId) { id orderId status refundStatus orderMerchantExternalId snapshotAmountDetails { total currency } } } ``` **Variables:** ```json theme={"system"} { "paymentId": "PAY_6eYCunG3IMmIgcQOnaXdoA" } ``` ### Look Up Payment by Your Business Number (`orderMerchantExternalId`) Pass the same `orderMerchantExternalId` you attached at checkout creation. Field name mirrors webhook payload `data.orderMerchantExternalId`. ```graphql theme={"system"} query($ref: String!) { payments(filter: { orderMerchantExternalId: { eq: $ref } }) { id orderId status refundStatus orderMerchantExternalId createdAt } } ``` **Variables:** ```json theme={"system"} { "ref": "ORDER-2026-00891" } ``` > [!NOTE] > > For subscription orders, every renewal payment **inherits the same `orderMerchantExternalId`** set at checkout. The query above returns the full payment history for the same business reference, ordered by `createdAt DESC`. ### Which Billing Period a Charge Paid For `periodNumber` is the period **that charge** belongs to — `1` for the first charge, `N` for the Nth renewal — the same value the subscription payment webhook carried for it. A failed charge still consumes a period, so this is not a count of successful charges. Null on one-time payments and on payments created before this field shipped. It is frozen to its charge: a subscription now in period `3` still has `periodNumber: 1` on its first payment. Use `SubscriptionOrder.currentPeriodNumber` when you want where the subscription is today. ```graphql theme={"system"} query($ref: String!) { payments(filter: { orderMerchantExternalId: { eq: $ref } }) { id orderId status periodNumber createdAt } } ``` **Variables:** ```json theme={"system"} { "ref": "SUB-2026-01045" } ``` *** ## Aggregations & Sorting ### Aggregate Payments by Day `paymentsAggregate` returns `count` plus `amount` metrics (`sum`, `avg`, `min`, `max`) over all matching rows, optionally grouped by up to 2 dimensions. Available dimensions: `status`, `currency`, `payment_method_type`, `card_brand`, `store`, and the time dimension `created_period`. `granularity` (`day`, `week`, `month`, `quarter`, `year`; default `day`) only applies to the time dimension. ```graphql theme={"system"} query { paymentsAggregate( filter: { status: { eq: "succeeded" }, currency: { eq: "USD" } } groupBy: [created_period] granularity: day ) { count amount { sum avg min max } groups { keys { dimension value } count amount { sum } } isTruncated } } ``` > [!NOTE] > > Aggregate `amount` values are integer strings in **minor currency units** (e.g. cents). Amounts are summed across whatever rows match the filter, so group or filter by `currency` when multiple currencies are involved. Groups are sorted by `count` descending and capped at 100 (`isTruncated` flags truncation); the top-level `count`/`amount` always cover all matching rows. Other entities expose the same shape: `refundsAggregate`, `onetimeOrdersAggregate`, `subscriptionOrdersAggregate`, `payoutTicketsAggregate`, `settlementBatchesAggregate`, `webhookDeliveriesAggregate`, `emailDeliveriesAggregate`. ### Sort with `orderBy` List queries that support sorting accept `orderBy: [XxxOrderBy!]` (an enum whitelist), defaulting to `created_at DESC`. For payments the options are `created_at_desc`, `created_at_asc`, `amount_desc`, `amount_asc`. ```graphql theme={"system"} query { payments( filter: { status: { eq: "succeeded" } } orderBy: [amount_desc] limit: 20 ) { id status snapshotAmountDetails { total currency } createdAt } } ``` *** ## Refunds (executed records) Refund records (`order.refunds`) are written after the PSP confirms the refund. They are **separate from refund tickets** — tickets carry the request lifecycle, refund records carry the executed result. ### Look Up Refund by Waffo Refund ID `Refund` exposes both business numbers as flat fields (`orderMerchantExternalId` from the originating order, `refundTicketMerchantExternalId` from the originating refund ticket) — same naming as the webhook payload. ```graphql theme={"system"} query($refundId: String!) { refund(id: $refundId) { id paymentId ticketId status orderMerchantExternalId refundTicketMerchantExternalId pspAmountDetails { amount currency } createdAt } } ``` **Variables:** ```json theme={"system"} { "refundId": "RFD_8aHbCcDdEeFfGgHhIiJjKk" } ``` > [!NOTE] > > `Refund` carries two amounts. `amount` is a `Money` object in minor currency units (`"4900"` for USD 49.00, with `display` giving `"49.00"`), while `pspAmountDetails.amount` is the amount the payment channel actually returned to the buyer, already as a display string (`"49.00"`). Reconcile against your channel statement with `pspAmountDetails`; `isAmountMismatch` is `true` when the requested and channel amounts differ. ### Look Up Refunds by Payment (Waffo Payment ID) ```graphql theme={"system"} query($paymentId: String!) { refunds(filter: { paymentId: { eq: $paymentId } }) { id status orderMerchantExternalId refundTicketMerchantExternalId pspAmountDetails { amount currency } createdAt } } ``` ### Look Up Refunds by Your Business Number Match by **the refund ticket's business reference** (what you attached when creating the refund ticket) — use the `refundTicketMerchantExternalId` filter: ```graphql theme={"system"} query($ref: String!) { refunds(filter: { refundTicketMerchantExternalId: { eq: $ref } }) { id paymentId ticketId status orderMerchantExternalId refundTicketMerchantExternalId pspAmountDetails { amount currency } createdAt } } ``` Or match by **the order's business reference** (returns all refunds against any payment carrying that reference, useful for subscription renewals) — filter at the payment layer and read its nested refunds: ```graphql theme={"system"} query($paymentRef: String!) { payments(filter: { orderMerchantExternalId: { eq: $paymentRef } }) { id orderMerchantExternalId refunds { id status refundTicketMerchantExternalId pspAmountDetails { amount currency } createdAt } } } ``` *** ## Refund Tickets ### List All Refund Tickets ```graphql theme={"system"} query { refundTickets { id paymentId status requestedAmount reason createdAt } refundTicketsCount } ``` ### Filter Pending Refunds ```graphql theme={"system"} query { refundTickets(filter: { status: { eq: "pending" } }) { id paymentId requestedAmount reason createdAt } } ``` ### Refunds for a Specific Payment ```graphql theme={"system"} query($paymentId: String!) { refundTickets(filter: { subjectId: { eq: $paymentId } }) { id status refundTicketMerchantExternalId versionData { reason requestedAmount { amount currency } } createdAt } } ``` **Variables:** ```json theme={"system"} { "paymentId": "PAY_6eYCunG3IMmIgcQOnaXdoA" } ``` ### Look Up Refund Tickets by Your Business Number (`refundTicketMerchantExternalId`) ```graphql theme={"system"} query($ref: String!) { refundTickets(filter: { refundTicketMerchantExternalId: { eq: $ref } }) { id status refundTicketMerchantExternalId versionData { reason requestedAmount { amount currency } } reviewNote rejectReason executedAt createdAt } } ``` **Variables:** ```json theme={"system"} { "ref": "REF-2026-00891" } ``` > [!TIP] > > `RefundTicket` (the request) and `Refund` (the executed record) are **two different GraphQL types**, but their business-side identifiers share the same flat names as the webhook payload: `refundTicketMerchantExternalId` on both `RefundTicket` and `Refund`; `orderMerchantExternalId` is additionally exposed on `Refund` (inherited from the originating order). Webhook payloads carry the same two values as `data.orderMerchantExternalId` and `data.refundTicketMerchantExternalId`. # GraphQL API Source: https://docs.waffo.ai/api-reference/endpoints/graphql/overview Query all your data with GraphQL read-only queries ## Overview The Waffo Pancake GraphQL API provides **read-only** access to all your data. Use REST action endpoints for writes, and GraphQL for queries. ``` POST /v1/graphql ``` **Authentication:** API Key > [!NOTE] > > The GraphQL API supports **queries only**. All write operations (create, update, delete) use the [REST action endpoints](/api-reference/introduction#endpoint-groups). ## Making a Request ### Request Body | Field | Type | Required | Description | | - | - | - | - | | `query` | string | Yes | GraphQL query string | | `variables` | object | No | Query variables | ```typescript SDK theme={"system"} import { WaffoPancake } from "@waffo/pancake-ts"; const client = new WaffoPancake({ merchantId: process.env.WAFFO_MERCHANT_ID!, privateKey: process.env.WAFFO_PRIVATE_KEY!, }); interface StoresQuery { stores: Array<{ id: string; name: string; status: string }>; } const result = await client.graphql.query({ query: `{ stores { id name status } }`, }); console.log(result.stores); // => [{ id: "STO_2aUyqjCzEIiEcYMKj7TZtw", name: "My Store", status: "active" }] ``` ```typescript TypeScript (fetch) theme={"system"} // Uses callApi() helper from authentication.mdx const result = await callApi("POST", "/v1/graphql", { query: "query { stores { id name status } }", variables: {}, }); console.log(result.data.stores); // => [{ id: "STO_2aUyqjCzEIiEcYMKj7TZtw", name: "My Store", status: "active" }] ``` ```java Java theme={"system"} // Uses callApi() helper from authentication.mdx String body = """ {"query":"query { stores { id name status } }","variables":{}}"""; String response = callApi("POST", "/v1/graphql", body); System.out.println(response); // => {"data":{"stores":[{"id":"STO_2aUyqjCzEIiEcYMKj7TZtw","name":"My Store","status":"active"}]}} ``` ```python Python theme={"system"} # Uses call_api() helper from authentication.mdx result = call_api("POST", "/v1/graphql", { "query": "query { stores { id name status } }", "variables": {}, }) stores = result["data"]["stores"] print(stores) # => [{"id": "STO_2aUyqjCzEIiEcYMKj7TZtw", "name": "My Store", "status": "active"}] ``` ```go Go theme={"system"} // Uses callAPI() helper from authentication.mdx body := map[string]interface{}{ "query": "query { stores { id name status } }", "variables": map[string]interface{}{}, } result, err := callAPI("POST", "/v1/graphql", body) if err != nil { log.Fatal(err) } fmt.Println(string(result)) // => {"data":{"stores":[{"id":"STO_2aUyqjCzEIiEcYMKj7TZtw","name":"My Store","status":"active"}]}} ``` ```rust Rust theme={"system"} // Uses call_api() helper from authentication.mdx let body = serde_json::json!({ "query": "query { stores { id name status } }", "variables": {} }); let result = call_api("POST", "/v1/graphql", &body).await?; println!("{}", result); // => {"data":{"stores":[{"id":"STO_2aUyqjCzEIiEcYMKj7TZtw","name":"My Store","status":"active"}]}} ``` ```c C theme={"system"} /* Uses call_api() helper from authentication.mdx */ const char *body = "{\"query\":\"query { stores { id name status } }\",\"variables\":{}}"; char *response = call_api("POST", "/v1/graphql", body); printf("%s\n", response); free(response); ``` ```cpp C++ theme={"system"} // Uses callApi() helper from authentication.mdx std::string body = R"({"query":"query { stores { id name status } }","variables":{}})"; std::string response = callApi("POST", "/v1/graphql", body); std::cout << response << std::endl; // => {"data":{"stores":[{"id":"STO_2aUyqjCzEIiEcYMKj7TZtw","name":"My Store","status":"active"}]}} ``` ```bash cURL theme={"system"} MERCHANT_ID="MER_2aUyqjCzEIiEcYMKj7TZtw" TIMESTAMP=$(date +%s) BODY='{"query":"query { stores { id name status } }","variables":{}}' BODY_HASH=$(echo -n "$BODY" | openssl dgst -sha256 -binary | base64 | tr -d '\n') CANONICAL_REQUEST="POST /v1/graphql $TIMESTAMP $BODY_HASH" SIGNATURE=$(echo -n "$CANONICAL_REQUEST" | openssl dgst -sha256 -sign private_key.pem | base64 | tr -d '\n') curl -X POST "https://api.waffo.ai/v1/graphql" \ -H "Content-Type: application/json" \ -H "X-Merchant-Id: $MERCHANT_ID" \ -H "X-Timestamp: $TIMESTAMP" \ -H "X-Signature: $SIGNATURE" \ -d "$BODY" ``` ```bash wget theme={"system"} MERCHANT_ID="MER_2aUyqjCzEIiEcYMKj7TZtw" TIMESTAMP=$(date +%s) BODY='{"query":"query { stores { id name status } }","variables":{}}' BODY_HASH=$(echo -n "$BODY" | openssl dgst -sha256 -binary | base64 | tr -d '\n') CANONICAL_REQUEST="POST /v1/graphql $TIMESTAMP $BODY_HASH" SIGNATURE=$(echo -n "$CANONICAL_REQUEST" | openssl dgst -sha256 -sign private_key.pem | base64 | tr -d '\n') wget -qO- "https://api.waffo.ai/v1/graphql" \ --header="Content-Type: application/json" \ --header="X-Merchant-Id: $MERCHANT_ID" \ --header="X-Timestamp: $TIMESTAMP" \ --header="X-Signature: $SIGNATURE" \ --post-data="$BODY" ``` ### Status Codes | Status | Description | | - | - | | 200 | Query succeeded (GraphQL errors in response body `errors` field) | | 400 | Missing query / query syntax error / invalid environment / missing or invalid role | | 401 | Authentication failed | | 403 | Operation type not allowed (only Query supported) / role not permitted for this endpoint | | 429 | Rate limit exceeded — retry after the interval in the `Retry-After` header | | 500 | Internal server error | *** ## Schema Introspection > [!TIP] > > **Recommended:** Use standard GraphQL introspection to discover the full schema. This ensures you always work with the latest types and fields. > [!WARNING] > > **GraphQL types differ from REST/SDK types.** For example, `prices` is a `Record` in REST but `[CurrencyPrice!]!` (array of `{currency, priceInfo}`) in GraphQL, and `metadata` is a parsed object in REST but a JSON string in GraphQL. Do not use SDK TypeScript type definitions to construct GraphQL queries — always use introspection or the examples below. ### Discover All Available Queries ```graphql theme={"system"} query { __schema { queryType { fields { name description args { name type { name kind } } } } } } ``` ### Discover Type Fields ```graphql theme={"system"} query { __type(name: "Store") { name fields { name type { name kind ofType { name } } } } } ``` API Key authentication gives you access to **18 query types** including single-entity queries, list queries with filters, count queries, and analytics queries. *** ## Filtering GraphQL queries support filters using typed filter objects: | Type | Operators | Example | | - | - | - | | `StringFilter` | `eq`, `ne`, `in`, `contains` | `{ storeId: { eq: "STO_xxx" } }` | | `DateTimeFilter` | `eq`, `gt`, `lt`, `gte`, `lte` | `{ createdAt: { gte: "2026-01-01" } }` | | `IntFilter` | `eq`, `gt`, `lt`, `gte`, `lte` | `{ attemptCount: { gte: 3 } }` | | `AmountFilter` | `eq`, `ne`, `gt`, `gte`, `lt`, `lte` | `{ amount: { gte: "9.99" }, currency: { eq: "USD" } }` | | `BooleanFilter` | `eq` | `{ isActive: { eq: true } }` | > [!NOTE] > > `AmountFilter` values are decimal strings in the currency's major unit (e.g. `"9.99"`). An amount filter **must** be accompanied by a sibling `currency: { eq: "..." }` in the same `filter` object — a single currency per query. Cross-currency amount comparison is not supported. ```graphql theme={"system"} query { onetimeProducts( filter: { storeId: { eq: "STO_3bVzrkD0FJjFdZNLk8Ualx" } status: { eq: "active" } } ) { id name prices } } ``` *** ## Pagination Use `limit` and `offset` for pagination. Use `*Count` queries to get total counts. ```graphql theme={"system"} query { onetimeProducts( filter: { storeId: { eq: "STO_3bVzrkD0FJjFdZNLk8Ualx" } } limit: 10 offset: 0 ) { id name } onetimeProductsCount( filter: { storeId: { eq: "STO_3bVzrkD0FJjFdZNLk8Ualx" } } ) } ``` | Parameter | Type | Description | | - | - | - | | `limit` | integer | Maximum number of results to return | | `offset` | integer | Number of results to skip | *** ## Environment-Specific Fields The API Key environment affects which product data is returned: * `version` -- Returns the version for the specified environment * `status` -- Returns the status in the specified environment A product may be `active` in test but `inactive` in production if it hasn't been published yet. *** ## Query Examples > **[Stores & Products](/api-reference/endpoints/graphql/stores-and-products)** > > Query stores, one-time products, subscription products, and product versions > **[Orders & Payments](/api-reference/endpoints/graphql/orders-and-payments)** > > Query orders, subscription orders, payments, and refund tickets > **[Analytics](/api-reference/endpoints/graphql/analytics)** > > Revenue statistics, payment analytics, trend analysis, and customer insights # Stores & Products Source: https://docs.waffo.ai/api-reference/endpoints/graphql/stores-and-products GraphQL query examples for stores, products, and product versions ## Stores ### List All Stores ```graphql theme={"system"} query { stores { id name status slug supportEmail website prodEnabled createdAt updatedAt } } ``` ### Single Store with Nested Products ```graphql theme={"system"} query($storeId: String!) { store(id: $storeId) { id name status onetimeProducts { id name prices status } subscriptionProducts { id name billingPeriod prices status } } } ``` **Variables:** ```json theme={"system"} { "storeId": "STO_3bVzrkD0FJjFdZNLk8Ualx" } ``` *** ## One-Time Products ### List Products with Filtering ```graphql theme={"system"} query($storeId: String!) { onetimeProducts( filter: { storeId: { eq: $storeId } status: { eq: "active" } } limit: 20 offset: 0 ) { id name description prices status version media successUrl metadata createdAt updatedAt } onetimeProductsCount( filter: { storeId: { eq: $storeId } } ) } ``` **Variables:** ```json theme={"system"} { "storeId": "STO_3bVzrkD0FJjFdZNLk8Ualx" } ``` ### SDK Example ```typescript theme={"system"} const result = await client.graphql.query<{ onetimeProducts: Array<{ id: string; name: string; prices: Record; status: string; }>; onetimeProductsCount: number; }>({ query: `query($storeId: String!) { onetimeProducts(filter: { storeId: { eq: $storeId }, status: { eq: "active" } }, limit: 20) { id name prices status } onetimeProductsCount(filter: { storeId: { eq: $storeId } }) }`, variables: { storeId: "STO_3bVzrkD0FJjFdZNLk8Ualx" }, }); ``` *** ## Subscription Products ### List Subscription Products ```graphql theme={"system"} query($storeId: String!) { subscriptionProducts(filter: { storeId: { eq: $storeId } }) { id name description billingPeriod prices status version media metadata createdAt updatedAt } subscriptionProductsCount(filter: { storeId: { eq: $storeId } }) } ``` *** ## Product Versions ### Query Version History Each product update creates an immutable version. Query version history to see all past configurations: ```graphql theme={"system"} query($productId: String!) { onetimeProductVersions(filter: { productId: { eq: $productId } }) { id versionNumber name description prices media createdAt } } ``` ### Subscription Product Versions ```graphql theme={"system"} query($productId: String!) { subscriptionProductVersions(filter: { productId: { eq: $productId } }) { id versionNumber name billingPeriod prices metadata createdAt } } ``` **Variables:** ```json theme={"system"} { "productId": "PROD_4cWAslE1GKkGeaOMl9Vbmy" } ``` *** ## Merchants ### List Merchants ```graphql theme={"system"} query { merchants { id email status createdAt } merchantsCount } ``` ### Single Merchant ```graphql theme={"system"} query($id: String!) { merchant(id: $id) { id email status createdAt updatedAt } } ``` # Cancel One-Time Order Source: https://docs.waffo.ai/api-reference/endpoints/orders/cancel-onetime-order Cancel a pending one-time order before payment is completed Cancel a pending one-time order. Only orders in `pending` status can be canceled. ``` POST /v1/actions/onetime-order/cancel-order ``` **Authentication:** Session Token — see [Customer Endpoints](/api-reference/endpoints/auth/customer-endpoints) (customer or customer role) ## Cancellation Behavior | Current Status | Action | Result Status | | - | - | - | | `pending` | Immediate cancel | `canceled` | | `completed` | Rejected | unchanged (terminal) | | `canceled` | Rejected | unchanged (terminal) | > [!NOTE] > > * **pending**: The order is canceled immediately and its status becomes `canceled` > * The underlying PSP checkout session expires automatically — there is no separate PSP cancel call to make > * `completed` and `canceled` are terminal states and cannot be canceled again ## Request Body | Field | Type | Required | Description | | - | - | - | - | | `orderId` | string | Yes | One-time order ID (Short ID format `ORD_xxx`) | ## Example Request ```typescript TypeScript (SDK) theme={"system"} import { WaffoPancake } from "@waffo/pancake-ts"; const client = new WaffoPancake({ sessionToken: window.WAFFO_SESSION_TOKEN, // injected by the merchant's portal environment: "prod", }); const result = await client.orders.cancelOnetime({ orderId: "ORD_2aUyqjCzEIiEcYMKj7TZtw", }); console.log(result.orderId); // "ORD_2aUyqjCzEIiEcYMKj7TZtw" console.log(result.status); // "canceled" ``` ```typescript TypeScript (Manual) theme={"system"} const result = await fetch("https://api.waffo.ai/v1/actions/onetime-order/cancel-order", { method: "POST", headers: { "Authorization": `Bearer ${SESSION_TOKEN}`, "Content-Type": "application/json", "X-Environment": "prod", }, body: JSON.stringify({ orderId: "ORD_2aUyqjCzEIiEcYMKj7TZtw", }), }).then(r => r.json()); ``` ```bash cURL theme={"system"} curl -X POST "https://api.waffo.ai/v1/actions/onetime-order/cancel-order" \ -H "Authorization: Bearer $SESSION_TOKEN" \ -H "Content-Type: application/json" \ -H "X-Environment: prod" \ -d '{"orderId":"ORD_2aUyqjCzEIiEcYMKj7TZtw"}' ``` ```bash wget theme={"system"} wget -qO- \ --header="Authorization: Bearer $SESSION_TOKEN" \ --header="Content-Type: application/json" \ --header="X-Environment: prod" \ --post-data='{"orderId":"ORD_2aUyqjCzEIiEcYMKj7TZtw"}' \ "https://api.waffo.ai/v1/actions/onetime-order/cancel-order" ``` ## Success Response (200) ```json theme={"system"} { "data": { "orderId": "ORD_2aUyqjCzEIiEcYMKj7TZtw", "status": "canceled" } } ``` ### Response Fields | Field | Type | Description | | - | - | - | | `orderId` | string | Order ID (Short ID) | | `status` | string | New order status (always `canceled` on success) | ## Errors > **Retry policy:** Never retry 4xx — fix the request and resubmit. Retry 5xx with exponential backoff (start 5s, max 3 attempts). | Status | `errors[0].message` | What it means | Recommended handling | | - | - | - | - | | 400 | `Missing required field: orderId` | `orderId` was not provided in the body | Fix the request body, then resubmit | | 400 | `Expected format: ORD_xxx, got "..."` | `orderId` Short ID could not be decoded | Fix the `orderId` format, then resubmit | | 400 | `Order cannot be canceled, current status: X` | Order status is not `pending` (e.g. already `completed` or `canceled`) | The order is no longer cancellable | | 401 | `Authentication failed` | Session token invalid, expired, or malformed | Re-mint the session token via Issue Session Token | | 403 | `Order does not belong to user` | Ownership check failed | Verify the caller owns the order | | 404 | `Order not found` | Order does not exist | Verify the order ID | | 500 | `Internal server error` | Unexpected server-side failure | Retry with exponential backoff (start 5s, max 3 attempts) | # Create Checkout Session Source: https://docs.waffo.ai/api-reference/endpoints/orders/create-checkout-session Lock product version, pricing, and currency for checkout Create a checkout session that locks product version, pricing, and currency. This is the first step in the checkout flow for both one-time and subscription products. The typical flow is: 1. Merchant creates a checkout session (server-side) 2. Returns `checkoutUrl` to the frontend 3. Customer clicks the link and lands on the hosted checkout page 4. Customer fills in billing details, previews tax, and completes the order ``` POST /v1/actions/checkout/create-session ``` **Authentication:** API Key or Store Slug ## Request Body (API Key) | Field | Type | Required | Description | | - | - | - | - | | `productId` | string | Yes | Product ID in Short ID format (`PROD_xxx`) | | `currency` | string | Yes | ISO 4217 currency code (e.g. `USD`, `EUR`, `JPY`) | | `priceSnapshot` | object | No | Override pricing at session creation (API Key only, see below) | | `withTrial` | boolean | No | Trial period for subscription products, three-state: `true` grants one, `false` withholds one, and omitting the field follows the product group's own rule. Identical on a new purchase and on a plan change | | `buyerEmail` | string | No | Pre-fill customer's email on the checkout page. **Ignored in [plan change mode](#plan-change-mode)** — the email comes from the origin subscription | | `billingDetail` | object | No | Pre-fill billing details (see below). **Ignored in [plan change mode](#plan-change-mode)** — billing details and tax come from the origin subscription | | `successUrl` | string | No | Override redirect URL after successful payment. Must be an absolute `https://` URL: a relative or scheme-less value is accepted here but rejected by the payment channel when the buyer pays (`[A0003] Parameter validation failed (successRedirectUrl is invalid)`), and the buyer only sees a generic payment-failed message. After paying, the buyer lands on the cashier's success page and is sent to this URL when they click **Done** — there is no automatic redirect today | | `expiresInSeconds` | number | No | Session TTL in seconds (default `86400` = 24 hours; recommended range `60`–`604800` (1 minute to 7 days); API Key only). Keep it as short as your flow allows, because the price snapshot stays locked for the session's whole life | | `darkMode` | boolean | No | Enable dark mode for the checkout page | | `metadata` | object | No | Custom key-value pairs attached to the session | | `orderMerchantExternalId` | string | No | Your business-side order reference (max 128 chars). | | `language` | string | No | Cashier UI language (IETF BCP 47). Must be one of the supported enum values: en, pt-BR, es-MX, id-ID, vi-VN, ru-RU, en-KE, es-PE, es-CO, es-CL, zh-Hant-TW, zh-Hant-HK, th-TH, ja-JP, en-NG, ko-KR, en-HK, zh-Hans-HK, pl-PL, tr-TR, zh-Hans, ms-MY. Sets the checkout page's default language; the customer can switch it on the page. | | `includePaymentMethods` / `excludePaymentMethods` | string\[] | No | Mutually exclusive — pass at most one. **include** is a whitelist: offer only these (`card`, `applepay`, `googlepay`, `wechat`), and every value must be supported by the product type × currency pair. **exclude** is a blacklist: offer everything the currency supports except these, with values the currency does not offer silently ignored, so one blacklist can be reused across currencies. Omit both to offer every method the currency supports. | | `couponId` | string | No | Coupon to apply, in Short ID format (`CPN_xxx`). The discount is **locked**: the customer sees the discount (its name, amount and duration) but not a code — even when the coupon has its own code — and cannot change or remove it. Merchant credentials only (API Key or JWT). Mutually exclusive with `allowPromotionCodes` and `promotionCode`. See [Discounts](#discounts) | | `promotionCode` | string | No | Coupon code or promotion code to pre-fill, as the code text (case-insensitive). The customer sees the code, including when it is the coupon's own code; with `allowPromotionCodes: true` they can replace or remove it, otherwise it is locked. Merchant credentials only (API Key or JWT). Mutually exclusive with `couponId`. See [Discounts](#discounts) | | `allowPromotionCodes` | boolean | No | Show a code entry field on the checkout page, where the customer can enter a coupon code or promotion code. When omitted, the field is shown only if the store has a code that can be used on this product — see [Default code entry field](#default-code-entry-field). Together with `promotionCode`, lets the customer replace or remove the pre-filled code. Mutually exclusive with `couponId`. See [Discounts](#discounts) | | `originOrderId` | string | No | Order ID of an existing subscription in Short ID format (`ORD_xxx`). **Passing it switches the endpoint into plan change mode** — see [Plan Change Mode](#plan-change-mode) | | `changeTiming` | string | No | When the new plan takes effect: `immediate` or `next_period`. Omit to let the platform derive it from the change direction. **Only valid together with `originOrderId`** | | `changeAmount` | string | No | What to actually charge for this change, as a display format string, tax inclusive (e.g. `"12.00"`). **Only valid together with `originOrderId`**, API Key only, and mutually exclusive with `changeCreditAmount` | | `changeCreditAmount` | string | No | How much to credit against this change instead, as a display format string, tax inclusive (e.g. `"8.00"`) — same unit and tax basis as `changeAmount`. **Only valid together with `originOrderId`**, API Key only, and mutually exclusive with `changeAmount` | ## Request Body (Store Slug) | Field | Type | Required | Description | | - | - | - | - | | `productId` | string | Yes | Product ID in Short ID format (`PROD_xxx`) | | `currency` | string | Yes | ISO 4217 currency code | | `buyerEmail` | string | No | Pre-fill customer's email | | `billingDetail` | object | No | Pre-fill billing details (see below) | | `successUrl` | string | No | Override redirect URL after successful payment. Must be an absolute `https://` URL: a relative or scheme-less value is accepted here but rejected by the payment channel when the buyer pays (`[A0003] Parameter validation failed (successRedirectUrl is invalid)`), and the buyer only sees a generic payment-failed message. After paying, the buyer lands on the cashier's success page and is sent to this URL when they click **Done** — there is no automatic redirect today | | `darkMode` | boolean | No | Enable dark mode for the checkout page | | `language` | string | No | Cashier UI language (IETF BCP 47). Must be one of the supported enum values: en, pt-BR, es-MX, id-ID, vi-VN, ru-RU, en-KE, es-PE, es-CO, es-CL, zh-Hant-TW, zh-Hant-HK, th-TH, ja-JP, en-NG, ko-KR, en-HK, zh-Hans-HK, pl-PL, tr-TR, zh-Hans, ms-MY. Sets the checkout page's default language; the customer can switch it on the page. | | `allowPromotionCodes` | boolean | No | Show the code entry field on the checkout page. When omitted, the field is shown only if the store has a code that can be used on this product — see [Default code entry field](#default-code-entry-field). `true` or `false` always takes effect as sent | | `discountCode` | string | No | Code carried by a product link's `discount_code` parameter (case-insensitive). The discount is applied and **locked**: the customer sees the code and cannot change or remove it. Not available with merchant credentials (`400`; use `couponId`), with a buyer session token (`403`), or in [plan change mode](#plan-change-mode) (`409`). Mutually exclusive with `allowPromotionCodes`, `couponId` and `promotionCode` | > [!NOTE] > > Store Slug authentication does not support `priceSnapshot`, `expiresInSeconds`, `metadata`, `orderMerchantExternalId`, `withTrial`, `changeAmount`, `changeCreditAmount`, `includePaymentMethods`, or `excludePaymentMethods`. These fields are silently ignored to prevent price tampering and session manipulation from the client side. Payment method selection is a merchant-side commercial decision (channel fees, settlement terms), so a browser cannot narrow or widen it — Store Slug sessions always offer everything the currency supports. > > `couponId` and `promotionCode` are the exceptions: they are rejected with `403` instead of being ignored, so a customer can never choose a coupon for themselves. > [!NOTE] > > **ID-naming convention**: the same flat dual-key names (`orderMerchantExternalId` on checkout-side, `refundTicketMerchantExternalId` on refund-ticket-side) are used across request bodies, webhook payloads, and every GraphQL type that carries the value — so a value written at checkout can be read back from `Order`, `Payment`, `Refund`, or a webhook payload under the same field name. > [!NOTE] > > **There is no `cancelUrl`.** If the buyer closes the cashier or abandons payment, nothing redirects them back to your site. The session simply expires (24 hours by default), the order ends `canceled` without a charge, and no webhook fires — there is nothing for you to handle. `cancelUrl`, `returnUrl` and similar fields are silently ignored if you send them. Keep your own "back to store" link on the page that opened the cashier. ## Price Snapshot Object | Field | Type | Required | Description | | - | - | - | - | | `amount` | string | Yes | Price as a non-negative display-format decimal string (e.g., "29.00" = \$29.00). Any other format — negative, exponent, thousands separator — is rejected with `400`, and so is an amount with more decimal places than the currency allows (trailing zeros do not count) | | `taxIncluded` | boolean | No | Whether the amount already includes tax (default: `false`) | | `taxCategory` | string | Yes | Tax category for tax calculation (e.g., `saas`, `digital_goods`) | For one-time products, `amount` replaces the product's price outright. For subscription products it replaces the **regular period** price only — the trial period price comes from the product version locked into the session and cannot be overridden here. ## Billing Detail Object | Field | Type | Required | Description | | - | - | - | - | | `country` | string | Yes | ISO 3166-1 alpha-2 country code (e.g. `US`, `JP`, `DE`) | | `isBusiness` | boolean | Yes | Whether this is a business purchase | | `postcode` | string | No | Postal or ZIP code | | `state` | string | No | State or province code (e.g. `CA`, `NY`, `ON`). Some billing countries require it | | `businessName` | string | No | Legal business name. Supply it alongside `isBusiness: true` so it appears on the invoice | | `taxId` | string | No | Tax registration number, e.g. an EU VAT number. Some billing countries require it | > [!NOTE] > > `billingDetail` only pre-fills the cashier. The country you send becomes the initial value of the editable country selector (a merchant value takes priority over IP-based detection), the buyer can change it, and the buyer's final choice is what the order records. No session or URL parameter locks or hides the billing fields. Payment methods are not driven by the country: they are resolved from product type × currency plus `includePaymentMethods` / `excludePaymentMethods`; the country is used only for the tax preview and for which address fields are shown, and it does not affect the buyer's payment currency — that is determined by the buyer's IP location when they open the payment page; see [Local currency pricing](/features/local-currency#how-the-currency-is-chosen). ## Plan Change Mode Passing `originOrderId` switches this endpoint into **plan change mode**: instead of a new-purchase link, the returned `checkoutUrl` points at a change confirmation page for an existing subscription — the path segment after the store slug is `change` instead of `checkout` (`…/store/{storeSlug}/change/{sessionId}`). A plan change is two steps — this endpoint issues the link, and the customer confirms on that page. A plan change is modelled as one cancellation plus one new subscription: the old order reaches its cancelled end state and a new order runs the normal creation lifecycle. It is not an in-place edit of the existing subscription. **Who can issue the link**: API Key (yours, server-side) or a customer session token. Store Slug is anonymous, so it has no subscription to attribute the change to — passing `originOrderId` with Store Slug auth always returns 403. ### Issuing the link with an SDK Every SDK gives plan change its own method with `originOrderId` required, so the "only valid together with `originOrderId`" rejections above cannot be expressed: ```typescript TypeScript theme={"system"} import { ChangeTiming, WaffoPancake } from "@waffo/pancake-ts"; const session = await client.checkout.createPlanChangeSession({ originOrderId: "ORD_5dXBtmF2HLlHfbPNm0Wcnz", productId: "PROD_3kF9mNpQrStUvWxYz1A2bC", currency: "USD", changeTiming: ChangeTiming.Immediate, changeCreditAmount: "8.00", // or changeAmount — never both }); // session.checkoutUrl → https://pancake.waffo.ai/store/{slug}/change/{sessionId} ``` ```go Go theme={"system"} session, err := client.Checkout.CreatePlanChangeSession(ctx, pancake.CreatePlanChangeSessionParams{ OriginOrderID: "ORD_5dXBtmF2HLlHfbPNm0Wcnz", ProductID: "PROD_3kF9mNpQrStUvWxYz1A2bC", Currency: "USD", ChangeTiming: pancake.Ptr(pancake.ChangeTimingImmediate), ChangeCreditAmount: pancake.Ptr("8.00"), }) ``` ```typescript Next.js theme={"system"} // Server action from createCheckoutAction() const session = await checkout({ type: "planChange", originOrderId: "ORD_5dXBtmF2HLlHfbPNm0Wcnz", productId: "PROD_3kF9mNpQrStUvWxYz1A2bC", currency: "USD", }); ``` These three sign with your API Key, so the pricing fields and `withTrial` are honored. Use `checkout.authenticated.createPlanChange()` (TypeScript / Next.js `authenticatedPlanChange`) or `Checkout.Authenticated.CreatePlanChange` (Go) to have the customer session token appended for you — that is the token the confirmation page needs, described next. For the customer-issued half, call `customer.createPlanChangeSession()` on a customer session (`client.customer(token)` in TypeScript, `client.Customer(token)` in Go, `customerAction(token, "createPlanChangeSession", …)` in Next.js). It runs under the customer's own credential, so the three 403 checks above apply and the API-Key-only fields are absent from its params — the platform would drop them unannounced. ### Building the link the customer opens The returned `checkoutUrl` carries **neither a buyer credential nor an environment flag** — the session was created with your server-side credential, so the platform cannot vouch for the buyer at that point. Opening the bare URL renders the comparison page, but the confirm step fails with a missing-authorisation message. You append both parts yourself: ``` {checkoutUrl}?test=true#token={customerSessionToken} ``` Query parameter first, fragment second. Drop `?test=true` in production. | Part | Rules | | - | - | | `#token=` | Must be the **fragment**, not a query parameter. The page consumes it on first paint and scrubs it from the address bar, so it never reaches server logs, referrers, or browser history — a `?token=` query parameter gets none of that, and the page does not read it | | Token type | A **customer** token from [`issue-session-token`](/api-reference/endpoints/auth/issue-session-token) or a buyer token. A shopper token (`request-session-token`) is **rejected** — it is a single-use guest credential and cannot modify an existing subscription | | `buyerIdentity` | Must match the origin subscription's buyer, or the submit is rejected as unauthorised | | Token lifetime | Customer tokens live **15 minutes** (sliding); the session lives 24 hours by default. Mint the token right before redirecting, not when you create the session | | `?test=true` | Required for test-mode sessions. The confirmation page trusts the session's own environment once it loads, but the flag keeps the first paint and the fallback paths on the right environment | Without a token the page falls back to asking the buyer to verify their email — a working but slower path. A wrong-environment link used to fail with `Environment mismatch between request and session` at the confirm step. > [!NOTE] > > `changeAmount`, `changeCreditAmount` and `withTrial` are **API Key only**. With any other credential they are silently ignored, the same way `priceSnapshot` is on a new purchase — you will not get an error telling you they were dropped. ### What the origin subscription supplies In plan change mode these values come from the subscription you are changing, not from your request body: | Value | Where it comes from | | - | - | | `buyerEmail` | The origin subscription. Passing it has no effect | | `billingDetail` | The origin subscription. Passing it has no effect | | Tax | Calculated from the **origin subscription's** billing address, not from a `billingDetail` you send | The currency must also match the origin subscription — cross-currency plan changes are rejected. ### Pricing the change Two fields, two ways to price the same change. They are **mutually exclusive** — sending both returns 400. | Field | Means | Example | | - | - | - | | `changeAmount` | Charge this much for this period | Target plan charges `20.00`, you send `"12.00"` → the customer pays 12.00 | | `changeCreditAmount` | Credit this much against this period | Target plan charges `20.00`, you send `"8.00"` → the customer pays 12.00 | Both are display format strings on the same unit and tax basis (tax inclusive), and both must leave a non-negative result: an amount above the target plan's charge for this period is rejected, and so is a credit above it. The two rejections are separate messages so you can tell which field to lower. A [discount](#discounts) on the change applies on top: on a change that takes effect immediately, the amount you set is the first period's price before the discount, and the customer pays it minus the discount. The discount itself is worked out on the target plan's full price and capped at the amount you set: target plan `20.00`, `changeAmount: "12.00"` and a 20% code → the discount is 4.00 and the customer pays 8.00. The same number means the opposite thing under each field, which is why the platform never picks one for you. Pick whichever matches how you priced the change: `changeAmount` when you know the final figure, `changeCreditAmount` when you know the discount. Either one counts as "the merchant priced this change" for the timing rules below. Internally the session stores one figure — the charge for this period — so a credit you specify is converted at issue time using the target plan's charge at that moment. ### When the new plan takes effect `changeTiming` accepts `immediate` or `next_period`. Omit it and the platform derives it from the change direction, which it works out by comparing pre-tax prices: an upgrade defaults to `immediate`, a downgrade or same-price switch defaults to `next_period`. | Rule | Behavior | | - | - | | `immediate` window | Requires at least 24 hours before the next charge, otherwise 400 | | `next_period` window | Requires at least 1 hour before the current period ends, otherwise 400 | | Downgrade or same-price with `immediate` | Rejected unless you also price the change (`changeAmount` or `changeCreditAmount`), or send `withTrial: true` | | Prorated credit | Applied on `immediate` only. `next_period` never prorates — the credit is zero. The credit is based on what the customer pays for the current period: the discounted amount when that period is discounted, the list price otherwise | > [!WARNING] > > **An upgrade inside the last 24 hours does not silently fall back to next period.** The upgrade default is `immediate`, so within 24 hours of the next charge a request that omits `changeTiming` gets a 400 — send `changeTiming: "next_period"` explicitly. A downgrade already defaults to `next_period`, so the same window does not affect it. ### One confirmed change at a time You can issue and submit several candidate changes for the same subscription while the customer makes up their mind. The subscription is locked to one change only once a change has been confirmed by the payment channel; after that, further attempts return 409. ### Response The response body is **identical to new-purchase mode** — `sessionId`, `checkoutUrl`, `expiresAt`, and no extra fields. The change direction, the resolved timing, and the prorated credit preview are written into the session for the confirmation page to read; they are not echoed back. Two consequences: * If you omit `changeTiming` you will not learn which tier the platform derived. Send it explicitly when you need certainty. * The prorated credit is an estimate taken at issue time and is **recalculated at submission** against the days actually remaining. Do not present it to the customer as a final figure. * A `next_period` change confirms the card with a `$0` payment record. In the Dashboard transaction list that row shows the plan price with **Charged \$0.00** underneath, and it is excluded from the subscription's charge count. For what arrives after the change lands, see [`subscription.plan_changed` and the two plan-change events](/api-reference/webhooks). For the customer-facing behavior of upgrades and downgrades, see [Subscriptions](/features/subscriptions). ## Discounts A checkout session — for a one-time product, a new subscription or a [plan change](#plan-change-mode) — can carry a discount in these ways. `couponId` cannot be combined with `promotionCode` or `allowPromotionCodes` — sending both returns `400`. | Field | What the customer sees | Who can set it | | - | - | - | | `couponId` | The discount is already applied and locked: the customer sees the discount and the discounted total but no code — even when the coupon has its own code — and has no code entry field. Wherever your customer reads the discount (checkout page, plan change page, their orders and subscriptions, emails), its `code` is `null`; you still see the code | Merchant credentials only (API Key or JWT). Any other credential gets `403` | | `promotionCode` | The code is already applied and the customer sees it — also when you pre-fill the coupon's own code. With `allowPromotionCodes: true` they can replace or remove it; otherwise it is locked | Merchant credentials only (API Key or JWT). Any other credential gets `403` | | `allowPromotionCodes: true` | A code entry field where the customer types a coupon code or promotion code, and can replace or remove it | Any credential — merchant credentials (API Key or JWT), Store Slug, and a customer or buyer session token issuing a plan change. When omitted, the field is shown only when a code can be used on the product (see below) | **Default code entry field.** When a request does not send `allowPromotionCodes` — with any credential: merchant credentials (API Key or JWT), Store Slug (product link or store page), or a customer or buyer session token issuing a plan change — the field is shown only if at least one coupon in this store and environment can be used on the session's product — on a plan change, the new plan's product. That coupon must be `active`, not expire within the next 60 seconds (`redeemBy`), still be under its total `maxRedemptions`, and cover the product (`productIds` empty or including it); and its own code or at least one of its promotion codes must be `active`, not expire within the next 60 seconds and still be under its own `maxRedemptions`. Rules that depend on the customer — eligible customers, uses per customer, minimum amount — and the currencies of a fixed-amount coupon are not considered here; they are checked when the customer enters a code. A coupon or code that has just expired or reached its limit can keep the field showing for up to 5 minutes. When you send `allowPromotionCodes`, your value is used as sent; sessions with a `couponId`, a product link's `discount_code`, or a `promotionCode` sent without `allowPromotionCodes` never show the field. **Checked when the session is created.** With `couponId` or `promotionCode`, the discount is checked right away against the rules that do not depend on the customer: it must belong to this store and environment, be `active`, not expire within the next 60 seconds, cover the product — on a plan change, the new plan's product — and, for a fixed-amount coupon, have an amount in the session currency. `promotionCode` is matched case-insensitively against the store's active codes. Otherwise the request fails with `409` and `errors[0].message` is the reason code (see [Errors](#errors)). **Checked when the order is placed.** Rules that depend on the customer — eligible customers, uses per customer — the coupon's total uses, and a promotion code's own total uses (`maxRedemptions`) and minimum amount (`minimumAmount`) are checked again when the customer places the order. If one fails, no order is created, nothing is charged and the checkout session stays usable. What the customer can do next depends on how the discount was applied: a code they typed can be removed to pay the full price, or replaced with another code; a code from a product link is locked, so the customer reopens the product link without `discount_code` (when a link's code is rejected as the page opens, that page offers **Continue without discount**); a `couponId` you set is locked too, so create a new checkout session without it, and so is a `promotionCode` you set without `allowPromotionCodes: true`. See [Discounts & Promotions](/guides/discounts#when-a-code-cannot-be-used) for every reason code. **Subscriptions.** On a new subscription the coupon's `duration` decides how many billing periods are discounted; a free trial uses no discount, which starts with the first paid period, while a paid trial is discounted. See [Discounts & Promotions](/guides/discounts#subscriptions). **Plan changes.** A plan change session (with `originOrderId`) takes `couponId`, `promotionCode` and `allowPromotionCodes` the same way. A code that comes with the change — set by you or entered by the customer — replaces the subscription's current discount and is a new use of the code: every rule is checked again when the customer confirms the change, and a promotion code's minimum amount is checked against the new plan's regular price before the discount and tax. Without a code, the current discount carries over to the new plan while it can, with its used periods kept. The first period's price before the discount is the new plan's price minus the prorated credit, or the amount you set with `changeAmount` / `changeCreditAmount`. The discount is worked out on the new plan's full price and then the credit is taken off, so the customer pays that price minus the discount, never below zero; when it is zero, the discount starts with the second period. See [Discounts & Promotions](/guides/discounts#plan-changes). ```typescript TypeScript theme={"system"} // Locked coupon await client.checkout.createSession({ productId: "PROD_xxx", currency: "USD", couponId: "CPN_xxx" }); // Code entry field await client.checkout.createSession({ productId: "PROD_xxx", currency: "USD", allowPromotionCodes: true }); // Pre-filled promotion code the customer can replace or remove await client.checkout.createSession({ productId: "PROD_xxx", currency: "USD", promotionCode: "KOL-ALICE", allowPromotionCodes: true }); // Plan change with a locked coupon await client.checkout.createPlanChangeSession({ originOrderId: "ORD_xxx", productId: "PROD_xxx", currency: "USD", couponId: "CPN_xxx" }); ``` ```go Go theme={"system"} _, err := client.Checkout.CreateSession(ctx, pancake.CreateCheckoutSessionParams{ ProductID: "PROD_xxx", Currency: "USD", CouponID: pancake.Ptr("CPN_xxx"), }) ``` Both SDKs reject `couponId` together with `allowPromotionCodes` or `promotionCode`, and a `couponId` without the `CPN_` prefix, before sending the request. The Next.js SDK server action strips `couponId` and `promotionCode` — see [Next.js Integration](/integrate/nextjs#discounts). ## Session Locks When a checkout session is created, the following values are locked and cannot change during the session lifetime: `productVersionId`, `productName`, `priceInfo`, `storeName`, `billingPeriod`, `withTrial`, `theme`, `buyerEmail`, `billingDetail` In [plan change mode](#plan-change-mode) the session additionally locks the change context: the origin subscription's snapshot, the change direction, the resolved timing and effective moment, the prorated credit preview, the amount you specified (a `changeCreditAmount` is stored as the charge it converts to), and the discount set on the session. The confirmation page reads all of it from the session, so none of it can be overridden at submission — the target plan, timing, and amount are settled the moment the link is issued. **Email normalization**: All email fields (`email`, `buyerEmail`, `contactEmail`) are normalized server-side via `trim().toLowerCase()` before storage, cache writes, and downstream calls. `Foo@Bar.COM` and `foo@bar.com` are treated as the same account. ## Example Request ```typescript SDK theme={"system"} import { WaffoPancake } from "@waffo/pancake-ts"; const client = new WaffoPancake({ merchantId: process.env.WAFFO_MERCHANT_ID!, privateKey: process.env.WAFFO_PRIVATE_KEY!, }); const session = await client.checkout.createSession({ productId: "PROD_7J3K5L8M2N4P6Q9R", currency: "USD", buyerEmail: "customer@example.com", language: "en", successUrl: "https://example.com/thank-you", }); console.log(session.sessionId); // "cs_550e8400-e29b-41d4-a716-446655440000" console.log(session.checkoutUrl); // "https://checkout.waffo.ai/..." console.log(session.expiresAt); // "2026-01-22T10:30:00.000Z" ``` ```bash cURL (API Key) theme={"system"} curl -X POST https://api.waffo.ai/v1/actions/checkout/create-session \ -H "Content-Type: application/json" \ -H "X-Merchant-Id: MER_2D5F8G3H1K4M6N9P" \ -H "X-Timestamp: 1711800000" \ -H "X-Signature: BASE64_RSA_SIGNATURE" \ -d '{ "productId": "PROD_7J3K5L8M2N4P6Q9R", "currency": "USD", "buyerEmail": "customer@example.com", "language": "en", "successUrl": "https://example.com/thank-you" }' ``` ```bash cURL (Store Slug) theme={"system"} curl -X POST https://api.waffo.ai/v1/actions/checkout/create-session \ -H "Content-Type: application/json" \ -H "X-Store-Slug: my-store-abc123" \ -H "X-Environment: test" \ -d '{ "productId": "PROD_7J3K5L8M2N4P6Q9R", "currency": "USD" }' ``` ```python Python theme={"system"} import requests response = requests.post( "https://api.waffo.ai/v1/actions/checkout/create-session", headers={ "Content-Type": "application/json", "X-Merchant-Id": "MER_2D5F8G3H1K4M6N9P", "X-Timestamp": "1711800000", "X-Signature": "BASE64_RSA_SIGNATURE", }, json={ "productId": "PROD_7J3K5L8M2N4P6Q9R", "currency": "USD", "buyerEmail": "customer@example.com", "language": "en", }, ) data = response.json()["data"] print(data["checkoutUrl"]) ``` ## Success Response (200) ```json theme={"system"} { "data": { "sessionId": "cs_550e8400-e29b-41d4-a716-446655440000", "checkoutUrl": "https://checkout.waffo.ai/my-store-abc123/checkout/cs_550e8400-e29b-41d4-a716-446655440000", "expiresAt": "2026-01-22T10:30:00.000Z" } } ``` ## Response Fields | Field | Type | Description | | - | - | - | | `sessionId` | string | Checkout session ID (`cs_` + UUID format, not a Short ID) | | `checkoutUrl` | string | Full URL to redirect the customer to the hosted checkout page | | `expiresAt` | string | ISO 8601 timestamp when the session expires | ## Errors > **Retry policy:** Never retry 4xx — fix the request and resubmit. The 409s below are exceptions in kind, not in policy: they report the subscription's state, not a malformed body, so resubmitting the same request keeps failing until that state changes. Retry 5xx with exponential backoff (start 5s, max 3 attempts). | Status | `errors[0].message` | What it means | Recommended handling | | - | - | - | - | | 400 | `Missing or invalid header: x-context-environment` | Environment header missing or not `test` / `prod` | Fix the header, resubmit | | 400 | `Invalid JSON body` | Request body is not valid JSON | Fix the body, resubmit | | 400 | `Missing required fields: productId, currency` | `productId` or `currency` is missing | Fix the body, resubmit | | 400 | `Invalid currency format: "X". Must be 3 uppercase letters (e.g., "USD", "EUR", "JPY")` | Currency is not 3 uppercase letters (ISO 4217) | Use a valid ISO 4217 code, resubmit | | 400 | `Invalid language, must be one of: en, pt-BR, … ms-MY` | `language` is not one of the supported cashier languages | Use a supported `language`, or omit it | | 400 | `includePaymentMethods and excludePaymentMethods are mutually exclusive` | Both lists were provided | Pass only one of them | | 400 | `Invalid includePaymentMethods, must be one of: card, applepay, googlepay, wechat` | A value outside the enum | Use supported values, or omit the field | | 400 | `Currency X is not supported for onetime payments` | The currency is outside the payment method matrix (one-time: USD, EUR, GBP, HKD, JPY, CNY; subscription: USD, EUR, GBP, HKD, JPY) | Use a supported currency | | 400 | `Payment methods not supported for X (onetime): wechat` | `includePaymentMethods` asks for a method this product type × currency does not offer | Drop the unsupported methods | | 400 | `No payment method remains for X (onetime) after applying excludePaymentMethods` | The blacklist removed everything | Exclude fewer methods | | 400 | `Expected format: PROD_xxx, got "..."` | `productId` Short ID could not be decoded | Fix `productId` format, resubmit | | 400 | `orderMerchantExternalId must not be empty` | Field was provided but is empty after trim | Omit the field or pass a non-empty value | | 400 | `orderMerchantExternalId must be at most 128 characters` | Value exceeds 128 chars | Shorten to 128 chars or less | | 400 | `Currency X is not supported for this product` | Product has no price snapshot for the requested currency | Use a currency supported by the product | | 400 | `originOrderId must not be empty` | Field was provided but is empty after trim | Omit the field or pass a non-empty value | | 400 | `changeAmount must not be empty` | Field was provided but is empty after trim | Omit the field or pass a non-empty value | | 400 | `changeCreditAmount must not be empty` | Field was provided but is empty after trim | Omit the field or pass a non-empty value | | 400 | `Invalid changeTiming, must be one of: immediate, next_period` | A value outside the enum | Use a supported value, or omit the field | | 400 | `changeTiming is only valid together with originOrderId` | `changeTiming` sent without `originOrderId` | Add `originOrderId`, or drop `changeTiming` | | 400 | `changeAmount is only valid together with originOrderId` | `changeAmount` sent without `originOrderId` | Add `originOrderId`, or drop `changeAmount` | | 400 | `changeCreditAmount is only valid together with originOrderId` | `changeCreditAmount` sent without `originOrderId` | Add `originOrderId`, or drop `changeCreditAmount` | | 400 | `changeAmount and changeCreditAmount are mutually exclusive` | Both pricing fields were sent | Pass only one of them | | 400 | `couponId and allowPromotionCodes are mutually exclusive` | Both discount fields were sent | Pass only one of them | | 400 | `couponId and promotionCode are mutually exclusive` | Both discount fields were sent | Pass only one of them | | 400 | `discountCode and allowPromotionCodes are mutually exclusive` / `couponId and discountCode are mutually exclusive` / `promotionCode and discountCode are mutually exclusive` | `discountCode` was sent with another discount field | Pass only one of them | | 400 | `discountCode is only available on product links; use couponId instead` | `discountCode` was sent with merchant credentials (API Key or JWT) | Use `couponId` or `promotionCode` | | 400 | `couponId must not be empty` | Field was provided but is empty after trim | Omit the field or pass a coupon ID | | 400 | `promotionCode must not be empty` | Field was provided but is empty after trim | Omit the field or pass a code | | 400 | `discountCode must not be empty` | Field was provided but is empty after trim | Omit the field or pass a code | | 400 | `Expected format: CPN_xxx, got "..."` | `couponId` Short ID could not be decoded | Fix `couponId` format, resubmit | | 400 | `Expected format: ORD_xxx, got "..."` | `originOrderId` Short ID could not be decoded | Fix `originOrderId` format, resubmit | | 400 | `Plan change is only available for subscription products` | `originOrderId` was sent with a one-time `productId` | Target a subscription product | | 400 | `Plan change must keep the original currency X, got Y` | `currency` differs from the origin subscription's | Resubmit with the origin subscription's currency | | 400 | `Target plan is the same as the current plan` | `productId` resolves to the plan the subscription is already on | Target a different plan | | 400 | `Missing required billing fields: X` | Tax could not be calculated from the origin subscription's billing address | Have the customer complete their billing details first | | 400 | `Specified amount exceeds the target plan's charge for this period` | `changeAmount` is above what the target plan charges for this period | Lower `changeAmount` to at most that charge | | 400 | `Specified credit amount exceeds the target plan's charge for this period` | `changeCreditAmount` is above what the target plan charges for this period | Lower `changeCreditAmount` to at most that charge | | 400 | `priceSnapshot.amount must be a non-negative decimal string (e.g., "9.99")` | `priceSnapshot.amount` is negative or not a plain decimal number | Send a non-negative amount such as `"29.00"` | | 400 | `Invalid priceSnapshot.amount for USD: "9.999". USD allows at most 2 decimal places` (`JPY does not allow decimal places` for zero-decimal currencies) | `priceSnapshot.amount` has more decimal places than the currency allows | Round the amount to the currency's precision yourself — it is never rounded for you | | 400 | `changeAmount must be a non-negative decimal string (e.g., "9.99")` / `changeCreditAmount must be a non-negative decimal string (e.g., "9.99")` | The field is negative or not a plain decimal number | Send a non-negative amount such as `"12.00"` | | 400 | `Invalid changeAmount for USD: "9.999". USD allows at most 2 decimal places` (`JPY does not allow decimal places` for zero-decimal currencies; same for `changeCreditAmount`) | The amount has more decimal places than the currency allows | Round the amount to the currency's precision yourself — it is never rounded for you | | 400 | `Immediate plan change requires at least 24 hours before the next charge` | `immediate` requested — or derived for an upgrade — inside the 24-hour window | Send `changeTiming: "next_period"` explicitly | | 400 | `Next-period plan change requires at least 1 hour before the period ends` | `next_period` requested inside the final hour of the period | Wait for the new period to start, then reissue | | 400 | `A downgrade or same-price change cannot take effect immediately unless the merchant specifies an amount or grants a trial` | `immediate` requested for a downgrade or same-price switch with neither pricing field and no `withTrial: true` | Drop `changeTiming`, or add `changeAmount` / `changeCreditAmount` / `withTrial: true` | | 400 | `Subscription has no current period end; plan change is unavailable until the channel reports one` | The origin subscription has no billing period recorded yet | Retry once the subscription has billed at least once | | 401 | `Unauthorized` | Invalid API Key signature or Store Slug | Verify auth headers | | 403 | `Store is not active` | Store status is not `active` | Activate the store first | | 403 | `Store is not accepting payments` | In the `prod` environment, the platform has suspended payment acceptance for this store | Platform-side switch — contact Waffo support | | 403 | `Store is not approved for production payments` | In the `prod` environment, the store has not passed production approval (`prod_enabled`, i.e. KYB review) | Use the `test` environment, or complete KYB review | | 403 | `No payment method is currently available for this store` | Every payment method available for this currency and product type has been suspended by the platform (applies in both `test` and `prod`) | Platform-side switch — contact Waffo support | | 403 | `Product does not belong to this store` | Product is not owned by the visiting store | Verify the product/store pair | | 403 | `Anonymous visitors cannot change an existing subscription` | `originOrderId` was sent with Store Slug auth | Issue the link with an API Key or a customer session token | | 403 | `couponId is only available with merchant credentials (API Key or JWT)` | `couponId` was sent with Store Slug auth or a customer session token | Create the session with your API Key, or use `allowPromotionCodes` | | 403 | `promotionCode is only available with merchant credentials (API Key or JWT)` | `promotionCode` was sent with Store Slug auth or a customer session token | Create the session with your API Key, or use `allowPromotionCodes` | | 403 | `discountCode is not available with buyer credentials` | `discountCode` was sent with a buyer session token | Create the session with Store Slug auth (product link), or use `allowPromotionCodes` | | 403 | `Subscription order does not belong to this credential` | The origin subscription is not yours (API Key) or not the signed-in customer's | Verify the `originOrderId` belongs to the caller | | 403 | `Target plan is not in the same product group as the current plan` | Customer-initiated change across product groups. API Key changes are not group-restricted | Target a plan in the same group, or issue the link with an API Key | | 403 | `Self-service plan change is not enabled for this product group` | Customer-initiated change while the group does not allow self-service changes | Enable self-service plan change on the group, or issue the link with an API Key | | 404 | `Store not found` | No store matches the given slug | Verify slug and environment | | 404 | `Product not found` | Product does not exist | Verify the `productId` | | 404 | `Product not found or not active for this environment` | Product has no active version for the given environment | Activate a product version for this environment | | 404 | `Subscription order not found` | No subscription matches `originOrderId` | Verify the `originOrderId` | | 409 | `Only an active subscription can change plan` | The origin subscription is not `active` — pending, past due, cancelling, or already ended | Do not resubmit; a subscription in these states cannot change plan | | 409 | `This subscription already has a confirmed plan change` | A change on this subscription has already been confirmed by the payment channel | Do not resubmit; change the new subscription once it is active | | 409 | `A subscription in its trial period cannot change plan` | The origin subscription is still in its trial or introductory phase | Wait for the regular period to begin, then reissue | | 409 | `Product link discount codes are not available for subscription plan changes` | `discountCode` was sent with `originOrderId` | Drop `discountCode`; use `promotionCode` or `allowPromotionCodes` for a plan change | | 409 | `CODE_NOT_FOUND` | `couponId` does not exist in this store and environment, or `promotionCode` / `discountCode` matches no active code there | Check the coupon ID or code, and the environment | | 409 | `CODE_INACTIVE` | The coupon is not `active` — deactivated or failed. A deactivated `promotionCode` is no longer an active code and returns `CODE_NOT_FOUND` instead | Use an `active` coupon or code | | 409 | `CODE_EXPIRED` | The coupon or promotion code has expired or expires within 60 seconds | Use a coupon or code that has not expired | | 409 | `PRODUCT_NOT_ELIGIBLE` | The coupon does not cover this product (on a plan change, the new plan's product) | Use a coupon that covers the product, or add the product to a new coupon | | 409 | `CURRENCY_MISMATCH` | The fixed-amount coupon has no amount in the session currency | Use another currency or another coupon | | 500 | `Internal server error` | Unexpected server-side failure | Retry with exponential backoff (start 5s, max 3 attempts) | > [!NOTE] > > Payment acceptance and production approval are two independent conditions: the former is a platform-controlled switch (which can suspend the whole store or individual payment methods), the latter is the production-approval (KYB) gate. Either one alone yields a 403 in the `prod` environment. Neither applies in the `test` environment. > [!TIP] > > The default session TTL is 24 hours (86400 seconds). When using API Key auth, you can customize this with `expiresInSeconds` (recommended range 1 minute to 7 days). Sessions lock the product version and pricing at creation time, so price changes will not affect existing sessions. # Order Endpoints Source: https://docs.waffo.ai/api-reference/endpoints/orders/overview Create checkout sessions and manage orders The order flow follows a session-based checkout pattern: 1. **Create a checkout session** -- locks the product version, pricing, and currency 2. **Create an order** -- initiates payment and returns a PSP-hosted checkout URL 3. **Cancel an order** -- cancels a pending (unpaid) order before payment completes > [!NOTE] > > **Create-order requires more than the obvious fields.** Alongside `checkoutSessionId` and `billingDetail`, both `/v1/actions/onetime-order/create-order` and `/v1/actions/subscription-order/create-order` require `language` and `userTerminal` (e.g. `"en"` / `"desktop"`) — omitting either returns `400 Invalid input` with no hint about which field is missing. Authenticate with the session token **alone**: adding `X-Store-Slug` next to the `Authorization` header fails with `Multiple authentication methods detected`. ## One-Time Order Status Values | Status | Description | | - | - | | `pending` | Order created, awaiting payment. Can be canceled. | | `completed` | Payment succeeded, order fulfilled. | | `canceled` | Order canceled before payment was completed. Terminal state. | ## Endpoints > **[Create Checkout Session](/api-reference/endpoints/orders/create-checkout-session)** > > Lock product version and pricing for checkout > **[Cancel One-Time Order](/api-reference/endpoints/orders/cancel-onetime-order)** > > Cancel a pending order before payment # Create Promotion Code Source: https://docs.waffo.ai/api-reference/endpoints/promotion-codes/create-promotion-code Add a promotion code to a coupon Add one promotion code to an `active` coupon. Pass your own `code`, or omit it to get a random one. ``` POST /v1/actions/promotion-code/create-promotion-code ``` **Authentication:** API Key ## Request Body | Field | Type | Required | Description | | - | - | - | - | | `couponId` | string | Yes | Coupon ID (Short ID format `CPN_xxx`). The coupon must be `active` | | `code` | string | No | Code buyers type: 3–32 letters, digits or `-`, case-insensitive, stored in uppercase. Must not match an active code in the same store and environment. Omit it to generate a random 10-character code | | `restrictions` | object | No | Buyer restrictions of this code (see below); the coupon's `redeemBy` and `maxRedemptions` also apply | ## Restrictions Object | Field | Type | Description | | - | - | - | | `customerEmails` | string\[] | Only these buyers (max 100 emails, case-insensitive). Empty means any buyer | | `perCustomerLimit` | integer \| null | Lifetime uses per buyer (≥ 1). `null` = unlimited | | `maxRedemptions` | integer \| null | Uses of this promotion code (≥ 1). Must not exceed the coupon's `maxRedemptions`. `null` = no extra limit | | `expiresAt` | string \| null | Expiry (ISO 8601, more than 60 seconds in the future). Must not be later than the coupon's `redeemBy`. Defaults to the coupon's `redeemBy`. Returns 409 if the coupon has expired | | `minimumAmount` | object \| null | Minimum order amount per currency, before discount and tax, as display-format strings (e.g. `{ "USD": "50.00" }`), with no more decimal places than the currency allows. Currencies not listed have no minimum | ## Example Request ```typescript SDK theme={"system"} const { promotionCode } = await client.promotionCodes.create( { couponId: "CPN_5dXBtmF2HLlHfbPNm0Wcnz", code: "kol-alice", // optional; a random code is generated when omitted restrictions: { maxRedemptions: 100, minimumAmount: { USD: "50.00" }, }, }, { idempotencyKey: "MER_2aUyqjCzEIiEcYMKj7TZtw-0f8e2a9c-5b1d-4e7a-9c3f-2d6b8e1a4c70" }, ); console.log(promotionCode.code); // => "KOL-ALICE" ``` ```bash cURL theme={"system"} MERCHANT_ID="MER_2aUyqjCzEIiEcYMKj7TZtw" IDEMPOTENCY_KEY="MER_2aUyqjCzEIiEcYMKj7TZtw-0f8e2a9c-5b1d-4e7a-9c3f-2d6b8e1a4c70" TIMESTAMP=$(date +%s) BODY='{"couponId":"CPN_5dXBtmF2HLlHfbPNm0Wcnz","code":"kol-alice","restrictions":{"maxRedemptions":100,"minimumAmount":{"USD":"50.00"}}}' BODY_HASH=$(echo -n "$BODY" | openssl dgst -sha256 -binary | base64 | tr -d '\n') CANONICAL_REQUEST="POST /v1/actions/promotion-code/create-promotion-code $TIMESTAMP $BODY_HASH" SIGNATURE=$(echo -n "$CANONICAL_REQUEST" | openssl dgst -sha256 -sign private_key.pem | base64 | tr -d '\n') curl -X POST "https://api.waffo.ai/v1/actions/promotion-code/create-promotion-code" \ -H "Content-Type: application/json" \ -H "X-Merchant-Id: $MERCHANT_ID" \ -H "X-Timestamp: $TIMESTAMP" \ -H "X-Signature: $SIGNATURE" \ -H "X-Idempotency-Key: $IDEMPOTENCY_KEY" \ -d "$BODY" ``` ```python Python theme={"system"} import hashlib, time, base64, json, requests from cryptography.hazmat.primitives import hashes, serialization from cryptography.hazmat.primitives.asymmetric import padding merchant_id = "MER_2aUyqjCzEIiEcYMKj7TZtw" timestamp = str(int(time.time())) body = { "couponId": "CPN_5dXBtmF2HLlHfbPNm0Wcnz", "code": "kol-alice", "restrictions": {"maxRedemptions": 100, "minimumAmount": {"USD": "50.00"}}, } body_json = json.dumps(body, separators=(",", ":")) body_hash = base64.b64encode(hashlib.sha256(body_json.encode()).digest()).decode() path = "/v1/actions/promotion-code/create-promotion-code" canonical = f"POST\n{path}\n{timestamp}\n{body_hash}" with open("private_key.pem", "rb") as f: private_key = serialization.load_pem_private_key(f.read(), password=None) signature = base64.b64encode( private_key.sign(canonical.encode(), padding.PKCS1v15(), hashes.SHA256()) ).decode() resp = requests.post( f"https://api.waffo.ai{path}", headers={ "Content-Type": "application/json", "X-Merchant-Id": merchant_id, "X-Timestamp": timestamp, "X-Signature": signature, "X-Idempotency-Key": "MER_2aUyqjCzEIiEcYMKj7TZtw-0f8e2a9c-5b1d-4e7a-9c3f-2d6b8e1a4c70", }, data=body_json, ) print(resp.json()) ``` ## Success Response (200) ```json theme={"system"} { "data": { "promotionCode": { "id": "PMC_6eYCunG3IMmIgcQOnaXdoA", "couponId": "CPN_5dXBtmF2HLlHfbPNm0Wcnz", "code": "KOL-ALICE", "status": "active", "restrictions": { "customerEmails": [], "perCustomerLimit": null, "maxRedemptions": 100, "expiresAt": "2026-12-01T00:00:00.000Z", "minimumAmount": { "USD": "50.00" } }, "batchId": null, "createdAt": "2026-11-02T08:00:00.000Z" } } } ``` ## Response Fields The response is wrapped in `data.promotionCode`. | Field | Type | Description | | - | - | - | | `id` | string | Promotion code ID (`PMC_xxx`) | | `couponId` | string | Coupon ID (`CPN_xxx`) | | `code` | string | The code, in uppercase | | `status` | string | `active` or `inactive` | | `restrictions` | object | `customerEmails`, `perCustomerLimit`, `maxRedemptions`, `expiresAt`, `minimumAmount` | | `batchId` | string \| null | Batch ID when created by [Generate Promotion Codes](/api-reference/endpoints/promotion-codes/generate-promotion-codes); otherwise `null` | | `createdAt` | string | Creation timestamp (ISO 8601) | ## Errors > **Retry policy:** Never retry 4xx — fix the request and resubmit. Retry 5xx with exponential backoff (start 5s, max 3 attempts). Always retry with the same `X-Idempotency-Key`. | Status | `errors[0].message` | What it means | Recommended handling | | - | - | - | - | | 400 | `Missing header: x-context-merchant-id` | The merchant context header was not forwarded | Fix your SDK configuration | | 400 | `Missing or invalid header: x-context-environment` | Environment header is missing or not `test` / `prod` | Set `X-Environment` to `test` or `prod` | | 400 | `Invalid JSON body` | The body is not valid JSON | Fix the body, resubmit | | 400 | `Missing required field: couponId` | `couponId` was omitted | Add `couponId`, resubmit | | 400 | `Expected format: CPN_xxx, got "X"` | `couponId` is not a valid Short ID | Use a `CPN_` prefixed Short ID | | 400 | `code must be a string` / `code must be 3-32 characters of letters, digits or '-'` | `code` is not a string, or has an invalid character or length | Fix `code`, or omit it to get a random code | | 400 | `restrictions.customerEmails[N] must be a valid email address` / `restrictions.customerEmails must not exceed 100 entries` | Email `N` (0-based) in `customerEmails` is not a valid address, or the list has more than 100 entries | Fix the list, resubmit | | 400 | `restrictions.firstTimeOnly is not supported` / `restrictions.dailyRedemptionLimit is not supported` | `restrictions` includes `firstTimeOnly` or `dailyRedemptionLimit` (any value, including `null` / `false`). These fields are not supported | Remove the field | | 400 | `restrictions.X must be an integer` / `restrictions.X must be at least 1` / `restrictions.X must not exceed 2147483647` | `perCustomerLimit` or `maxRedemptions` is not a positive integer, or is too large. `X` is the field, e.g. `restrictions.perCustomerLimit must be at least 1` | Use an integer from 1 to 2147483647, or `null` | | 400 | `restrictions.expiresAt must be an ISO 8601 datetime` | `expiresAt` is malformed | Send an ISO 8601 time with an offset (e.g. `Z`) | | 400 | `X: Invalid input: expected Y, received Z` | Field `X` has the wrong JSON type. `X` is its full path, e.g. `restrictions.maxRedemptions: Invalid input: expected number, received string` | Send the field with the type documented above | | 400 | `restrictions.minimumAmount: At least one currency is required` | `minimumAmount` is an empty object | Add a currency, or send `null` | | 400 | `restrictions.minimumAmount: Invalid currency code: "X". Must be 3 uppercase letters (e.g., "USD", "EUR", "JPY")` | A key in `minimumAmount` is not an ISO 4217 code | Use 3 uppercase letters | | 400 | `restrictions.minimumAmount: Invalid amount for X: "Y". Must be a positive number string (e.g., "5.00", "500")` | A `minimumAmount` value is not a positive number string | Use a positive decimal string | | 400 | `restrictions.minimumAmount: Invalid amount for X: "Y". X allows at most N decimal places` / `restrictions.minimumAmount: Invalid amount for X: "Y". X does not allow decimal places` | An `minimumAmount` value has more decimal places than the currency allows (e.g. USD `"0.001"`, JPY `"5.5"`). Amounts are not rounded | Use the currency's decimal places (USD 2, JPY 0, BHD 3) | | 400 | `restrictions.minimumAmount: Invalid amount for X: "Y". Must be at least Z X` | An `minimumAmount` value is less than one minor unit of the currency | Send at least the currency's minor unit (e.g. USD `"0.01"`) | | 400 | `restrictions.maxRedemptions must not exceed the coupon's maxRedemptions (X)` | The limit is higher than the coupon's | Lower `maxRedemptions` to at most the coupon's | | 400 | `restrictions.expiresAt must not be later than the coupon's redeemBy (X)` | The expiry is after the coupon's expiry | Use a time no later than the coupon's `redeemBy` | | 400 | `restrictions.expiresAt must be more than 60 seconds in the future` | The `expiresAt` you sent is less than 60 seconds away, or has already passed | Send an `expiresAt` more than 60 seconds in the future | | 401 | `Authentication required` | Authentication failed | Verify API key, timestamp, and signature | | 404 | `Coupon not found` | The coupon does not exist, belongs to another merchant, or is in the other environment | Verify `couponId` and the environment of your API key | | 409 | `Coupon is not active (status: X)` / `Coupon is not active` | The coupon is `pending` (still being created), `failed` or `inactive` | Use an active coupon | | 409 | `Coupon has expired (redeemBy: X); new promotion codes cannot be added` | The coupon has expired (less than 60 seconds before `redeemBy` counts as expired), whether or not `expiresAt` was sent | An expired coupon cannot get new promotion codes; create a new coupon | | 409 | `Generated code kept colliding with existing codes; retry the request or pass a code` | `code` was omitted and the random code kept matching existing active codes. No promotion code was created | Retry with a new idempotency key, or pass a `code` | | 409 | `Code "X" is already used by an active code in this store` | Another active code in this store and environment — a coupon's code or a promotion code — has this code, including the one your first attempt created, if you retried without an idempotency key | Choose another code. If this is a retry, look the promotion code up with GraphQL instead | | 409 | `Request is being processed` | A request with the same `X-Idempotency-Key` is still running | **Wait a few seconds, then retry with the same key** | | 500 | `Internal server error` | Unexpected server-side failure | Retry with exponential backoff (start 5s, max 3 attempts), same idempotency key | # Deactivate Promotion Code Source: https://docs.waffo.ai/api-reference/endpoints/promotion-codes/deactivate-promotion-code Permanently deactivate a promotion code and release its code Deactivate a promotion code. Buyers can no longer redeem it, and its code is released immediately: a new promotion code or coupon in the same store and environment can use it. ``` POST /v1/actions/promotion-code/deactivate-promotion-code ``` **Authentication:** API Key > [!WARNING] > > Deactivation is **permanent**. An inactive promotion code cannot be reactivated. To offer the code again, create a new promotion code with it. ## Request Body | Field | Type | Required | Description | | - | - | - | - | | `id` | string | Yes | Promotion code ID (Short ID format `PMC_xxx`) | ## Example Request ```typescript SDK theme={"system"} const { promotionCode } = await client.promotionCodes.deactivate({ id: "PMC_6eYCunG3IMmIgcQOnaXdoA" }); console.log(promotionCode.status); // => "inactive" ``` ```bash cURL theme={"system"} MERCHANT_ID="MER_2aUyqjCzEIiEcYMKj7TZtw" TIMESTAMP=$(date +%s) BODY='{"id":"PMC_6eYCunG3IMmIgcQOnaXdoA"}' BODY_HASH=$(echo -n "$BODY" | openssl dgst -sha256 -binary | base64 | tr -d '\n') CANONICAL_REQUEST="POST /v1/actions/promotion-code/deactivate-promotion-code $TIMESTAMP $BODY_HASH" SIGNATURE=$(echo -n "$CANONICAL_REQUEST" | openssl dgst -sha256 -sign private_key.pem | base64 | tr -d '\n') curl -X POST "https://api.waffo.ai/v1/actions/promotion-code/deactivate-promotion-code" \ -H "Content-Type: application/json" \ -H "X-Merchant-Id: $MERCHANT_ID" \ -H "X-Timestamp: $TIMESTAMP" \ -H "X-Signature: $SIGNATURE" \ -d "$BODY" ``` ```python Python theme={"system"} import hashlib, time, base64, json, requests from cryptography.hazmat.primitives import hashes, serialization from cryptography.hazmat.primitives.asymmetric import padding merchant_id = "MER_2aUyqjCzEIiEcYMKj7TZtw" timestamp = str(int(time.time())) body = {"id": "PMC_6eYCunG3IMmIgcQOnaXdoA"} body_json = json.dumps(body, separators=(",", ":")) body_hash = base64.b64encode(hashlib.sha256(body_json.encode()).digest()).decode() path = "/v1/actions/promotion-code/deactivate-promotion-code" canonical = f"POST\n{path}\n{timestamp}\n{body_hash}" with open("private_key.pem", "rb") as f: private_key = serialization.load_pem_private_key(f.read(), password=None) signature = base64.b64encode( private_key.sign(canonical.encode(), padding.PKCS1v15(), hashes.SHA256()) ).decode() resp = requests.post( f"https://api.waffo.ai{path}", headers={ "Content-Type": "application/json", "X-Merchant-Id": merchant_id, "X-Timestamp": timestamp, "X-Signature": signature, }, data=body_json, ) print(resp.json()) ``` ## Success Response (200) ```json theme={"system"} { "data": { "promotionCode": { "id": "PMC_6eYCunG3IMmIgcQOnaXdoA", "couponId": "CPN_5dXBtmF2HLlHfbPNm0Wcnz", "code": "KOL-ALICE", "status": "inactive", "restrictions": { "customerEmails": [], "perCustomerLimit": null, "maxRedemptions": 100, "expiresAt": "2026-12-01T00:00:00.000Z", "minimumAmount": { "USD": "50.00" } }, "batchId": null, "createdAt": "2026-11-02T08:00:00.000Z" } } } ``` ## Response Fields Same as [Create Promotion Code response](/api-reference/endpoints/promotion-codes/create-promotion-code). > [!NOTE] > > Existing orders keep the code they were placed with and are not affected. Deactivating an already inactive promotion code returns `200` with it unchanged. Deactivating a promotion code never deactivates its coupon. The coupon's own code can only be deactivated by [deactivating the coupon](/api-reference/endpoints/coupons/deactivate-coupon), which also stops all its promotion codes. ## Errors > **Retry policy:** Never retry 4xx — fix the request and resubmit. Retry 5xx with exponential backoff (start 5s, max 3 attempts). | Status | `errors[0].message` | What it means | Recommended handling | | - | - | - | - | | 400 | `Missing or invalid header: x-context-environment` | Environment header is missing or not `test` / `prod` | Set `X-Environment` to `test` or `prod` | | 400 | `Invalid JSON body` | The body is not valid JSON | Fix the body, resubmit | | 400 | `Missing required field: id` | `id` was omitted | Add `id`, resubmit | | 400 | `Expected format: PMC_xxx, got "X"` | `id` is not a valid Short ID | Use a `PMC_` prefixed Short ID | | 401 | `Authentication required` | Authentication failed | Verify API key, timestamp, and signature | | 404 | `Promotion code not found` | The promotion code does not exist, belongs to another merchant, or is in the other environment | Verify the `id` and the environment of your API key | | 409 | `The coupon's own code can only be deactivated together with the coupon` | The ID is the coupon's own code, not one of its promotion codes | Deactivate the coupon instead | | 500 | `Internal server error` | Unexpected server-side failure | Retry with exponential backoff (start 5s, max 3 attempts) | # Generate Promotion Codes Source: https://docs.waffo.ai/api-reference/endpoints/promotion-codes/generate-promotion-codes Generate 1–500 random promotion codes for a coupon in one call Generate 1–500 random promotion codes for an `active` coupon. All codes in the batch share the same restrictions and `batchId`, and are returned together in the response — for example, to export as a CSV of single-use codes. ``` POST /v1/actions/promotion-code/generate-promotion-codes ``` **Authentication:** API Key > [!WARNING] > > **Always send an `X-Idempotency-Key` and retry with the same key.** Codes are random, so a retry without the key creates a second batch. ## Request Body | Field | Type | Required | Description | | - | - | - | - | | `couponId` | string | Yes | Coupon ID (Short ID format `CPN_xxx`). The coupon must be `active` | | `count` | integer | Yes | Number of codes, 1–500 | | `prefix` | string | No | Code prefix, 1–12 letters, digits or `-`, converted to uppercase | | `length` | integer | No | Length of the random part, 8–16. Default `10`. Uses uppercase letters and digits without `0`, `O`, `1`, `I` and `L` | | `restrictions` | object | No | Applied to every code. Same fields as [Create Promotion Code](/api-reference/endpoints/promotion-codes/create-promotion-code); for single-use codes set `maxRedemptions: 1` | Each code is `prefix` + random part, e.g. `VIP-7KQ2MZ9H3X`. Generated codes never match an active code in the same store and environment. ## Example Request ```typescript SDK theme={"system"} const { batchId, promotionCodes } = await client.promotionCodes.generate( { couponId: "CPN_5dXBtmF2HLlHfbPNm0Wcnz", count: 100, prefix: "vip-", length: 10, restrictions: { maxRedemptions: 1 }, }, { idempotencyKey: "MER_2aUyqjCzEIiEcYMKj7TZtw-7c41d0b2-93ae-4f68-b5d1-6a2e9f03c8d4" }, ); console.log(promotionCodes.length, promotionCodes[0].code); // => 100 "VIP-7KQ2MZ9H3X" ``` ```bash cURL theme={"system"} MERCHANT_ID="MER_2aUyqjCzEIiEcYMKj7TZtw" IDEMPOTENCY_KEY="MER_2aUyqjCzEIiEcYMKj7TZtw-7c41d0b2-93ae-4f68-b5d1-6a2e9f03c8d4" TIMESTAMP=$(date +%s) BODY='{"couponId":"CPN_5dXBtmF2HLlHfbPNm0Wcnz","count":100,"prefix":"vip-","length":10,"restrictions":{"maxRedemptions":1}}' BODY_HASH=$(echo -n "$BODY" | openssl dgst -sha256 -binary | base64 | tr -d '\n') CANONICAL_REQUEST="POST /v1/actions/promotion-code/generate-promotion-codes $TIMESTAMP $BODY_HASH" SIGNATURE=$(echo -n "$CANONICAL_REQUEST" | openssl dgst -sha256 -sign private_key.pem | base64 | tr -d '\n') curl -X POST "https://api.waffo.ai/v1/actions/promotion-code/generate-promotion-codes" \ -H "Content-Type: application/json" \ -H "X-Merchant-Id: $MERCHANT_ID" \ -H "X-Timestamp: $TIMESTAMP" \ -H "X-Signature: $SIGNATURE" \ -H "X-Idempotency-Key: $IDEMPOTENCY_KEY" \ -d "$BODY" ``` ```python Python theme={"system"} import hashlib, time, base64, json, requests from cryptography.hazmat.primitives import hashes, serialization from cryptography.hazmat.primitives.asymmetric import padding merchant_id = "MER_2aUyqjCzEIiEcYMKj7TZtw" timestamp = str(int(time.time())) body = { "couponId": "CPN_5dXBtmF2HLlHfbPNm0Wcnz", "count": 100, "prefix": "vip-", "length": 10, "restrictions": {"maxRedemptions": 1}, } body_json = json.dumps(body, separators=(",", ":")) body_hash = base64.b64encode(hashlib.sha256(body_json.encode()).digest()).decode() path = "/v1/actions/promotion-code/generate-promotion-codes" canonical = f"POST\n{path}\n{timestamp}\n{body_hash}" with open("private_key.pem", "rb") as f: private_key = serialization.load_pem_private_key(f.read(), password=None) signature = base64.b64encode( private_key.sign(canonical.encode(), padding.PKCS1v15(), hashes.SHA256()) ).decode() resp = requests.post( f"https://api.waffo.ai{path}", headers={ "Content-Type": "application/json", "X-Merchant-Id": merchant_id, "X-Timestamp": timestamp, "X-Signature": signature, "X-Idempotency-Key": "MER_2aUyqjCzEIiEcYMKj7TZtw-7c41d0b2-93ae-4f68-b5d1-6a2e9f03c8d4", }, data=body_json, ) print(resp.json()) ``` ## Success Response (200) ```json theme={"system"} { "data": { "batchId": "9b2f6c1e-3d4a-4f5b-8c7d-1e2f3a4b5c6d", "promotionCodes": [ { "id": "PMC_7fZDvoH4JNnJhdRPobYepB", "couponId": "CPN_5dXBtmF2HLlHfbPNm0Wcnz", "code": "VIP-7KQ2MZ9H3X", "status": "active", "restrictions": { "customerEmails": [], "perCustomerLimit": null, "maxRedemptions": 1, "expiresAt": "2026-12-01T00:00:00.000Z", "minimumAmount": null }, "batchId": "9b2f6c1e-3d4a-4f5b-8c7d-1e2f3a4b5c6d", "createdAt": "2026-11-03T08:00:00.000Z" } ] } } ``` ## Response Fields | Field | Type | Description | | - | - | - | | `batchId` | string | Batch ID shared by all codes in this call. Filter GraphQL `promotionCodes` by it to read the batch again | | `promotionCodes` | array | The generated promotion codes. Each item has the same fields as the [Create Promotion Code response](/api-reference/endpoints/promotion-codes/create-promotion-code) | ## Errors > **Retry policy:** Never retry 4xx — fix the request and resubmit. Retry 5xx with exponential backoff (start 5s, max 3 attempts). Always retry with the same `X-Idempotency-Key`. | Status | `errors[0].message` | What it means | Recommended handling | | - | - | - | - | | 400 | `Missing header: x-context-merchant-id` | The merchant context header was not forwarded | Fix your SDK configuration | | 400 | `Missing or invalid header: x-context-environment` | Environment header is missing or not `test` / `prod` | Set `X-Environment` to `test` or `prod` | | 400 | `Invalid JSON body` | The body is not valid JSON | Fix the body, resubmit | | 400 | `Missing required field: couponId` / `Missing required field: count` | A required field was omitted | Add the missing field, resubmit | | 400 | `Expected format: CPN_xxx, got "X"` | `couponId` is not a valid Short ID | Use a `CPN_` prefixed Short ID | | 400 | `count must be an integer` / `count must be between 1 and 500` | `count` is out of range | Use an integer from 1 to 500; split larger batches into several calls | | 400 | `prefix must be 1-12 characters of letters, digits or '-'` | `prefix` has an invalid character or length | Fix `prefix`, resubmit | | 400 | `length must be an integer` / `length must be between 8 and 16` | `length` is out of range | Use an integer from 8 to 16 | | 400 | `restrictions.maxRedemptions must not exceed the coupon's maxRedemptions (X)` | The limit is higher than the coupon's | Lower `maxRedemptions` to at most the coupon's | | 400 | `restrictions.expiresAt must not be later than the coupon's redeemBy (X)` | The expiry is after the coupon's expiry | Use a time no later than the coupon's `redeemBy` | | 400 | `restrictions.expiresAt must be more than 60 seconds in the future` | The `expiresAt` you sent is less than 60 seconds away, or has already passed | Send an `expiresAt` more than 60 seconds in the future | | 400 | `restrictions.customerEmails[N] must be a valid email address` / `restrictions.customerEmails must not exceed 100 entries` | Email `N` (0-based) in `customerEmails` is not a valid address, or the list has more than 100 entries | Fix the list, resubmit | | 400 | `restrictions.firstTimeOnly is not supported` / `restrictions.dailyRedemptionLimit is not supported` | `restrictions` includes `firstTimeOnly` or `dailyRedemptionLimit` (any value, including `null` / `false`). These fields are not supported | Remove the field | | 400 | `restrictions.X must be an integer` / `restrictions.X must be at least 1` / `restrictions.X must not exceed 2147483647` | `perCustomerLimit` or `maxRedemptions` is not a positive integer, or is too large. `X` is the field, e.g. `restrictions.perCustomerLimit must be at least 1` | Use an integer from 1 to 2147483647, or `null` | | 400 | `restrictions.expiresAt must be an ISO 8601 datetime` | `expiresAt` is malformed | Send an ISO 8601 time with an offset (e.g. `Z`) | | 400 | `X: Invalid input: expected Y, received Z` | Field `X` has the wrong JSON type. `X` is its full path, e.g. `length: Invalid input: expected number, received string` or `restrictions.maxRedemptions: Invalid input: expected number, received string` | Send the field with the type documented above | | 400 | `restrictions.minimumAmount: At least one currency is required` | `minimumAmount` is an empty object | Add a currency, or send `null` | | 400 | `restrictions.minimumAmount: Invalid currency code: "X". Must be 3 uppercase letters (e.g., "USD", "EUR", "JPY")` | A key in `minimumAmount` is not an ISO 4217 code | Use 3 uppercase letters | | 400 | `restrictions.minimumAmount: Invalid amount for X: "Y". Must be a positive number string (e.g., "5.00", "500")` | A `minimumAmount` value is not a positive number string | Use a positive decimal string | | 400 | `restrictions.minimumAmount: Invalid amount for X: "Y". X allows at most N decimal places` / `restrictions.minimumAmount: Invalid amount for X: "Y". X does not allow decimal places` | An `minimumAmount` value has more decimal places than the currency allows (e.g. USD `"0.001"`, JPY `"5.5"`). Amounts are not rounded | Use the currency's decimal places (USD 2, JPY 0, BHD 3) | | 400 | `restrictions.minimumAmount: Invalid amount for X: "Y". Must be at least Z X` | An `minimumAmount` value is less than one minor unit of the currency | Send at least the currency's minor unit (e.g. USD `"0.01"`) | | 401 | `Authentication required` | Authentication failed | Verify API key, timestamp, and signature | | 404 | `Coupon not found` | The coupon does not exist, belongs to another merchant, or is in the other environment | Verify `couponId` and the environment of your API key | | 409 | `Coupon is not active (status: X)` / `Coupon is not active` | The coupon is `pending` (still being created), `failed` or `inactive` | Use an active coupon | | 409 | `Coupon has expired (redeemBy: X); new promotion codes cannot be added` | The coupon has expired (less than 60 seconds before `redeemBy` counts as expired), whether or not `expiresAt` was sent | An expired coupon cannot get new promotion codes; create a new coupon | | 409 | `Generated codes kept colliding with existing codes; try a longer length or another prefix` | Random codes kept matching existing active codes. No codes were created | Increase `length` or change `prefix`, then retry | | 409 | `Request is being processed` | A request with the same `X-Idempotency-Key` is still running | **Wait a few seconds, then retry with the same key** | | 500 | `Internal server error` | Unexpected server-side failure | Retry with exponential backoff (start 5s, max 3 attempts), same idempotency key | # Promotion Code Endpoints Source: https://docs.waffo.ai/api-reference/endpoints/promotion-codes/overview Give buyers more codes for a coupon, each with its own restrictions A promotion code is another code buyers can type for an existing [coupon](/api-reference/endpoints/coupons/overview). It gives the coupon's discount. The coupon only limits its expiry and total uses; buyer restrictions are set on each promotion code. Use promotion codes for an influencer, a campaign channel, or a batch of single-use codes. Promotion codes only exist for `active` coupons, in the coupon's store and environment. Creating promotion codes does not change the coupon's discount. ## Promotion Code Status Values | Status | Description | | - | - | | `active` | Usable at checkout while its coupon is `active` | | `inactive` | Deactivated. This is permanent — an inactive promotion code cannot be reactivated | ## Restrictions Each promotion code has its own buyer restrictions. The coupon's `redeemBy` and `maxRedemptions` apply to every code as well: | Field | Description | | - | - | | `customerEmails` | Only these buyers (max 100 emails, case-insensitive) | | `perCustomerLimit` | Lifetime uses per buyer | | `maxRedemptions` | Uses of this promotion code. Must not exceed the coupon's `maxRedemptions`; the coupon's limit still applies | | `expiresAt` | Expiry. Must not be later than the coupon's `redeemBy`. Defaults to the coupon's `redeemBy` | | `minimumAmount` | Minimum order amount per currency, before discount and tax, e.g. `{ "USD": "50.00" }`. Currencies not listed have no minimum | Create promotion codes together with the coupon ([Create Coupon](/api-reference/endpoints/coupons/create-coupon), up to 20) or one by one and in bulk with the endpoints below. The coupon's own `code` is not one of its promotion codes: it has no restrictions of its own, is not returned by `promotionCodes`, and can only be deactivated together with the coupon. ## Codes Promotion codes follow the same [code format](/api-reference/endpoints/coupons/overview) as coupons: 3–32 letters, digits or `-`, case-insensitive, stored in uppercase, unique among the store's active codes in the same environment, and released when deactivated. When you omit `code`, or generate codes in bulk, the random part uses uppercase letters and digits without the look-alike characters `0`, `O`, `1`, `I` and `L`. ## Safe Retries Send an `X-Idempotency-Key` header (SDK: the `idempotencyKey` option) and reuse it when you retry. This matters most for [Generate Promotion Codes](/api-reference/endpoints/promotion-codes/generate-promotion-codes): codes are random, so a retry without the key generates a second batch. See [Errors](/api-reference/errors) for the key requirements. ## Reading Promotion Codes These endpoints only write. List a coupon's promotion codes with [GraphQL](/api-reference/endpoints/graphql/overview): `promotionCodes` and `promotionCodesCount`. Filter by `batchId` to read back a generated batch. ```graphql theme={"system"} query PromotionCodes($couponId: String!) { promotionCodes(couponId: $couponId, limit: 50, offset: 0) { id code status batchId timesRedeemed } promotionCodesCount(couponId: $couponId) } ``` ## Endpoints > **[Create Promotion Code](/api-reference/endpoints/promotion-codes/create-promotion-code)** > > Add one promotion code to a coupon. > **[Generate Promotion Codes](/api-reference/endpoints/promotion-codes/generate-promotion-codes)** > > Generate 1–500 random promotion codes in one call. > **[Deactivate Promotion Code](/api-reference/endpoints/promotion-codes/deactivate-promotion-code)** > > Permanently deactivate a promotion code and release its code. # Create Refund Ticket Source: https://docs.waffo.ai/api-reference/endpoints/refunds/create-refund-ticket Request a refund for a previously succeeded payment `POST /v1/actions/refund-ticket/create-ticket` **Authentication:** Merchant API Key (server-to-server). ## Request body | Field | Type | Required | Description | | - | - | - | - | | `paymentId` | string | Yes | Short ID of the payment to refund, e.g. `PAY_6eYCunG3IMmIgcQOnaXdoA` | | `reason` | string | Yes | Free-text reason shown to the customer / dashboard | | `requestedAmount.amount` | string | Yes | Refund amount in display format (e.g. `"10.50"`), must be `> 0` and `≤ payment.amount` | | `requestedAmount.currency` | string | Yes | ISO 4217 code, must match the payment currency | | `refundTicketMerchantExternalId` | string | No | Your business-side refund-ticket reference (max 128 chars). | ## Success response (200) ```json theme={"system"} { "data": { "ticket": { "id": "TKT_3bVzrkD0FJjFdZNLk8Ualx", "status": "processing", "subjectId": "PAY_6eYCunG3IMmIgcQOnaXdoA", "refundTicketMerchantExternalId": "REF-2026-00891" } } } ``` When the merchant submits via API Key, the ticket is auto-approved and goes straight to `processing`. ## Errors > **Retry policy:** Never retry 4xx — fix the request and resubmit. Retry 5xx with exponential backoff (start 5s, max 3 attempts). | Status | `errors[0].message` | What it means | Recommended handling | | - | - | - | - | | 400 | `Missing required field: ` | Required field missing (`paymentId`, `reason`, `requestedAmount.amount`, `requestedAmount.currency`) | Fix the body, resubmit | | 400 | `Expected format: PAY_xxx, got "..."` | `paymentId` Short ID could not be decoded | Fix `paymentId` format, resubmit | | 400 | `Invalid requestedAmount.amount format` | Amount string could not be parsed | Use a display string like `"10.50"` (not minor units) | | 400 | `refundTicketMerchantExternalId must be at most 128 characters` | Value exceeds 128 chars | Shorten to 128 chars or less | | 401 | `Unauthorized` | Invalid API Key signature | Verify auth headers | | 404 | `Payment not found` | Payment doesn't exist or doesn't belong to your store | Verify `paymentId` | | 409 | `Payment status is X, must be succeeded` | Original payment is not in `succeeded` state | Do not retry — the payment never succeeded | | 409 | `Payment is not yet fully processed by PSP, please retry later` | PSP confirmation hasn't been written back yet | Retry after 5–30 seconds (transient) | | 409 | `Requested amount must be greater than 0` | Amount is ≤ 0 | Fix the amount, resubmit | | 409 | `Requested amount exceeds payment amount` | Amount > `payment.amount` | Fix the amount, resubmit | | 409 | `Currency mismatch: requested X, payment Y` | Currency must match the original payment | Use the payment's currency | | 409 | `A refund record already exists for this payment` | A previous refund already succeeded against this payment | Do not retry — query existing refunds via GraphQL | | 409 | `A refund ticket already exists for this payment` | Another in-flight ticket is blocking | Wait for the existing ticket to terminate, then resubmit if still needed | | 409 | `Insufficient available balance for refund: requested X, available Y (CCY)` | The payment has settled and the refund exceeds your available balance | Refund a smaller amount, or retry once your available balance is sufficient | | 409 | `Store owner merchant not found` | The payment has settled, but the store owner's balance cannot be resolved for your account | Do not retry — ask the store owner to issue the refund | | 503 | `Balance check temporarily unavailable, please retry later` | The balance check is temporarily unavailable; no ticket was created | Retry with exponential backoff (start 5s, max 3 attempts) | | 500 | `Internal server error` | Unexpected server-side failure | Retry with exponential backoff (start 5s, max 3 attempts) | > [!TIP] > > Use [GraphQL](/api-reference/endpoints/graphql/orders-and-payments) to query the created ticket and the executed refund record. Filter executed refunds by the ticket reference using `refunds(filter: { refundTicketMerchantExternalId: ... })`. # Refund Endpoints Source: https://docs.waffo.ai/api-reference/endpoints/refunds/overview Request refunds and query refund records via REST + GraphQL Refund endpoints allow merchants to issue refunds for previously succeeded payments. Refunds are modelled as **refund tickets** (the request) and **refund records** (the executed result, written after PSP confirms). *** ## Business Rules > [!NOTE] > > * Refunds you issue as a merchant have **no time limit** — you can refund at any time after the original payment succeeds > * Refund amount can be **partial** (any value `> 0` and `≤ payment.amount`), but must use the **same currency** as the payment > * The original payment must already be **fully confirmed by the PSP** — calling refund immediately after a payment webhook arrives may transiently fail; retry after a few seconds > * A payment that already has a pending or succeeded refund **cannot have another refund ticket created** at the same time > * When the merchant submits the refund (server-to-server via API Key), the ticket is **auto-approved** and goes straight to processing — no manual review step *** ## Refund Ticket Status Values | Status | Meaning for merchant | | - | - | | `pending` | Awaiting Waffo review (only seen when customer self-initiated) | | `approved` | Approved, will be dispatched to PSP shortly | | `rejected` | Rejected — see `rejectReason` in GraphQL | | `processing` | Dispatched to PSP, awaiting upstream completion | | `succeeded` | Funds returned to the customer | | `failed` | PSP returned failure — can be reviewed and resubmitted | > [!TIP] > > Merchant-initiated refunds skip `pending` and `approved` entirely — they appear as `processing` immediately after creation. *** ## Business identifiers — link your records to Waffo You can attach an optional business-side identifier (max **128 characters**) at two creation points; on the wire each one carries its own flat key so a single payload can hold both without ambiguity: | Created at | Request body field | Stored as | | - | - | - | | `checkout/create-session` | `orderMerchantExternalId` | `orders.merchant_external_id` (inherited by first and renewal payments) | | `refund-ticket/create-ticket` | `refundTicketMerchantExternalId` | `refund_tickets.merchant_external_id` (inherited by the executed refund record) | End-to-end propagation (the same flat dual-key names are used everywhere — request bodies, webhook payloads, and GraphQL types): ``` checkout/create-session (request: orderMerchantExternalId) │ ├──► OnetimeOrder / SubscriptionOrder . orderMerchantExternalId ├──► Payment . orderMerchantExternalId (first + subscription renewals) │ refund-ticket/create-ticket (request: refundTicketMerchantExternalId) │ ├──► RefundTicket . refundTicketMerchantExternalId │ └──► Refund carries BOTH: • orderMerchantExternalId (from the originating order) • refundTicketMerchantExternalId (from the originating refund ticket) ``` These identifiers are **not** idempotency keys — Waffo does not enforce uniqueness; the same reference can be attached to multiple records and you are responsible for any uniqueness guarantees on your side. The same field names appear in three places — request body, webhook payload, GraphQL — so the value you write at checkout/refund-ticket creation can be read back without renaming. Use these identifiers to **query** Payments, Refunds, and Refund Tickets via GraphQL — see the [GraphQL orders & payments](/api-reference/endpoints/graphql/orders-and-payments) guide. *** ## Endpoints > **[Create Refund Ticket](/api-reference/endpoints/refunds/create-refund-ticket)** > > Request a refund for a succeeded payment. Supports full and partial refunds. > **[Resubmit Refund Ticket](/api-reference/endpoints/refunds/resubmit-refund-ticket)** > > Revise and resubmit a rejected or failed refund ticket. > [!TIP] > > Use [GraphQL](/api-reference/endpoints/graphql/orders-and-payments) to query refund tickets and the executed refund records. On `Refund`, the two business numbers are exposed as flat fields `refund.orderMerchantExternalId` and `refund.refundTicketMerchantExternalId` — same names as the webhook payload. Filter executed refunds by the refund ticket reference using `refunds(filter: { refundTicketMerchantExternalId: ... })`. # Resubmit Refund Ticket Source: https://docs.waffo.ai/api-reference/endpoints/refunds/resubmit-refund-ticket Revise and resubmit a rejected or failed refund ticket `POST /v1/actions/refund-ticket/resubmit-ticket` **Authentication:** Merchant API Key (server-to-server). Resubmit reuses the request shape of [Create Refund Ticket](/api-reference/endpoints/refunds/create-refund-ticket), plus a `ticketId` to identify the ticket being revised. The originating `paymentId` is bound to the existing ticket and cannot be changed. ## Request body | Field | Type | Required | Description | | - | - | - | - | | `ticketId` | string | Yes | Short ID of the refund ticket being revised, e.g. `TKT_3bVzrkD0FJjFdZNLk8Ualx` | | `reason` | string | Yes | Free-text reason for the revised request | | `requestedAmount.amount` | string | Yes | Revised refund amount (display format, must be `> 0` and `≤ payment.amount`) | | `requestedAmount.currency` | string | Yes | ISO 4217 code, must match the payment currency | The `refundTicketMerchantExternalId` written at create time is **immutable** across resubmits — it cannot be changed once the ticket exists. ## Success response (200) ```json theme={"system"} { "data": { "ticket": { "id": "TKT_3bVzrkD0FJjFdZNLk8Ualx", "status": "pending", "subjectId": "PAY_6eYCunG3IMmIgcQOnaXdoA", "versionNumber": 2, "refundTicketMerchantExternalId": "REF-2026-00891" } } } ``` A new ticket version is appended; `versionNumber` increments. The ticket re-enters the review queue (`pending` for customer-initiated, `processing` for merchant-initiated). ## Errors > **Retry policy:** Never retry 4xx — fix the request and resubmit. Retry 5xx with exponential backoff (start 5s, max 3 attempts). | Status | `errors[0].message` | What it means | Recommended handling | | - | - | - | - | | 400 | `Missing required field: ticketId` | `ticketId` not provided | Add `ticketId`, resubmit | | 400 | `Expected format: TKT_xxx, got "..."` | `ticketId` Short ID could not be decoded | Fix `ticketId` format, resubmit | | 400 | `Invalid requestedAmount.amount format` | Amount string could not be parsed | Use a display string like `"10.50"` | | 401 | `Unauthorized` | Invalid API Key signature | Verify auth headers | | 403 | `Submitter is not the original ticket owner` | The caller didn't create this ticket | Only the original submitter can resubmit | | 404 | `Ticket not found` | Ticket doesn't exist or doesn't belong to the caller | Verify `ticketId` | | 409 | `Ticket status is X, only rejected/failed can be resubmitted` | Ticket is not in a resubmittable state | Wait for `rejected` / `failed`, or open a new ticket | | 409 | `Requested amount exceeds payment amount` | Revised amount > `payment.amount` | Fix the amount | | 500 | `Internal server error` | Unexpected server-side failure | Retry with exponential backoff (start 5s, max 3 attempts) | # Cancel Subscription Source: https://docs.waffo.ai/api-reference/endpoints/subscriptions/cancel-subscription Cancel a pending, active, or past-due subscription Cancel a pending, active, or past-due subscription. The behavior depends on the current subscription status. ``` POST /v1/actions/subscription-order/cancel-order ``` **Authentication:** API Key (merchant, owner role) > [!NOTE] > > This endpoint also has a customer-side flow with session-token auth: see [Cancel Subscription (Customer)](/api-reference/endpoints/subscriptions/cancel-subscription-customer). ## Cancellation Behavior | Current Status | Action | Result Status | | - | - | - | | `pending` (new purchase) | Immediate cancel, no PSP call | `canceled` | | `pending` (plan-change subscription) | Immediate cancel, PSP cancellation dispatched now | `canceled` | | `active` | Cancel at period end (via PSP) | `canceling` -> `canceled` at period end | | `past_due` | Cancel immediately (via PSP) | `canceling` -> `canceled` once the PSP confirms | > [!NOTE] > > * **pending**: Directly canceled, status becomes `canceled` — it never passes through `canceling` > * **pending plan-change subscription**: also becomes `canceled` directly, but the PSP cancellation for that scheduled subscription is dispatched right away, so it neither activates nor charges at the planned switch time. The original subscription is left untouched: it stays `canceling` and does not return to `active` > * **Already ended while canceling (idempotent)**: if a `pending` order reaches a terminal status after it was read but before the cancellation is written — for example two plan-change candidates were created concurrently for the same subscription and the PSP closed the one that yielded, pushing the close notification back first, or a concurrent cancellation landed first — the request converges as canceled: any discount reservation still held is released (an already released one is not released twice), and it returns 200 with the current terminal status (e.g. `closed`). No cancellation reason is stored in this case > * **active**: PSP cancellation is triggered (takes effect at billing period end). Local status becomes `canceling`, then updated to `canceled` via Webhook when the period ends > * **past\_due**: PSP cancellation is dispatched immediately, not deferred to period end. Local status becomes `canceling`, then updated to `canceled` via Webhook once the PSP confirms. No "cancellation scheduled, access until X" email is sent on this path, because the billing period has already lapsed > [!WARNING] > > A `canceling` subscription can normally be reverted with [Reactivate Subscription](/api-reference/endpoints/subscriptions/reactivate-order), but **a subscription that had an unpaid charge at the moment cancellation was requested cannot be reverted** and that endpoint returns 400. Cancelling a `past_due` subscription always falls into this category. > [!WARNING] > > **A subscription that is `canceling` because of a confirmed plan change can never be reverted**, not even after that change is voided by cancelling its pending new subscription: the payment channel put the original subscription into pending cancellation when it confirmed the change and offers no way back. It moves one way to `canceled`; to keep the buyer paying, place a new order. ## Request Body | Field | Type | Required | Description | | - | - | - | - | | `orderId` | string | Yes | Subscription order ID (Short ID format `ORD_xxx`) | ## Example Request ```typescript TypeScript (SDK) theme={"system"} import { WaffoPancake } from "@waffo/pancake-ts"; const client = new WaffoPancake({ merchantId: process.env.WAFFO_MERCHANT_ID!, privateKey: process.env.WAFFO_PRIVATE_KEY!, }); const result = await client.orders.cancelSubscription({ orderId: "ORD_2aUyqjCzEIiEcYMKj7TZtw", }); console.log(result.orderId); // "ORD_2aUyqjCzEIiEcYMKj7TZtw" console.log(result.status); // "canceling" or "canceled" ``` ```typescript TypeScript (Manual) theme={"system"} // Assumes callApi() is defined as shown in the Authentication guide const result = await callApi("POST", "/v1/actions/subscription-order/cancel-order", { orderId: "ORD_2aUyqjCzEIiEcYMKj7TZtw", }); ``` ```java Java theme={"system"} // Assumes callApi() is defined as shown in the Authentication guide String result = callApi("POST", "/v1/actions/subscription-order/cancel-order", "{\"orderId\":\"ORD_2aUyqjCzEIiEcYMKj7TZtw\"}"); ``` ```python Python theme={"system"} # Assumes call_api() is defined as shown in the Authentication guide result = call_api("POST", "/v1/actions/subscription-order/cancel-order", { "orderId": "ORD_2aUyqjCzEIiEcYMKj7TZtw", }) ``` ```go Go theme={"system"} // Assumes callAPI() is defined as shown in the Authentication guide result, err := callAPI("POST", "/v1/actions/subscription-order/cancel-order", `{"orderId":"ORD_2aUyqjCzEIiEcYMKj7TZtw"}`) ``` ```rust Rust theme={"system"} // Assumes call_api() is defined as shown in the Authentication guide let result = call_api("POST", "/v1/actions/subscription-order/cancel-order", r#"{"orderId":"ORD_2aUyqjCzEIiEcYMKj7TZtw"}"# ).await?; ``` ```c C theme={"system"} // Assumes call_api() is defined as shown in the Authentication guide call_api("/v1/actions/subscription-order/cancel-order", "{\"orderId\":\"ORD_2aUyqjCzEIiEcYMKj7TZtw\"}"); ``` ```cpp C++ theme={"system"} // Assumes call_api() is defined as shown in the Authentication guide auto result = call_api("/v1/actions/subscription-order/cancel-order", R"({"orderId":"ORD_2aUyqjCzEIiEcYMKj7TZtw"})"); ``` ```bash cURL theme={"system"} MERCHANT_ID="MER_2aUyqjCzEIiEcYMKj7TZtw" TIMESTAMP=$(date +%s) BODY='{"orderId":"ORD_2aUyqjCzEIiEcYMKj7TZtw"}' BODY_HASH=$(echo -n "$BODY" | openssl dgst -sha256 -binary | base64 | tr -d '\n') CANONICAL="POST /v1/actions/subscription-order/cancel-order $TIMESTAMP $BODY_HASH" SIGNATURE=$(echo -n "$CANONICAL" | openssl dgst -sha256 -sign private_key.pem | base64 | tr -d '\n') curl -X POST "https://api.waffo.ai/v1/actions/subscription-order/cancel-order" \ -H "Content-Type: application/json" \ -H "X-Merchant-Id: $MERCHANT_ID" \ -H "X-Timestamp: $TIMESTAMP" \ -H "X-Signature: $SIGNATURE" \ -d "$BODY" ``` ```bash wget theme={"system"} MERCHANT_ID="MER_2aUyqjCzEIiEcYMKj7TZtw" TIMESTAMP=$(date +%s) BODY='{"orderId":"ORD_2aUyqjCzEIiEcYMKj7TZtw"}' BODY_HASH=$(echo -n "$BODY" | openssl dgst -sha256 -binary | base64 | tr -d '\n') CANONICAL="POST /v1/actions/subscription-order/cancel-order $TIMESTAMP $BODY_HASH" SIGNATURE=$(echo -n "$CANONICAL" | openssl dgst -sha256 -sign private_key.pem | base64 | tr -d '\n') wget -qO- --post-data="$BODY" \ --header="Content-Type: application/json" \ --header="X-Merchant-Id: $MERCHANT_ID" \ --header="X-Timestamp: $TIMESTAMP" \ --header="X-Signature: $SIGNATURE" \ "https://api.waffo.ai/v1/actions/subscription-order/cancel-order" ``` ## Success Response (200) -- Active Subscription ```json theme={"system"} { "data": { "orderId": "ORD_2aUyqjCzEIiEcYMKj7TZtw", "status": "canceling" } } ``` ## Success Response (200) -- Pending Subscription ```json theme={"system"} { "data": { "orderId": "ORD_2aUyqjCzEIiEcYMKj7TZtw", "status": "canceled" } } ``` ### Response Fields | Field | Type | Description | | - | - | - | | `orderId` | string | Order ID (Short ID) | | `status` | string | New order status (`canceling` or `canceled`; when the cancellation converges on an order that already ended, its current terminal status — `canceled`, `closed`, or `expired`) | ## Errors > **Retry policy:** Never retry 4xx — fix the request and resubmit. Retry 5xx with exponential backoff (start 5s, max 3 attempts). | Status | `errors[0].message` | What it means | Recommended handling | | - | - | - | - | | 400 | `Missing X-Context-Merchant-Id header` | Merchant context missing in API Key auth | Verify the auth pipeline | | 400 | `Missing required field: orderId` | `orderId` is missing, empty, or not a string | Fix the request body, then resubmit | | 400 | `Invalid JSON body` | Request body is not valid JSON | Fix the request body, then resubmit | | 400 | `Expected format: ORD_xxx, got "..."` | `orderId` Short ID could not be decoded | Fix the `orderId` format, then resubmit | | 400 | `Subscription cannot be canceled, current status: X` | Order status is not `pending`, `active`, or `past_due` (e.g. already `canceled`, `canceling`, `closed`, `expired`) | The subscription is no longer cancellable | | 401 | `Authentication failed` | Invalid API Key signature | Verify auth headers | | 403 | `Order does not belong to user` | Ownership check failed | Verify the caller owns the order | | 404 | `Order not found` | Order does not exist | Verify the order ID | | 409 | `Subscription order changed during cancellation, current status: X` | A `pending` order was changed concurrently while it was being canceled and has not ended — a version conflict, or a plan-change subscription that was activated at its switch time before the cancellation could apply | Re-read the order; if it is still `pending`, retry the cancellation (it is idempotent). An activated plan-change subscription whose PSP cancellation already went through needs manual reconciliation | | 500 | `Internal server error` | Unexpected server-side failure | Retry with exponential backoff (start 5s, max 3 attempts) | | 502 | `Failed to cancel subscription` | PSP cancellation failed and the order has not ended | Retry with exponential backoff (start 5s, max 3 attempts) | # Cancel Subscription (Customer) Source: https://docs.waffo.ai/api-reference/endpoints/subscriptions/cancel-subscription-customer Customer-side cancellation of a subscription using a session token This is the customer-token call path of the same endpoint described in [Cancel Subscription (Merchant API Key)](/api-reference/endpoints/subscriptions/cancel-subscription). Behavior and response shape are identical — the customer path additionally accepts the optional cancellation-reason fields below, and only the auth surface and the call site differ. ``` POST /v1/actions/subscription-order/cancel-order ``` **Authentication:** Session Token — see [Customer Endpoints](/api-reference/endpoints/auth/customer-endpoints) (customer or customer role) > [!NOTE] > > The `orderId` must belong to the customer that the session token was minted for. Tokens minted for one customer cannot cancel another customer's subscription. ## Cancellation Behavior | Current Status | Action | Result Status | | - | - | - | | `pending` (new purchase) | Immediate cancel, no PSP call | `canceled` | | `pending` (plan-change subscription) | Immediate cancel, PSP cancellation dispatched now | `canceled` | | `active` | Cancel at period end (via PSP) | `canceling` → `canceled` at period end | | `past_due` | Cancel immediately (via PSP) | `canceling` → `canceled` once the PSP confirms | > [!NOTE] > > Cancelling a pending plan-change subscription voids that change: the new subscription becomes `canceled` directly and its PSP cancellation is dispatched right away, so nothing activates or is charged at the planned switch time. The original subscription is **not** put back into service — it stays `canceling` and moves one way to `canceled`, and [Reactivate Subscription](/api-reference/endpoints/subscriptions/reactivate-order) refuses it with 400. To keep paying, the customer places a new order. > [!NOTE] > > A `pending` order that ends on its own while the cancellation is in flight — for example the PSP closes one of two plan-change candidates created concurrently for the same subscription — is treated as already canceled: the request returns 200 with the current terminal status (e.g. `closed`), any discount reservation still held is released once, and no cancellation reason is stored. If the order was changed concurrently but has not ended, the request returns 409 with the current status; re-read the order and retry. > [!NOTE] > > Cancelling a `past_due` subscription takes effect immediately rather than at period end, and sends no "cancellation scheduled, access until X" email — the billing period has already lapsed. Such a cancellation **cannot be reverted** with [Reactivate Subscription](/api-reference/endpoints/subscriptions/reactivate-order): any subscription that had an unpaid charge at the moment cancellation was requested is refused with 400. ## Request Body | Field | Type | Required | Description | | - | - | - | - | | `orderId` | string | Yes | Subscription order ID (Short ID format `ORD_xxx`) | | `cancelReason` | string | No | Cancellation reason code chosen by the customer. `snake_case`, at most 64 characters. The value set is not constrained — any well-formed code is accepted, so adding or removing reasons needs no API release | | `cancelComment` | string | No | Free-text comment from the customer, at most 500 characters. Stored only when the cancellation produces a record | The reason is stored only for buyer-side credentials and only once the cancellation actually succeeds — one row per cancellation action, so cancel → reactivate → cancel leaves two. Storing the reason is a side path: if it fails the cancellation still succeeds and the response is unchanged; a failed cancellation (400 / 409 / 500 / 502), or one that converges on an order that already ended, stores nothing. Merchants read the stored reasons through GraphQL. What happens when `cancelReason` is omitted depends on which credential made the call: | Credential | `cancelReason` omitted | Meaning | | - | - | - | | **Customer session token (this page)** | **No record is stored** | Merchant-built integration: the request body carries only `orderId`, so an absent field means the buyer was never asked | | Buyer session token | One row is stored with `reason_code` = `not_provided` | The buyer portal's cancellation dialog always asks, so an absent field means the buyer saw it and skipped | | Merchant JWT / API key | No record is stored | The merchant cancelled on the buyer's behalf | The two channels deliberately do not share the sentinel: folding "never asked" and "asked but declined" into one value would make the `not_provided` share unreadable for merchants. If your integration also offers reason options and you want skips counted in the denominator, submit `cancelReason` explicitly (the value set is open, e.g. `not_provided`). ## Example Request ```typescript TypeScript (SDK) theme={"system"} import { WaffoPancake } from "@waffo/pancake-ts"; const client = new WaffoPancake({ sessionToken: window.WAFFO_SESSION_TOKEN, // injected by the merchant's portal environment: "prod", }); const result = await client.orders.cancelSubscription({ orderId: "ORD_2aUyqjCzEIiEcYMKj7TZtw", cancelReason: "too_expensive", }); console.log(result.orderId); // "ORD_2aUyqjCzEIiEcYMKj7TZtw" console.log(result.status); // "canceling" or "canceled" ``` ```typescript TypeScript (Manual) theme={"system"} const result = await fetch("https://api.waffo.ai/v1/actions/subscription-order/cancel-order", { method: "POST", headers: { "Authorization": `Bearer ${SESSION_TOKEN}`, "Content-Type": "application/json", "X-Environment": "prod", }, body: JSON.stringify({ orderId: "ORD_2aUyqjCzEIiEcYMKj7TZtw", cancelReason: "too_expensive", }), }).then(r => r.json()); ``` ```bash cURL theme={"system"} curl -X POST "https://api.waffo.ai/v1/actions/subscription-order/cancel-order" \ -H "Authorization: Bearer $SESSION_TOKEN" \ -H "Content-Type: application/json" \ -H "X-Environment: prod" \ -d '{"orderId":"ORD_2aUyqjCzEIiEcYMKj7TZtw","cancelReason":"too_expensive"}' ``` ```bash wget theme={"system"} wget -qO- \ --header="Authorization: Bearer $SESSION_TOKEN" \ --header="Content-Type: application/json" \ --header="X-Environment: prod" \ --post-data='{"orderId":"ORD_2aUyqjCzEIiEcYMKj7TZtw","cancelReason":"too_expensive"}' \ "https://api.waffo.ai/v1/actions/subscription-order/cancel-order" ``` ## Success Response (200) ```json theme={"system"} { "data": { "orderId": "ORD_2aUyqjCzEIiEcYMKj7TZtw", "status": "canceling" } } ``` ### Response Fields | Field | Type | Description | | - | - | - | | `orderId` | string | Order ID (Short ID) | | `status` | string | New order status (`canceling` or `canceled`; when the cancellation converges on an order that already ended, its current terminal status — `canceled`, `closed`, or `expired`) | ## Errors > **Retry policy:** Never retry 4xx — fix the request and resubmit. Retry 5xx with exponential backoff (start 5s, max 3 attempts). | Status | `errors[0].message` | What it means | Recommended handling | | - | - | - | - | | 400 | `Missing required field: orderId` | `orderId` is missing, empty, or not a string | Fix the body, resubmit | | 400 | `Invalid JSON body` | Request body is not valid JSON | Fix the body, resubmit | | 400 | `Expected format: ORD_xxx, got "..."` | `orderId` Short ID could not be decoded | Fix the `orderId` format, resubmit | | 400 | `cancelReason must not be empty` / `cancelReason must be snake_case` / `cancelReason must be at most 64 characters` | `cancelReason` is blank or not a well-formed code | Send a non-blank `snake_case` code of at most 64 characters, or omit the field | | 400 | `cancelComment must be at most 500 characters` | `cancelComment` exceeds the length limit | Truncate the comment to 500 characters | | 400 | `Subscription cannot be canceled, current status: X` | Order status is not `pending`, `active`, or `past_due` (e.g. already `canceled`, `canceling`, `closed`, `expired`) | The subscription is no longer cancellable | | 401 | `Authentication failed` | Session token invalid, expired, or malformed | Re-mint the session token via Issue Session Token | | 403 | `Order does not belong to user` | The token's customer is not the order owner | Mint a token for the correct customer | | 404 | `Order not found` | Order does not exist | Verify the order ID | | 409 | `Subscription order changed during cancellation, current status: X` | A `pending` order was changed concurrently while it was being canceled and has not ended — a version conflict, or a plan-change subscription that was activated at its switch time before the cancellation could apply | Re-read the order; if it is still `pending`, retry the cancellation (it is idempotent). An activated plan-change subscription whose PSP cancellation already went through needs manual reconciliation | | 500 | `Internal server error` | Unexpected server-side failure | Retry with exponential backoff (start 5s, max 3 attempts) | | 502 | `Failed to cancel subscription` | PSP cancellation failed and the order has not ended | Retry with exponential backoff (start 5s, max 3 attempts) | # Subscription Order Endpoints Source: https://docs.waffo.ai/api-reference/endpoints/subscriptions/overview Create and manage subscription orders Subscription order endpoints allow you to create recurring billing orders and manage their lifecycle. Subscriptions are created through checkout sessions (with `productType: "subscription"`) and managed via cancellation and status transitions. ## Subscription Status Values | Status | Description | | - | - | | `pending` | Subscription created, awaiting first payment | | `active` | Active and billing normally | | `trialing` | In free trial period | | `canceling` | Cancellation requested, active until period end | | `past_due` | Payment failed, retrying | | `canceled` | Subscription ended, no further billing | | `expired` | Subscription expired | ## Endpoints > **[Cancel Subscription](/api-reference/endpoints/subscriptions/cancel-subscription)** > > Cancel an active or pending subscription. # Reactivate Subscription Source: https://docs.waffo.ai/api-reference/endpoints/subscriptions/reactivate-order Reactivate a subscription that is canceling at the end of the current period Reactivate a subscription that is currently in `canceling` state. The pending end-of-period cancellation is removed and the subscription continues to renew as scheduled. ``` POST /v1/actions/subscription-order/reactivate-order ``` **Authentication:** Session Token — see [Customer Endpoints](/api-reference/endpoints/auth/customer-endpoints) (customer or customer role) ## Reactivation Behavior | Current Status | Action | Result Status | | - | - | - | | `canceling` | Remove pending end-of-period cancellation (via PSP) | `active` | | `canceled` | Not allowed — already fully canceled | — | | `pending` / `active` / `past_due` / `expired` | Not allowed — only `canceling` is reactivatable | — | > [!NOTE] > > * Only subscriptions in `canceling` (cancellation scheduled at period end) can be reactivated. > * Fully canceled (`canceled`) subscriptions cannot be reactivated — start a new subscription instead. > * **A subscription that had an unpaid charge at the moment cancellation was requested cannot be reactivated** — the request is refused with 400 and a distinct message. Cancelling a `past_due` subscription always falls into this category; a normal end-of-period cancellation from `active` usually does not. > * **A subscription whose plan change has been confirmed by the payment channel cannot be reactivated** — it is `canceling` because of that change, not because the buyer cancelled, and the channel put it into pending cancellation the moment it confirmed the change, with no way back. The refusal also stands after the change is voided (its pending new subscription cancelled or closed). Such a subscription moves one way to `canceled`; to keep paying, the buyer has to place a new order. > * No additional charge — the current billing period continues, and renewal resumes at its original schedule. ## Request Body | Field | Type | Required | Description | | - | - | - | - | | `orderId` | string | Yes | Subscription order ID (Short ID format `ORD_xxx`) | ## Example Request ```typescript TypeScript (SDK) theme={"system"} import { WaffoPancake } from "@waffo/pancake-ts"; const client = new WaffoPancake({ sessionToken: window.WAFFO_SESSION_TOKEN, // injected by the merchant's portal environment: "prod", }); const result = await client.orders.reactivateSubscription({ orderId: "ORD_2aUyqjCzEIiEcYMKj7TZtw", }); console.log(result.orderId); // "ORD_2aUyqjCzEIiEcYMKj7TZtw" console.log(result.status); // "active" ``` ```typescript TypeScript (Manual) theme={"system"} const result = await fetch("https://api.waffo.ai/v1/actions/subscription-order/reactivate-order", { method: "POST", headers: { "Authorization": `Bearer ${SESSION_TOKEN}`, "Content-Type": "application/json", "X-Environment": "prod", }, body: JSON.stringify({ orderId: "ORD_2aUyqjCzEIiEcYMKj7TZtw", }), }).then(r => r.json()); ``` ```bash cURL theme={"system"} curl -X POST "https://api.waffo.ai/v1/actions/subscription-order/reactivate-order" \ -H "Authorization: Bearer $SESSION_TOKEN" \ -H "Content-Type: application/json" \ -H "X-Environment: prod" \ -d '{"orderId":"ORD_2aUyqjCzEIiEcYMKj7TZtw"}' ``` ```bash wget theme={"system"} wget -qO- \ --header="Authorization: Bearer $SESSION_TOKEN" \ --header="Content-Type: application/json" \ --header="X-Environment: prod" \ --post-data='{"orderId":"ORD_2aUyqjCzEIiEcYMKj7TZtw"}' \ "https://api.waffo.ai/v1/actions/subscription-order/reactivate-order" ``` ## Success Response (200) ```json theme={"system"} { "data": { "orderId": "ORD_2aUyqjCzEIiEcYMKj7TZtw", "status": "active" } } ``` ### Response Fields | Field | Type | Description | | - | - | - | | `orderId` | string | Order ID (Short ID) | | `status` | string | New order status (`active`) | ## Errors > **Retry policy:** Never retry 4xx — fix the request and resubmit. Retry 5xx with exponential backoff (start 5s, max 3 attempts). | Status | `errors[0].message` | What it means | Recommended handling | | - | - | - | - | | 400 | `Missing required field: orderId` | `orderId` is missing, empty, or not a string | Fix the request body, then resubmit | | 400 | `Invalid JSON body` | Request body is not valid JSON | Fix the request body, then resubmit | | 400 | `Expected format: ORD_xxx, got "..."` | `orderId` Short ID could not be decoded | Fix the `orderId` format, then resubmit | | 400 | `Only canceling subscriptions can be reactivated` | Order status is not `canceling` (e.g. `canceled`, `active`, `expired`) | The subscription is not reactivatable | | 400 | `Subscription with an unpaid balance cannot be reactivated` | The subscription had an unpaid charge when cancellation was requested (always true for a `past_due` cancellation) | Cannot be reverted — start a new subscription instead. The message differs from the one above so the two refusals can be told apart | | 400 | `Subscription with a confirmed plan change cannot be reactivated` | The subscription already has a plan change confirmed by the payment channel; the refusal stands whether or not that change was later voided | Cannot be reverted — the subscription moves one way to `canceled`. To keep paying, place a new order | | 401 | `Authentication failed` | Session token invalid, expired, or malformed | Re-mint the session token via Issue Session Token | | 403 | `Order does not belong to user` | Ownership check failed | Verify the caller owns the order | | 404 | `Order not found` | Order does not exist | Verify the order ID | | 500 | `Internal server error` | Unexpected server-side failure | Retry with exponential backoff (start 5s, max 3 attempts) | # Billing Questions Source: https://docs.waffo.ai/customers/billing Understanding charges on your statement ## Why "Waffo Pancake" on My Statement? Waffo Pancake is a **Merchant of Record**. We process payments for many businesses. When you buy from a business using us, you may see: * "WAFFO" or "WAFFO PANCAKE" on your bank statement * Our name on invoices **This is normal.** We process payments on behalf of the business you purchased from. *** ## Invoices Invoices are automatically included in your order confirmation email after each purchase. ### View or Download Invoice **1. Consumer Portal** Log in to the [Consumer Portal](https://pancake.waffo.ai/consumer/portal/login), open the order in **Payment History**, and click **View Invoice**. ![View Invoice in Consumer Portal](https://mintcdn.com/waffo/T2o-9IfHowuXiiQ9/images/customer-portal-invoice.png?fit=max\&auto=format\&n=T2o-9IfHowuXiiQ9\&q=85\&s=0e03445938bb6279e12779cc1f501ea9) **2. Order Email** Check the order confirmation email sent to your inbox. The invoice is attached or linked. **3. Contact Business** You can also request an invoice directly from the business. ### Update Invoice Details Need to add or change billing information on your invoice? Click **Edit Details** on the invoice page, fill in your company name, Tax ID, and other details, then save. ![Edit Invoice Details](https://mintcdn.com/waffo/T2o-9IfHowuXiiQ9/images/customer-portal-edit-invoice.png?fit=max\&auto=format\&n=T2o-9IfHowuXiiQ9\&q=85\&s=1a2a16f43a4113d3746c3f28e9a40807) ### Can't Download? If you're unable to download your invoice: * Email us at `support@waffo.ai` with your order details * Or click **Report Issue** in the [Consumer Portal](https://pancake.waffo.ai/consumer/portal/login) *** ## Refunds Refunds are issued by the merchant. If there was a problem with an item you purchased, contact the original merchant. You can find the merchant's contact email at the bottom of your receipt email. If the issue persists and you can't resolve it with the seller, you can let us know through the [Consumer Portal](https://pancake.waffo.ai/consumer/portal/login). ### How to Report an Issue In the Consumer Portal, find the order in **Payment History**, click **Report Issue**, select a category, describe the issue, and submit. ![Report an issue in the Consumer Portal](https://mintcdn.com/waffo/SxqgCDstcQGlxHc_/images/consumer-portal-report-issue.png?fit=max\&auto=format\&n=SxqgCDstcQGlxHc_\&q=85\&s=1b3a8a4c991a39f9454098ed45e52f30) > [!NOTE] > > If you opened the portal from the business's website, **Report Issue** isn't shown there. Contact the business directly, or log in at the [Consumer Portal](https://pancake.waffo.ai/consumer/portal/login) with your checkout email to report the issue. ### Refund Policy * There is **no time limit** on refunds * Refunds may be approved in the following cases: | Condition | Description | | - | - | | Defective product | Product is defective or does not function as described | | Unauthorized transaction | Transaction was unauthorized or made in genuine error | | Technical issues | Unable to access product due to technical issues on our end | | Legal requirement | Other situations required by law | * Once approved, refunds are returned to your original payment method. **WeChat Pay** refunds arrive immediately; **card** refunds are processed by your issuing bank and typically arrive within **3–10 business days**, and no later than 14 business days * Once you begin downloading or using digital content, the statutory 14-day cancellation period is waived * Unused subscription periods are not refundable > [!TIP] > > Refunds appear as separate credit, not reversal of original charge. If you disagree with a refund decision, email `support@waffo.ai` to appeal. # For Customers Source: https://docs.waffo.ai/customers/overview Bought something? We're here to help. ## Customer Portal Made a purchase from a business using Waffo Pancake? Find answers here. > **[Consumer Portal](https://pancake.waffo.ai/consumer/portal/login)** > > Log in to view orders, manage subscriptions, and download invoices. ### How to Log In There are two ways into the Consumer Portal. #### Log In with Email (Magic Link) We use **Magic Link** login — no password needed. **1. Enter Email** Go to [Consumer Portal](https://pancake.waffo.ai/consumer/portal/login) and enter the email address you used when making your purchase. **2. Check Inbox** We'll send an email with a login link. Click the link to log in. #### From a Business Website If the business's website has a **Manage orders** button (or similar), log in on their site and click it. You go straight into that business's portal — no email code needed. * The portal shows only your orders with that business * After 15 minutes without activity the session ends. Click the button on the business's site again to re-enter * **Report Issue** isn't shown in this portal. For a refund, contact the business directly ### Can't Log In? > **Didn't receive the login email?** > > 1. Make sure you're using the exact email address from your purchase (check your receipt) > 2. Check your spam folder for emails from `auth@waffo.ai` > 3. Go back to the login page and request a new Magic Link > **Opened the portal from the business's website?** > > That portal session ends after 15 minutes without activity, and the portal asks you to re-enter from the business's site. Go back to the business's website and open the portal from there again — no email code is needed. > > If you open the portal again in the same browser (in another tab, for another store, or with a Magic Link), the newest session takes over. Earlier tabs show **Session switched** and take you to the current session. > **Still can't log in?** > > Email `support@waffo.ai` with your purchase email and order details, and we'll help you out. *** ## Common Topics > **[Billing Questions](/customers/billing)** > > Charges, refunds, invoices, and taxes. > **[Subscriptions](/customers/subscriptions)** > > View or cancel subscriptions, and reactivate or change plan where eligible. *** ## Contact > **Contact Business** > > Product or service usage and delivery issues. Find their contact in your receipt email. > **Contact Waffo Pancake** > > Unrecognized charges, payment processing, or billing issues. Email [support@waffo.ai](mailto:support@waffo.ai). # Manage Subscription Source: https://docs.waffo.ai/customers/subscriptions View or cancel anytime ## Access Consumer Portal Manage subscriptions through the [**Consumer Portal**](https://pancake.waffo.ai/consumer/portal/login). Self-service. No waiting. **1. Open Consumer Portal** Go to [Consumer Portal](https://pancake.waffo.ai/consumer/portal/login) and log in with your email. If the business's website has a **Manage orders** button, you can also click it there to go straight in — no email code needed ([how it works](/customers/overview#from-a-business-website)). **2. Find Subscription** View all your active subscriptions under **Subscriptions**. **3. Manage** View or cancel. Where eligible, you can also reactivate a subscription you canceled before it ends, or change plan — this depends on the subscription's status and the business's settings. *** ## View Subscription Details Click any subscription under **Subscriptions** in the Consumer Portal to view: | Info | Description | | - | - | | Status | Subscription status (Active, Trialing, Canceling, Canceled) | | Start Date | When the subscription started | | Renewal Date | Next renewal date | | Order Details | Product name, price, and billing interval | | Payment Information | Payment method on file | | History | Past transaction records | ![View subscription details](https://mintcdn.com/waffo/SxqgCDstcQGlxHc_/images/consumer-portal-subscription-details.png?fit=max\&auto=format\&n=SxqgCDstcQGlxHc_\&q=85\&s=a36b4081c351f8d0af11d08553e1f6ec) *** ## Subscription Billing ### When Subscriptions Bill | Interval | Billing Day | | - | - | | Weekly | Same day each week | | Monthly | Same date each month | | Quarterly | Same date every 3 months | | Yearly | Same date each year | ### Price Changes Businesses must notify you: * Immediately for decreases * 30+ days for increases *** ## Cancel Subscription 1. Open portal link 2. Find subscription 3. Click **Cancel Subscription** 4. Confirm ![Cancel Subscription](https://mintcdn.com/waffo/SxqgCDstcQGlxHc_/images/consumer-portal-cancel-subscription.png?fit=max\&auto=format\&n=SxqgCDstcQGlxHc_\&q=85\&s=659b514bd40a7c3df0956da8c5a927b6) A confirmation dialog will appear. Click **Confirm Cancellation** to complete. ![Confirm Cancellation](https://mintcdn.com/waffo/SxqgCDstcQGlxHc_/images/consumer-portal-cancel-subscription-confirm.png?fit=max\&auto=format\&n=SxqgCDstcQGlxHc_\&q=85\&s=930315b7fdf7acc762b8019f0d66fca0) ### Telling us why (optional) The dialog asks why you are leaving: * Choosing a reason is **optional** — skip it and your cancellation goes through unchanged * Picking **Other** opens a comment box for your own words The business you subscribed to sees this feedback and uses it to improve their pricing, features, and service. > [!WARNING] > > If your subscription is paid up, submit your cancellation request at least **1 hour** before the end of the current billing period; cancellation then takes effect on the next payment date. If a charge on your subscription has failed and is still unpaid, cancellation takes effect **immediately** instead. ### After Cancellation What happens next depends on whether the subscription is paid up at the moment you cancel: | Situation | When cancellation takes effect | Can it be undone? | | - | - | - | | Paid up (normal active subscription) | On the next payment date — you keep access until the end of the current paid period | Yes — click **Resume Subscription** before the End Date | | A charge has failed and is still unpaid | Immediately — there is no remaining paid period to use | No — start a new subscription instead | If you change your mind on a paid-up subscription, you can click **Resume Subscription** in the subscription details before the End Date to restore it. ![Resume Subscription](https://mintcdn.com/waffo/omzg1JkLuy_VmELQ/images/consumer-portal-resume-subscription.png?fit=max\&auto=format\&n=omzg1JkLuy_VmELQ\&q=85\&s=2bffd3953c51c476711348ae848b3a5f) *** ## Renewal ### Automatic Renewal Paid subscriptions renew automatically until you cancel. You'll receive: * Email reminder before renewal (1 day for weekly, 3 days for monthly and quarterly, 7 days for yearly) * Email reminder before a trial ends (1 day ahead; 8 hours ahead when the trial is 1 day long) * Receipt after each charge If the subscription price increases, we will notify you and seek your consent where required. ### Stop Renewal Submit your cancellation request at least **1 hour** before the end of the current billing period: * Current period: Access continues until period ends * Next period: No charge, access ends * If a charge has already failed and is unpaid, there is no remaining paid period — cancellation ends access right away *** ## FAQ > **Will I get a refund if I cancel?** > > Canceling stops future charges, but unused subscription periods are not refundable. See [Refund Policy](/customers/billing#refund-policy) for details. > **Can I cancel anytime?** > > Yes. No cancellation fees unless specified by the business. > **Cancel and change my mind?** > > Before the subscription's End Date, you can click **Resume Subscription** in the subscription details to restore it. > > This is not available if the subscription had an unpaid failed charge when you cancelled — that cancellation is final, and you would need to start a new subscription. > > ![Resume Subscription](https://mintcdn.com/waffo/omzg1JkLuy_VmELQ/images/consumer-portal-resume-subscription.png?fit=max\&auto=format\&n=omzg1JkLuy_VmELQ\&q=85\&s=2bffd3953c51c476711348ae848b3a5f) > **Charged after canceling?** > > Possible reasons: > > * Cancellation set for "end of period" > * Multiple subscriptions > * Cancellation didn't complete — contact us *** ## Contact > **Contact Business** > > Product or service usage and delivery issues. Find their contact in your receipt email. > **Contact Waffo Pancake** > > Unrecognized charges, payment processing, or billing issues. Email [support@waffo.ai](mailto:support@waffo.ai).