# Authenticate 3DS session (standalone) Source: https://docs.tagada.io/api-reference/3ds/authenticate-3ds-session-standalone /openapi.json post /api/public/v1/threeds/authenticate Trigger BasisTheory 3DS authentication for a previously created session. Returns challenge/frictionless decision and all 3DS values (ECI, CAVV, transStatus, etc.). Supports both CIT (payment-transaction) and MIT (recurring-transaction) authentication types. For recurring, pass authenticationType: "recurring-transaction" with recurringInfo. **Requires:** org:admin role # Create 3DS session Source: https://docs.tagada.io/api-reference/3ds/create-3ds-session /openapi.json post /api/public/v1/threeds/create-session Create a 3DS (Three Domain Secure) authentication session for enhanced payment security. This should be called BEFORE processing a payment to pre-create the 3DS session. The session ID can then be passed to the payment processing endpoint. **Security & Permissions:** - Requires org:admin role - Requires storeId - validates that the authenticated account owns the store - Validates that the payment instrument belongs to the authenticated account - All operations are scoped to the authenticated user's account **Workflow:** 1. Create payment instrument 2. Create 3DS session (this endpoint) ← Optional but recommended 3. Process payment with threedsSessionId **Benefits of Pre-Creating Session:** - Enhanced fraud detection - Better PSD2/SCA compliance - Faster payment processing - Improved success rates # Create 3DS session from external authentication values (bring your own 3DS) Source: https://docs.tagada.io/api-reference/3ds/create-3ds-session-from-external-authentication-values-bring-your-own-3ds /openapi.json post /api/public/v1/threeds/create-from-values You already run 3-D Secure with your own MPI / 3DS server and only want Tagada to charge. Report the final authentication values (ECI, CAVV/AAV, DS transaction id, protocol version) and Tagada stores them as an already-authenticated 3DS session. Pass the returned `id` as `threedsSessionId` to `POST /payments/process` (or `/checkout/pay-v2`): the values are forwarded verbatim to the acquirer, with no Tagada-side authentication. The acquirer can still ask the shopper to authenticate if the issuer or its own rules require it. **When to use it** - You collect cards and run 3DS in your own PCI environment and use Tagada as one PSP among others. - You authenticated once (3RI / `type: merchant`) and charge later as a MIT — pair it with `initiatedBy: 'merchant'` on the charge. **Rules** - Only `transStatus` `Y` (authenticated) and `A` (attempted, network stand-in) create a usable session; `N` / `U` / `R` / `I` are stored as failed and their values are never forwarded. - `dsTransID` is required for a 3DS 2.x result with `Y` / `A`, but the session is still created without one: many callers create sessions they never use. Its values are not forwarded to the charge, because acquirers reject an authenticated 2.x result with no DS transaction id. - The values are forwarded as-is; the acquirer validates the CAVV. Liability shift follows the scheme rules for the ECI you report, not a Tagada decision. **Acquirer support** — the target processor must accept externally-authenticated values: NMI, RouteSense, Mastercard MPGS, Adyen (`mpiData`), Airwallex (`external_three_ds`). The processor must have `enable3DS` on and the payment flow `threeDsEnabled`. Stripe accounts connected directly (not through TagadaPay) ignore them and run their own 3DS. **TagadaPay processors (Adyen, Stripe, Checkout.com)** — on a TagadaPay account whose PSP is Adyen, Stripe or Checkout.com, the values are used without `enable3DS` or `threeDsEnabled`, on customer-initiated card charges: the PSP receives them in place of Tagada's request for its own 3DS. They are not used, and the payment runs as if none had been sent (the PSP's own 3DS included), for a 3RI (`type: merchant`) session, a result other than `Y` / `A`, a CAVV that is not 28-character base64, a `dsTransID` that is not a UUID, an ECI other than 01 / 02 / 05 / 06, a 3DS version other than 2.1.x / 2.2.x, a Cartes Bancaires card, an authentication older than 90 days, a merchant-initiated charge, a wallet payment or a $0 card verification. Stripe also skips them on a co-badged Cartes Bancaires card and on a charge without customer-initiated stored credentials; Checkout.com skips them on a card saved at Checkout.com. TagadaPay accounts on another PSP ignore them. Also used by the internal payment sandbox to replay specific 3DS outcomes. **Requires:** org:admin role # Create 3RI (merchant-initiated) 3DS session Source: https://docs.tagada.io/api-reference/3ds/create-3ri-merchant-initiated-3ds-session /openapi.json post /api/public/v1/threeds/create-merchant-session Create a server-side 3DS session for merchant-initiated (3RI) authentication. No browser or device info needed — uses just the card token. Used for recurring rebill authentication without cardholder interaction. **Requires:** org:admin role # Get 3DS challenge result Source: https://docs.tagada.io/api-reference/3ds/get-3ds-challenge-result /openapi.json post /api/public/v1/threeds/challenge-result After a 3DS challenge has been completed by the cardholder, retrieve the final authentication result. Returns updated 3DS values (ECI, CAVV, transStatus, etc.). **Requires:** org:admin role # Test authentication Source: https://docs.tagada.io/api-reference/auth/test-authentication /openapi.json post /api/public/v1/auth/test Test if the API key is valid and return user information # Create block rule Source: https://docs.tagada.io/api-reference/block-rules/create-block-rule /openapi.json post /api/public/v1/block-rules Create a new block rule for fraud prevention # Delete block rule Source: https://docs.tagada.io/api-reference/block-rules/delete-block-rule /openapi.json delete /api/public/v1/block-rules/{id} Delete a block rule by ID # Get block rule by ID Source: https://docs.tagada.io/api-reference/block-rules/get-block-rule-by-id /openapi.json get /api/public/v1/block-rules/{id} Retrieve detailed information about a specific block rule # List block rules Source: https://docs.tagada.io/api-reference/block-rules/list-block-rules /openapi.json post /api/public/v1/block-rules/list Get all block rules for the authenticated account with filtering and pagination # Update block rule Source: https://docs.tagada.io/api-reference/block-rules/update-block-rule /openapi.json put /api/public/v1/block-rules/{id} Update an existing block rule # Create builder session token Source: https://docs.tagada.io/api-reference/builder/create-builder-session-token /openapi.json post /api/public/v1/builder/sessions Generate a short-lived JWT token for external builder authentication. **Use Case**: When CRM redirects a user to an external page builder, it generates a session token that the builder uses for API calls. This avoids exposing API keys to client-side code. **Token Scoping**: Optionally scope the token to specific resources (plugin, deployment, store). If scoped, the token can only access those specific resources. **Expiration**: Default is 2 hours. Configurable via `expiresIn` parameter. # Validate builder session token Source: https://docs.tagada.io/api-reference/builder/validate-builder-session-token /openapi.json post /api/public/v1/builder/sessions/validate Validate a builder session token and return its decoded payload. Useful for debugging and testing token validity. **Note**: This endpoint does not require authentication - it just verifies the token signature. # Create checkout offer Source: https://docs.tagada.io/api-reference/checkout-offers/create-checkout-offer /openapi.json post /api/public/v1/checkout-offers/create Create a checkout offer (used by native offer pages). Unlike /offers/create which creates upsell/bump records, this creates a proper checkout offer with line items and promotions. # Delete checkout offers Source: https://docs.tagada.io/api-reference/checkout-offers/delete-checkout-offers /openapi.json post /api/public/v1/checkout-offers/delete Delete one or more checkout offers by their IDs. # Get checkout offer by ID Source: https://docs.tagada.io/api-reference/checkout-offers/get-checkout-offer-by-id /openapi.json post /api/public/v1/checkout-offers/{id} Retrieve a single checkout offer with its line items and promotions. # List checkout offers Source: https://docs.tagada.io/api-reference/checkout-offers/list-checkout-offers /openapi.json post /api/public/v1/checkout-offers/list List checkout offers for a store. Filter by search text. # Initialize checkout session Source: https://docs.tagada.io/api-reference/checkout/initialize-checkout-session /openapi.json get /api/public/v1/checkout/init Initialize a checkout session and automatically redirect to the checkout URL. This endpoint works exactly like the current CMS checkout-init page - you can navigate to it with query parameters and it will automatically redirect the browser to the checkout page. Perfect for direct links, email links, or anywhere you want automatic redirection. **Closed merchant**: when the store's merchant is closed, no checkout session is created and the endpoint answers **403** instead of redirecting: `code: "FORBIDDEN"`, message "This store is not taking orders at the moment.", and `data` a JSON string decoding to `{ "code": "MERCHANT_CLOSED", "message": ... }`. **This endpoint is completely public and requires no authentication.** **Additional Query Parameters**: Any extra query parameters you add will be automatically forwarded to the checkout URL. This is useful for tracking parameters (utm_source, utm_campaign, etc.) or custom parameters. **Customer Prefill**: You can prefill customer information to streamline checkout: - `customerId`: Link to existing customer account - `customerEmail`: Prefill customer email - `customerFirstName`: Prefill customer first name - `customerLastName`: Prefill customer last name - `customerPhone`: Prefill customer phone number - `customerTags`: Apply tags to customer (comma-separated or JSON array: "segment:vip,source:facebook") **Checkout Token Forwarding**: Include the checkout token in the final checkout URL: - `includeCheckoutToken`: Set to the desired query parameter name (default: "checkoutToken") - Example: `includeCheckoutToken=checkoutToken` will append `?checkoutToken=ch_abc123` to the checkout URL - Example: `includeCheckoutToken=token` will append `?token=ch_abc123` to the checkout URL **WooCommerce**: if WooCommerce already owns the order, pass its order id as the reserved `metadata.wooOrderId` key, spelled exactly like that. Tagada then updates that order after payment instead of creating a second one, shows the merchant's order number on the thank-you page, and pushes `failed` back to it when the payment is declined. Without it, every payment creates a duplicate WooCommerce order. **No other spelling is recognized** — `woocommerceOrderId`, `woo_order_id`, `wc_order_id` and the like are ignored, and each one has cost a merchant a duplicate order per payment. Example usage: ``` GET /api/public/v1/checkout/init?storeId=store_123&items=[{"variantId":"var_123","quantity":1}]¤cy=USD → Redirects to: https://checkout.example.com/checkout/ch_abc123/op?token=cms_token_xyz GET /api/public/v1/checkout/init?storeId=store_123&items=[...]¤cy=USD&utm_source=email&custom_param=value → Redirects to: https://checkout.example.com/checkout/ch_abc123/op?token=cms_token_xyz&utm_source=email&custom_param=value GET /api/public/v1/checkout/init?storeId=store_123&items=[...]¤cy=USD&customerEmail=john@example.com&customerFirstName=John&customerLastName=Doe → Redirects to checkout with customer information prefilled ``` # Pay checkout session V2 Source: https://docs.tagada.io/api-reference/checkout/pay-checkout-session-v2 /openapi.json post /api/public/v1/checkout/pay-v2 Pay for a checkout session with enhanced control over payment initiation. **Authentication**: send the buyer session token in the `x-cms-token` header. It is the `token` query parameter of the checkout URL that `/checkout/init` redirects to. The merchant API key alone is not sufficient: without the token, the call returns 401. This V2 endpoint provides additional parameters: - initiatedBy: Specify whether payment was initiated by 'customer' (default) or 'merchant' - source: Specify the payment source, defaults to 'checkout' - paymentFlowId: The payment flow the checkout page was set to charge through. It is used only when the merchant set it for this checkout: a flow pinned on a step of the checkout's funnel (or of one of the store's funnels when there is no funnel), or the store's own flow. Any other flow is ignored and the checkout charges through the funnel step's pin, else the store's flow. These parameters are used for tracking and payment routing. **Calling from your server**: send your API key in `Authorization: Bearer` beside the token, and the shopper's IP and user agent as your server saw them in `customer` (`ipAddress`, `userAgent`). With the key, your server's own address is never taken for the shopper's: without `customer`, the payment keeps the IP the shopper's browser gave the checkout, if any. Without the key, the shopper is the caller and `customer` is ignored. **Closed merchant**: when the store's merchant is closed, the call answers **403** with `code: "FORBIDDEN"`, the top-level `message` "This store is not taking orders at the moment." and `data`, a JSON string like every error of this API, decoding to `{ "code": "MERCHANT_CLOSED", "message": ... }`, whatever `initiatedBy` says. Nothing is written: no order, no payment. Show the message to the shopper; retrying cannot help. # Create customer Source: https://docs.tagada.io/api-reference/customers/create-customer /openapi.json post /api/public/v1/customers/create Returns the store's existing customer when one already has this email, case-insensitive; creates it otherwise # Get customer by ID Source: https://docs.tagada.io/api-reference/customers/get-customer-by-id /openapi.json get /api/public/v1/customers/{customerId} Get customer details including payment instruments and device info # List customers Source: https://docs.tagada.io/api-reference/customers/list-customers /openapi.json post /api/public/v1/customers/list List activated customers with filtering, sorting and pagination. Customers are activated when their first order, payment, or subscription is created; a successful payment is not required. Creating a customer alone does not include it in this list. Retrieve a customer by ID using GET /customers/{customerId} before activation. # Add custom domain Source: https://docs.tagada.io/api-reference/domains/add-custom-domain /openapi.json post /api/public/v1/domains/add Add a new custom domain to the account # Get domain configuration Source: https://docs.tagada.io/api-reference/domains/get-domain-configuration /openapi.json post /api/public/v1/domains/config Get DNS configuration status and recommended CNAME for a custom domain # List custom domains Source: https://docs.tagada.io/api-reference/domains/list-custom-domains /openapi.json post /api/public/v1/domains/list Get all custom domains for the authenticated account # Lookup DNS records Source: https://docs.tagada.io/api-reference/domains/lookup-dns-records /openapi.json post /api/public/v1/domains/dns-lookup Query DNS records for a domain using both standard and Google DNS resolvers # Remove custom domain Source: https://docs.tagada.io/api-reference/domains/remove-custom-domain /openapi.json post /api/public/v1/domains/remove Remove a custom domain and all associated routes # Verify custom domain Source: https://docs.tagada.io/api-reference/domains/verify-custom-domain /openapi.json post /api/public/v1/domains/verify Verify DNS configuration and ownership of a custom domain # Create email template Source: https://docs.tagada.io/api-reference/email-templates/create-email-template /openapi.json post /api/public/v1/email-templates Create a new email template for a store # Delete email template Source: https://docs.tagada.io/api-reference/email-templates/delete-email-template /openapi.json post /api/public/v1/email-templates/delete Delete an email template # List email templates Source: https://docs.tagada.io/api-reference/email-templates/list-email-templates /openapi.json post /api/public/v1/email-templates/list List all email templates for a store # List template types Source: https://docs.tagada.io/api-reference/email-templates/list-template-types /openapi.json post /api/public/v1/email-templates/types List all available email template types with labels and descriptions # Preview email template Source: https://docs.tagada.io/api-reference/email-templates/preview-email-template /openapi.json post /api/public/v1/email-templates/preview Preview a rendered email template with mock data # Send test email Source: https://docs.tagada.io/api-reference/email-templates/send-test-email /openapi.json post /api/public/v1/email-templates/test Send a test email using a template # Update email template Source: https://docs.tagada.io/api-reference/email-templates/update-email-template /openapi.json post /api/public/v1/email-templates/update Update an existing email template # Get event by ID (Admin Only) Source: https://docs.tagada.io/api-reference/events/get-event-by-id-admin-only /openapi.json get /api/public/v1/events/{eventId} Retrieve a specific app event by its ID including related customer and store information. **Requires org:admin role.** # Get event statistics (Admin Only) Source: https://docs.tagada.io/api-reference/events/get-event-statistics-admin-only /openapi.json post /api/public/v1/events/statistics Get aggregated statistics about events for the authenticated account including counts by type and processing status. **Requires org:admin role.** # Get recent events (Admin Only) Source: https://docs.tagada.io/api-reference/events/get-recent-events-admin-only /openapi.json post /api/public/v1/events/recent Get the most recent events for the authenticated account with optional limit. **Requires org:admin role.** # List app events (Admin Only) Source: https://docs.tagada.io/api-reference/events/list-app-events-admin-only /openapi.json post /api/public/v1/events/list Get all app events for the authenticated account with filtering, sorting, and pagination. Events track user and system activities within the application. Pages are numbered from 0: `pagination.page: 0` returns the first page and the last page is `pageCount - 1`. **Requires org:admin role.** # Get funnel session data Source: https://docs.tagada.io/api-reference/funnel-sessions/get-funnel-session-data /openapi.json get /api/public/v1/funnel-sessions/{sessionId} Retrieve full funnel session data from KV storage including customer history, resources, and metadata. Useful for debugging funnel flows. # Track funnel step event Source: https://docs.tagada.io/api-reference/funnel-tracking/track-funnel-step-event /openapi.json post /api/public/v1/funnel-tracking/step Track funnel step events for analytics and conversion tracking. Supports multiple event types: - **view**: Step page was viewed (impression) - **enter**: User navigated to the step - **convert**: User completed a conversion goal (e.g., purchase) - **custom**: Custom event within the funnel Works with both: - **Native funnel system**: Include funnelId and funnelSessionId - **Standalone pages**: Include url for page context # Create a new funnel Source: https://docs.tagada.io/api-reference/funnels/create-a-new-funnel /openapi.json post /api/public/v1/funnels Create a new funnel with the provided configuration # Create a preview session Source: https://docs.tagada.io/api-reference/funnels/create-a-preview-session /openapi.json post /api/public/v1/funnels/{funnelId}/preview-session Create a preview funnel session with pre-filled context for testing # Delete a funnel Source: https://docs.tagada.io/api-reference/funnels/delete-a-funnel /openapi.json delete /api/public/v1/funnels/{funnelId} Delete a funnel and clean up all associated routes # Get funnel by ID Source: https://docs.tagada.io/api-reference/funnels/get-funnel-by-id /openapi.json get /api/public/v1/funnels/{id} Retrieve configuration and details for a specific funnel # List funnels for a store Source: https://docs.tagada.io/api-reference/funnels/list-funnels-for-a-store /openapi.json get /api/public/v1/stores/{storeId}/funnels Retrieve all funnels for a specific store. Each funnel carries `conversionRate`: the percentage (0-100, two decimals) of its sessions started in the last 30 days that led to a paid first order. Draft and preview sessions and test orders are excluded. It is `null` when the funnel had no session in that window or the rate could not be computed. # Promote funnel to production Source: https://docs.tagada.io/api-reference/funnels/promote-funnel-to-production /openapi.json post /api/public/v1/funnels/{funnelId}/promote Promote the staging funnel configuration to production on the specified custom domain. Handles instance cloning, route setup, and prebuilds automatically. # Update funnel with routing Source: https://docs.tagada.io/api-reference/funnels/update-funnel-with-routing /openapi.json put /api/public/v1/funnels/{funnelId} Update a funnel configuration and automatically handle plugin mount/unmount/swap operations # Health check Source: https://docs.tagada.io/api-reference/health/health-check /openapi.json get /api/public/v1/health Simple health check endpoint to verify API is running # IAM Overview Source: https://docs.tagada.io/api-reference/iam-overview Job × Scope IAM — payment_ops, partneradmin, assignable sets, and the matrix behind every /iam/* endpoint. Clerk-session only. # Identity & Access Management The `/iam/*` endpoints let you manage users, roles, and partner staff across the Tagada platform from your own application — typically a sales CRM, a partner portal, or any backoffice that needs to provision or audit access without going through the dashboard UI. The same role matrix that gates the dashboard gates these endpoints. There is no "REST is more permissive" path. > [!WARNING] > > IAM is **not** part of the public, API-key-authenticated surface > documented in the rest of this API Reference. It lives on the > internal `/api/v1/iam/*` router and accepts **only Clerk session > authentication** — Bearer API keys are explicitly rejected. > > See [Authentication](#authentication) below for the full rationale > and how to call these endpoints from an external app. ## Why a separate auth model? Bearer API keys act on behalf of the account owner with full authority. That's fine for `createStore` or `refundPayment`, but for mutations like "grant superadmin" it would mean a leaked key becomes a one-shot privilege-escalation vector with no human in the loop. To avoid that, all IAM mutations require a real Clerk session so that: * The audit log always names a Clerk user (not "the API key for account X"). * Role escalation is bounded by what *that user* is allowed to assign — even if their session is stolen, they can only grant what they themselves can grant. * API keys cannot be silently used to flip roles by anyone with read access to a key store. ## Concepts IAM is modelled as **Job × Scope × Product × Membership** — never encode the tenant in the role name. | Axis | Where it lives | What it means | | - | - | - | | **Job** | Clerk `publicMetadata.tgdRoles` | What the person does (`payment_ops`, `partneradmin`, …) | | **Scope** | Clerk `publicMetadata.whitelabelOwnership` | `null` = Tagada platform; `"slug"` = that partner's book | | **Product** | Partner / merchant flags (e.g. payfac) | Which product surfaces they may touch | | **Membership** | `memberships` row | Active (non-revoked) attachment to a partner | ### `tgdRoles` The canonical list of Tagada platform roles. Stored on Clerk as `publicMetadata.tgdRoles` (single source of truth) and mirrored locally on `public.users.tgd_roles` for indexed queries. > [!TIP] > > Until 2026-05 there was a parallel `privateMetadata.tgdRoles` > fallback that the backend would read if `publicMetadata` was > empty. That fallback was dropped (and the residual rows wiped > from Clerk) in favour of a single, auditable source. If you see > `privateMetadata.tgdRoles` referenced in older docs or code, it > is no longer authoritative. #### Grantable roles | Role | Scope | Typical use | | - | - | - | | `founder` | Tagada-wide (`null`) | Root of trust — only role that can grant `superadmin` / `founder` | | `superadmin` | Tagada-wide (`null`) | Full platform admin (founder-gated) | | **`payment_ops`** | `null` **or** partner slug | **Canonical payment Ops job** (dashboard.tagadapay.io / payfac). Scope chooses the book. | | `rx_admin` | `null` **or** partner slug | **TagadaRx module admin** — storefronts, clinical config, offerings, support mailboxes and desk. `null` = TGD Care platform, slug = the partner's white-label Rx book. Holding it is the partner's **Rx option**. | | `rx_ops` | `null` **or** partner slug | **TagadaRx support desk** — patient conversations (reply, notes, assign, status), mailbox health. No configuration. Implied by `rx_admin`. | | `partneradmin` | Partner slug (required) | Owns one partner's roster (invite / revoke teammates). Does **not** include Rx by itself. | | `accountmanager` | `null` or partner slug | Sales / CS tooling — **never** an Ops substitute | #### Non-grantable (preserved / dual-read) Still accepted on *read* so legacy Clerk rows keep working. **Never mint these** via IAM / invites / CRM checkboxes — backfill to `payment_ops` (+ appropriate scope). | Role | Notes | | - | - | | `tagadapaymentAdmin` | Legacy unscoped Ops alias → prefer `payment_ops` + `null` scope | | `partner_ops` | Renamed → `payment_ops` (usually with a partner slug) | | `crmAdmin` | Legacy CRM-only; preserved so role-update flows don't 400 | #### Removed from the product `hubadmin` and `partnerstaff` were migrated to `payment_ops` (+ scope) and deleted from `VALID_TGD_ROLES`. Do not grant or document them as live roles. ### `whitelabelOwnership` The partner slug a user is scoped to, or `null` for unscoped (Tagada internal) staff. | Scope | Meaning for `payment_ops` | | - | - | | `null` | Tagada platform Ops — global TPA / partner book | | `"acme"` | Partner-book Ops — only the `acme` payfac partner | A `partneradmin` with `whitelabelOwnership: "acme"` can only manage staff for the `acme` partner. **Scoped** `payment_ops` must never satisfy platform-admin gates (`adminClerkAuth`, unscoped Hub admin procedures, merchant ownership bypasses). ### Partner A **partner** is a Tagada-platform-wide concept (CRM + processor), not exclusive to TagadaPay. A partner can have the CRM only, the processor only, or both. Partner staff is tracked in the `memberships` table (one row per `(user, partner)` pair, with a status of `pending`, `active`, or `revoked`). ### Partner Ops (payfac white-label) Payfac white-label partners (e.g. Suby) operate **their own TPA book** in the same Ops dashboard Tagada uses — without receiving platform-only roles (`superadmin` / `founder`). Same job string: **`payment_ops`**. Scope separates the books. | Gate | Required | | - | - | | Job | `payment_ops` (or `partneradmin` where the surface allows owner+Ops) | | Scope | `whitelabelOwnership = ` for a partner book; `null` = Tagada global only | | Product | partner `subscribed_products` includes `payfac` | | Membership | non-revoked `memberships` row for that partner (Clerk slug alone is **not** enough) | | Job | Scope `null` | Scope `"suby"` | | - | - | - | | `payment_ops` | Tagada global Ops | Suby book only | | `partneradmin` | invalid / no Ops | Suby owner (+ Ops if payfac + membership) | **Do not grant** deprecated roles (`tagadapaymentAdmin`, `partner_ops`). Use `payment_ops` + scope. See the internal ADR `docs/iam-model.md`. Data scope: only TPAs where `tagadapay_accounts.partner_id = `. Cross-book access returns `403`. Tagada-only surfaces (Risk, global deals, eligibility rules, partner CRUD) stay behind **unscoped** `payment_ops` / platform auth. > [!WARNING] > > **Clerk roles ≠ Partner API keys.** IAM (this page) gates humans in > dashboards via Clerk session. Partner / CRM / Processing **API keys** > authenticate the Node SDK and server integrations — they do **not** > carry `tgdRoles`, open the Ops dashboard, or call `/api/v2/ops/*`. > See [Partners → API keys](/developer-tools/partners/api-keys). ## Roles at a glance ### The role tree ```mermaid theme={null} flowchart TD Platform([Tagada platform]) Platform --> Internal["Internal staff
whitelabelOwnership = null"] Platform --> Scoped["Partner-scoped staff
whitelabelOwnership = slug"] Internal --> Founder["founder
root of trust"] Internal --> Super["superadmin
full power, every partner"] Internal --> OpsGlobal["payment_ops null scope
TagadaPay Ops — global book"] Internal --> AmInt["accountmanager unscoped
cross-partner sales / CS — not Ops"] Scoped --> OpsBook["payment_ops scope X
same Ops UI, partner X book only"] Scoped --> PA["partneradmin scope X
owns partner X roster"] Scoped --> AmScoped["accountmanager scope X
AM dedicated to one partner — not Ops"] ``` ```text theme={null} Tagada platform │ ├── Internal staff (whitelabelOwnership = null) │ ├── founder root of trust; grants superadmin / founder │ ├── superadmin full power; every partner │ ├── payment_ops TagadaPay Ops — global book │ └── accountmanager cross-partner sales / CS (not Ops) │ └── Partner-scoped staff (whitelabelOwnership = "") ├── payment_ops same Ops job, that partner's book only ├── partneradmin owns one partner's roster └── accountmanager AM dedicated to one partner (not Ops) ``` > **Note** — `accountmanager` appears on both branches. The same role > string can be either unscoped (Tagada-wide AM) or scoped (AM dedicated > to one partner) depending on `whitelabelOwnership`. It is **never** an > Ops substitute. ### One-line role guide | Role | Plain English | | - | - | | `founder` | "I am root of trust — I can mint superadmins." | | `superadmin` | "I can do anything in Tagada, including creating partners." | | `payment_ops` | "I run TagadaPay Ops. Scope null = global book; scope slug = that partner's book only." | | `accountmanager` | "I'm the human relationship for one or more partners. CRM/AM tooling — not payment Ops." | | `partneradmin` | "I run my partner team — invite / revoke teammates inside my partner." | ### Common scenarios | I want to... | Who can do it | | - | - | | Sign in to a Tagada dashboard | any role | | Operate **Ops** for my payfac partner book | scoped `payment_ops` (or `partneradmin` where allowed) + payfac + active membership — see [Partner Ops](#partner-ops-payfac-white-label) | | Operate **Ops** platform-wide (all books, Risk, deals) | **unscoped** `payment_ops` / `superadmin` / `founder` | | **Create** / **archive** a partner | `superadmin` / `founder` only | | Edit a partner's branding / commercial terms | **unscoped** `payment_ops` or above | | List every partner / view a partner profile | **unscoped** `payment_ops` or above (`list` also allows AM / partneradmin with scope clamp) | | Invite / revoke a teammate on **my** partner | `partneradmin` of that partner — or **unscoped** `payment_ops` / `superadmin` | | Grant `superadmin` / `founder` | `founder` only | | Grant unscoped `payment_ops` / `accountmanager` | `superadmin` / `founder` (plus founder rules for privileged roles) | | Grant `partneradmin` / scoped `payment_ops` / `accountmanager` on **my** partner | `partneradmin` of that partner — or unscoped `payment_ops` / `superadmin` | | Move a user from one partner to another | `superadmin` / `founder` only | | Change a merchant's partner attribution | `superadmin` / `founder` only — see [Partner attribution](#partner-attribution-accounts) | > **Self-promotion is always denied.** No role — not even `superadmin` — > can edit its own `tgdRoles`. You always need a peer to grant or > revoke a role on your own account. ## Authorization matrix Every mutation goes through one of the pure policy functions below. ### `canAssignTgdRole` Used by every endpoint that writes to `tgdRoles`. | Caller | May assign... | | - | - | | `founder` | any role, including `superadmin` / `founder` | | `superadmin` | any grantable role **except** `superadmin` / `founder` | | `partneradmin` (scope X) | `PARTNER_ASSIGNABLE_ROLES` only, only to users scoped to X | | anyone else | nothing (returns `{ ok: false, reason }`) | #### Assignable role sets | Constant | Roles | Used when target... | | - | - | - | | `INTERNAL_ASSIGNABLE_ROLES` | `accountmanager`, `payment_ops`, `rx_admin`, `rx_ops`, `superadmin`, `founder` | has `whitelabelOwnership IS NULL` | | `PARTNER_ASSIGNABLE_ROLES` | `payment_ops`, `partneradmin`, `accountmanager`, `rx_admin`, `rx_ops` | is scoped to a partner | A `partneradmin` may grant `rx_admin` / `rx_ops` to their staff **only if they hold `rx_admin` themselves** (`partneradmin_rx_option_required` otherwise). Tagada switches Rx on for a partner by granting `rx_admin` to the partner owner. `partneradmin` is excluded from the internal set (it requires a scope — route through "set partner scope + set roles"). Deprecated aliases (`tagadapaymentAdmin`, `partner_ops`, `crmAdmin`) are **never** in either set. > [!TIP] > > When building an external IAM UI: read the target's current > `whitelabelOwnership` first, then render checkboxes from the > appropriate set. Any deprecated role still on the target should show > as **read-only** (preserve until backfill), but the picker must not > let it be re-added. ### `canManagePartnerStaff` Used by revoke / delete / resend-invitation. | Caller | May manage staff for... | | - | - | | `superadmin` / `founder` | any partner | | **unscoped** `payment_ops` (or legacy `tagadapaymentAdmin`) | any partner | | `partneradmin` (scope X) | partner X only | | anyone else | nothing | ### `canManagePartners` Used by the partner-entity verbs (`list` / `get` / `create` / `update` / `archive`). | Action | Required role | | - | - | | `list` | `superadmin` / `founder`, **unscoped** `payment_ops` (or legacy `tagadapaymentAdmin`), `accountmanager`, or `partneradmin` (auto-clamped to the actor's `partnerScope`) | | `get` / `update` | `superadmin` / `founder`, or **unscoped** `payment_ops` (or legacy `tagadapaymentAdmin`) | | `create` | `superadmin` / `founder` only | | `archive` | `superadmin` / `founder` only | ### `canManageOrgMembership` Used by the merchant-org membership verbs (`list` / `add` / `remove` / `change_role`) and by the merchant **service-API-key** verb (`manage_api_keys`). | Caller | Scope | | - | - | | `superadmin` / `founder`, **unscoped** `payment_ops` (or legacy `tagadapaymentAdmin`) | any merchant org | | `accountmanager` (no scope = internal AM) | any merchant org | | `accountmanager` (scoped to X) | only orgs whose `partnerSlug == X` | | `partneradmin` (scope X) | only orgs whose `partnerSlug == X` | | anyone else | nothing | Self-`remove` and self-`change_role` are always denied (locking yourself out is rarely intentional). Self-`add` is allowed (support join flow). The membership verbs live on the CRM tRPC surface (`api.iamOrgs.{list,membersList,membersAdd,membersRemove,membersSetRole}`), not the public REST `/iam/*` router — they're only ever called from the IAM panel in the CRM. Promote to REST when an external caller needs them. The `manage_api_keys` verb has **no self-action guard** (keys are not scoped to a user, so there is nobody to lock out) — it flows straight through the same actor × org-partner gate as the other verbs. It is exposed on **both** surfaces: the CRM tRPC (`api.partners.{listMerchantApiKeys,createMerchantApiKey,revokeMerchantApiKey}`) *and* the public REST `/iam/*` router (see [Merchant service API keys](#merchant-service-api-keys) below), so a white-label partner can manage keys either from the CRM UI or server-to-server. Why `create` and `archive` are stricter: * **`create`** = onboarding a new partner. In practice this happens after out-of-band steps (legal contract, commercial terms, banking setup), so it stays a Tagada-team-only verb to prevent stray rows. * **`archive`** = the only delete-shaped verb a partner exposes. It has billing implications (open settlement runs, pending payouts), so we gate it behind the most-privileged role. `update` callers that pass `status="offboarded"` are rerouted internally through `archive`, so the strict policy applies regardless of which verb the adapter used. `partneradmin` is allowed `list` (UI affordance — auto-clamped to their own partner) but excluded from the write verbs — partner self-service is the partner-staff lifecycle, not partner-entity CRUD. `accountmanager` is allowed `list` for the same reason: the merchant-org table needs partner attribution. ## Authentication The `/iam/*` endpoints are mounted under `/api/v1/iam/*` (the **internal** OpenAPI router) and accept **Clerk session authentication only**. Bearer API keys, builder sessions, and any other service-account credential are rejected with `401`. ### From a browser-based dashboard (same Clerk instance) The session cookie set by Clerk's standard sign-in flow is enough. Just `fetch()` the endpoint with `credentials: 'include'`. ```ts theme={null} await fetch('/api/v1/iam/permissions/assign-role', { method: 'POST', credentials: 'include', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ targetUserId: 'user_2abc...', requestedRoles: ['accountmanager'], requestedScope: 'acme', }), }); ``` ### From an external app (the sales CRM use case) Use Clerk's standard sign-in flow (OIDC / Clerk-hosted UI / Clerk SDK) on your own domain to sign the operator in against the same Clerk instance that powers Tagada. Then either: * Forward the Clerk session cookie when proxying through your backend, or * Mint a short-lived Clerk session JWT with [`getToken()`](https://clerk.com/docs/references/javascript/session#get-token) and pass it as `Authorization: Bearer ` from server to server. ```bash theme={null} curl https://api.tagada.io/api/v1/iam/users/find \ -H "Authorization: Bearer ${CLERK_SESSION_JWT}" \ -H "Content-Type: application/json" \ -d '{"email": "alice@acme.com"}' ``` A request without a valid Clerk session — including one that carries a Bearer **API key** — returns: ```json theme={null} { "code": "NOT_AUTHORIZED", "message": "IAM endpoints require a Clerk user session, not a service account." } ``` ### Why these endpoints aren't in the right-hand API Reference The auto-generated reference panes on the right side of every page are built from `openapi.json`, which is the **public-API** spec (API-key authenticated). IAM is intentionally absent from that file. The endpoint catalogue below is maintained by hand and lives only in this guide. ## Endpoint catalogue All paths are relative to the base URL of the **API** deployment you are calling — `https://api.tagada.io` in production (the value of `NEXT_PUBLIC_APP_URL`). Note this is **not** `app.tagada.io`, which serves the CRM single-page app and will return a `405` / HTML page for these routes. ### Permission probes These never return `403`. They always return `200` with a decision object — use them to render-then-mutate (see [Patterns](#patterns) below). | Method | Path | Returns | | - | - | - | | `POST` | `/api/v1/iam/permissions/assign-role` | `{ ok: boolean, reason?: string }` | | `POST` | `/api/v1/iam/permissions/manage-partner-staff` | `{ ok: boolean, reason?: string }` | ### Partner entities (CRUD) Lifecycle of partner *records* themselves (rows in `partners`). Mounted under a distinct `partners-admin` prefix so a slug literally named `list` / `create` / `archive` cannot route ambiguously. | Method | Path | Required role | Purpose | | - | - | - | - | | `POST` | `/api/v1/iam/partners-admin/list` | unscoped payment\_ops or above | All partners with `staffCount`, `merchantCount` (Processing TPAs), and `orgCount` (Clerk orgs tagged on the partner via `accounts.partner_id`). Optional `status` filter. | | `POST` | `/api/v1/iam/partners-admin/get` | unscoped payment\_ops or above | Single partner row by `id` XOR `slug`, including branding / preferences / commercial terms. | | `POST` | `/api/v1/iam/partners-admin/list-staff` | unscoped payment\_ops or above | Every staff member attached to a partner (by `id` XOR `slug`). Returns `pending` invites + `active` + `revoked` rows. Reads `memberships` directly so it doesn't depend on the Clerk users mirror. Optional `status` filter to narrow. | | `POST` | `/api/v1/iam/partners-admin/list-orgs` | unscoped payment\_ops or above | Every Clerk organization tagged on a partner (by `id` XOR `slug`). Returns `accountId`, Clerk org id/name/slug, `kind` (`self_serve` \| `partner_managed`), and `createdAt`. Paginate via `limit` (1..500, default 100) + `offset`. Optional `kind` filter. | | `POST` | `/api/v1/iam/partners-admin/create` | **superadmin only** | New partner row. Optional `adminEmails[]` are invited as `partneradmin`. | | `POST` | `/api/v1/iam/partners-admin/update` | unscoped payment\_ops or above (`status="offboarded"` requires superadmin) | Patch name / status / branding / preferences / commercial terms. jsonb fields are partial-merged. | | `POST` | `/api/v1/iam/partners-admin/archive` | **superadmin only** | Soft delete — sets `status="offboarded"`. Idempotent. There is no hard delete on partner rows. | ### Partner-staff lifecycle Scoped to one partner via the `:partnerSlug` path parameter. Caller must satisfy `canManagePartnerStaff` for that partner. | Method | Path | Purpose | | - | - | - | | `POST` | `/api/v1/iam/partners/:partnerSlug/staff/invite` | Idempotent invite — see [Inviting a teammate](#inviting-a-teammate) | | `POST` | `/api/v1/iam/partners/:partnerSlug/staff/revoke` | Soft revoke — see [Revoke vs delete](#revoke-vs-delete) | | `POST` | `/api/v1/iam/partners/:partnerSlug/staff/delete` | Hard delete — see [Revoke vs delete](#revoke-vs-delete) | | `POST` | `/api/v1/iam/partners/:partnerSlug/staff/resend-invitation` | Re-issue a pending Clerk invitation | | `POST` | `/api/v1/iam/partners/:partnerSlug/staff/set-roles` | Rewrite `tgdRoles` of a teammate already on the roster | ### Internal users (Tagada staff) Superadmin-only. These act on unscoped users (`whitelabelOwnership IS NULL`) — Tagada operations team, account managers without a partner scope, etc. | Method | Path | Purpose | | - | - | - | | `POST` | `/api/v1/iam/internal-users/set-roles` | Rewrite a Clerk user's `tgdRoles` | | `POST` | `/api/v1/iam/internal-users/set-partner-scope` | Set or detach a Clerk user's `whitelabelOwnership` | ### Organizations | Method | Path | Purpose | | - | - | - | | `POST` | `/api/v1/iam/orgs/list` | Flat list of every Clerk org / merchant with the partner it belongs to **pre-joined** — `partnerId`, `partnerSlug`, `partnerName` per row (null when unaffiliated). Use this instead of N+1 `partners-admin/get` lookups when rendering an "all merchants" CRM table. Filters: `q` (substring on org name/slug/accountId), `partnerId` XOR `partnerSlug` (use `partnerId="__none__"` for unaffiliated only), `kind`. Paginate via `limit` (1..500, default 100) + `offset`. Payment Ops or above. | ### Merchant service API keys Lets a CRM reseller (e.g. BNP) mint / list / revoke an `org:admin` **service API key** for each of its merchant `accounts`. The minted key is the **Bearer token** the merchant then uses against the public API (`/api/public/v1/*`) — these endpoints are the IAM way to provision that token without going through the merchant dashboard. Authorization is `canManageOrgMembership('manage_api_keys')`: a `partneradmin` scoped to X can only touch merchants whose `accounts.partner_id` resolves to X (scope clamp), and the account ownership is re-checked on every call. unscoped `payment_ops` / `superadmin` reach any merchant. Keys are tagged with a partner-provisioning marker, so **only keys this partner minted are listed or revocable** — the merchant's own self-served keys are never exposed here. | Method | Path | Purpose | | - | - | - | | `POST` | `/api/v1/iam/partners/:partnerSlug/merchants/:accountId/api-keys` | List the partner-provisioned service keys of one merchant account. Secrets are **never** returned on read. | | `POST` | `/api/v1/iam/partners/:partnerSlug/merchants/:accountId/api-keys/create` | Mint a new `org:admin` (full read+write) service key for the merchant. The secret `token` is returned **once** in this response and never again. | | `POST` | `/api/v1/iam/partners/:partnerSlug/api-keys/:keyId/revoke` | Revoke a partner-provisioned key. Only keys this partner minted are revocable (`404` otherwise). An unknown or already-revoked key returns `NOT_FOUND`. | > [!WARNING] > > Minted keys are **`org:admin` — full read + write** on the > merchant account (orders, payments, refunds, …). They are not > read-only or permission-scoped. Treat the returned `token` like a > production secret: surface it once to the operator, never log it, > and revoke + re-mint if it leaks. ### Partner attribution (accounts) > [!WARNING] > > **Tagada-internal only.** These endpoints are listed for transparency > and so that the internal sales CRM has a canonical contract to call > against. They are **superadmin / founder** gated and refuse > impersonated Clerk sessions — in practice only a human on the Tagada > operations team can invoke them. Partners (Suby, BNP, …) do **not** > have credentials that pass these gates and cannot use these routes > to retag their own merchants. Re-attribute a merchant account (or an orphan partner-managed account) to a different partner. Every call is recorded in the `partner_change_log` audit table and fans out across all of the surfaces that have to stay in sync — there is no longer any way to update one of them without the others. | Method | Path | Purpose | | - | - | - | | `POST` | `/api/v1/iam/accounts/change-partner` | Canonical multi-surface partner change. **Platform-admin only** (superadmin or founder). See payload + surface contract below. | | `POST` | `/api/v1/iam/orgs/assign-to-partner` | **Deprecated** back-compat alias for `change-partner`. Same auth, same fan-out, same audit row — just the older `{ clerkOrgId, whitelabel }` payload shape. New integrations should target `accounts/change-partner` so they can pass `reason`, `dryRun` and `bulkJobId`. | **`accounts/change-partner` payload** ```jsonc theme={null} theme={null} { // Either an org-scoped change (the 97% case) ... "scope": { "kind": "org", "clerkOrgId": "org_..." }, // ... or an orphan partner-managed account (no Clerk org yet): // "scope": { "kind": "account", "accountId": "acc_..." }, // Partner slug to attach, or `null` to detach. "toPartner": "bnp", // Operator-supplied free text, 5..2000 chars. Stored verbatim on // the audit row so a future dispute ("why did BNP lose that // commission?") has a human-written explanation attached. "reason": "Migration from FMJ — see ticket #4821", // Optional. When true, no surface is mutated but a `dry_run=true` // row is still written so the preview shows up in the timeline UI. "dryRun": false, // Optional. Shared across all rows of the same CSV batch so the // timeline UI can group them. "bulkJobId": "bulk_2026-05-26_bnp-grid" } ``` **Surfaces fanned out on every successful call** 1. `accounts.partner` + `accounts.partner_id` (Postgres) — legacy slug column and canonical FK, written atomically. 2. `hub_requests.business_info.partner` (Postgres JSONB) — keeps every in-flight onboarding request consistent with the org's new partner. 3. `org.publicMetadata.whitelabel` (Clerk) — drives the `activeOrgWhitelabel` session claim and per-partner branding. Also auto-adds every `partneradmin` of the new partner to the org. 4. Clerk member users' `publicMetadata.partner` tag — so existing members see the new attribution on their next token rotation. 5. Stripe Connect sub-accounts' `payments_pricing` group — resolved from `partners.stripe_pricing_group` so commissions follow the partner's grid immediately. 6. ClickHouse `stripe_txns_all.partner` — historical backfill so commission reports for past traffic are restated under the new partner. 7. `hub_request_assignments` tags — keeps the routing/queue view aligned with the new attribution. The response is a structured per-surface result blob (the same shape stored on the `partner_change_log.surfaces` JSONB column) so an operator dialog can show "Stripe OK, ClickHouse deferred, …" without having to query the audit table. **`orgs/assign-to-partner` (deprecated)** Kept for the older CRM build that hasn't migrated to the new payload yet. Internally it just wraps `change-partner` with a synthetic `reason="auto:assignOrgToPartnerAction(legacy REST alias, …)"` so the audit trail stays honest. There is no behavioural difference at the surface level — both endpoints write the same audit row and trigger the same 7-surface fan-out. ### Read-side queries Both query the local Clerk mirror (synced via webhook). Eventually consistent — typically \<1s lag. For freshness-critical paths (login, immediately after a role re-grant) call the Clerk Backend API directly. | Method | Path | Returns | | - | - | - | | `POST` | `/api/v1/iam/users/list` | `{ rows, total, limit, offset }`. Filters: `q`, `tgdRole`, `partnerScope` (sentinel `"__internal__"` selects unscoped staff). | | `POST` | `/api/v1/iam/users/find` | `{ found, user }`. Lookup by `email` or `clerkUserId`. | ## Patterns ### "Render-then-mutate" — pre-flight permission checks Before showing a destructive button, hit `POST /api/v1/iam/permissions/assign-role` or `POST /api/v1/iam/permissions/manage-partner-staff`. They always return `200` with `{ ok: boolean, reason? }` so you can disable the button instead of letting the user mash it and discover the `403`. ### Inviting a teammate `POST /api/v1/iam/partners/:partnerSlug/staff/invite` is idempotent on `(partnerSlug, email)`: * If the email is already a Clerk user **scoped to this partner**, the endpoint just appends the requested roles to their existing `tgdRoles` and returns `{ status: "role_updated" }`. * Otherwise it creates a fresh Clerk invitation with the partner's branded email + redirect URL and returns `{ status: "invited" }`. The `roles[]` payload is restricted to `PARTNER_ASSIGNABLE_ROLES` (`payment_ops`, `partneradmin`, `accountmanager`) — see [Assignable role sets](#assignable-role-sets). The partner-staff `set-roles` endpoint enforces the same constraint. Scoped `payment_ops` is granted **with** the partner slug (normal invite). To grant **unscoped** platform roles (`payment_ops` with `null` scope, `superadmin`, …) you must first detach the user via `internal-users/set-partner-scope` and then call `internal-users/set-roles` (superadmin / founder). Cross-partner / hijack guard: if the email belongs to a Clerk user who is **already scoped to a different partner**, or is an internal Tagada staff member, or owns a merchant org, the invite is **rejected** even by `superadmin` callers — superadmin must intervene via `internal-users/set-partner-scope` first. ### Revoke vs delete * **Revoke** (`POST .../revoke`) is the soft path: strips Clerk roles and scope, flips the audit row in `memberships` to `revoked`. The Clerk user account itself is untouched. * **Delete** (`POST .../delete`) is the hard path: drops the audit row entirely (and revokes any pending invitation in Clerk). Use this when the user was added by mistake and shouldn't appear in the audit log at all. ### Creating a partner `POST /api/v1/iam/partners-admin/create` is superadmin-only. Pass `adminEmails: ["alice@acme.com", ...]` to invite the founding partner admins as `partneradmin` in the same call. Each invitation is idempotent on `(partnerSlug, email)`. Failures on individual invitations don't roll back the partner row — they show up as `{ status: "error", error: "..." }` entries in the response's `invited[]` and you can re-invite from the Team tab. ### Archiving (soft delete) a partner There is **no hard delete** on partner rows. Archiving sets `status="offboarded"` so: * Merchants still resolve their `partner_id` correctly. * Billing snapshots and settlement reports keep referencing the row. * The slug remains reserved (you cannot create a new partner with the same slug after archive). Archiving is idempotent. The endpoint returns `previousStatus` so you can detect "already archived" at the UI layer: ```bash theme={null} curl https://api.tagada.io/api/v1/iam/partners-admin/archive \ -H "Authorization: Bearer ${CLERK_SESSION_JWT}" \ -H "Content-Type: application/json" \ -d '{"id": "ptr_01H..."}' ``` Calling `update` with `status="offboarded"` is rerouted internally through `archive`, so the strict (superadmin-only) policy applies either way. ### Provisioning a merchant's API key (end-to-end) The merchant key lifecycle spans **two** auth models: you *mint* the key through IAM (Clerk-session), then the merchant *uses* it as a Bearer API key against the public API. Concretely: 1. **Mint** (Clerk-session, partneradmin of `bnp`). The secret comes back exactly once — store it immediately. ```bash theme={null} curl https://api.tagada.io/api/v1/iam/partners/bnp/merchants/acc_01H.../api-keys/create \ -H "Authorization: Bearer ${CLERK_SESSION_JWT}" \ -H "Content-Type: application/json" # → { "object": "service_api_key", "id": "...", "name": "BNP · Acme Store", # "orgRole": "org:admin", "token": "tgd_live_…", "createdAt": "…" } ``` 2. **Use** (Bearer API key — the merchant's own integration). The `token` from step 1 is now a normal public-API credential: ```bash theme={null} curl https://api.tagada.io/api/public/v1/orders \ -H "Authorization: Bearer tgd_live_…" ``` 3. **List** what you've provisioned for that merchant (secrets are never returned on read): ```bash theme={null} curl https://api.tagada.io/api/v1/iam/partners/bnp/merchants/acc_01H.../api-keys \ -H "Authorization: Bearer ${CLERK_SESSION_JWT}" ``` 4. **Revoke** when rotating or offboarding: ```bash theme={null} curl https://api.tagada.io/api/v1/iam/partners/bnp/api-keys/key_01H.../revoke \ -H "Authorization: Bearer ${CLERK_SESSION_JWT}" ``` The same flow is available without code from the CRM white-label UI under the partner-admin **API keys** tab — it calls the equivalent `api.partners.*` tRPC procedures, which delegate to the identical IAM use-cases (same scope clamp, same ownership check, same reveal-once behaviour). ### Read-side queries The `users.list` and `users.find` endpoints query the local mirror synced from Clerk via webhook. The mirror is **eventually consistent** — typically \<1s lag. For freshness-critical paths (login, immediately after a role re-grant) call the Clerk Backend API directly. The `partnerScope` filter on `users.list` accepts the sentinel `"__internal__"` to select unscoped staff (`whitelabelOwnership IS NULL`). ## Errors All `/iam/*` endpoints return standard HTTP codes: | Code | Meaning | | - | - | | 401 | Missing or invalid Clerk session — *or* a Bearer API key was sent (rejected by `clerkSessionOnlyProcedure`) | | 403 | Caller is authenticated but the policy denied the action | | 404 | Partner / user / invitation not found | | 409 | Conflict (e.g. user already on roster with the same role) | | 422 | Input validation failed | The body is a JSON object with `code` (a string from the ZSA error enum) and `message` (a human-readable description). # Commerce API reference Source: https://docs.tagada.io/api-reference/introduction Reference for the TagadaPay Commerce API, including V2 payments # TagadaPay Commerce API The Commerce API is a REST API that lets you process payments, manage subscriptions, handle customers, deploy plugins, and orchestrate checkout funnels, all programmatically. > [!NOTE] > > **Payments on this API are V2.** They are the reference for every live integration today. The new [Payments API (V3)](/payments-api/overview) lives on the same host under `/v1` and is in preview. See [V2 or V3: which one should I use?](/payments-api/v2-or-v3) ## Base URL ``` https://api.tagada.io/api/public/v1 ``` A staging environment is available for testing: ``` https://api.tagada.dev/api/public/v1 ``` See [API hosts](/developer-tools/api-hosts) for every environment and the Payments API paths. ## Authentication Authenticate every request with a Bearer token in the `Authorization` header. Get your API key from the [TagadaPay Dashboard](https://app.tagada.io). ```bash theme={null} curl https://api.tagada.io/api/public/v1/auth/test \ -H "Authorization: Bearer your-api-key" ``` > [!WARNING] > > Keep your API keys secure. Never expose them in client-side code, public repositories, or logs. ### Authentication troubleshooting A missing, empty, or malformed `Authorization` header returns **401** with a message explaining what was wrong: ```json theme={null} { "code": "NOT_AUTHORIZED", "message": "Missing or invalid API key. No `Authorization` header (or an empty Bearer token) was provided. Authenticate by sending your API key as a Bearer token: `Authorization: Bearer `. ..." } ``` Common causes: * **Empty shell variable** — `Authorization: Bearer $KEY` with `$KEY` unset sends an empty token. Verify with `echo ${#KEY}` before calling. * **Wrong header** — the key must be in `Authorization: Bearer `, not in a custom header. * **Wrong key type** — public API endpoints accept dashboard API keys (Settings → API Keys) and TPA-restricted `tp_sk_…` partner keys. > [!NOTE] > > Older API versions surfaced this situation as a confusing 500 mentioning `Clerk: auth() was called but Clerk can't detect usage of clerkMiddleware()`. If you see that error, it means the same thing: your API key did not reach the server — fix the `Authorization` header. ## Request format * All requests must use **HTTPS** * Set `Content-Type: application/json` for POST/PUT requests * All responses return JSON ```bash theme={null} curl -X POST https://api.tagada.io/api/public/v1/payments \ -H "Authorization: Bearer your-api-key" \ -H "Content-Type: application/json" \ -d '{"pagination": {"page": 1, "pageSize": 20}}' ``` ## Rate limits Each account can make up to **600 requests per minute**, counted across all of its API keys. The counter resets at the start of every clock minute. Exceeding it returns `429 Too Many Requests` with a `Retry-After` header: the number of seconds until the counter resets. These endpoints are not counted against that limit: `/stores`, `/stores/{id}/payment-setup`, `/plugins/*`, `/payments/export`, `/processing/enroll`, `/chargeblast/*`, `/atp/*` and `/funnels/republish-runtime`. Separately, our network edge caps each source IP address at 200 requests per minute. A 429 from that cap carries no `Retry-After` and no `x-request-id`. Other 429 responses, such as the one returned after repeated invalid API keys, carry no `Retry-After` either. Whenever `Retry-After` is missing, back off exponentially. Apart from that edge 429, every API response carries an `x-request-id` header. Include it when you contact support about a specific call. ## Error codes | Code | Meaning | | - | - | | 400 | Bad request — invalid or missing parameters | | 401 | Unauthorized — missing or invalid API key | | 403 | Forbidden — insufficient permissions | | 404 | Resource not found | | 409 | Conflict with another request | | 429 | Rate limited | | 500 | Server error | Error responses follow this structure: ```json theme={null} { "code": "ERROR", "message": "Human-readable error description", "data": {} } ``` ## Pagination List endpoints support pagination via request body parameters: > [tab] Offset pagination > > Used by payments, orders, customers, and block rules. > > ```json theme={null} > { > "pagination": { > "page": 1, > "pageSize": 20 > }, > "sortBy": { > "field": "createdAt", > "direction": "desc" > } > } > ``` > [tab] Simple pagination > > Used by subscriptions. > > ```json theme={null} > { > "page": 1, > "per_page": 20, > "sort": "subscriptions.createdAt", > "sort_order": "desc" > } > ``` ## Filtering Most list endpoints accept a `filters` object. Common patterns: ```json theme={null} { "filters": { "status": ["active", "trialing"], "currency": ["USD", "EUR"], "date": { "condition": "is-after-date", "value": ["2024-01-01"] }, "email": { "condition": "contains", "value": "john@" } } } ``` Date filter conditions: `is-equal-date`, `is-between-date`, `is-after-date`, `is-before-date`. ## Webhooks Register webhook endpoints to receive real-time event notifications for payments, orders, subscriptions, and more. See the [Webhooks API](/api-reference/webhooks) section. ## SDKs > [card] [Node.js SDK](/developer-tools/node-sdk/quick-start) > > Server-side SDK for Node.js / TypeScript > [card] [Plugin SDK](/developer-tools/sdk/introduction) > > Build custom checkout plugins with React > [card] [Plugin CLI](/developer-tools/cli/introduction) > > Deploy and manage plugins from the command line ## Need help? * **Email**: [api-support@tagadapay.com](mailto:api-support@tagadapay.com) * **Dashboard**: [app.tagada.io](https://app.tagada.io) # Create offer Source: https://docs.tagada.io/api-reference/offers/create-offer /openapi.json post /api/public/v1/offers/create Create a new upsell offer or order bump for a store. # Delete offers Source: https://docs.tagada.io/api-reference/offers/delete-offers /openapi.json post /api/public/v1/offers/delete Delete one or more upsell offers or order bumps by their IDs. # Get offer by ID Source: https://docs.tagada.io/api-reference/offers/get-offer-by-id /openapi.json get /api/public/v1/offers/{id} Retrieve a single upsell offer or order bump by its ID. # List offers Source: https://docs.tagada.io/api-reference/offers/list-offers /openapi.json post /api/public/v1/offers/list List upsell offers and order bumps for a store. Filter by type (upsell or orderbump), enabled status, and search text. # Update offer Source: https://docs.tagada.io/api-reference/offers/update-offer /openapi.json put /api/public/v1/offers/{id} Update an existing upsell offer or order bump. # Get order by ID Source: https://docs.tagada.io/api-reference/orders/get-order-by-id /openapi.json get /api/public/v1/orders/{orderId} Retrieve detailed information about a specific order including line items, payments, and customer data # List orders Source: https://docs.tagada.io/api-reference/orders/list-orders /openapi.json post /api/public/v1/orders/list Get all orders for the authenticated account with filtering, sorting, and pagination # Create payment flow Source: https://docs.tagada.io/api-reference/payment-flows/create-payment-flow /openapi.json post /api/public/v1/payment-flows/create Create a new payment flow (processor orchestration configuration). Requires org:admin role. A payment flow defines: - **strategy**: `simple` (single processor) or `cascade` (fallback chain) - **processorConfigs**: weighted list of processors to route payments through - **fallbackProcessorConfigs**: ordered fallback processors when primary fails - **pickProcessorStrategy**: `weighted`, `lowestCapacity`, or `automatic` - **threeDsEnabled**: whether 3D Secure is enforced - **stickyProcessorEnabled**: reuse last successful processor for returning customers - **abuseDetectionConfig**: optional fraud/velocity rules # Delete payment flow Source: https://docs.tagada.io/api-reference/payment-flows/delete-payment-flow /openapi.json post /api/public/v1/payment-flows/delete Soft-delete a payment flow (sets archivedAt). Also clears this flow from any stores that had it as default. Requires org:admin role. # Get payment flow by ID Source: https://docs.tagada.io/api-reference/payment-flows/get-payment-flow-by-id /openapi.json post /api/public/v1/payment-flows/get Retrieve a single payment flow by its ID. Requires org:admin role. # Get payment flow with processor details Source: https://docs.tagada.io/api-reference/payment-flows/get-payment-flow-with-processor-details /openapi.json post /api/public/v1/payment-flows/get-with-processors Retrieve a single payment flow with full processor information resolved inline. Requires org:admin role. # List payment flows Source: https://docs.tagada.io/api-reference/payment-flows/list-payment-flows /openapi.json get /api/public/v1/payment-flows List all active (non-archived) payment flows for the authenticated account. Requires org:admin role. # List payment flows with processor details Source: https://docs.tagada.io/api-reference/payment-flows/list-payment-flows-with-processor-details /openapi.json get /api/public/v1/payment-flows/with-processors List all active payment flows with full processor information (name, type, config) resolved inline. Requires org:admin role. # Update payment flow Source: https://docs.tagada.io/api-reference/payment-flows/update-payment-flow /openapi.json post /api/public/v1/payment-flows/update Update an existing payment flow. All fields in `data` are optional except fallbackProcessorConfigs. Requires org:admin role. # Create payment instrument from TagadaToken Source: https://docs.tagada.io/api-reference/payment-instruments/create-payment-instrument-from-tagadatoken /openapi.json post /api/public/v1/payment-instruments/create-from-token Create a payment instrument from a base64 encoded TagadaToken. This endpoint decodes the TagadaToken and extracts the necessary payment information to create a payment instrument. The TagadaToken should contain: - type: 'card' - token: BasisTheory token ID - provider: 'basistheory' - nonSensitiveMetadata: Card details like last4, brand, expiry, etc. **Security & Permissions:** - Requires org:admin role - Requires storeId - validates that the authenticated account owns the store - All operations are scoped to the authenticated user's account - If customerId is provided, it must belong to the authenticated account - If customerData is provided, the instrument belongs to the store's customer resolved by email **Customer Handling:** - Provide either customerId (existing customer) OR customerData (find or create by email) - Cannot provide both customerId and customerData - With customerData, the store's existing customer with the same email receives the instrument (case-insensitive, surrounding spaces ignored); a customer is created only when none exists - Provided non-empty billing/shipping addresses replace the stored addresses; empty names are filled - An existing customer's currency, locale and marketing consent are kept **Shopper context (`customer`):** - Your server is the caller, so Tagada cannot see the shopper. Pass the shopper's IP and User-Agent as your server received them in `customer: { ipAddress, userAgent }` - Kept on the customer's device record, returned as `device` by `GET /customers/{customerId}` - Every later `POST /payments/process` on this customer, rebills included, sends that IP to the processor (Stripe Radar, Adyen risk) even when the call omits `customer` - The User-Agent is stored, not sent to the processor, except as 3-D Secure browser data to the processors that ask for it - Never your own server's address. Tagada never substitutes it either; an invalid IP is refused (400) # Get payment instrument by ID Source: https://docs.tagada.io/api-reference/payment-instruments/get-payment-instrument-by-id /openapi.json get /api/public/v1/payment-instruments/{paymentInstrumentId} Get payment instrument details including customer info and card enrichment # List customer payment instruments Source: https://docs.tagada.io/api-reference/payment-instruments/list-customer-payment-instruments /openapi.json get /api/public/v1/customers/{customerId}/payment-instruments Get all active payment instruments for a customer # List payment instruments Source: https://docs.tagada.io/api-reference/payment-instruments/list-payment-instruments /openapi.json post /api/public/v1/payment-instruments/list List payment instruments with filtering, sorting and pagination # Raw card data capability (SDK internal) Source: https://docs.tagada.io/api-reference/payment-instruments/raw-card-data-capability-sdk-internal /openapi.json get /api/public/v1/payment-instruments/raw-card/config Used by `@tagadapay/node-sdk` `paymentInstruments.createFromCard()`. Returns the public, create-only vault key the SDK uses to tokenize a card **from the merchant's server directly into Tagada's PCI vault** — the card number never reaches the Tagada API. Not meant to be called by hand. The capability is off by default and enabled per account by Tagada support. When it is not enabled the endpoint answers `403` with `Please contact support to ask for raw card data enablement`. # Continue a paused payment Source: https://docs.tagada.io/api-reference/payments/continue-a-paused-payment /openapi.json post /api/public/v1/payments/continue Resume a payment that was paused mid-flow requiring a client-side action (e.g. Airwallex Radar device fingerprinting, 3DS authentication). Intended for API consumers using `@tagadapay/core-js`. Pass the `paymentId` returned from the original payment attempt. The server will re-run the payment flow from where it left off and return the updated payment status. # Get available processors Source: https://docs.tagada.io/api-reference/payments/get-available-processors /openapi.json post /api/public/v1/payments/processors Get all enabled payment processors for the authenticated account # Get payment by ID Source: https://docs.tagada.io/api-reference/payments/get-payment-by-id /openapi.json get /api/public/v1/payments/{paymentId} Retrieve detailed information about a specific payment including transactions and customer data # Get payment currencies Source: https://docs.tagada.io/api-reference/payments/get-payment-currencies /openapi.json post /api/public/v1/payments/currencies Get all currencies used in payments for the authenticated account # List payments with transactions Source: https://docs.tagada.io/api-reference/payments/list-payments-with-transactions /openapi.json post /api/public/v1/payments List and filter payments with their associated transactions. Supports pagination, sorting, and advanced filtering options. Supported filters: - Store IDs - Payment status and sub-status - Currency and amount - Card details (last4, brand, expiry) - Customer information (email, name) - Date ranges - Dispute status and type # Mark payment as disputed Source: https://docs.tagada.io/api-reference/payments/mark-payment-as-disputed /openapi.json post /api/public/v1/payments/mark-disputed Mark a payment as disputed with initial dispute information. This endpoint is used to initiate a dispute on a payment. Required fields: - paymentId: The ID of the payment to mark as disputed - disputeStatus: Initial status of the dispute - disputeType: Type of dispute - disputeReasonCode: Reason code for the dispute Optional fields: - disputedTransactionId: ID of the specific transaction being disputed - disputeNote: Additional notes about the dispute # Process payment Source: https://docs.tagada.io/api-reference/payments/process-payment /openapi.json post /api/public/v1/payments/process Process a payment using the payment flow system with comprehensive options for different payment scenarios. When the merchant is closed, a customer-initiated purchase, authorization or card verification answers 403 with data.code MERCHANT_CLOSED and the message "This store is not taking orders at the moment."; nothing is written. Merchant-initiated charges and captures are not affected. # Refund payment Source: https://docs.tagada.io/api-reference/payments/refund-payment /openapi.json post /api/public/v1/payments/refund Process a full or partial refund for a payment # Update payment dispute status Source: https://docs.tagada.io/api-reference/payments/update-payment-dispute-status /openapi.json post /api/public/v1/payments/dispute Update the dispute status of a payment. Supports various dispute statuses including RDR (Rapid Dispute Resolution) and Alert notifications. Available dispute statuses: - response-needed: Requires merchant response - under-review: Currently being reviewed - forfeited: Dispute forfeited - won: Dispute won by merchant - lost: Dispute lost by merchant - unknown: Status unknown - rdr: Rapid Dispute Resolution - expedited dispute handling - alert: Alert notification # Void payment Source: https://docs.tagada.io/api-reference/payments/void-payment /openapi.json post /api/public/v1/payments/void Void an authorized payment transaction. This cancels a previously authorized payment before it has been captured. Important notes: - Only works for payments with 'authorized' status - Must be performed before the payment is captured - Once voided, the authorization is released and funds are no longer held - Cannot be undone once voided Common error codes: - PAYMENT_NOT_FOUND: The specified payment does not exist - TRANSACTION_NOT_AUTHORIZE: The payment is not in authorized status - TRANSACTION_NO_PROCESSOR: No processor found for the transaction - TRANSACTION_VOID_FAILED: The void operation failed at the processor level # Configure split testing (V2) Source: https://docs.tagada.io/api-reference/plugins-v2/configure-split-testing-v2 /openapi.json post /api/public/v1/plugins/v2/split Configure A/B or geo-based split testing on an existing route. **Split types:** - **weighted**: Traffic split by percentage (weights must sum to 100) - **geo**: Traffic split by visitor country (ISO 3166-1 alpha-2 codes) **Sticky sessions**: Visitors are pinned to the same variant for `stickyDuration` seconds (default 7 days). **Authentication required**: API key must be authorized for the account. # Delete deployment (V2) Source: https://docs.tagada.io/api-reference/plugins-v2/delete-deployment-v2 /openapi.json post /api/public/v1/plugins/v2/deployment/delete Delete a specific deployment # Delete plugin (V2) Source: https://docs.tagada.io/api-reference/plugins-v2/delete-plugin-v2 /openapi.json post /api/public/v1/plugins/v2/delete Delete a plugin and all its deployments # Deploy plugin from URL (V2) Source: https://docs.tagada.io/api-reference/plugins-v2/deploy-plugin-from-url-v2 /openapi.json post /api/public/v1/plugins/v2/deploy-from-url Deploy plugin from URL (CRM feature - uses V2 schema). ⚠️ **OVERWRITE MODE**: Set 'overwrite: true' to replace assets for an existing deployment with the same version. **BEHAVIOR**: Overwrite mode will: - Keep the existing deployment record (same deploymentId, blobPrefix) - Keep all instances and routes intact (zero downtime) - Replace assets in blob storage (ZIP + extracted files) - Update the zipUrl in the database - All mounted instances will immediately serve the NEW assets - Old assets are permanently overwritten (NOT REVERSIBLE) Use overwrite mode when you want to hot-swap plugin assets without recreating instances/routes. # Deploy plugin with inline assets (V2) Source: https://docs.tagada.io/api-reference/plugins-v2/deploy-plugin-with-inline-assets-v2 /openapi.json post /api/public/v1/plugins/v2/deploy Deploy a plugin with base64-encoded inline assets. This endpoint is for external builders that generate assets client-side and don't have their own CDN infrastructure. **Authentication required**: API key must be authorized for the account. **Request body:** - **manifest**: Plugin manifest with name, version, pages, etc. - **storeId**: The store ID to associate the plugin with - **inlineAssets**: Array of assets with path, base64 content, and contentType - **sourceData**: (optional) Source data for external editors (e.g., TagadaStudio FunnelTemplate) - **overwrite**: Set to true to replace an existing deployment **Returns:** - **success**: Whether deployment succeeded - **pluginId**: The generated plugin ID - **deploymentId**: The deployment ID - **version**: The deployed version - **message**: Human-readable status message - **uploadedFiles**: Number of files uploaded # Fork for edit (V2) Source: https://docs.tagada.io/api-reference/plugins-v2/fork-for-edit-v2 /openapi.json post /api/public/v1/plugins/v2/fork Fork an instance for editing (optimized atomic operation) # Get available features (V2) Source: https://docs.tagada.io/api-reference/plugins-v2/get-available-features-v2 /openapi.json post /api/public/v1/plugins/v2/features Get available features across all deployments for filtering # Get deployment details (V2) Source: https://docs.tagada.io/api-reference/plugins-v2/get-deployment-details-v2 /openapi.json post /api/public/v1/plugins/v2/deployment/details Get detailed information about a specific deployment with instances and routes # Get deployment source data (V2) Source: https://docs.tagada.io/api-reference/plugins-v2/get-deployment-source-data-v2 /openapi.json post /api/public/v1/plugins/v2/source-data Fetch the source data (e.g., FunnelTemplate) for a deployment. This enables round-trip editing with external editors like TagadaStudio: 1. Deploy plugin with sourceData 2. CRM redirects to external editor with pluginId 3. External editor fetches sourceData 4. User edits and re-deploys **Authentication required**: API key must be authorized for the account. **Request body:** - **pluginId**: The plugin ID to fetch source data for - **deploymentId**: (optional) Specific deployment ID. If not provided, fetches latest. **Returns:** - **success**: Whether fetch succeeded - **pluginId**: The plugin ID - **deploymentId**: The deployment ID - **sourceDataUrl**: URL to the source data file - **sourceData**: The actual source data (fetched from URL) - **message**: Human-readable status message # Get plugin details Source: https://docs.tagada.io/api-reference/plugins-v2/get-plugin-details /openapi.json get /api/public/v1/plugins/v2/details/{pluginId} Get detailed information about a specific plugin (GET alternative to POST /plugins/v2/details) # Get plugin details (V2) Source: https://docs.tagada.io/api-reference/plugins-v2/get-plugin-details-v2 /openapi.json post /api/public/v1/plugins/v2/details Get detailed information about a specific plugin # Instantiate plugin (V2) Source: https://docs.tagada.io/api-reference/plugins-v2/instantiate-plugin-v2 /openapi.json post /api/public/v1/plugins/v2/instantiate Create a new instance of a deployment with a given config (without mounting). Supports API key auth. # List all plugins (V2) Source: https://docs.tagada.io/api-reference/plugins-v2/list-all-plugins-v2 /openapi.json post /api/public/v1/plugins/v2/list List all plugins for the account with their deployments using V2 schema # List instances for a store Source: https://docs.tagada.io/api-reference/plugins-v2/list-instances-for-a-store /openapi.json get /api/public/v1/plugins/v2/instances/{storeId} List all plugin instances for a store. Optionally filter by deploymentId query param. # List instances (V2) Source: https://docs.tagada.io/api-reference/plugins-v2/list-instances-v2 /openapi.json post /api/public/v1/plugins/v2/instances List all instances for a store (including those without routes) # List mount points for a store Source: https://docs.tagada.io/api-reference/plugins-v2/list-mount-points-for-a-store /openapi.json get /api/public/v1/plugins/v2/mount-points/{storeId} List all mount points grouped by route (GET alternative to POST /plugins/v2/mount-points) # List mount points (V2) Source: https://docs.tagada.io/api-reference/plugins-v2/list-mount-points-v2 /openapi.json post /api/public/v1/plugins/v2/mount-points List all mount points grouped by route (hostname + basePath) # List plugins for a store Source: https://docs.tagada.io/api-reference/plugins-v2/list-plugins-for-a-store /openapi.json get /api/public/v1/plugins/v2/list/{storeId} List all plugins for a store (GET alternative to POST /plugins/v2/list) # List verified domains (V2) Source: https://docs.tagada.io/api-reference/plugins-v2/list-verified-domains-v2 /openapi.json get /api/public/v1/plugins/v2/domains List all verified custom domains for the account # Mount plugin (V2) Source: https://docs.tagada.io/api-reference/plugins-v2/mount-plugin-v2 /openapi.json post /api/public/v1/plugins/v2/mount Mount a deployment to a target (hostname, alias, or custom domain) # Promote preview (V2) Source: https://docs.tagada.io/api-reference/plugins-v2/promote-preview-v2 /openapi.json post /api/public/v1/plugins/v2/promote Promote a preview instance to production (commit) # Remove instance (V2) Source: https://docs.tagada.io/api-reference/plugins-v2/remove-instance-v2 /openapi.json post /api/public/v1/plugins/v2/instance/remove Remove an instance (and its direct CDN route if it exists) # Remove route(s) from instance (V2) Source: https://docs.tagada.io/api-reference/plugins-v2/remove-routes-from-instance-v2 /openapi.json post /api/public/v1/plugins/v2/unmount Remove route(s) from an instance. If routeId is provided, removes that specific route. If routeId is not provided, removes ALL routes for the instance (complete unmount). # Retrieve a deployment Source: https://docs.tagada.io/api-reference/plugins-v2/retrieve-a-deployment /openapi.json get /api/public/v1/plugins/v2/deployments/{deploymentId} Get deployment details by ID. Unlike the POST endpoint, this does not require storeId — deployments are global resources. # Retrieve a single instance Source: https://docs.tagada.io/api-reference/plugins-v2/retrieve-a-single-instance /openapi.json get /api/public/v1/plugins/v2/instances/detail/{instanceId} Get detailed information about a specific plugin instance by ID, including its deployment data. # Set deployment visibility (V2) Source: https://docs.tagada.io/api-reference/plugins-v2/set-deployment-visibility-v2 /openapi.json post /api/public/v1/plugins/v2/deployment/visibility Set deployment visibility (public/private) # Swap instance (V2) Source: https://docs.tagada.io/api-reference/plugins-v2/swap-instance-v2 /openapi.json post /api/public/v1/plugins/v2/swap Swap an instance (atomic unmount + mount for switching) # Sync deployment config (V2) Source: https://docs.tagada.io/api-reference/plugins-v2/sync-deployment-config-v2 /openapi.json post /api/public/v1/plugins/v2/deployment/sync-config Sync config presets, schema, and uiSchema to an existing deployment without redeploying # Update instance config (V2) Source: https://docs.tagada.io/api-reference/plugins-v2/update-instance-config-v2 /openapi.json post /api/public/v1/plugins/v2/instance/config Update instance config (live config editor) # Update route (V2) Source: https://docs.tagada.io/api-reference/plugins-v2/update-route-v2 /openapi.json post /api/public/v1/plugins/v2/route/update Update route matcher, excluder, and priority for an existing instance # Validate plugin manifest (V2) Source: https://docs.tagada.io/api-reference/plugins-v2/validate-plugin-manifest-v2 /openapi.json post /api/public/v1/plugins/v2/manifest/validate Validate a plugin manifest without deploying. Returns structured validation results: - **valid**: Is the manifest deployable? (no errors) - **errors**: Blocking issues that prevent deployment - **warnings**: Deprecation notices and suggestions - **info**: Helpful tips and best practices - **summary**: Counts and metadata - **normalized**: Manifest with defaults applied (if valid) This endpoint is: - **Retro compatible**: Old manifests work, new fields are optional - **Not aggressive**: Warns but doesn't block on optional improvements - **Helpful**: Provides actionable suggestions for each issue # Count public plugins by type Source: https://docs.tagada.io/api-reference/plugins/count-public-plugins-by-type /openapi.json get /api/public/v1/plugins-count Get a count of public plugins grouped by type. This endpoint is completely public and requires no authentication. Returns counts for each plugin type: - landing: Landing page plugins - checkout: Checkout and payment plugins - advertorial: Advertorial and marketing plugins - loyalty: Customer loyalty and retention plugins - postpurchase: Post-purchase experience plugins # Deploy plugin from blob URL Source: https://docs.tagada.io/api-reference/plugins/deploy-plugin-from-blob-url /openapi.json post /api/public/v1/plugins/deploy-from-blob Deploy a plugin from a blob URL. This endpoint is used after uploading a large ZIP file to blob storage to bypass the 4.5MB serverless function limit. # Deploy plugin from marketplace Source: https://docs.tagada.io/api-reference/plugins/deploy-plugin-from-marketplace /openapi.json post /api/public/v1/plugins/deploy-from-marketplace Deploy a plugin from the public marketplace # Deploy plugin version from CLI Source: https://docs.tagada.io/api-reference/plugins/deploy-plugin-version-from-cli /openapi.json post /api/public/v1/plugins/deploy Deploy a new version of a plugin to the CMS from the CLI tool. Supports custom domains for direct-mode plugins. Validates that custom domain + path combinations are unique to prevent conflicts. # Get plugin by ID Source: https://docs.tagada.io/api-reference/plugins/get-plugin-by-id /openapi.json get /api/public/v1/plugins/{id} Retrieve a specific plugin by its ID # Get public plugins Source: https://docs.tagada.io/api-reference/plugins/get-public-plugins /openapi.json get /api/public/v1/plugins/public/{id} Get all public plugins # List plugin deployments Source: https://docs.tagada.io/api-reference/plugins/list-plugin-deployments /openapi.json post /api/public/v1/plugins/deployments Get all deployments for plugins in a store # List plugins for a store Source: https://docs.tagada.io/api-reference/plugins/list-plugins-for-a-store /openapi.json post /api/public/v1/plugins/list Get all plugins associated with a specific store # Promote plugin deployment to alias Source: https://docs.tagada.io/api-reference/plugins/promote-plugin-deployment-to-alias /openapi.json post /api/public/v1/plugins/promote-to-alias Promote an existing plugin deployment to a new alias. This reassigns the alias without creating a new deployment. # Promote plugin to custom domain Source: https://docs.tagada.io/api-reference/plugins/promote-plugin-to-custom-domain /openapi.json post /api/public/v1/plugins/promote-to-custom-domain Promote a plugin to a custom domain. This will create a new route for the plugin. # Undeploy plugin Source: https://docs.tagada.io/api-reference/plugins/undeploy-plugin /openapi.json post /api/public/v1/plugins/undeploy Remove a deployed plugin and make it inactive # Accept the upsell of a signed email link and pay it Source: https://docs.tagada.io/api-reference/portal/accept-the-upsell-of-a-signed-email-link-and-pay-it /openapi.json post /api/v1/portal/offers/accept Accept the upsell of a signed email link and pay it # Add an address to the address book, or replace the one with that id Source: https://docs.tagada.io/api-reference/portal/add-an-address-to-the-address-book-or-replace-the-one-with-that-id /openapi.json post /api/v1/portal/addresses Add an address to the address book, or replace the one with that id # Apply the retention offer the customer took instead of cancelling Source: https://docs.tagada.io/api-reference/portal/apply-the-retention-offer-the-customer-took-instead-of-cancelling /openapi.json post /api/v1/portal/cancel-flow/accept Apply the retention offer the customer took instead of cancelling # Buy a credit pack with the default saved card Source: https://docs.tagada.io/api-reference/portal/buy-a-credit-pack-with-the-default-saved-card /openapi.json post /api/v1/portal/credits/packs/buy Buy a credit pack with the default saved card # Buy the monthly or yearly Membership option with the default card Source: https://docs.tagada.io/api-reference/portal/buy-the-monthly-or-yearly-membership-option-with-the-default-card /openapi.json post /api/v1/portal/membership/join Buy the monthly or yearly Membership option with the default card # Cancel a subscription or the membership at the end of the cancel flow, with the reason given Source: https://docs.tagada.io/api-reference/portal/cancel-a-subscription-or-the-membership-at-the-end-of-the-cancel-flow-with-the-reason-given /openapi.json post /api/v1/portal/cancel-flow Cancel a subscription or the membership at the end of the cancel flow, with the reason given # Charge a past-due subscription again now, with its card Source: https://docs.tagada.io/api-reference/portal/charge-a-past-due-subscription-again-now-with-its-card /openapi.json post /api/v1/portal/retry-payment Charge a past-due subscription again now, with its card # Email a code to a new address; the profile saves that email with it Source: https://docs.tagada.io/api-reference/portal/email-a-code-to-a-new-address;-the-profile-saves-that-email-with-it /openapi.json post /api/v1/portal/profile/email-code Email a code to a new address; the profile saves that email with it # Get the credit balance and ledger of the logged-in customer Source: https://docs.tagada.io/api-reference/portal/get-the-credit-balance-and-ledger-of-the-logged-in-customer /openapi.json get /api/v1/portal/credits Get the credit balance and ledger of the logged-in customer # Get the logged-in customer with orders, subscriptions, membership and credit ledger Source: https://docs.tagada.io/api-reference/portal/get-the-logged-in-customer-with-orders-subscriptions-membership-and-credit-ledger /openapi.json get /api/v1/portal/me Get the logged-in customer with orders, subscriptions, membership and credit ledger # Get the published customer portal of the store with its retention, Membership and products Source: https://docs.tagada.io/api-reference/portal/get-the-published-customer-portal-of-the-store-with-its-retention-membership-and-products /openapi.json get /api/v1/portal/config Get the published customer portal of the store with its retention, Membership and products # Get the upsell a signed email link offers Source: https://docs.tagada.io/api-reference/portal/get-the-upsell-a-signed-email-link-offers /openapi.json get /api/v1/portal/offers/{token} Get the upsell a signed email link offers # Make a card the default one, and the card of every live subscription Source: https://docs.tagada.io/api-reference/portal/make-a-card-the-default-one-and-the-card-of-every-live-subscription /openapi.json post /api/v1/portal/payment-methods/default Make a card the default one, and the card of every live subscription # Make an address the default shipping address Source: https://docs.tagada.io/api-reference/portal/make-an-address-the-default-shipping-address /openapi.json post /api/v1/portal/addresses/default Make an address the default shipping address # Move a subscription or the membership to another option now, charging the new price Source: https://docs.tagada.io/api-reference/portal/move-a-subscription-or-the-membership-to-another-option-now-charging-the-new-price /openapi.json post /api/v1/portal/switch Move a subscription or the membership to another option now, charging the new price # Order products again at their one-time price, with the default card and address Source: https://docs.tagada.io/api-reference/portal/order-products-again-at-their-one-time-price-with-the-default-card-and-address /openapi.json post /api/v1/portal/buy-again Order products again at their one-time price, with the default card and address # Remove a saved card that no live subscription is paid with Source: https://docs.tagada.io/api-reference/portal/remove-a-saved-card-that-no-live-subscription-is-paid-with /openapi.json post /api/v1/portal/payment-methods/remove Remove a saved card that no live subscription is paid with # Remove an address that is not the default one Source: https://docs.tagada.io/api-reference/portal/remove-an-address-that-is-not-the-default-one /openapi.json post /api/v1/portal/addresses/remove Remove an address that is not the default one # Save a card tokenized in the browser, optionally as the default card Source: https://docs.tagada.io/api-reference/portal/save-a-card-tokenized-in-the-browser-optionally-as-the-default-card /openapi.json post /api/v1/portal/payment-methods Save a card tokenized in the browser, optionally as the default card # Set the quantity of a one-time item on the next renewal of a subscription (0 takes it off) Source: https://docs.tagada.io/api-reference/portal/set-the-quantity-of-a-one-time-item-on-the-next-renewal-of-a-subscription-0-takes-it-off /openapi.json post /api/v1/portal/next-order Set the quantity of a one-time item on the next renewal of a subscription (0 takes it off) # Spend credits on a product Source: https://docs.tagada.io/api-reference/portal/spend-credits-on-a-product /openapi.json post /api/v1/portal/credits/redeem Spend credits on a product # Update the customer's name, email and phone Source: https://docs.tagada.io/api-reference/portal/update-the-customers-name-email-and-phone /openapi.json post /api/v1/portal/profile Update the customer's name, email and phone # Create processor Source: https://docs.tagada.io/api-reference/processors/create-processor /openapi.json post /api/public/v1/processors/create Create a new payment processor (PSP/gateway) connection. Requires org:admin role. A processor defines: - **type**: the gateway type (e.g. `stripe`, `nmi`, `checkout`, `adyen`, `airwallex`, `sandbox`, etc.) - **name**: a friendly label for this connection - **options**: gateway-specific credentials and configuration - **supportedCurrencies**: which currencies this processor can handle - **baseCurrency**: the processor's settlement currency # Delete processors Source: https://docs.tagada.io/api-reference/processors/delete-processors /openapi.json post /api/public/v1/processors/delete Soft-delete (archive) one or more processors by their IDs. Archived processors are excluded from payment flows. Requires org:admin role. # Disconnect Stripe Connect account Source: https://docs.tagada.io/api-reference/processors/disconnect-stripe-connect-account /openapi.json post /api/public/v1/processors/stripe-connect/disconnect Revoke the OAuth connection for a Stripe Connect account. This deauthorizes the connected Stripe account and disables the processor. Requires org:admin role. # Get processor by ID Source: https://docs.tagada.io/api-reference/processors/get-processor-by-id /openapi.json post /api/public/v1/processors/get Retrieve a single processor by its ID. Returns full processor details including options and supported currencies. Requires org:admin role. # Get Stripe Connect account details Source: https://docs.tagada.io/api-reference/processors/get-stripe-connect-account-details /openapi.json post /api/public/v1/processors/stripe-connect/account Retrieve details about a connected Stripe account (capabilities, charges enabled, payouts enabled, country, etc.). Requires org:admin role. # Initiate Stripe Connect OAuth Source: https://docs.tagada.io/api-reference/processors/initiate-stripe-connect-oauth /openapi.json post /api/public/v1/processors/stripe-connect/initiate Start the Stripe Connect OAuth flow for a processor. Returns a URL that the merchant must visit in their browser to authorize their Stripe account. **Flow:** 1. Call this endpoint with the `processorId` of a Stripe-type processor 2. Redirect the merchant to the returned `url` 3. After authorization, Stripe redirects back to TagadaPay which saves the connected account credentials 4. The processor is now ready to accept payments via Stripe Connect # List processors Source: https://docs.tagada.io/api-reference/processors/list-processors /openapi.json get /api/public/v1/processors List all active (non-archived) processors for the authenticated account. Requires org:admin role. Returns processor config including acquirer BINs and supported currencies. # Update processor Source: https://docs.tagada.io/api-reference/processors/update-processor /openapi.json post /api/public/v1/processors/update Update an existing processor configuration (name, credentials, currencies, enabled status). Requires org:admin role. # Create product Source: https://docs.tagada.io/api-reference/products/create-product /openapi.json post /api/public/v1/products/create Create a new product with variants and prices for a specific store # Delete products Source: https://docs.tagada.io/api-reference/products/delete-products /openapi.json post /api/public/v1/products/delete Delete one or more products by their IDs # Get product by ID Source: https://docs.tagada.io/api-reference/products/get-product-by-id /openapi.json get /api/public/v1/products/{productId} Retrieve detailed information about a specific product including variants and pricing # List products Source: https://docs.tagada.io/api-reference/products/list-products /openapi.json post /api/public/v1/products/list Get all products for a specific store with filtering, sorting, and pagination # Update product Source: https://docs.tagada.io/api-reference/products/update-product /openapi.json put /api/public/v1/products/{productId} Update an existing product's fields such as name, description, active status, tax settings, and shipping configuration # Create promotion code Source: https://docs.tagada.io/api-reference/promotion-codes/create-promotion-code /openapi.json post /api/public/v1/promotion-codes/create Create a new promotion code linked to an existing promotion # Delete promotion codes Source: https://docs.tagada.io/api-reference/promotion-codes/delete-promotion-codes /openapi.json post /api/public/v1/promotion-codes/delete Delete one or more promotion codes by their IDs # List promotion codes Source: https://docs.tagada.io/api-reference/promotion-codes/list-promotion-codes /openapi.json post /api/public/v1/promotion-codes/list Get promotion codes with filtering and pagination # Update promotion code Source: https://docs.tagada.io/api-reference/promotion-codes/update-promotion-code /openapi.json post /api/public/v1/promotion-codes/update Update an existing promotion code by ID # Create promotion Source: https://docs.tagada.io/api-reference/promotions/create-promotion /openapi.json post /api/public/v1/promotions/create Create a new promotion with rules and actions for a specific store # Delete promotions Source: https://docs.tagada.io/api-reference/promotions/delete-promotions /openapi.json post /api/public/v1/promotions/delete Delete one or more promotions by their IDs # Get promotion by ID Source: https://docs.tagada.io/api-reference/promotions/get-promotion-by-id /openapi.json post /api/public/v1/promotions/getById Retrieve detailed information about a specific promotion including rules and actions # List promotions Source: https://docs.tagada.io/api-reference/promotions/list-promotions /openapi.json post /api/public/v1/promotions/list Get all promotions for a specific store with filtering, sorting, and pagination # Update promotion Source: https://docs.tagada.io/api-reference/promotions/update-promotion /openapi.json post /api/public/v1/promotions/update Update an existing promotion by ID. To manage redeemable codes for the promotion, use the `/promotion-codes/*` endpoints — this endpoint does not accept a `promotionCodes` array. # Create radar session Source: https://docs.tagada.io/api-reference/radar-sessions/create-radar-session /openapi.json post /api/public/v1/radar-sessions Save a device fingerprint / fraud-detection session ID generated by a provider's client-side SDK (e.g. Airwallex Radar). Intended for API consumers using `@tagadapay/core-js`. Provide at least one of `paymentId`, `orderId`, or `checkoutSessionId` so the session can be matched when the payment is resumed. # Create a shipping rate Source: https://docs.tagada.io/api-reference/shipping/create-a-shipping-rate /openapi.json post /api/public/v1/shipping-rates Create a shipping rate for a store. The new rate is matched against incoming checkout sessions on country, cart subtotal, and total weight, and surfaced via `GET /checkout-sessions/:id/shipping-rates`. Conditions interact additively — a customer must satisfy *all* set thresholds. Leave a field undefined to skip the corresponding check (e.g. omit `countryCodes` to allow any country). `countryCodes` takes ISO 3166-1 codes in any form — alpha-2 (`"US"`), alpha-3 (`"USA"`) or numeric (`"840"`). They are stored and matched as numeric codes; an unknown code is rejected with a 400. Requires the `org:admin` role (granted automatically to UUID-format API keys). # Create store Source: https://docs.tagada.io/api-reference/stores/create-store /openapi.json post /api/public/v1/stores/create Create a new store for the authenticated account # Get store by ID Source: https://docs.tagada.io/api-reference/stores/get-store-by-id /openapi.json get /api/public/v1/stores/{storeId} Retrieve detailed information about a specific store # List stores Source: https://docs.tagada.io/api-reference/stores/list-stores /openapi.json post /api/public/v1/stores/list Get all stores for the authenticated account with filtering, sorting, and pagination # Apply a subscription discount in place Source: https://docs.tagada.io/api-reference/subscriptions/apply-a-subscription-discount-in-place /openapi.json post /api/public/v1/subscriptions/apply-discount Give a subscription 1–99 percent off its next 1–24 rebills, or every rebill with rebills: null. A trial-end charge counts as rebill 1. No charge occurs now. With retentionOfferId (1–100 characters), source is retention; otherwise source is manual. replaceRunning defaults to false: a running discount answers 409. With true, the old row ends as replaced and the new one starts. Supports Idempotency-Key. An unknown subscription or one of another account answers 404; a store without Subscriptions V3 answers 412 because its rebill does not read discounts; a canceled subscription answers 409. An open renewal charge answers 409 (RENEWAL_IN_PROGRESS); retry after it settles. # Cancel subscriptions Source: https://docs.tagada.io/api-reference/subscriptions/cancel-subscriptions /openapi.json post /api/public/v1/subscriptions/cancel Cancel one or more subscriptions with option to cancel immediately or at period end # Change subscription price in place Source: https://docs.tagada.io/api-reference/subscriptions/change-subscription-price-in-place /openapi.json post /api/public/v1/subscriptions/change-price Move a subscription to a recurring price of the same store, including another product. The next billing date is kept; that rebill uses the new amount and subsequent dates follow the new interval. When cadence changes, the cycle anchor moves to that kept date so the following charge is one full new interval later. No proration or charge occurs now. The current price is an idempotent no-op. Supports Idempotency-Key. An unknown subscription or one of another account, or a price outside its store, answers 404. A non-recurring price, missing interval or non-positive amount in the subscription currency answers 422. Canceled or grouped subscriptions answer 409: the group owns its members' price and dates. An open renewal charge answers 409 (RENEWAL_IN_PROGRESS); retry after it settles. # Change subscription processor Source: https://docs.tagada.io/api-reference/subscriptions/change-subscription-processor /openapi.json post /api/public/v1/subscriptions/change-processor Change the preferred payment processor for a subscription or remove processor preference # Create subscription Source: https://docs.tagada.io/api-reference/subscriptions/create-subscription /openapi.json post /api/public/v1/subscriptions/create Create a new subscription for a customer with specified product and pricing. `billingCycleAnchor` is a Unix timestamp in milliseconds, as a number or a string of digits, and sets the first billing date; a value below 100000000000 is read as Unix seconds, and a date string is rejected. When omitted the subscription bills immediately. `initiatePayment` is deprecated and rejected — it was never implemented. # Extend a subscription trial in place Source: https://docs.tagada.io/api-reference/subscriptions/extend-a-subscription-trial-in-place /openapi.json post /api/public/v1/subscriptions/extend-trial Extend a trialing subscription without charging. trialEnd is a Unix timestamp in milliseconds (number or digit string; values below 100000000000 are read as seconds, date strings refused). It must be later than the current trial end, in the future and at most 365 days after the current end. The same end is an idempotent no-op. trialEnd, billingCycleAnchor and nextBillingDate are written to that exact instant; status, trialStart and trialSettings are kept. Supports Idempotency-Key. An unknown subscription or one of another account answers 404. A non-trialing subscription (including a paused trial), or a grouped member whose dates belong to the group, answers 409. An earlier or too distant end answers 422. An open renewal charge answers 409 (RENEWAL_IN_PROGRESS); retry after it settles. # Get subscription by ID Source: https://docs.tagada.io/api-reference/subscriptions/get-subscription-by-id /openapi.json get /api/public/v1/subscriptions/{subscriptionId} Retrieve detailed information about a specific subscription including customer, product, and payment details # List subscriptions Source: https://docs.tagada.io/api-reference/subscriptions/list-subscriptions /openapi.json post /api/public/v1/subscriptions/list Get all subscriptions for the authenticated account with filtering, sorting, and pagination # Rebill subscription Source: https://docs.tagada.io/api-reference/subscriptions/rebill-subscription /openapi.json post /api/public/v1/subscriptions/rebill Attempt to rebill a subscription. When a next billing date is set, it must be due or within the next 12 hours, including exactly 12 hours from now. If the next billing date is more than 12 hours away, the API returns HTTP 200 with `success: false`, `outcome.status: skipped`, and `outcome.reason: not_due_yet`; no charge is made and the next billing date is unchanged. A subscription billed as part of a subscription group is rebilled as one charge for the whole group: the amount covers every billable member and the outcome reports that group attempt. Retry metadata count and attempts are handled internally. The response reports what the attempt actually did: `outcome.status` is one of `captured`, `pending`, `declined`, `skipped` or `cancelled`, and `success` is true only when the customer was charged. Returns 404 when the subscription does not exist and 409 when its status does not allow a rebill. # Resume subscriptions Source: https://docs.tagada.io/api-reference/subscriptions/resume-subscriptions /openapi.json post /api/public/v1/subscriptions/resume Resume paused or past_due subscriptions, or undo cancellation scheduled at period end for active subscriptions. Subscriptions with a pending cancelAt date cannot be resumed. Canceled subscriptions cannot be resumed (HTTP 409). # Update billing cycle Source: https://docs.tagada.io/api-reference/subscriptions/update-billing-cycle /openapi.json post /api/public/v1/subscriptions/update-billing-cycle Move the next billing date of one or more subscriptions, for example to skip a month. `billingCycleAnchor` is the new date as a Unix timestamp in milliseconds, as a number or a string of digits; a value below 100000000000 is read as Unix seconds, and a date string is rejected. By default the subscription keeps its usual time of day and only the date moves: send midnight UTC of the target day. With `timeOfDay: "exact"` it bills at that exact instant, which must be in the future. A date before today is refused. The response has one result per id: `success`, `failed` with an `error`, or `skipped` with `skipReason: not_found_or_trialing_or_canceled` for an id that is not on your account, or a subscription that is trialing or canceled. # Bulk create tax exemptions Source: https://docs.tagada.io/api-reference/tax-exemptions/bulk-create-tax-exemptions /openapi.json post /api/public/v1/tax-exemptions Create one or more tax exemptions for a store. Customers whose email matches an exemption are excluded from tax calculations at checkout. Requires the `org:admin` role. # Delete tax exemptions Source: https://docs.tagada.io/api-reference/tax-exemptions/delete-tax-exemptions /openapi.json delete /api/public/v1/tax-exemptions Delete one or more tax exemptions by ID. Only exemptions belonging to your account will be removed. Requires the `org:admin` role. # List tax exemptions Source: https://docs.tagada.io/api-reference/tax-exemptions/list-tax-exemptions /openapi.json get /api/public/v1/tax-exemptions List tax exemptions for a store with pagination. Requires the `org:admin` role. # Create webhook endpoint Source: https://docs.tagada.io/api-reference/webhooks/create-webhook-endpoint /openapi.json post /api/public/v1/webhooks Create a new webhook endpoint to receive event notifications # Delete webhook endpoint Source: https://docs.tagada.io/api-reference/webhooks/delete-webhook-endpoint /openapi.json delete /api/public/v1/webhooks/{id} Delete an existing webhook endpoint # List webhook deliveries Source: https://docs.tagada.io/api-reference/webhooks/list-webhook-deliveries /openapi.json get /api/public/v1/webhooks/{id}/deliveries List delivery attempts for a webhook endpoint, most recent first. Paginated and filterable by event type, delivery status, and creation date range. Delivery history is retained for 6 months. # List webhook endpoints Source: https://docs.tagada.io/api-reference/webhooks/list-webhook-endpoints /openapi.json get /api/public/v1/webhooks List all webhook endpoints for a store # API hosts and base URLs Source: https://docs.tagada.io/developer-tools/api-hosts One host per environment. The Commerce API and the Payments API share it. TagadaPay serves its public APIs from one host per environment. | Environment | Host | Commerce API (V2) | Payments API (V3, Preview) | | - | - | - | - | | Production | `https://api.tagada.io` | `https://api.tagada.io/api/public/v1` | `https://api.tagada.io/v1` | | Staging | `https://api.tagada.dev` | `https://api.tagada.dev/api/public/v1` | Not open yet. Use production with a `tsk_test_` key. | * **Production** is where your live store runs. On the Payments API, the key sets test or live mode (`tsk_test_` or `tsk_live_`), not the host. * **Staging** runs the next release before it reaches production. Staging accounts and keys are separate from production ones. ## Which path for which call | You want to | Use | | - | - | | Manage stores, products, orders, customers, subscriptions, funnels | Commerce API, `/api/public/v1` | | Pay with V2 (`checkout/pay-v2`, `payments/process`, `threeds/*`) | Commerce API, `/api/public/v1` | | Create and confirm Payments API payments | Payments API, `/v1` | The SDKs set the right base URL for you: | SDK | Default base URL | | - | - | | `@tagadapay/node-sdk` | `https://api.tagada.io/api/public/v1` | | `@tagadapay/headless-sdk` | `https://api.tagada.io` (`environment: 'production'`), `https://api.tagada.dev` (`environment: 'development'`) | | `@tagadapay/core-js/payments-v3` | `https://api.tagada.io` (`apiBase` option) | See [SDK versions](/developer-tools/sdk-versions). # CLI Configuration Source: https://docs.tagada.io/developer-tools/cli/configuration Plugin manifest, config variants, and environment setup # CLI Configuration ## Plugin Manifest The `plugin.manifest.json` file defines your plugin. The CLI validates it before every deployment. ### Complete Example ```json theme={null} { "pluginId": "my-checkout-plugin", "name": "My Checkout Plugin", "version": "2.1.0", "description": "A premium checkout experience", "author": "Your Name", "category": "checkout", "mode": "direct-mode", "tags": ["checkout", "premium"], "pages": [ { "path": "/", "features": ["landing"], "remappable": false, "description": "Landing page" }, { "path": "/checkout", "features": [ { "type": "checkout", "requirements": ["payment", "shipping"] } ], "remappable": true, "description": "Checkout flow" }, { "path": "/thankyou/:orderId", "features": [ { "type": "thankyou", "requirements": ["order"] } ], "remappable": true, "description": "Order confirmation" } ], "router": { "basePath": "/", "matcher": ".*", "excluder": null }, "requirements": { "sdk": "@tagadapay/plugin-sdk", "sdkVersion": "v2" }, "configuration": { "schema": "config/schema.json", "uiSchema": "config/ui-schema.json" }, "homepage": "https://yourwebsite.com", "repository": "https://github.com/you/my-plugin", "license": "MIT" } ``` ### Field Reference > [accordion] pluginId (required) > > Unique identifier for your plugin across TagadaPay. Cannot be changed once deployed. > > ```json theme={null} > "pluginId": "my-checkout-plugin" > ``` > [accordion] name, version, description, author (required) > > Basic metadata. Version must follow semver (`MAJOR.MINOR.PATCH`). > > ```json theme={null} > "name": "My Plugin", > "version": "2.1.0", > "description": "A custom checkout", > "author": "Your Name" > ``` > [accordion] category (required) > > Plugin category for organization. Examples: `checkout`, `landing`, `upsell`, `post-purchase`. > > ```json theme={null} > "category": "checkout" > ``` > [accordion] pages (required) > > At least one page. Each page has a `path`, optional `features`, and `remappable` flag. > > ```json theme={null} > "pages": [ > { > "path": "/checkout", > "features": [ > { > "type": "checkout", > "requirements": ["payment", "shipping"] > } > ], > "remappable": true > } > ] > ``` > > **Feature types**: `landing`, `checkout`, `thankyou`, `product-page`, `catalog`, `upsell`, `post-purchase`, `static` > > **Requirements**: `payment`, `shipping`, `customer`, `order`, `cart`, `inventory` > [accordion] router (required) > > Controls how URLs match your plugin. > > * `basePath`: Root path for the plugin (usually `/`) > * `matcher`: Regex pattern for matching URLs (usually `.*`) > * `excluder`: Pattern to exclude from matching (or `null`) > > ```json theme={null} > "router": { > "basePath": "/", > "matcher": ".*", > "excluder": null > } > ``` > [accordion] requirements (required) > > SDK dependency info. > > ```json theme={null} > "requirements": { > "sdk": "@tagadapay/plugin-sdk", > "sdkVersion": "v2" > } > ``` > > `sdkVersion` must be `"v1"` or `"v2"`. > [accordion] mode (optional) > > Plugin loading mode: > > * `"direct-mode"` (default) — Plugin is served directly > * `"proxy-mode"` — Plugin is proxied > > ```json theme={null} > "mode": "direct-mode" > ``` > [accordion] configuration (optional) > > Allows the CRM to configure instances with a form UI. References JSON Schema files in your `config/` directory. > > ```json theme={null} > "configuration": { > "schema": "config/schema.json", > "uiSchema": "config/ui-schema.json" > } > ``` > > Without this, your plugin won't be configurable from the CRM dashboard. ## Config Directory The CLI looks for a `config/` directory in your plugin root. Files found there are auto-synced after deployment. ``` my-plugin/ ├── plugin.manifest.json ├── dist/ ├── config/ │ ├── schema.json # JSON Schema for config form │ ├── ui-schema.json # UI hints for the config form │ ├── default.preset.json # Default config values │ ├── blue-theme.preset.json # Named preset │ └── green-theme.config.json # Another named preset ``` ### Naming Conventions | Pattern | Purpose | | - | - | | `*.preset.json` | Config preset (synced to deployment) | | `*.config.json` | Config preset (synced to deployment) | | `schema.json` or `config.schema.json` | JSON Schema for the config form | | `ui-schema.json` or `config.ui-schema.json` | UI Schema for form layout | ### Example: Config Schema ```json title="config/schema.json" theme={null} { "type": "object", "properties": { "theme": { "type": "object", "properties": { "primaryColor": { "type": "string", "format": "color" }, "fontFamily": { "type": "string" } } }, "features": { "type": "object", "properties": { "expressCheckout": { "type": "boolean" }, "upsells": { "type": "boolean" } } } } } ``` ### Example: Config Preset ```json title="config/blue-theme.preset.json" theme={null} { "theme": { "primaryColor": "#007bff", "fontFamily": "Inter, sans-serif" }, "features": { "expressCheckout": true, "upsells": true } } ``` When you deploy, the CLI auto-detects these files and syncs them via the `/plugins/v2/deployment/sync-config` API. This makes the presets and schema available in the CRM when creating instances. ## Local Development Create `.local.json` in your plugin root for local development: ```json title=".local.json" theme={null} { "storeId": "store_dev_123", "accountId": "acc_dev_456", "config": "blue-theme", "apiUrl": "https://app.tagadapay.dev" } ``` | Field | Description | | - | - | | `storeId` | Your development store ID | | `accountId` | Your account ID | | `config` | Preset name (matches `config/*.preset.json` filename without extension) | | `apiUrl` | API endpoint for development | ## Path Remapping Pages with `"remappable": true` can have their URLs remapped by the CRM. This allows merchants to customize URL paths without changing plugin code. ```json theme={null} { "pages": [ { "path": "/products/:id", "features": ["product-page"], "remappable": true } ] } ``` When a merchant configures a remap (e.g., external `/p/:slug` → internal `/products/:id`), the routing engine handles the translation automatically. See the [Path Remapping guide](/developer-tools/sdk/path-remapping) for details. ## Environments The CLI supports three environments plus custom URLs: | Name | Flag | API URL | | - | - | - | | Production | `--prod` (default) | `https://api.tagada.io` | | Development | `--dev` | `https://app.tagadapay.dev` | | Local | `--local` | `http://app.localhost:3000` | | Custom | `--base-url ` | Any URL | ```bash theme={null} tgd login --dev tgd deploy --local --store store_123 tgd login --base-url https://custom.tagadapay.com ``` ## Troubleshooting > [accordion] Manifest validation failed > > The CLI validates your manifest before deploying. Common missing fields: > > * `category` — required (e.g. `"checkout"`) > * `router` — required (`basePath`, `matcher`, `excluder`) > * `requirements` — required (`sdk`, `sdkVersion`) > > Check validation output for specific errors. > [accordion] Invalid JSON > > ```bash theme={null} > cat plugin.manifest.json | python3 -m json.tool > ``` > [accordion] Path remapping not working > > 1. Verify `"remappable": true` on the page in your manifest > 2. Check the CRM routing configuration > 3. See the [Path Remapping guide](/developer-tools/sdk/path-remapping) for debugging tips > [accordion] Config not appearing in CRM > > Make sure you have a `configuration` field in your manifest pointing to valid schema files, and that your `config/` directory contains the referenced files. They are synced automatically after `tgd deploy`. ## Next Steps > [card] [Quick Start](/developer-tools/cli/quick-start) > > Deploy your first plugin > [card] [CLI Reference](/developer-tools/cli/introduction) > > All commands and flags > [card] [Plugin SDK](/developer-tools/sdk/introduction) > > Build interactive plugins with React hooks > [card] [Hosting & A/B Testing](/developer-tools/hosting/deploy-and-ab-test) > > Host pages and set up A/B tests via API # Plugin CLI Source: https://docs.tagada.io/developer-tools/cli/introduction Deploy and manage plugins with the TagadaPay CLI # TagadaPay Plugin CLI > [card] Latest Version > > **v3.0.3** — `@tagadapay/plugin-cli` A command-line tool for deploying React apps, static websites, and plugins on TagadaPay with routing, domain management, and instance management. ```bash theme={null} npm install -g @tagadapay/plugin-cli ``` The CLI installs two binary aliases: **`tgd`** (short) and `tgdcli` (long). All examples below use `tgd`. ## Quick Start **1. Login** ```bash theme={null} tgd login ``` Opens your browser for secure authentication. Defaults to production. **2. Deploy your plugin** ```bash theme={null} cd my-plugin tgd deploy ``` The CLI reads `plugin.manifest.json`, creates a ZIP of your `dist/` folder, uploads it, and deploys. ## Interactive Mode The easiest way to manage everything — deploy, mount, install, manage domains: ```bash theme={null} tgd interactive ``` ``` 🎛️ TagadaPay Plugin Manager ──────────────────────────── ? What would you like to do? (Use arrow keys) ❯ 🚀 Deploy Plugin 📋 List Deployments 🔌 Install Plugin from Store 🔗 Mount Plugin to Alias 📊 List Instances 🌐 Manage Domains ❌ Exit ``` Interactive mode provides store selection, config variant picking, real-time upload progress, and guided workflows. ## Commands ### Authentication ```bash Login theme={null} tgd login # Production (default) tgd login --dev # Development tgd login --local # Local dev server ``` ```bash Logout theme={null} tgd logout tgd logout --dev ``` ```bash Check Status theme={null} tgd whoami ``` ### Deploy ```bash theme={null} tgd deploy # Auto-detect manifest, prompt for store tgd deploy --store store_abc123 # Specify store tgd deploy --store store_abc123 --config config/production.json tgd deploy --plugin-id "custom-id" # Override plugin ID tgd deploy --auto-suffix # Append random suffix to plugin ID tgd deploy --overwrite # Replace existing deployment (same plugin+version) ``` | Flag | Alias | Description | | - | - | - | | `--store` | `--store-id`, `-s` | Target store ID (prompts if omitted) | | `--config` | `-c` | Path to manifest (default: `plugin.manifest.json`) | | `--env` | `-e` | Environment: `dev`, `local`, `prod` | | `--dev` | `-d` | Shortcut for `--env dev` | | `--local` | `-l` | Shortcut for `--env local` | | `--prod` | `-p` | Shortcut for `--env prod` (default) | | `--plugin-id` | | Override plugin ID from manifest | | `--auto-suffix` | | Append random 6-char suffix to plugin ID | | `--overwrite` | `--force` | Delete existing deployment and replace | | `--verbose` | | Show detailed API logs | > [!WARNING] > > `--overwrite` permanently deletes the existing deployment (record, instances, routes) and replaces it. This is not reversible. After deploying, the CLI auto-syncs config templates if a `config/` folder exists (presets, schema, uiSchema). ### Archive Create a local ZIP without deploying: ```bash theme={null} tgd archive # Creates archive from current dir tgd archive --output my-plugin.zip # Custom output filename ``` ### List ```bash theme={null} tgd list --store store_abc123 # List active plugins tgd list --store store_abc123 --inactive # Include inactive ``` ### Instance Management ```bash Install Plugin theme={null} tgd install --store store_abc123 # Interactive — select plugin, configure, create instance ``` ```bash List Instances theme={null} tgd list-instances --store store_abc123 # Shows instances grouped by plugin → version → config ``` ```bash Mount to Alias theme={null} tgd mount-alias --store store_abc123 # Interactive — select instance, pick alias ``` ```bash List Mount Points theme={null} tgd list-mounts --store store_abc123 # Shows all aliases/domains and their mounted routes ``` ### Domain Management Domain commands authenticate via your login session. They do **not** require `--store-id`. ```bash List Domains theme={null} tgd list-domains tgd list-domains --dev ``` ```bash Add Domain theme={null} tgd add-domain checkout.example.com # Adds and auto-verifies ``` ```bash Verify Domain theme={null} tgd verify-domain cdm_abc123 # Takes a domain ID (not domain name) ``` ```bash Remove Domain theme={null} tgd remove-domain cdm_abc123 ``` ```bash Domain Info theme={null} tgd domain-info checkout.example.com ``` ```bash Auto-Verify All theme={null} tgd auto-verify-domains ``` ## Plugin Manifest Every plugin requires a `plugin.manifest.json`. The CLI validates it before deploying. ### Required Fields ```json theme={null} { "pluginId": "my-checkout-plugin", "name": "My Checkout Plugin", "version": "1.0.0", "description": "A custom checkout experience", "author": "Your Name", "category": "checkout", "mode": "direct-mode", "pages": [ { "path": "/", "features": ["landing"], "remappable": false }, { "path": "/checkout", "features": [ { "type": "checkout", "requirements": ["payment"] } ], "remappable": true }, { "path": "/thankyou/:orderId", "features": [ { "type": "thankyou" } ], "remappable": true } ], "router": { "basePath": "/", "matcher": ".*", "excluder": null }, "requirements": { "sdk": "@tagadapay/plugin-sdk", "sdkVersion": "v2" } } ``` ### All Manifest Fields | Field | Required | Description | | - | - | - | | `pluginId` | Yes | Unique plugin identifier | | `name` | Yes | Human-readable name | | `version` | Yes | Semver (`1.0.0`) | | `description` | Yes | Short description | | `author` | Yes | Author name | | `category` | Yes | Category (e.g. `checkout`, `landing`, `upsell`) | | `pages` | Yes | Array of page definitions (at least one) | | `router` | Yes | Routing config: `basePath`, `matcher`, `excluder` | | `requirements` | Yes | SDK info: `sdk`, `sdkVersion` (`v1` or `v2`) | | `mode` | No | `direct-mode` (default) or `proxy-mode` | | `configuration` | No | Config schema for CRM: `schema`, `uiSchema`, `presets` | | `homepage` | No | URL to plugin homepage | | `repository` | No | URL to source repository | | `license` | No | License identifier | | `tags` | No | Array of tag strings | | `landingImgUrl` | No | Preview image URL | | `public` | No | Whether plugin is listed publicly | ### Page Features Simple string features: ```json theme={null} { "path": "/", "features": ["landing"] } ``` Features with requirements (for pages that need data): ```json theme={null} { "path": "/checkout", "features": [ { "type": "checkout", "requirements": ["payment", "shipping", "customer"] } ] } ``` **Feature types**: `landing`, `checkout`, `thankyou`, `product-page`, `catalog`, `upsell`, `post-purchase`, `static` **Requirements**: `payment`, `shipping`, `customer`, `order`, `cart`, `inventory` ## Environments The CLI supports three built-in environments: | Flag | Environment | API URL | | - | - | - | | `--prod` (default) | Production | `https://api.tagada.io` | | `--dev` | Development | `https://app.tagadapay.dev` | | `--local` | Local | `http://app.localhost:3000` | You can also pass a custom URL: ```bash theme={null} tgd login --base-url https://custom.tagadapay.com ``` ## Workflow Examples ### Deploy & Mount **1. Build your plugin** ```bash theme={null} npm run build ``` **2. Deploy** ```bash theme={null} tgd deploy --store store_abc123 ``` Note the deployment ID from the output. **3. Install (create instance)** ```bash theme={null} tgd install --store store_abc123 ``` Select the deployment, optionally configure it. **4. Mount to alias** ```bash theme={null} tgd mount-alias --store store_abc123 ``` Select the instance and choose an alias path. ### Update a Plugin ```bash theme={null} # Bump version in plugin.manifest.json npm run build tgd deploy --store store_abc123 # Or overwrite same version tgd deploy --store store_abc123 --overwrite ``` ### A/B Testing Deploy two variants and mount them via the [A/B testing API](/developer-tools/hosting/deploy-and-ab-test): ```bash theme={null} tgd deploy --config config/variant-a.json --store store_abc123 # Note: deployment ID A tgd deploy --config config/variant-b.json --store store_abc123 # Note: deployment ID B ``` Then configure split testing via the API or CRM. ### Custom Domain ```bash theme={null} tgd add-domain checkout.mystore.com # CLI will show CNAME record to add tgd verify-domain cdm_abc123 # After DNS propagation ``` ## Troubleshooting > [accordion] Authentication failed > > ```bash theme={null} > tgd logout > tgd login > tgd whoami > ``` > [accordion] Plugin manifest not found > > Ensure `plugin.manifest.json` exists in your current directory and is valid JSON: > > ```bash theme={null} > cat plugin.manifest.json | python3 -m json.tool > ``` > [accordion] Build directory missing > > Build your plugin before deploying: > > ```bash theme={null} > npm run build > ls dist/ > ``` > [accordion] Version conflict on deploy > > A deployment already exists for this plugin ID + version. Either: > > * Bump the `version` in your manifest > * Use `--overwrite` to replace the existing deployment > [accordion] Domain verification failed > > DNS can take up to 48 hours to propagate. Check status: > > ```bash theme={null} > tgd domain-info checkout.mystore.com > tgd verify-domain cdm_abc123 > ``` ### Verbose Mode For detailed API request/response logs: ```bash theme={null} tgd --verbose deploy ``` ## Support * **Documentation**: [docs.tagadapay.com](https://docs.tagadapay.com) * **Support**: [developer-support@tagadapay.com](mailto:developer-support@tagadapay.com) * **GitHub**: [Report issues](https://github.com/tagadapay/tagadapay/issues) # CLI Quick Start Source: https://docs.tagada.io/developer-tools/cli/quick-start Get up and running with the TagadaPay CLI in minutes # CLI Quick Start Deploy your plugin to TagadaPay in 5 minutes. ## Prerequisites * **Node.js 18+** ([Download](https://nodejs.org/)) * A TagadaPay account with access to a store * Your plugin built (`dist/` directory with `index.html`) ## Install & Login **1. Install the CLI** ```bash theme={null} npm install -g @tagadapay/plugin-cli ``` Verify: ```bash theme={null} tgd --version ``` **2. Login** ```bash theme={null} tgd login ``` This opens your browser for authentication. Once complete: ``` ✅ Successfully logged in ``` ## Deploy Your Plugin ### Option 1: Interactive (Recommended) ```bash theme={null} tgd interactive ``` Select **"Deploy Plugin"**, then follow the wizard: 1. Pick a store from the list 2. Select a config variant (or skip) 3. Confirm and deploy 4. Get your deployment ID ### Option 2: Direct Command ```bash theme={null} cd my-plugin tgd deploy --store store_abc123 ``` The CLI will: 1. Validate `plugin.manifest.json` 2. ZIP your `dist/` folder + manifest 3. Upload to blob storage 4. Deploy via API 5. Return the deployment ID ## Plugin Structure Your plugin directory should look like this: ``` my-plugin/ ├── plugin.manifest.json # Required ├── dist/ # Required (built files) │ ├── index.html │ └── assets/ │ ├── index.js │ └── style.css └── config/ # Optional (presets, schema) ├── default.preset.json └── schema.json ``` ### Create plugin.manifest.json > [!WARNING] > > All fields below are **required** by the CLI validator. Missing any will fail deployment. ```json theme={null} { "pluginId": "my-first-plugin", "name": "My First Plugin", "version": "1.0.0", "description": "My first TagadaPay plugin", "author": "Your Name", "category": "checkout", "pages": [ { "path": "/", "features": ["landing"], "remappable": false }, { "path": "/checkout", "features": [ { "type": "checkout", "requirements": ["payment"] } ], "remappable": true }, { "path": "/thankyou/:orderId", "features": [{ "type": "thankyou" }], "remappable": true } ], "router": { "basePath": "/", "matcher": ".*", "excluder": null }, "requirements": { "sdk": "@tagadapay/plugin-sdk", "sdkVersion": "v2" } } ``` ### Build ```bash theme={null} npm run build ls dist/ # Should contain index.html ``` ## Step-by-Step Walkthrough ### 1. Verify Everything ```bash theme={null} ls plugin.manifest.json # Must exist ls dist/index.html # Must exist cat plugin.manifest.json | python3 -m json.tool # Must be valid JSON ``` ### 2. Deploy > [tab] Interactive > > ```bash theme={null} > tgd interactive > ``` > > 1. Select **Deploy Plugin** > 2. Choose your store > 3. Optionally pick a config from `config/` directory > 4. Confirm and deploy > [tab] Command Line > > ```bash theme={null} > tgd deploy --store store_abc123 > ``` > > Output: > > ``` > 📄 Reading plugin manifest from: plugin.manifest.json > ✅ Manifest validation passed > 🚀 Deploying plugin: My First Plugin (my-first-plugin) > 📊 Version: 1.0.0 > 📦 Creating deployment archive... > ✓ Archive created: 0.45 MB > ☁️ Uploading to blob storage... > ✓ Uploaded > 🚀 Deploying via API... > > ✅ Deployment successful! > ──────────────────────────────────────────────────────────── > Plugin ID: my-first-plugin > Version: 1.0.0 > Deployment ID: mlw1234abcdef > ──────────────────────────────────────────────────────────── > ``` ### 3. Install & Mount After deploying, create an instance and mount it: ```bash theme={null} tgd install --store store_abc123 # Select your deployment, configure if needed tgd mount-alias --store store_abc123 # Select the instance, choose an alias path ``` Your plugin is now live. ### 4. Verify ```bash theme={null} tgd list --store store_abc123 tgd list-instances --store store_abc123 tgd list-mounts --store store_abc123 ``` ## Common Workflows ### Update a Plugin ```bash theme={null} # 1. Bump version in plugin.manifest.json # 2. Rebuild npm run build # 3. Deploy new version tgd deploy --store store_abc123 # Or overwrite same version tgd deploy --store store_abc123 --overwrite ``` ### Deploy to Multiple Environments ```bash theme={null} tgd deploy --store store_dev --dev tgd deploy --store store_staging --dev tgd deploy --store store_prod --prod ``` ### Add a Custom Domain ```bash theme={null} tgd add-domain checkout.mystore.com # Add the CNAME record shown in the output, then: tgd verify-domain cdm_abc123 ``` ## Quick Reference ```bash theme={null} # Auth tgd login # Login (production) tgd login --dev # Login (development) tgd logout # Logout tgd whoami # Check auth status # Deploy tgd deploy # Interactive store selection tgd deploy -s store_123 # Direct deploy tgd deploy -s store_123 --overwrite # Replace existing # Manage tgd list -s store_123 # List deployments tgd install -s store_123 # Create instance tgd mount-alias -s store_123 # Mount instance tgd list-instances -s store_123 # List instances tgd list-mounts -s store_123 # List mount points # Domains tgd list-domains # List all domains tgd add-domain my.domain.com # Add domain # Interactive (all-in-one) tgd interactive # Menu-driven interface ``` ## What's Next? > [card] [Full CLI Reference](/developer-tools/cli/introduction) > > All commands and flags > [card] [CLI Configuration](/developer-tools/cli/configuration) > > Manifest, config variants, environments > [card] [Plugin SDK](/developer-tools/sdk/introduction) > > Build interactive plugins with React > [card] [Hosting & A/B Testing](/developer-tools/hosting/deploy-and-ab-test) > > Host pages and set up A/B tests # Prompt Library Source: https://docs.tagada.io/developer-tools/crm-mcp/examples Three ready-to-use prompts for the Tagada Config MCP. Open one, copy it, replace the placeholders. Each prompt carries the order the checks should run in — which is rarely the order you would guess. > [accordion] Diagnose a broken store > > Something is wrong and you want the cause, not a checklist. > > ```text theme={null} > You have access to the Tagada Config MCP. Diagnose this store. > > Store: > Symptom: > > Work in this order: > > 1. Call list_stores and match the store by name. Never guess a store id. > > 2. Pick the first check from the symptom: > - No orders at all, or a sudden stop -> diagnose_store area checkout. A store taking > zero orders is almost always unreachable (no active funnel, an > unpublished one, or an unverified domain), not a payment problem. > - Cards declined, payments failing -> diagnose_store area payment. > - Complaints from one country -> diagnose_store area shipping. > - One product cannot be bought -> diagnose_store area catalog. > - Unclear -> diagnose_store area checkout, then diagnose_store area payment. > > 3. Run the remaining checks anyway. A second blocker is common and the first > one hides it. > > 4. Call diagnose_store area setup last, and point out every step the checklist calls > "completed" that a check contradicts. > > Report all ERROR findings before any WARNING. For each one give the message, > the evidence, and where in the CRM I fix it. If a check fails because of my > permissions, say so instead of guessing. > ``` > [accordion] Pre-launch go / no-go > > A store is about to open and you want a verdict, not a status. > > ```text theme={null} > You have access to the Tagada Config MCP. Run a pre-launch check on this > store and give me a go / no-go. > > Store: > Launching in: > Selling in: > > 1. Call list_stores and match the store by name. Never guess a store id. > 2. Call diagnose_store with no area: the setup checklist and the catalog, > shipping, payment and checkout checks come back in one reply. > 3. Note any step the checklist calls "completed" that a check contradicts. > > Then answer in this order: > > - VERDICT: GO or NO-GO. > - BLOCKERS: every ERROR, one line each, with the CRM screen to fix it. > - RISKS: every WARNING, one line each. > - NOT VERIFIED: anything you could not check, and why. > > Confirm explicitly that the catalog is priced in , that shipping > covers , and that at least one processor can charge in . > A store can pass the checklist at 5/5 and still be unable to take an order. > ``` > [accordion] Portfolio audit > > You manage several stores and want to know which ones are broken. > > ```text theme={null} > You have access to the Tagada Config MCP. Audit every store I can reach. > > 1. Call list_stores. It spans every organisation I belong to - cover all of > them, not just the first. > 2. For each store, run diagnose_store area checkout and diagnose_store area payment. Those two decide > whether an order can be placed at all. > 3. For any store failing either one, also run diagnose_store area catalog and > diagnose_store area shipping to get the full picture. > > Give me a single table: > > Store | Organisation | Can take orders? | Blockers > > Broken stores first. One short line per blocker, no evidence dumps. > > End with the stores you could not check and why. A missing permission is a > result, not a store to leave out. > ``` ## Next > [card] [Tools Reference](/developer-tools/crm-mcp/tools-reference) > > The nine tools, what they report, and the one that writes. > [card] [Get Started](/developer-tools/crm-mcp/introduction) > > Connect your client. # Get Started Source: https://docs.tagada.io/developer-tools/crm-mcp/introduction Connect an AI assistant to your Tagada account and find out why a store is not taking payments. The Tagada **Config MCP** lets an AI assistant inspect how your stores are configured. The setup checklist in the CRM marks a step completed as soon as the record exists; these tools tell you whether it actually works — a processor can be saved *and* archived, and the checklist counts it either way. ```text theme={null} https://api.tagada.io/api/mcp ``` Nothing to install, no API key. The tools come in four groups: | Group | What the assistant can do | | - | - | | **Stores** | List your stores and diagnose their setup: catalog, shipping, payment, checkout | | **Canvas** | Read a funnel and change it through the [canvas](/developer-tools/funnels/canvas): pages, wires, rules | | **Studio** | Drive the Studio tabs you have open: read a page, edit it live, screenshot it, save it | | **Actions** | Find and run the CRM actions your role allows, with a confirmation step before anything destructive or involving money | The assistant sees exactly what your CRM role lets you see, across every organisation you belong to, and it can only change what your role lets you change. ## Drive Studio from your assistant Open a page in Studio from the CRM, then ask your assistant to work on it. The Studio tab talks to the Tagada API on its own, so the assistant reaches it with nothing to install and no browser permission, in any browser. See [Studio MCP](/developer-tools/studio-mcp/introduction) for how it works. * `open_in_studio` gives the Studio link of a page, for you to open. * `studio_tabs` lists the Studio tabs you have open. With more than one, pass its `tabId` to the other Studio tools. * `studio_view_tree`, `studio_update_nodes_batch`, `studio_add_page_from_template`, `studio_screenshot` and `studio_save` cover a page build. * `studio_run` runs any other Studio tool; `studio_run` with `tool: "help"` lists them. Edits land in your open tab, where you can undo them. Nothing is deployed until you, or the assistant through `studio_save`, save the page. ## Connect your client > [tab] Claude Code > > ```bash theme={null} > claude mcp add --transport http tagada https://api.tagada.io/api/mcp > ``` > > Then run `/mcp` and pick **tagada** to sign in. > [tab] Claude (web, desktop, mobile) > > In **Settings → Connectors**, choose **Add custom connector** and paste: > > ```text theme={null} > https://api.tagada.io/api/mcp > ``` > > Leave the optional OAuth client fields empty, then sign in when the browser opens. All three surfaces share one connector — adding it once is enough. > > On Team and Enterprise plans, only an owner can add a connector for the whole organisation. > [tab] Cursor > > In `.cursor/mcp.json`, or your global Cursor settings: > > ```json theme={null} > { > "mcpServers": { > "tagada": { > "url": "https://api.tagada.io/api/mcp" > } > } > } > ``` > > Cursor prompts for sign-in the first time a tool is called. > [tab] Codex > > ```bash theme={null} > codex mcp add tagada --url https://api.tagada.io/api/mcp > codex mcp login tagada > ``` > [tab] ChatGPT > > Custom connectors sit behind **developer mode**, which you switch on in ChatGPT's settings. Once it is on, add a custom connector and paste: > > ```text theme={null} > https://api.tagada.io/api/mcp > ``` > > Developer mode is a web-app feature and needs a paid plan. On Business and Enterprise workspaces, an admin may have to allow connected data before it appears. > [tab] Le Chat (Mistral) > > Open **Connectors**, click **Add Connector**, choose **Custom MCP Connector**, name it **Tagada** and paste: > > ```text theme={null} > https://api.tagada.io/api/mcp > ``` > > Click **Connect**, sign in, then turn **Tagada** on in the chat's tools menu. Only a workspace admin can add a connector. > [tab] Gemini CLI > > ```bash theme={null} > gemini mcp add --transport http tagada https://api.tagada.io/api/mcp > ``` > > Then run `/mcp auth tagada` in Gemini CLI to sign in. > [tab] Other clients > > Any client speaking **Streamable HTTP** with **OAuth 2.1** works, usually with the same JSON: > > ```json theme={null} > { > "mcpServers": { > "tagada": { > "url": "https://api.tagada.io/api/mcp" > } > } > } > ``` Your client should now list the server `tagada-crm-config` and its tools. Staging accounts use `https://api.tagada.dev/api/mcp` instead. ## Troubleshooting > [accordion] No Tagada tools appear > > Restart the client after saving its MCP configuration. Most clients only read their config at startup. > [accordion] 'This login is not linked to any Tagada account' > > Your user is not a member of any organisation. Ask an admin to invite you, then reconnect. > [accordion] 'Store not found, or not reachable with this authorization' > > Either the store id is wrong, or it belongs to an organisation you are not a member of — the message is deliberately the same in both cases. Run `list_stores` for the ids you can reach. > [accordion] 'Your role on … does not grant …' > > The tool needs a permission your role lacks — `diagnose_store` area `payment` needs processor-read rights. Ask an admin to widen your role. > [accordion] 'No Studio tab is open' > > Open the page in Studio from the CRM, signed in with the same account as your assistant, and keep the tab open. A tab counts as open while it has been seen in the last 30 seconds; a tab in the background of a sleeping laptop drops out until it wakes. > [accordion] 'Rate limit exceeded' > > You passed 120 tool calls in a minute. Wait for the delay in the `Retry-After` header. Your API keys are on a separate budget. ## Next > [card] [Prompt Library](/developer-tools/crm-mcp/examples) > > Three prompts, ready to copy. > [card] [Tools Reference](/developer-tools/crm-mcp/tools-reference) > > The nine tools, what they report, and the one that writes. # Tools Reference Source: https://docs.tagada.io/developer-tools/crm-mcp/tools-reference The configuration tools on the Tagada Config MCP, what each one reports, and the one that writes a funnel. The configuration tools. All of them only read except `canvas_apply`, which writes nothing but a funnel. Every tool except `list_stores` and `search_docs` takes a `storeId`. | Tool | Input | Answers | | - | - | - | | `list_stores` | — | Which stores can I reach, in which organisation, in which currency? | | `diagnose_store` | `storeId`, `area?` | Every check below in one reply, or one `area`: `setup`, `catalog`, `shipping`, `payment`, `checkout`. | | `diagnose_store` area `setup` | `storeId` | Which required steps does the checklist consider done? | | `diagnose_store` area `catalog` | `storeId` | Are there active products, with active variants, priced in the store currency? | | `diagnose_store` area `shipping` | `storeId` | Are there live rates, covering which countries, for the shippable products? | | `diagnose_store` area `payment` | `storeId` | Is the payment flow live, and can any processor actually take a charge? | | `diagnose_store` area `checkout` | `storeId` | Is a funnel active, published, on a verified domain? | | `canvas_get` | `storeId`, `funnelId?`, `topic?` | What does this funnel actually look like — entries, pages, exits, wires, satellites, what fires where? `topic: "commands"` returns the `canvas_apply` reference. | | `canvas_apply` | `storeId`, `commandId`, `expectedSeq`, `commands` | **Writes.** 1 to 20 commands on one funnel: `add`, `remove`, `connect`, `bind` or `set` | | `search_docs` | `query` | What do the Tagada docs say about this? | Call `list_stores` first — it is the only source of valid store ids, and it spans every organisation you belong to. Every diagnosis echoes the store name it inspected. Rate limit: 120 tool calls per minute per signed-in user, separate from your API keys. `canvas_apply` has a second, tighter budget: 60 commands per minute per funnel, so an agent cannot starve the merchant editing the same canvas. ## How a diagnosis reads The four deep checks of `diagnose_store` (`catalog`, `shipping`, `payment`, `checkout`) share one output shape. ```text theme={null} Store: Acme EU (store_7f3a91c2) Check: payment — PROBLEMS FOUND [ERROR] Processor "Stripe EU" is archived. evidence: {"processorId":"proc_x9y8","processorName":"Stripe EU","archivedAt":"2026-06-02T09:14:00.000Z"} [ERROR] No processor can currently take a charge — the checkout will decline every card even though the setup checklist shows green. Learn more: https://help.tagada.io/articles/19-add-processors-to-your-organization ``` Severities are `OK`, `WARNING`, `ERROR`. `evidence` carries the rows and values that prove the claim. Each finding also has a stable `code` — `processor_archived` above — that survives a change of wording. ## `diagnose_store` area `setup` The five required steps (`store`, `catalog`, `shipping`, `payment`, `checkout`) and their status: `completed`, `pending`, `not_started`, or `locked`. This is the shallow view. A 5/5 checklist and a store that declines every card are compatible states, which is why the deep checks exist. ## `diagnose_store` area `catalog` At least one active product, with active variants, each priced in the base currency and in every presentment currency. `catalog_empty` · `no_active_product` · `product_without_active_variant` · `all_variants_out_of_stock` · `variant_missing_base_currency_price` · `variant_missing_presentment_currency_price` · `variant_priced_only_on_legacy_fields` The last one catches a quiet failure: a variant priced only on the legacy field looks priced in the CRM and is invisible to the checkout. ## `diagnose_store` area `shipping` Live (non-deleted) rates that name countries, are priced in the base currency, and cover every shippable product. Digital stores return `shipping_not_applicable`. `shipping_rates_all_deleted` · `shipping_rate_without_country` · `shipping_rate_missing_base_currency` · `shippable_products_without_rate` > [!WARNING] > > Amount and weight brackets are not evaluated. A rate no real cart reaches is still reported as live. ## `diagnose_store` area `payment` A payment flow that is selected, found and not archived, with processors that are not all disabled; then, per enabled processor, that it is enabled, not archived, and lists the store's base currency. `payment_flow_not_selected` · `payment_flow_not_found` · `payment_flow_archived` · `payment_flow_has_no_processors` · `payment_flow_all_processors_disabled` · `processor_not_found` · `processor_disabled` · `processor_archived` · `processor_currency_unsupported` · `no_usable_processor` Needs store-read **and** processor-read permissions; it names the missing one rather than returning a partial answer. Processor credentials are never read from the database, so they cannot reach the assistant even in an error path. > [!WARNING] > > Monthly processing capacity is not checked. A processor over its cap is reported as usable. ## `diagnose_store` area `checkout` An active, published funnel whose production domains are registered, enabled and verified. `no_funnel` · `no_active_funnel` · `funnel_not_published` · `domain_not_registered` · `domain_disabled` · `domain_not_verified` An unverified domain is the classic silent outage: the funnel is live, the CRM is green, and the URL you gave your customers does not resolve. ## `canvas_get` The whole canvas of one store in a single reply: `store`, `funnel` (with its sequence numbers, drift flag and publication state), `entries`, `nodes` with their typed `exits`, `edges`, `satellites` and `bindings`. Pass `funnelId` to pick a funnel when the store has several; leave it out for the default one. Read this before every `canvas_apply`: the ids you need — node ids, exit ids, integration ids — and the `funnel.pendingSeq` you must echo back all come from here. ## `canvas_apply` The only tool on this server that changes anything. It takes one command out of five, refuses everything it cannot prove, journals it, and lets the compile queue write the funnel. ```json theme={null} { "storeId": "store_abc123", "commandId": "01J9Z2X4V7A8B9C0D1E2F3G4H5", "expectedSeq": 12, "commands": [ { "type": "add", "kind": "page.offer", "after": { "node": "step_checkout", "exit": "step_checkout:paid" }, "props": { "name": "Post-purchase upsell", "offerId": "offer_2f1c" } } ] } ``` * **`commandId` is yours, and replaying it is safe.** An id already seen returns the original reply, never a second command. Retry a timeout with the same id. * **`expectedSeq` is the `funnel.pendingSeq` you just read.** If the canvas moved in between, the command is refused with `stale` and the fresh document comes back with the refusal. * **A refusal is data, not an exception.** It carries `code`, `message`, `cause`, `fix` and `docs`. Act on `fix`; branch on `code`, which is versioned and never changes meaning. * **A malformed command is a different answer.** The tool re-validates its input, so a name over 120 characters or an `http://` address comes back as *"Nothing was written: these commands do not parse"* naming the command and the field — `#1 props.url` — and never reaches the refusal codes. The five commands, the exits each block has, and the fifteen refusal codes are in the [Funnel Canvas](/developer-tools/funnels/canvas) reference. > [!WARNING] > > `canvas_apply` edits a live funnel. It publishes on its own once the funnel compiles, so a command an agent sends is a change a customer can hit. Show the merchant what you are about to send. ## `search_docs` Searches the public documentation behind [docs.tagada.io](https://docs.tagada.io). Use it to turn a finding into a fix. If it is unavailable it says so, and the rest of the session keeps working. ## Next > [card] [Prompt Library](/developer-tools/crm-mcp/examples) > > Three prompts, ready to copy. > [card] [Get Started](/developer-tools/crm-mcp/introduction) > > Connect your client. # Wallet tokenization example Source: https://docs.tagada.io/developer-tools/examples/apple-google-pay Native wallet buttons with @tagadapay/core-js — wallet token in, TagadaToken out, then the exact same charge path as a card # Apple Pay & Google Pay **Time**: \~25 minutes | **Difficulty**: Intermediate | **Type**: part of [Examples](/developer-tools/examples/introduction) > [!NOTE] > > **Finished project:** [`apple-google-tokenization`](https://github.com/TagadaPay/examples/tree/main/apple-google-tokenization). Clone it if you want working wallet buttons first — or keep reading for the two things that actually differ from a card payment. The punchline of this demo: **wallets are just another tokenizer**. Apple Pay and Google Pay each hand you an encrypted token; you convert it to a `TagadaToken`, and from there the flow is byte-for-byte the [card tokenization flow](/developer-tools/examples/card-tokenization) — payment instrument, optional 3DS, charge. One charge path, three ways in. | Entry point | You get | Then | | - | - | - | | 🍎 Apple Pay button | `paymentData.token.paymentData` | → `TagadaToken` → instrument → charge | | 🟢 Google Pay button | `tokenizationData.token` | → `TagadaToken` → instrument → charge | | 💳 Card form | `tokenizeCard()` result | → same instrument → same charge | *** ## The two wallet-specific parts **1. The buttons.** `@tagadapay/core-js` ships both wallet session helpers. Each opens the native sheet and hands you the resulting token in `onSuccess`: ```tsx theme={null} import { isApplePayAvailable, startApplePaySession, startGooglePaySession, } from '@tagadapay/core-js'; // Apple Pay — must be called synchronously from a click handler button.addEventListener('click', () => { startApplePaySession( { basisTheoryApiKey, countryCode: 'US', storeName: 'My Store' }, { totalAmountMinor: 4999, currency: 'USD' }, { onSuccess: async (token) => { // token.id → createPaymentInstrument → processPayment, same as a card. // The sheet stays open until you return, and shows what you return. const approved = await chargeOnYourServer(token); return { status: approved ? 'success' : 'failure' }; }, onError: (msg) => console.error(msg), }, ); }); // Google Pay — same shape startGooglePaySession(googleConfig, request, { onSuccess, onError }); ``` > [!NOTE] > > Both helpers take `(config, request, callbacks)` and return `void` — they are not promises. The > token arrives in `onSuccess`, and for Apple Pay what `onSuccess` returns is what the sheet shows. > For the full wallet reference, including domain registration and > which processors accept wallets, see > [Apple Pay & Google Pay](/developer-tools/payments/wallets). **2. Environment config.** Google Pay needs the right tenant id per environment — don't hardcode it, the SDK resolves it: ```ts theme={null} import { getGoogleTenantId } from '@tagadapay/core-js/core'; const tenantId = getGoogleTenantId('development'); // or 'production' | 'local' ``` Everything after the `TagadaToken` — payment instrument, SCA detection, 3DS challenge, charge — is covered in [Card tokenization & 3DS](/developer-tools/examples/card-tokenization) and is shared code in this demo. *** ## Run it — Apple Pay needs HTTPS Google Pay and the card form work straight on `localhost`. **Apple Pay refuses non-HTTPS pages**, so tunnel your dev server: **1. Start the demo** ```bash theme={null} git clone https://github.com/TagadaPay/examples.git cd examples/apple-google-tokenization pnpm install && pnpm dev # http://localhost:5173 ``` **2. Tunnel with ngrok** ```bash theme={null} brew install ngrok # or: npm install -g ngrok ngrok http 5173 # prints https://abc123.ngrok.io ``` **3. Open the HTTPS URL in Safari** Open the `https://….ngrok.io` URL in **Safari** on a device with a card in Wallet — the Apple Pay button lights up and the full flow works, 3DS included. > [!TIP] > > No Apple device handy? The demo degrades gracefully: Google Pay in Chrome and the classic card form both run on plain `localhost`, so you can verify the whole charge path before touching ngrok. *** ## Next > [card] [Finished project on GitHub](https://github.com/TagadaPay/examples/tree/main/apple-google-tokenization) > > Wallet buttons, card form, 3DS — all three entry points in one app > [card] [Card tokenization & 3DS](/developer-tools/examples/card-tokenization) > > The shared charge path this demo plugs into > [card] [core-js reference](/developer-tools/payments/core-js-payments) > > Wallet sections included — full API detail > [card] [Choose your integration](/developer-tools/payments/choose-your-integration) > > Wallets on a TagadaPay-managed cart? That's the Headless SDK path # Card tokenization & 3DS Source: https://docs.tagada.io/developer-tools/examples/card-tokenization Tokenize a card in the browser with @tagadapay/core-js, create a payment instrument on your server, handle the 3DS challenge, charge # Card tokenization & 3DS **Time**: \~20 minutes | **Difficulty**: Intermediate | **Type**: part of [Examples](/developer-tools/examples/introduction) > [!NOTE] > > **Finished project:** [`core-js-tokenization`](https://github.com/TagadaPay/examples/tree/main/core-js-tokenization). Clone it if you want the working demo first — or keep reading to understand each hop of the flow. This is the **"you already have the order"** path: your cart lives in Medusa, WooCommerce, or your own order API, and TagadaPay only tokenizes and charges. The demo walks the entire flow with a UI that narrates every step — tokenize, create the instrument, detect SCA, run the 3DS challenge in a modal, charge, retry. > [!WARNING] > > If TagadaPay should manage the cart, upsells, and funnel, this is the wrong page — use the [Headless SDK](/developer-tools/headless-sdk/introduction) instead. Two minutes on [Choose how you accept payments](/developer-tools/payments/choose-your-integration) settles it. *** ## The flow — who runs what The whole point of this example is the **client / server split**. Raw card data stays in the browser; your API key stays on the server. Four hops: | # | Step | Where | Call | | - | - | - | - | | 1 | Tokenize the card | Browser | `tokenizeCard()` → `TagadaToken` | | 2 | Create the payment instrument | **Your server** | `POST /payment-instruments/create-from-token` | | 3 | 3DS session + challenge (if SCA) | Server creates, browser challenges | `startChallenge()` modal | | 4 | Charge | **Your server** | `POST /payments/process` | ```tsx theme={null} // 1 — browser: card data goes to Basis Theory, never to you const { tagadaToken } = await tokenizeCard({ cardNumber, expiryDate, cvc, cardholderName }); // 2 — your server: turn the token into a reusable instrument const { paymentInstrument } = await createPaymentInstrument( { tagadaToken, storeId }, process.env.TAGADAPAY_API_KEY, // server-side only ); ``` When the instrument requires Strong Customer Authentication, the demo creates a 3DS session server-side and runs the challenge client-side — a modal pops, the customer authenticates, and you charge with the session attached: ```tsx theme={null} // 3 — browser: the modal appears here const completion = await startChallenge({ acsChallengeUrl: threedsSession.acsChallengeUrl, creq: threedsSession.creq, threeDSVersion: threedsSession.messageVersion, }); // 4 — your server: charge, referencing the 3DS session await processPayment({ amount: 2999, // integer cents currency: 'USD', storeId, paymentInstrumentId: paymentInstrument.id, threedsSessionId: threedsSession.id, }); ``` > [!TIP] > > `src/api/paymentBackend.ts` in the demo is written to be **copied to your server** — every function is annotated with a Next.js Server Action and an Express route version. The demo calls them from the browser only so you can watch the flow in one page; in production those calls move behind your auth. *** ## Run it ```bash theme={null} git clone https://github.com/TagadaPay/examples.git cd examples/core-js-tokenization pnpm install && pnpm dev ``` Open `http://localhost:5173`, paste a store id, and use a [sandbox test card](/developer-tools/node-sdk/sandbox-testing). The right-hand sidebar keeps a history of tokens and store ids in `localStorage` so you can replay flows quickly, and a failed 3DS can be retried from the beginning. ## The minimal variant [`core-js-card-payment`](https://github.com/TagadaPay/examples/tree/main/core-js-card-payment) is the same flow with everything non-essential removed: one page, one card form, one charge, plus a `/return` route that shows how to resume after a processor redirect. Read `core-js-tokenization` to learn; copy `core-js-card-payment` when you just want the skeleton. *** ## Next > [card] [Finished project on GitHub](https://github.com/TagadaPay/examples/tree/main/core-js-tokenization) > > Clone `core-js-tokenization` and watch every hop in the UI > [card] [Apple Pay & Google Pay](/developer-tools/examples/apple-google-pay) > > Same charge path, wallet buttons instead of a card form > [card] [core-js reference](/developer-tools/payments/core-js-payments) > > The full API this demo is built on — every endpoint, every field > [card] [Sandbox testing](/developer-tools/node-sdk/sandbox-testing) > > Test cards, forced 3DS, simulated declines # Checkout in plain HTML Source: https://docs.tagada.io/developer-tools/examples/headless-vanilla A complete funnel — cart, checkout, 3DS, one-click upsells — in three HTML files. No React, no bundler, no build step. # Checkout in plain HTML **Time**: \~15 minutes | **Difficulty**: Beginner | **Type**: part of [Examples](/developer-tools/examples/introduction) > [!NOTE] > > **Finished project:** [`headless-vanilla`](https://github.com/TagadaPay/examples/tree/main/headless-vanilla). Clone it if you want the working funnel first — or keep reading and rebuild the three pages yourself. Proof that the Headless SDK needs **zero tooling**: three static HTML files, the SDK from a CDN, and you get a real store — catalog, cart, card payment with automatic 3DS, and one-click post-purchase upsells. If you can host a folder, you can host this. | Page | File | SDK calls | | - | - | - | | Home / cart | `index.html` | `catalog.listProducts()` → `checkout.createSessionUrl()` | | Checkout | `checkout.html` | `parseTokensFromUrl()` → `loadSession()` → `tokenizeCard()` → `processPayment()` | | Thank you | `thank-you.html` | `offers.listOffers()` → `offers.processOfferPayment()` | *** ## Setup — two lines to edit No `.env`, no build. Provision a demo store from the terminal, then paste your store id: ```bash theme={null} npx -p @tagadapay/node-sdk tagada-init you@example.com ``` ```js theme={null} // assets/config.js export const STORE_ID = 'store_xxxxxx'; // ← from tagada-init export const ENVIRONMENT = 'production'; // or 'development' ``` Serve the folder with anything (`npx serve`, nginx, S3, a USB stick) and open `index.html`. > [!NOTE] > > The SDK ships as an IIFE bundle on jsDelivr — `window.TagadaHeadless` appears after one `", "position": "body-end" } ], "pixels": { "facebook": { "enabled": true, "pixelId": "123456789", "events": { "PageView": true, "InitiateCheckout": true, "Purchase": true } } } } } } ``` The step config is available in the Plugin SDK via `useStepConfig()` or `window.__TGD_STEP_CONFIG__`. See [Step Config & Script Injection](/developer-tools/sdk/introduction#step-config--script-injection) for details. *** ## Tracking Funnel Events The SDK tracks events automatically when used inside a funnel. If you need manual tracking (e.g., from a server or external page), use the [Track Funnel Step](/api-reference/funnel-tracking/track-funnel-step-event) endpoint: ```bash theme={null} curl -X POST https://api.tagada.io/api/public/v1/funnel-tracking/step \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "eventType": "convert", "storeId": "store_abc123", "stepId": "step_thankyou", "stepName": "Thank You", "stepType": "thankyou", "funnelId": "funnelv2_abc123", "funnelSessionId": "fs_1234567890_abc123", "customerId": "cus_123", "isConversionStep": true, "orderId": "order_abc", "orderAmount": 4999, "orderCurrency": "USD" }' ``` | Event Type | When to use | | - | - | | `view` | Page was displayed (impression) | | `enter` | Customer navigated to the step | | `convert` | Customer completed the step's goal (e.g., purchase) | | `custom` | Any custom event you want to track | *** ## Debugging a Funnel Session To inspect what happened in a customer's session: ```bash theme={null} curl https://api.tagada.io/api/public/v1/funnel-sessions/SESSION_ID \ -H "Authorization: Bearer YOUR_API_KEY" ``` This returns the full session data: current step, furthest step reached, customer history, timestamps, metadata, and resources. Useful for debugging why a customer dropped off or got stuck. *** ## Complete API Reference | Endpoint | Method | What it does | | - | - | - | | [`/stores/{storeId}/funnels`](/api-reference/funnels/list-funnels-for-a-store) | GET | List all funnels for a store | | [`/funnels`](/api-reference/funnels/create-a-new-funnel) | POST | Create a new funnel | | [`/funnels/{id}`](/api-reference/funnels/get-funnel-by-id) | GET | Get funnel details | | [`/funnels/{funnelId}`](/api-reference/funnels/update-funnel-with-routing) | PUT | Update funnel (auto-mounts routes) | | [`/funnels/{funnelId}/promote`](/api-reference/funnels/promote-funnel-to-production) | POST | Publish the staging config to a production domain | | [`/funnels/{funnelId}`](/api-reference/funnels/delete-a-funnel) | DELETE | Delete funnel and clean up routes | | [`/funnels/{funnelId}/preview-session`](/api-reference/funnels/create-a-preview-session) | POST | Create a test session | | [`/funnel-sessions/{sessionId}`](/api-reference/funnel-sessions/get-funnel-session-data) | GET | Debug a session | | [`/funnel-tracking/step`](/api-reference/funnel-tracking/track-funnel-step-event) | POST | Track analytics events | *** ## Recap ``` 1. Create funnel → Define nodes (steps) and edges (flow) 2. TagadaPay mounts → Routes and plugins are configured automatically 3. Customer visits → SDK handles navigation between steps 4. You track results → Conversion analytics per step, per variant 5. Iterate → Update the funnel, add steps, split test ``` > [card] [Funnel Lifecycle: Save, Publish & Go-Live](/developer-tools/funnels/funnel-lifecycle) > > Duplicate, preview on staging, and promote to a production domain > [card] [Plugin SDK](/developer-tools/sdk/introduction) > > Build the pages that power each step > [card] [Hosting & A/B Testing](/developer-tools/hosting/deploy-and-ab-test) > > Host any page and run split tests > [card] [Direct Link Guide](/developer-tools/web-integration/trigger-checkout-from-website) > > Generate checkout URLs from any website > [card] [External Page Tracker](/developer-tools/web-integration/external-page-tracker) > > Connect external pages to the funnel # Build a Store with AI + TagadaPay Source: https://docs.tagada.io/developer-tools/headless-sdk/build-store-with-ai Use Claude, Lovable, or v0 to generate your storefront — TagadaPay handles payments, emails, and pixel tracking # Build a real store in 15 minutes — no Shopify, no WooCommerce. > **The Shopify era is over.** When your storefront *and* your payments both live on someone else's platform, you're one policy change away from losing the shop overnight — the only way to stay in business is to keep the monopoly on **your code** and the flexibility on **your payments**. > > **That's exactly what Tagada gives you:** a ready-made CRM, a payment orchestrator that plugs into your own PSPs *or* routes through TagadaPay (every vertical welcome — low-risk **and** high-risk, no judgment), and a Headless SDK that Claude or Lovable can wire into an AI-generated storefront in minutes. > > **The breakthrough:** even if you've never shipped a line of code, you can now ship a real, fully-owned store in an afternoon. That's what this tutorial is for. You bring an **AI coding tool** (Claude, Lovable, v0). It writes your storefront UI. **TagadaPay** is the headless backend — payments, emails, subscriptions, upsells, and pixel tracking all included. > [card] [Create your account from the terminal](#fastest-path--clone--ship-3-commands) > > `npx -p @tagadapay/node-sdk tagada-init you@example.com` — verify with a 6-digit code, get an API key in 30 seconds. No browser. > [card] [See the live demo](https://headless-react-eta.vercel.app) > > Real React store, real test payments, real upsells. > [!NOTE] > > **Three ways to get an API key, same outcome:** > > * **CLI** — `npx -p @tagadapay/node-sdk@latest tagada-init you@example.com` > * **SDK** — `Tagada.public().start(...)` then `verify(...)` ([snippet here](/developer-tools/node-sdk/get-api-key#path-2--the-sdk-programmatic)) > * **Web** — [app.tagada.io](https://app.tagada.io/sign-up?source=tagadapay-docs-ai-store) → Settings → Access Tokens > > Full walkthrough on [Get an API key from code](/developer-tools/node-sdk/get-api-key). ```mermaid theme={null} flowchart LR AI["AI coding tool
Claude · Lovable · v0"] --> UI["Your storefront
React · Next.js · Astro · plain HTML"] UI -->|"@tagadapay/headless-sdk"| TGD["TagadaPay
headless backend"] TGD --> Pay["Payments
Stripe · Checkout.com · 12+ PSPs"] TGD --> Mail["Emails
order · rebill · refund"] TGD --> Pix["Pixels
Meta · TikTok · GA4 · GTM"] TGD --> Sub["Subscriptions
upsells · CRM"] classDef primary fill:#16A34A,stroke:#15803D,color:#fff,font-weight:600; classDef plain fill:#F8FAFC,stroke:#CBD5E1,color:#0F172A; class TGD primary; class AI,UI,Pay,Mail,Pix,Sub plain; ``` > [!NOTE] > > **Time to first sale: \~15 minutes.** Seriously. You go from zero to a live store with real payments. The AI writes the UI, you paste a few SDK calls, TagadaPay does the rest. *** ## What you'll build A complete commerce flow — every page below is generated by the AI from one prompt: > [card] Product page > > Browse products from your Tagada catalog > [card] Cart > > Add, remove, change quantity, see totals > [card] Checkout > > Customer info · shipping · promo codes · Google address autocomplete > [card] Payment > > Card payments, PCI-safe tokenization, 3DS handled > [card] Thank you + upsells > > One-click upsells on the same card > [card] Subscriptions & rebills > > Recurring billing, dunning, customer portal No backend to write. TagadaPay **is** the backend. *** ## Fastest path — clone & ship (3 commands) If you just want to see it work, this is the shortest road. **No browser, no CRM tab, no copy-pasting API keys** — one CLI command provisions a fresh Tagada account, writes your `.env`, and seeds a demo store. You'll be on `localhost:5173` in under a minute. **1. Provision a fresh Tagada account from your terminal** `tagada-init` mails you a 6-digit code, verifies it, creates a free sandbox account, provisions a demo-seeded store (sandbox processor + payment flow + 2 demo products — an *Essential Tee* in 3 colorways and an *Essential Cap* — a checkout upsell, a default shipping rate, and a checkout funnel), and writes `TAGADA_API_KEY` / `TAGADA_STORE_ID` / `TAGADA_ACCOUNT_ID` to `.env` in the current directory. > [!TIP] > > Want a richer 6-product apparel catalog instead of the 2-product default? After `tagada-init`, run `pnpm seed $TAGADA_API_KEY` — the example ships with a `scripts/seed.ts` that overwrites the demo with a fuller storefront. Skip it if the default is enough. ```bash theme={null} git clone https://github.com/TagadaPay/examples.git cd examples/headless-react-store npx -p @tagadapay/node-sdk@latest tagada-init you@example.com ``` Paste the code from your inbox when prompted. That's it — no signup form, no dashboard navigation. > [accordion] Doing this from your own script instead of the CLI? > > Same flow, exposed as `Tagada.public()` in the Node SDK. Useful for AI agents, framework installers, or any tool that already has its own prompt loop: > > ```ts theme={null} > import Tagada from '@tagadapay/node-sdk'; > > const onboarding = Tagada.public(); > > await onboarding.start({ email: 'you@example.com' }); > > const { apiKey, storeId, accountId } = await onboarding.verify({ > email: 'you@example.com', > code: '123456', // however you collected it > }); > > const tagada = new Tagada(apiKey); // ready to use immediately > ``` > > Full reference: [Get an API key from code](/developer-tools/node-sdk/get-api-key). **2. Install + run** ```bash theme={null} pnpm install pnpm dev ``` Open [http://localhost:5173](http://localhost:5173) → buy something with `4242 4242 4242 4242`. Done. The demo products, payment flow, and funnel seed asynchronously (\~30s) — your store is already usable, the catalog will populate as you watch. > [!TIP] > > **Prefer the web flow?** Head to [app.tagada.io](https://app.tagada.io/sign-up?source=tagadapay-docs-ai-store), copy your API key from Settings → Access Tokens, then run `pnpm seed ` instead of `tagada-init`. Same outcome, two extra clicks. > [!TIP] > > **Two examples, two purposes:** > > * **[`headless-react-store`](https://github.com/TagadaPay/examples/tree/main/headless-react-store)** (above) — a fork-ready storefront. Hand it to a designer or paste it into Claude and iterate. **Start here if you want to ship.** > * **[`headless-react`](https://github.com/TagadaPay/examples/tree/main/headless-react)** — an interactive playground that explains every Headless SDK hook with side-by-side code panels. **Read this if you want to learn the SDK** before forking. > > Want to do it from scratch instead? Keep reading — the rest of this page walks through the same flow manually so an AI can generate it for you. *** ## Prerequisites * [Node.js](https://nodejs.org/) 18+ * An AI coding tool: [Claude](https://claude.ai), [Lovable](https://lovable.dev), [v0](https://v0.dev), or any IDE with AI * A free **Tagada account** — three ways to get one in \~30 seconds, all detailed on [Get an API key from code](/developer-tools/node-sdk/get-api-key): * **CLI:** `npx -p @tagadapay/node-sdk@latest tagada-init you@example.com` — interactive, writes `.env` for you. * **SDK:** `Tagada.public().start(...)` then `verify(...)` — programmatic, for AI agents or installers. * **Web:** [app.tagada.io](https://app.tagada.io/sign-up?source=tagadapay-docs-ai-store) → Settings → Access Tokens — same key, two extra clicks. No credit card required. > [!NOTE] > > **Tagada vs. TagadaPay vs. Hub — three things, one ecosystem:** > > * **Tagada** ([app.tagada.io](https://app.tagada.io/sign-up?source=tagadapay-docs-ai-store)) is the **CRM** — your account, your stores, your products, your API keys, your orchestrator. This is what `tagada-init` provisions, and what every code sample in this tutorial assumes you have. Free, instant, no credit card. > * **TagadaPay** is the **payment processor** — one of many PSPs you can plug into your Tagada account (alongside Stripe, Checkout.com, NMI, …). Becoming a TagadaPay-processed merchant requires KYB, applied for separately at [hub.tagada.io](https://hub.tagada.io/sign-up?source=tagadapay-docs-ai-store). > * **Hub** ([hub.tagada.io](https://hub.tagada.io/sign-up?source=tagadapay-docs-ai-store)) is the **TagadaPay application form**. KYB review, \~24h. Optional — you can ship a fully-working store with just your Tagada CRM account + your own Stripe keys. > > You can ship a fully-working store with just Tagada (CRM) + your own Stripe. TagadaPay (the processor) is optional and orthogonal. *** ## Step 1 — Create your store with the Node SDK This single script provisions everything you need for a headless storefront: processor, payment flow, store, and products. Routing (checkout → thank-you) lives in your React app, so there's nothing else to register server-side. ```bash theme={null} mkdir my-store && cd my-store npm init -y npm install @tagadapay/node-sdk @tagadapay/headless-sdk ``` Create `setup.ts`: ```typescript theme={null} import Tagada from '@tagadapay/node-sdk'; const tagada = new Tagada(process.env.TAGADA_API_KEY!); // 1. Processor — connect Stripe (or use 'sandbox' for testing). const { processor } = await tagada.processors.create({ processor: { name: 'Stripe', type: 'stripe', enabled: true, supportedCurrencies: ['USD', 'EUR'], baseCurrency: 'USD', options: { secretKey: 'sk_test_...', publicKey: 'pk_test_...', }, }, }); // 2. Payment flow — route transactions through that processor. const flow = await tagada.paymentFlows.create({ data: { name: 'Main Flow', strategy: 'simple', fallbackMode: false, maxFallbackRetries: 0, threeDsEnabled: false, stickyProcessorEnabled: false, pickProcessorStrategy: 'weighted', fallbackProcessorConfigs: [], processorConfigs: [ { processorId: processor.id, weight: 100, disabled: false, nonStickable: false }, ], }, }); // 3. Store const store = await tagada.stores.create({ name: 'My AI-Built Store', baseCurrency: 'USD', presentmentCurrencies: ['USD', 'EUR'], chargeCurrencies: ['USD'], selectedPaymentFlowId: flow.id, }); // 4. Product const tshirt = await tagada.products.create({ storeId: store.id, name: 'Premium T-Shirt', description: 'Organic cotton, available in 3 colors', active: true, variants: [{ name: 'Black / M', sku: 'tshirt-black-m', grams: 200, active: true, default: true, imageUrl: 'https://images.unsplash.com/photo-1521572163474-6864f9cf17ab?w=600&h=600&fit=crop', price: 3900, compareAtPrice: 4900, prices: [{ currencyOptions: { USD: { amount: 3900 }, EUR: { amount: 3500 } }, recurring: false, billingTiming: 'in_advance', default: true, }], }], }); // That's it — no funnel needed. In a headless store your React app // owns the routing (cart → checkout → thank-you), so the Tagada // `funnels` resource (which exists for the no-code Studio runtime) is // not required. The Headless SDK never reads it. See the // "Why no funnel here?" accordion below if you're wondering when // you would want one. console.log(`Store ready: ${store.id}`); ``` Run it: ```bash theme={null} npx tsx setup.ts ``` Copy the `store_xxx` ID it prints — you'll paste it into the AI prompt next. > [!NOTE] > > **Return shapes:** > > * `processors.create()` returns `{ processor: { id, name, type, ... } }` — destructure with `const { processor } = await ...` > * `paymentFlows.create()` returns a flat flow object: `{ id, name, strategy, ... }` > * `stores.create()` returns a flat store object: `{ id, name, baseCurrency, ... }` > * `products.create()` returns `{ id, variants: [{ id, name, prices: [{ id }] }] }` — a summary, not the full product > [accordion] Supported processor types > > TagadaPay is gateway-agnostic. Use the `type` field when creating a processor. The canonical > lists live in two places — link there rather than copying them here: > > * [Processors](/developer-tools/payments/processors) — every published processor type and which > operations each supports. > * [Processor credentials](/developer-tools/node-sdk/processor-credentials) — the exact credential > field names per type. > > All processors share optional fields: `enable3DS`, `testMode`, `descriptor`, `merchantName`, `merchantUrl`, `merchantCountryCode`. > [accordion] Payment flow fields reference > > | Field | Type | Description | > | - | - | - | > | `name` | `string` | Human-readable flow name | > | `strategy` | `'simple' \| 'cascade'` | `simple` = single processor, `cascade` = try next on failure | > | `fallbackMode` | `boolean` | Enable fallback when primary fails | > | `maxFallbackRetries` | `number` | Max retry attempts (0 = no retries) | > | `threeDsEnabled` | `boolean` | Enable 3D Secure authentication | > | `stickyProcessorEnabled` | `boolean` | Route returning customers to same processor | > | `pickProcessorStrategy` | `'weighted' \| 'lowestCapacity' \| 'automatic'` | How to pick among multiple processors | > | `processorConfigs` | `array` | Processors: `{ processorId, weight, disabled, nonStickable }` | > | `fallbackProcessorConfigs` | `array` | Fallback order: `{ processorId, orderIndex }` | > [accordion] Why no funnel here? (vs. Tagada Studio) > > If you've used Tagada **Studio** (the no-code page builder), you'll have noticed it asks you to create a `funnel` with `nodes` for `checkout`, `thankyou`, `offer`, etc. **That's a Studio-only construct** — it tells the Studio runtime which page to render at which path, and how to chain steps for built-in funnel attribution. > > In a **headless** setup, your React/Next/Astro app owns the routing. There is no Studio runtime to drive, no URL-to-step mapping to declare. The Headless SDK's `useCheckout`, `usePayment`, `useOffers` hit the API directly with `storeId` + tokens — they never read a funnel record. > > → **You do not need a funnel record** to charge, upsell, or show related orders on your own domain. Reproduce the [basic post-purchase](/developer-tools/funnel-demos/basic-post-purchase) type with your own routes. > > Create a funnel only if you want Tagada to host the step URLs or you call [`funnel.navigate()`](/developer-tools/headless-sdk/funnel-navigation) from your cart. > > If you later want pixel tracking (Meta, Google Ads, TikTok…) or multi-page funnel attribution that *survives* across domains, you have two options: > > * Add pixel snippets directly in your React app and fire `view_content` / `add_to_cart` / `purchase` events yourself. > * Use the standalone [`external-tracker`](https://www.npmjs.com/package/@tagadapay/plugin-sdk) from the **Plugin SDK** — it *does* require a funnel + step IDs, by design, since it's built for hybrid Studio-hosted setups. *** ## Step 2 — Generate the storefront with AI Paste this prompt into **Claude**, **Lovable**, or your AI tool. Replace the placeholder with the `store_xxx` ID from Step 1. > [accordion] Click to copy the prompt > > ```text theme={null} > Build me a modern e-commerce store using React + Tailwind CSS. > > The store uses @tagadapay/headless-sdk for ALL backend operations > (catalog, checkout, payment, upsells) — no custom API needed. > > Architecture: > - Wrap the app in > - Use these hooks from '@tagadapay/headless-sdk/react': > • useCatalog() — load products > • useCheckout(checkoutToken, sessionToken) — manage checkout session > • usePayment() — tokenize cards and process payments > • useOffers() — load and accept upsell offers > • useGoogleAutocomplete({ apiKey }) — address autocomplete > > Pages to build: > 1. Product listing — grid of products from useCatalog() > 2. Cart — line items, quantities, totals > 3. Checkout — email, name, address (Google autocomplete), shipping, promo > 4. Payment — card form (number, expiry, cvc), tokenize then pay > 5. Thank-you — order summary from useOrder() (main order + relatedOrders) + one-click upsell via useOffers() > > Style: dark theme, clean, minimal, mobile-first. Use shadcn/ui-like patterns. > Store ID: STORE_ID_FROM_STEP_1 > ``` The AI generates a working storefront. Below are the exact SDK calls it needs — paste these into the conversation if your AI gets confused. ### Loading products ```tsx theme={null} import { useCatalog } from '@tagadapay/headless-sdk/react'; function ProductPage() { const { products, isLoading, loadProducts } = useCatalog(); useEffect(() => { loadProducts(); }, [loadProducts]); return products.map(product => ( )); } ``` ### Creating a checkout session ```tsx theme={null} import { useHeadlessClient } from '@tagadapay/headless-sdk/react'; const client = useHeadlessClient(); const { checkoutToken, sessionToken } = await client.checkout.createSession({ items: cart.map(item => ({ variantId: item.variantId, quantity: item.quantity, })), currency: 'USD', }); ``` ### Customer + address + shipping + promo ```tsx theme={null} import { useCheckout } from '@tagadapay/headless-sdk/react'; const { session, updateCustomer, updateAddress, getShippingRates, applyPromo } = useCheckout(checkoutToken, sessionToken); await updateCustomer({ email, firstName, lastName }); await updateAddress({ shippingAddress: { line1, city, state, postalCode, country } }); const rates = await getShippingRates(); await applyPromo('WELCOME10'); ``` ### Payment (tokenize + pay, 3DS handled automatically) ```tsx theme={null} import { usePayment } from '@tagadapay/headless-sdk/react'; const { tokenizeCard, processPayment, isProcessing, loadPaymentSetup } = usePayment({ onPaymentSuccess: (result) => router.push(`/thank-you?orderId=${result.order?.id}`), onPaymentFailed: (result) => toast.error(result.error), }); useEffect(() => { if (session?.id) loadPaymentSetup(session.id); }, [session?.id]); const { tagadaToken } = await tokenizeCard({ cardNumber: '4242424242424242', expiryDate: '12/28', cvc: '123', cardholderName: 'Jane Doe', }); const result = await processPayment({ checkoutSessionId: session.id, tagadaToken, }); switch (result.status) { case 'succeeded': router.push(`/thank-you?orderId=${result.order?.id}`); break; case 'requires_redirect': // usePayment handles this automatically (redirects + resumes on return) break; case 'failed': toast.error(result.error); break; } ``` ### Post-purchase upsells ```tsx theme={null} import { useOffers } from '@tagadapay/headless-sdk/react'; const { previewOffer, processOfferPayment } = useOffers(); // Pin the offer id (dashboard / Node SDK). Do not take listOffers()[0]. await previewOffer({ offerId: 'offer_cap' }); const upsell = await processOfferPayment({ offerId: 'offer_cap', mainOrderId: result.order.id, // checkout order — not a payment id }); // Show it on the thank-you page with useOrder(mainOrderId) — the child // order lands async, the hook watches relatedOrders for you. ``` *** ## Step 3 — Deploy Your storefront is just static files. Pick the host that matches your stack. > [tab] TagadaPay (recommended for SPAs) > > Free, edge-CDN, custom domain, A/B testing — all included with your account. > > ```bash theme={null} > npm run build > npx tsx scripts/deploy.ts # picks up TAGADA_API_KEY from .env > ``` > > Full setup is in [Hosting your store](#hosting-your-store) below. > [tab] Vercel > > ```bash theme={null} > npm install -g vercel > vercel --prod > ``` > [tab] Netlify > > ```bash theme={null} > npm install -g netlify-cli > netlify deploy --prod > ``` > [tab] Cloudflare Pages > > ```bash theme={null} > npx wrangler pages deploy dist > ``` No server to maintain. No database. TagadaPay handles everything. *** ## Step 4 — Email flows (zero config) TagadaPay sends transactional emails automatically when events happen. Set up a custom sender domain in the dashboard for branded emails. | Event | Email sent | Configurable? | | - | - | - | | Order paid | Order confirmation with receipt | Yes — template, sender domain | | Subscription rebill | Recurring payment receipt | Yes | | Subscription canceled | Cancellation confirmation | Yes | | Payment refunded | Refund notification | Yes | | Subscription past due | Failed payment alert | Yes | **To brand your emails:** open the dashboard, go to **Settings → Emails → Custom Domain → Add `your-store.com`**, then add the SPF / DKIM / DMARC records it shows you. See the [Emails guide](/developer-tools/headless-sdk/emails) for editing templates programmatically. *** ## Step 5 — Pixel tracking (zero config) TagadaPay handles **client-side pixel tracking** for ad attribution and retargeting. Configure pixels in the dashboard once — TagadaPay injects the scripts and fires `PageView`, `AddToCart`, `InitiateCheckout`, `Purchase` to all active pixels at the right moments. **No code changes in your storefront.** **Setup:** open the dashboard → **Settings → Integrations → Add pixel** → Meta / TikTok / Google / Snapchat / Pinterest. The Google slot accepts GTM (`GTM-…`), GA4 (`G-…`), or Google Ads (`AW-…`) IDs and auto-detects the type from the prefix. See the [Pixels guide](/developer-tools/headless-sdk/pixels) for the full event mapping reference. *** ## Step 6 — Webhooks (optional) Listen to payment events on your backend to trigger custom logic — fulfillment, Slack notifications, ERP sync, etc. ```typescript theme={null} import Tagada from '@tagadapay/node-sdk'; const tagada = new Tagada(process.env.TAGADA_API_KEY!); await tagada.webhooks.create({ storeId: 'store_xxx', url: 'https://my-store.com/api/webhooks/tagada', eventTypes: ['order/paid', 'subscription/created', 'order/refunded'], }); ``` Handle incoming events: ```typescript theme={null} // api/webhooks/tagada.ts (Next.js example) export async function POST(req: Request) { const event = await req.json(); switch (event.topic) { case 'order/paid': console.log('New order:', event.data.orderId); break; case 'subscription/created': console.log('New subscriber:', event.data.customerId); break; } return new Response('OK'); } ``` *** ## Architecture summary ```mermaid theme={null} flowchart TB subgraph Front["Your storefront — you own this"] UI["UI
React · Next.js · Astro · plain HTML"] SDK["@tagadapay/headless-sdk
useCatalog · useCheckout · usePayment · useOffers · useGoogleAutocomplete"] UI --- SDK end subgraph Cloud["TagadaPay cloud — we handle this"] direction TB Pay["Payment orchestration
14+ PSPs · fallback · 3DS · sticky routing"] Mail["Transactional emails
order · rebill · canceled · refund · past due"] Pix["Pixel tracking
Meta · TikTok · GA4 · GTM · Snap · Pinterest"] Sub["Subscriptions & rebilling
dunning · retries · customer portal"] CRM["CRM dashboard
orders · customers · analytics"] Off["Offers & upsells
post-purchase · order bumps"] end Front -->|HTTPS| Cloud classDef yours fill:#F0FDF4,stroke:#16A34A,color:#0F172A; classDef ours fill:#16A34A,stroke:#15803D,color:#fff; class UI,SDK yours; class Pay,Mail,Pix,Sub,CRM,Off ours; ``` *** ## Why this beats Shopify / WooCommerce | | Shopify | WooCommerce | AI + TagadaPay | | - | - | - | - | | **Monthly fee** | $39 – $399 / mo | Hosting + plugins | \$0 (pay per transaction) | | **Storefront tech** | Liquid templates | PHP themes | Any framework, any AI tool | | **Customization** | Limited by theme | Plugin conflicts | Unlimited — you own the code | | **Payment routing** | Shopify Payments only | WooCommerce Payments | Multi-PSP · fallback · load balancing | | **Upsells** | \$50 / mo app | Plugin | Built-in | | **Emails** | Basic | Plugin | Built-in, customizable templates | | **Pixel tracking** | Basic | Plugin | Auto-injects Meta · TikTok · GA4 · GTM | | **Subscriptions** | \$39+/mo app | Plugin | Built-in (dunning, customer portal) | | **Lock-in** | High | Medium | Zero — it's your code | > [card] [Ready? Run it from your terminal](#fastest-path--clone--ship-3-commands) > > `npx -p @tagadapay/node-sdk tagada-init you@example.com` — sandbox account + API key + seeded store in 30 seconds. > [card] [Or sign up the classic way](https://app.tagada.io/sign-up?source=tagadapay-docs-ai-store) > > Web signup, copy your API key, ship in 15 minutes. *** ## Hosting your store Once your storefront is built, you need somewhere to host it. ### Option A — Deploy on TagadaPay (recommended for SPAs) If your store is a **client-side SPA** (React, Vue, Svelte, plain HTML), deploy it directly on TagadaPay's global edge CDN with a single script. No infrastructure to set up, no billing — included with your account. **You get:** * Global edge CDN (\~10 ms TTFB) * Custom domain with automatic TLS * Built-in A/B testing (weighted or geo-based) on the same URL * Zero bandwidth bills #### Deploy with the Node SDK The `@tagadapay/node-sdk` ships a one-call deploy helper. Add this as `scripts/deploy.ts`: ```typescript theme={null} import Tagada from '@tagadapay/node-sdk'; const tagada = new Tagada(process.env.TAGADA_API_KEY!); const result = await tagada.plugins.deployDirectory({ directory: './dist', storeId: 'store_xxx', name: 'my-store', }); console.log(`Live at: ${result.url}`); // https://my-store--store_xxx.cdn.tagadapay.com/ ``` #### Run it ```bash theme={null} npm run build TAGADA_API_KEY=your-api-key npx tsx scripts/deploy.ts ``` That's it — one SDK call, store live on `https://my-store--{storeId}.cdn.tagadapay.com/`. **What `deployDirectory()` does under the hood:** 1. Scans your build directory recursively 2. Detects MIME types for 20+ file extensions (HTML, JS, CSS, images, fonts, etc.) 3. Base64-encodes and uploads all files 4. Creates a live instance for your store 5. Mounts the instance to a CDN hostname > [!NOTE] > > This is the exact flow used to deploy the [`headless-react-store`](https://github.com/TagadaPay/examples/tree/main/headless-react-store) and [`headless-react`](https://github.com/TagadaPay/examples/tree/main/headless-react) examples. Works for any SPA — React, Vue, Svelte, or plain HTML. > [!TIP] > > **Updates?** Just run the script again. New version goes live instantly — no downtime, no cache purge. #### A/B testing Deploy two versions and split traffic between them: ```typescript theme={null} import Tagada from '@tagadapay/node-sdk'; const tagada = new Tagada(process.env.TAGADA_API_KEY!); const storeId = 'store_xxx'; const versionA = await tagada.plugins.deployDirectory({ directory: './dist-a', storeId, name: 'my-store-a', }); const versionB = await tagada.plugins.deployDirectory({ directory: './dist-b', storeId, name: 'my-store-b', }); const mountPoints = await tagada.plugins.listMountPoints(storeId); const routeId = mountPoints.mountPoints[0]?.id as string; await tagada.plugins.configureSplit({ routeId, storeId, splitConfig: { type: 'weighted', instances: [ { instanceId: versionA.instanceId, deploymentId: versionA.deploymentId, weight: 50 }, { instanceId: versionB.instanceId, deploymentId: versionB.deploymentId, weight: 50 }, ], }, }); ``` #### Advanced: lower-level deploy methods For full control, use the individual methods directly: ```typescript theme={null} const plugins = await tagada.plugins.list(storeId); const instances = await tagada.plugins.listInstances(storeId); const details = await tagada.plugins.retrieveDeployment(deploymentId); await tagada.plugins.unmount({ deploymentId, storeId, hostname }); await tagada.plugins.del(pluginId, storeId); ``` `deployDirectory()` handles builds up to 50 MB automatically — small builds use inline base64, larger builds are zipped and uploaded to blob storage. For full control, use `tagada.plugins.deploy()` with `zipUrl` or `inlineAssets` directly. > [card] [Full Deploy & A/B Test guide](/developer-tools/hosting/deploy-and-ab-test) > > Custom domains, geo-based A/B testing, large file uploads, and more. ### Option B — Vercel, Netlify, or Cloudflare Pages If your app uses **server-side rendering** (Next.js, Astro, Remix, SvelteKit), deploy to a platform that supports your framework: | Platform | Best for | Deploy command | | - | - | - | | [Vercel](https://vercel.com) | Next.js, SvelteKit | `vercel --prod` | | [Netlify](https://netlify.com) | Astro, static sites | `netlify deploy --prod` | | [Cloudflare Pages](https://pages.cloudflare.com) | Any framework | `wrangler pages deploy dist/` | ### Option C — Fly.io, Railway, or Docker For apps that need a **Node.js backend** (webhooks, database, background jobs): ```bash theme={null} fly launch && fly deploy ``` > [!TIP] > > **Which should I pick?** > > * **Static SPA (React, Vue, Svelte)?** → TagadaPay hosting (simplest, free, built-in A/B testing) > * **Next.js / SSR?** → Vercel or Netlify > * **Custom backend + webhooks?** → Fly.io or Railway *** ## Resources > [card] [Storefront template (fork-ready)](https://github.com/TagadaPay/examples/tree/main/headless-react-store) > > A real-looking boutique with localStorage cart and a pro checkout. Rebrand it in a day. > [card] [SDK playground (learn-by-doing)](https://github.com/TagadaPay/examples/tree/main/headless-react) > > Every Headless SDK hook explained with side-by-side code panels. > [card] [Live demo](https://headless-react-eta.vercel.app) > > Try the playground in the browser — browse, checkout, pay with test cards. > [card] [Node SDK](/developer-tools/node-sdk/quick-start) > > Server-side automation — create stores, products, webhooks, and more. > [card] [API reference](/api-reference/introduction) > > Full REST API documentation with request/response examples. *** ## FAQ > [accordion] Can I use this with Next.js / Astro / Remix / SvelteKit? > > Yes. The Headless SDK is framework-agnostic. The React hooks (`useCheckout`, `usePayment`, etc.) work in any React app. For non-React frameworks, use the vanilla `createHeadlessClient()` API. > [accordion] Do I need a server? > > Not for the checkout flow. The Headless SDK handles everything client-side (including PCI-safe card tokenization). You only need a server if you want webhooks or custom automation — use the Node SDK for that. > [accordion] Is card data safe? > > Yes. Card numbers are tokenized by `@tagadapay/core-js` before they reach your code. Your store never sees or stores raw card data. TagadaPay is PCI DSS Level 1 compliant. > [accordion] Can I use Lovable to generate the entire store? > > Yes. Give Lovable the prompt from Step 2 and it will generate a working storefront. You'll just need to paste your Store ID and deploy. > [accordion] How do subscriptions work? > > Create a product with a recurring price (`interval: 'month'`). The Headless SDK handles the initial charge. TagadaPay automatically rebills, retries failed charges (dunning), and sends email receipts on each cycle. Manage subscriptions from the CRM dashboard or the Node SDK. > [accordion] Can I process test payments? > > Yes. Use a sandbox processor or Stripe test mode. Test card: `4242 4242 4242 4242`, any future expiry, any CVC. > [accordion] What does TagadaPay actually cost? > > Per-transaction pricing — no monthly fees. See [tagadapay.com/pricing](https://tagadapay.com/pricing) for current rates and check the rate displayed on your account dashboard. *** > [card] [Start building — terminal flow](#fastest-path--clone--ship-3-commands) > > `npx -p @tagadapay/node-sdk tagada-init you@example.com` — verify your email, get a sandbox account + API key + seeded store, all without leaving your terminal. > [card] [Or use the web signup](https://app.tagada.io/sign-up?source=tagadapay-docs-ai-store) > > Sign up at app.tagada.io, copy your API key from Settings → Access Tokens. Same outcome, no credit card required. # Catalog Source: https://docs.tagada.io/developer-tools/headless-sdk/catalog Browse products, variants, and prices from your store # Catalog The catalog module lets you fetch products, variants, and prices from your TagadaPay store. Use it to build product listing pages, product detail pages, and dynamic carts. *** ## List Products ```typescript theme={null} const products = await tagada.catalog.getProducts(); ``` ### Filter by IDs ```typescript theme={null} const filtered = await tagada.catalog.getProducts({ productIds: ['prod_xxx'], variantIds: ['var_xxx'], }); ``` *** ## Get a Single Product ```typescript theme={null} const product = await tagada.catalog.getProduct('prod_xxx'); // Returns CatalogProduct or null if not found ``` *** ## Types ### `CatalogProduct` ```typescript theme={null} interface CatalogProduct { id: string; name: string; description?: string; active: boolean; variants: CatalogVariant[]; } ``` ### `CatalogVariant` ```typescript theme={null} interface CatalogVariant { id: string; productId: string; name: string; description?: string; sku?: string; price?: number; currency?: string; compareAtPrice?: number; imageUrl?: string; active: boolean; inStock: boolean; prices: CatalogPrice[]; } ``` ### `CatalogPrice` ```typescript theme={null} interface CatalogPrice { id: string; variantId?: string; default: boolean; currencyOptions: Record; recurring: boolean; interval?: string; // 'day', 'month', 'year' intervalCount?: number; } ``` > [!NOTE] > > Prices use `currencyOptions` — a map of currency codes to amounts in cents. For example, `{ USD: { amount: 3900 }, EUR: { amount: 3500 } }` means \$39.00 / 35.00. *** ## React Hook ```tsx theme={null} import { useCatalog } from '@tagadapay/headless-sdk/react'; function ProductList() { const { products, isLoading, error, loadProducts, loadProduct } = useCatalog(); useEffect(() => { loadProducts(); }, [loadProducts]); if (isLoading) return

Loading...

; if (error) return

Error: {error.message}

; return (
{products.map((product) => (

{product.name}

{product.variants.map((v) => (
{v.imageUrl && {v.name}} {v.name} {(v.prices[0]?.currencyOptions.USD?.amount ?? 0) / 100} USD
))}
))}
); } ``` ### Full Hook API | Property / Method | Description | | - | - | | `products` | Array of loaded products (empty until `loadProducts` is called) | | `isLoading` | True during any async operation | | `error` | Last error, if any | | `loadProducts(opts?)` | Fetch all products. Optional filter: `{ productIds?, variantIds? }` | | `loadProduct(productId)` | Fetch a single product by ID | # Checkout Flow Source: https://docs.tagada.io/developer-tools/headless-sdk/checkout-flow Manage checkout sessions, cart, promo codes, and shipping # Checkout Flow The checkout module manages the full session lifecycle -- load a session, update the cart, apply promo codes, and handle shipping. *** ## Load a Checkout Session A checkout session is typically created by the Node SDK on your server, then the token is passed to the frontend via URL parameter. ```typescript theme={null} // Token from URL: /checkout?checkoutToken=ct_abc123&token=eyJ... const checkoutToken = new URLSearchParams(window.location.search).get('checkoutToken'); const sessionToken = new URLSearchParams(window.location.search).get('token'); const session = await tagada.checkout.loadSession(checkoutToken, sessionToken); // session.id -- session ID (use for all subsequent calls) // session.items -- line items in the cart // session.totals -- subtotal, discount, shipping, tax, total // session.customer -- customer info if available // session.currency -- session currency (USD, EUR, etc.) ``` *** ## Create a Checkout Session (Client-Side) From a landing / cart page, create a session and send the shopper to **your** checkout. Pin the variant you sell — do not pick "whatever is in the catalog": ```typescript theme={null} const { url } = await tagada.checkout.createSessionUrl({ items: [{ variantId: 'var_xxx', quantity: 1 }], checkoutPath: '/checkout', // Page that hosts usePayment / maybeResumeFromUrl — 3DS returns here. returnUrl: 'https://mystore.com/checkout', }); window.location.href = url; // your origin, not checkoutUrl // → https://yoursite.com/checkout?checkoutToken=...&sessionToken=... ``` On `/checkout`, read both query names (`sessionToken` from `createSessionUrl`, `token` from a Tagada-hosted redirect): ```typescript theme={null} const tokens = tagada.checkout.parseTokensFromUrl(); if (!tokens) { window.location.href = '/'; } const session = await tagada.checkout.loadSession(tokens.checkoutToken, tokens.sessionToken); ``` `createSession()` is the same call without building the URL. It also returns `checkoutUrl` — that one is the **Tagada-hosted** checkout, not your page. ```typescript theme={null} const created = await tagada.checkout.createSession({ items: [{ variantId: 'var_xxx', quantity: 1 }], currency: 'USD', returnUrl: 'https://mystore.com/checkout', }); // created.checkoutToken / created.sessionToken — load this session on YOUR page // created.checkoutUrl — Tagada-hosted URL. Do NOT redirect here when self-hosting. ``` > [!WARNING] > > Headless **cannot set** `checkoutUrl`. It is generated by Tagada (plugin domain, funnel, or `store-unavailable`). On a self-hosted checkout, stay on your page and call `loadSession()`. To hop from a cart page to your own checkout path, use `createSessionUrl()` as above. *** ## Discount codes + affiliate attributes at hand-off When the cart lives on **your own site** (landing page, custom storefront, or server-rendered cart) and you send shoppers to **Tagada hosted checkout**, create the session on your side first, then redirect. Pass promo codes and attribution data **at session creation** so they land on the order as attributes and in the `order/paid` webhook — you do not need to call the raw REST endpoint yourself. ```typescript theme={null} const { checkoutUrl } = await tagada.checkout.createSession({ items: [{ variantId: 'var_xxx', quantity: 1 }], currency: 'USD', returnUrl: 'https://mystore.com/thank-you', discountCodes: ['SAVE10'], metadata: { cartCustomAttributes: [ { name: 'affiliate_id', value: 'partner_42' }, { name: 'campaign', value: 'spring_sale' }, ], }, customerMetadata: { queryParams: '?ref=partner&utm_source=fb&utm_campaign=spring', cookies: { _fbp: 'fb.1.1234567890' }, }, customerTags: ['affiliate'], }); // Redirect the shopper to Tagada hosted checkout window.location.href = checkoutUrl; ``` | Field | Purpose | | - | - | | `discountCodes` | Pre-apply promotion codes before the customer lands on checkout | | `metadata.cartCustomAttributes` | Custom order note attributes (visible in CRM → Order → Attributes) | | `customerMetadata.queryParams` | Persist `ref`, `utm_*`, and other query params on the customer/session | | `customerMetadata.cookies` | Snapshot affiliate cookies (e.g. Meta `_fbp`) | | `customerTags` | Tags for funnel routing (`customer.hasTag` conditions) | When you **self-host** the checkout page, pass the same fields on `createSessionUrl()` — attribution is applied at init before the shopper lands on your `/checkout`: ```typescript theme={null} const { url } = await tagada.checkout.createSessionUrl({ items: [{ variantId: 'var_xxx', quantity: 1 }], checkoutPath: '/checkout', returnUrl: 'https://mystore.com/checkout', discountCodes: ['SAVE10'], metadata: { cartCustomAttributes: [ { name: 'affiliate_id', value: 'partner_42' }, { name: 'campaign', value: 'spring_sale' }, ], }, customerMetadata: { queryParams: '?ref=partner&utm_source=fb&utm_campaign=spring', cookies: { _fbp: 'fb.1.1234567890' }, }, customerTags: ['affiliate'], }); window.location.href = url; // → https://yoursite.com/checkout?checkoutToken=...&sessionToken=... ``` *** ## Update Cart ```typescript theme={null} const updated = await tagada.checkout.updateCart(session.id, [ { variantId: 'var_xxx', quantity: 2 }, { variantId: 'var_yyy', quantity: 1 }, ]); // updated.totals reflects the new cart ``` *** ## Customer & Address The SDK uses a two-step pattern: first set customer identity, then set the address. Under the hood, both are sent in a single atomic API call when `updateAddress()` is called. ### Set Customer Info `updateCustomer()` stores email, name, and phone **in memory**. No API call is made yet — the data is sent together with the address in the next step. ```typescript theme={null} await tagada.checkout.updateCustomer(session.id, { email: 'jane@example.com', firstName: 'Jane', lastName: 'Doe', phone: '+33612345678', }); ``` ### Set Address `updateAddress()` sends customer info + address together in one atomic API call. The customer's `firstName`, `lastName`, and `phone` are automatically included in the address fields. > [tab] Shipped Product > > ```typescript theme={null} > // Billing defaults to shipping automatically > await tagada.checkout.updateAddress(session.id, { > shippingAddress: { > line1: '123 Main St', > city: 'San Francisco', > state: 'CA', > postalCode: '94102', > country: 'US', > }, > }); > ``` > [tab] Digital Product > > ```typescript theme={null} > // No shipping needed — just billing country for tax calculation > await tagada.checkout.updateAddress(session.id, { > billingAddress: { > country: 'US', > }, > }); > ``` > [tab] Separate Billing > > ```typescript theme={null} > // Different billing and shipping addresses > await tagada.checkout.updateAddress(session.id, { > shippingAddress: { > line1: '123 Main St', > city: 'San Francisco', > postalCode: '94102', > country: 'US', > }, > billingAddress: { > line1: '456 Oak Ave', > city: 'New York', > postalCode: '10001', > country: 'US', > }, > }); > ``` ### Combined Method If you prefer a single explicit call: ```typescript theme={null} await tagada.checkout.updateCustomerAndAddress(session.id, { customer: { email: 'jane@example.com', firstName: 'Jane', lastName: 'Doe', }, shippingAddress: { line1: '123 Main St', city: 'San Francisco', postalCode: '94102', country: 'US', }, }); ``` > [!NOTE] > > **Address fields:** `firstName`, `lastName`, `phone` can be passed directly in the address object too — they override the values from `updateCustomer()`. *** ## Promo Codes ```typescript theme={null} // Apply await tagada.checkout.applyPromoCode(session.id, 'SAVE20'); // Remove await tagada.checkout.removePromoCode(session.id); // Reload session to see updated totals const updated = await tagada.checkout.loadSession(checkoutToken, sessionToken); console.log(updated.totals.discount); // discount amount in cents ``` ### What each total means All amounts are in minor units (cents) in `totals.currency`. | Field | Meaning | | - | - | | `subtotal` | Line items before any promotion. An order-level promotion (e.g. "\$5 off") does **not** change it — look at `discount`. | | `discount` | Total promotion amount applied to the order, as a positive number. | | `shipping` | Selected shipping rate (`0` when none is selected or it is free). | | `tax` | Tax, computed on the discounted base. | | `total` | What the customer is charged: `subtotal − discount + shipping + tax`. | `total` is the same number the hosted checkout shows and the order is charged for — do not recompute it client-side. *** ## Shipping ```typescript theme={null} // Get available rates (requires address to be set first) const rates = await tagada.checkout.getShippingRates(session.id); // [{ id: 'rate_xxx', name: 'Standard', amount: 499, estimatedDays: 5 }] // Select a rate await tagada.checkout.selectShippingRate(session.id, rates[0].id); ``` > [!TIP] > > For **digital products**, skip shipping entirely — go straight from `updateAddress()` to payment. *** ## React Hook ```tsx theme={null} import { useCheckout } from '@tagadapay/headless-sdk/react'; function CheckoutPage() { const { session, isLoading, error, refresh, createSession, updateCart, updateCustomer, updateAddress, applyPromo, removePromo, getShippingRates, selectShippingRate, } = useCheckout(checkoutToken, sessionToken); // All methods auto-refresh the session after completion } ``` On a **landing page** there is no token yet — pass `null` and use `createSessionUrl` on the CTA: ```tsx theme={null} import { useCheckout, parseTokensFromUrl } from '@tagadapay/headless-sdk/react'; function LandingPage() { const { createSessionUrl } = useCheckout(null); async function buyNow() { const { url } = await createSessionUrl({ items: [{ variantId: 'variant_xxx', quantity: 1 }], checkoutPath: '/checkout', discountCodes: ['SAVE10'], metadata: { cartCustomAttributes: [{ name: 'affiliate_id', value: 'partner_42' }], }, customerMetadata: { queryParams: '?ref=partner&utm_source=fb' }, customerTags: ['affiliate'], }); window.location.href = url; } return ; } function CheckoutPage() { // The tokens arrive in the URL from the landing redirect const tokens = parseTokensFromUrl(); const { session } = useCheckout(tokens?.checkoutToken, tokens?.sessionToken); // ... } ``` ### Full Hook API | Method | Description | | - | - | | `session` | Current checkout session (null until loaded) | | `isLoading` | True during any async operation | | `error` | Last error, if any | | `refresh()` | Reload the session | | `createSession({ items, currency, returnUrl?, discountCodes?, metadata?, customerMetadata?, customerTags? })` | Create a session and load it in place (same page) | | `createSessionUrl({ items, checkoutPath?, returnUrl?, discountCodes?, metadata?, customerMetadata?, customerTags? })` | Create a session and get a redirect URL to your `/checkout` page — use on the landing CTA, then `window.location.href = url` | | `updateCart(items)` | Replace cart items | | `updateCustomer({ email, firstName, lastName, phone })` | Store customer identity (in memory) | | `updateAddress({ shippingAddress?, billingAddress? })` | Set addresses + persist customer data (single API call) | | `applyPromo(code)` | Apply a promo code | | `removePromo(promotionId?)` | Remove a promo code | | `getShippingRates()` | Fetch available shipping rates | | `selectShippingRate(rateId)` | Select a shipping rate | # Coded Funnels Source: https://docs.tagada.io/developer-tools/headless-sdk/coded-funnels Declare the steps of a funnel you code yourself, see them as cards on the canvas, and let TagadaPay fire your pixels on them # Coded Funnels A **coded funnel** is a funnel whose pages you build yourself — a React app, a Next.js site, a page generated by Claude Code or Lovable — with the Headless SDK doing the checkout. You describe its steps once in a file, `tagada.funnel.ts`, and push it. Each step then appears as a card on the [canvas](/developer-tools/funnels/canvas) of your store, next to the pages TagadaPay hosts, and you bind your pixels (Meta, TikTok, Snapchat, Google Tag Manager, Microsoft Clarity) to its events from there. Your code reports where the visitor is with one call per step; TagadaPay loads the pixels and fires them. Three pieces work together: | Piece | Package | What it does | | - | - | - | | `tagada.funnel.ts` + `npx tagada funnel push` | `@tagadapay/node-sdk` | Declares the funnel and its steps. Each step becomes a card on the canvas. | | `tagada.track` / `useStep` | `@tagadapay/headless-sdk` | Runs in the browser: reports the step the visitor is on and the events that happen there, and fires the pixels bound to them. | | The step card on the canvas | CRM | Where you choose which pixel hears which event. The card is read-only otherwise: the code owns the step. | > [!NOTE] > > **Coded funnel or external step?** An [external step](/developer-tools/node-sdk/external-steps) is one page of yours added to a funnel TagadaPay hosts, reported from your server or with `curl`. A coded funnel is the whole journey in your code, declared by a manifest, with pixels fired in the browser by the SDK. They are two separate mechanisms and do not share cards. **Requirements** * `@tagadapay/headless-sdk` **1.16.0** or later (1.15.0 introduced `track` but was never published to npm); **1.18.0** for the React provider form shown below. * `@tagadapay/node-sdk` **3.23.0** or later, as a dev dependency: it carries `defineFunnel` and the `tagada` command. **3.26.0** or later reads your credentials from `.env` files and prints the pixel origins in `funnel csp`. * A secret API key and your store id — see [Get an API key](/developer-tools/node-sdk/get-api-key). The key is only used by the command line, never in the browser. * Node.js 22.18 or later to load a `.ts` manifest. On an older Node, name the file `tagada.funnel.mjs` or write `tagada.funnel.json`. *** ## 1. Install ```bash theme={null} npm install @tagadapay/headless-sdk npm install --save-dev @tagadapay/node-sdk ``` *** ## 2. Declare the funnel Create `tagada.funnel.ts` at the root of your project (the command looks for `tagada.funnel.ts`, `.mjs`, `.js`, then `.json` in the current directory): ```typescript theme={null} import { defineFunnel } from '@tagadapay/node-sdk'; export default defineFunnel({ key: 'main', name: 'Main funnel', domains: ['shop.example.com', 'www.shop.example.com'], steps: [ { id: 'landing', type: 'page', name: 'Landing', path: '/', image: 'shots/landing.png', file: 'src/routes/index.tsx' }, { id: 'quiz', type: 'page', name: 'Quiz', path: '/quiz', events: [{ name: 'quiz_completed', title: 'Quiz completed', variables: { goal: 'string' } }], }, { id: 'email', type: 'lead', name: 'Email capture', path: '/email' }, { id: 'product', type: 'product', name: 'Product', path: '/products/:handle' }, { id: 'checkout', type: 'checkout', name: 'Checkout', path: '/checkout' }, { id: 'thanks', type: 'thankyou', name: 'Thank you', path: '/thank-you' }, ], }); ``` `defineFunnel` checks the whole manifest and throws one `TagadaValidationError` that lists every problem with its path (`steps[2].events[0].name: …`). `validateManifest` runs the same checks and returns `{ ok, errors }` instead of throwing. ### The funnel | Field | Required | What it is | | - | - | - | | `key` | yes | The funnel's id within the store. Pass the same value as the `funnel` option of the Headless SDK client. A store can have several coded funnels. | | `name` | yes | The name shown on the canvas. | | `domains` | yes | The hosts the funnel runs on: `shop.example.com`, no scheme, no path, no port. Events from a host that is not listed are ignored. `localhost` and `127.0.0.1` are always accepted and must not be listed; an empty array means "local only". | | `steps` | yes | The steps, in the order the canvas draws them. At least one. | ### A step | Field | Required | What it is | | - | - | - | | `id` | yes | The id your code passes to `track.step()`. It is how TagadaPay matches a visit to a card. | | `type` | yes | `page`, `product`, `cart`, `lead`, `checkout`, `thankyou` or `portal`. The type decides which pixel events the step offers by default (table below). | | `name` | yes | The card's title. | | `path` | yes | The route, starting with `/`. A dynamic route is one step: `/products/:handle`. Shown on the card only — a visit is matched by `id`, never by URL. | | `next` | no | The ids of the steps that follow. Omitted, the next step in the array; the last step has none. The literal `'@hosted'` means "continues into the hosted TagadaPay funnel of this canvas". | | `events` | no | The custom events this step reports, each `{ name, title?, variables? }`. `variables` maps a property name to `'string'`, `'number'` or `'boolean'`. | | `image` | no | A screenshot for the card: a local `.png`, `.jpg`/`.jpeg` or `.webp` file (uploaded by `funnel push`, 3 MB max) or an `https://` URL. | | `file` | no | The source file of the step, shown on the card so a teammate knows where to look. | ### Step types and their default events Every step has a **Page view** event. The type adds the standard events a step of that kind usually has: | `type` | Events the card offers by default | | - | - | | `page`, `thankyou`, `portal` | Page view | | `lead` | Page view, Lead | | `product` | Page view, ViewContent, AddToCart | | `cart` | Page view, AddToCart | | `checkout` | Page view, InitiateCheckout, Purchase | ### Names and limits * `key`, step `id` and event `name`: lowercase letters, digits, `-` and `_`, starting with a letter or a digit, 64 characters max (`/^[a-z0-9][a-z0-9_-]{0,63}$/`). * Reserved event names, refused because TagadaPay emits them itself: `page_view`, `checkout_started`, `purchase`, `checkoutStarted`, `cartAbandoned`, `paid`, `paymentFailed`, `orderConfirmed`, and anything starting with `checkout/`, `order/`, `payment/`, `subscription/` or `club/`. * 60 steps per funnel, 12 events per step, 20 variables per event, 20 domains, names up to 120 characters, `path` up to 512 characters. *** ## 3. Report the steps Pass the funnel `key` to the client, then call `track.step()` once when the visitor reaches a step. > [tab] JavaScript > > ```typescript theme={null} > import { createHeadlessClient } from '@tagadapay/headless-sdk'; > > export const tagada = createHeadlessClient({ > storeId: 'store_abc123', > funnel: 'main', // the manifest key; defaults to 'main' > }); > > // On the quiz page: > tagada.track.step('quiz'); > ``` > [tab] React > > ```tsx theme={null} > import { TagadaHeadlessProvider, useStep } from '@tagadapay/headless-sdk/react'; > > function App() { > return ( > > > > ); > } > > function QuizPage() { > useStep('quiz'); > return ; > } > ``` > > The provider has no `funnel` prop: pass it inside `config`, which replaces the individual props, `storeId` included. The client is rebuilt only when a value of `config` changes, so an inline object is fine. What `track.step()` does: * It fires the **Page view** of every pixel bound to that step. `path` defaults to `location.pathname`; pass `track.step('product', { path: '/products/blue-hoodie' })` to report another one. * Two calls for the same step and path within one second count once, so React StrictMode and two components of the same screen calling `useStep('quiz')` are safe. * Every later `track.event()` belongs to this step, until the next `track.step()`. > [!WARNING] > > **Use one client per page.** The checkout session and the tracking state live inside the client. If you create your own client with `createHeadlessClient`, do not also mount `TagadaHeadlessProvider`: it builds a second client, which loads the tracking configuration twice and does not see your checkout session. With your own client, call `tagada.track.step(id)` in a `useEffect` instead of using `useStep`. *** ## 4. Report events ```typescript theme={null} tagada.track.event('quiz_completed', { goal: 'sleep' }); tagada.track.event('lead', { email }); ``` Three names have a meaning for every pixel and are sent as the provider's standard event: | SDK name | Standard pixel event | | - | - | | `lead` | `Lead` | | `product_viewed` | `ViewContent` | | `added_to_cart` | `AddToCart` | Any other name is a **custom event**: declare it in the step's `events`, then bind it on the canvas. A custom event reaches no pixel until you bind it. A step only offers its Page view, the default events of its type and the events it declares. To send `lead` from a `page` step, for example, add `{ name: 'lead' }` to that step's `events`; an event the step does not offer reaches no pixel. * The properties must be flat: strings, numbers, booleans. A nested object or array is dropped, not stringified. * An event sent before the first `track.step()` of the page belongs to no step and is dropped. * Do not report `InitiateCheckout` or `Purchase` yourself — see [Checkout and purchase](#checkout-and-purchase). *** ## 5. Push the manifest ```bash .env theme={null} # or .env.local, at the root of your project — never shipped to the browser TAGADA_API_KEY=sk_... TAGADA_STORE_ID=store_abc123 ``` ```bash theme={null} npx tagada funnel push ``` ``` created landing created quiz created email created product created checkout created thanks ``` The command validates the manifest, declares the funnel, uploads the local screenshots, and prints one line per step: `created`, `updated`, `unchanged` or `removed`, then any warning. | Flag | Default | What it does | | - | - | - | | `--api-key=` | `TAGADA_API_KEY` | The secret API key. | | `--store=` | `TAGADA_STORE_ID` | The store id. | | `--base-url=` | production | Another TagadaPay host, for example a staging environment. | | `--dry-run` | — | Prints the normalized manifest and its hash, sends nothing, needs no key. | * Pushing an unchanged manifest does nothing. Push again whenever you add, rename or remove a step. * A step you remove from the manifest disappears from the canvas. If you add it back with the same `id`, it comes back with the pixels you had bound to it. * The key and the store id come from the flags first, then from environment variables, then from `.env.local`, then from `.env` in the current directory. Nothing is ever written to those files. * `npx tagada ` creates a sandbox account if you do not have one yet and writes `TAGADA_API_KEY` and `TAGADA_STORE_ID` to `.env`, so `funnel push` works right after it. From code, the same calls are on the Node SDK client: `tagada.funnels.declare(storeId, manifest)`, `tagada.funnels.uploadStepImage(storeId, key, stepId, { base64, contentType })` and `tagada.funnels.health(storeId, key?)`. `defineFunnel`, `validateManifest` and the CSP helpers are also exported from `@tagadapay/node-sdk/edge`, which has no Node.js import and runs on Cloudflare Workers, Vercel Edge and Deno. *** ## 6. Bind your pixels on the canvas Open the canvas of the store: the steps are there as cards with an **SDK** badge, in the order of the manifest, wired by `next`. A step nobody has reached yet carries a **Never seen** pill. **On the first push, TagadaPay binds the default events for you.** For every pixel integration the store has enabled (Meta, TikTok, Snapchat, Google Tag Manager, Microsoft Clarity), each new step gets its Page view and the default events of its type. This happens once per step: an event you unbind stays unbound on every later push. Custom events are never bound automatically. If the store has no pixel integration yet, nothing is bound, and the first push after you connect one does it. To change what fires, open a step card and switch pixels on or off per event. Through the API this is a [`bind`](/developer-tools/funnels/canvas#bind) command whose `target` is `{ "kind": "node", "nodeId": "" }` and whose `event` is one the step offers (`PageView`, a default event of its type, or one it declares — a declared `lead` binds as `Lead`). Any other command on an SDK card is refused with [`sdk-node-read-only`](/developer-tools/funnels/canvas#sdk-node-read-only), and an undeclared event with [`sdk-unknown-event`](/developer-tools/funnels/canvas#sdk-unknown-event): the step itself only changes through the manifest. > [!NOTE] > > A coded funnel loads Meta, TikTok, Snapchat, Google Tag Manager and Microsoft Clarity. Pinterest is not available there. *** ## Checkout and purchase You never send these two yourself. Once tracking is on (after a first `track.step()`), the SDK fires them from its own checkout and payment modules: * **InitiateCheckout** when `checkout.loadSession()` loads a checkout session, with the session's amount, currency and items. * **Purchase** when a payment made through the SDK reaches `succeeded`, directly or after a 3DS redirect. A payment that is only authorized is not a purchase and fires nothing. Both carry the same event id as the server-side events TagadaPay sends for that checkout and that order (`InitiateCheckout_`, `Purchase_`), so Meta and TikTok count each one once. They fire on the pixels bound to InitiateCheckout and Purchase on the checkout step. If your checkout step continues into a hosted TagadaPay page (`next: ['@hosted']`), the SDK does not fire Purchase: the hosted thank-you page fires it, and Snapchat, Google Tag Manager and Clarity have no event id to deduplicate a second one. *** ## Identify and consent ```typescript theme={null} tagada.track.identify({ email, phone, customerId }); tagada.track.consent({ marketing: false }); ``` * `identify` hands the visitor's email, phone and TagadaPay customer id to the pixels for their advanced matching. * Pixels fire without waiting for consent. `consent({ marketing: false })` stops them for the rest of the page and drops the events still waiting; a later `consent({ marketing: true })` on the same page does not turn them back on. Call it as soon as your consent banner knows the answer. *** ## What changes when you upgrade Nothing, until you call `track.step()`. The SDK makes no tracking request and loads no pixel before that first call, so a site that upgrades without touching its code behaves exactly as before. * The first `track.step()` turns tracking on for this browser and this store (a `__tgd_track` entry in `localStorage`). From then on, the checkout and purchase pixels above fire on later page loads too. * Every tracking method returns at once on the server, so server-side rendering is safe. * The pixel code is not in the main bundle: it is loaded on first use. With the CDN script tag, it is a second file, `tagada-pixels.min.js`, fetched from jsDelivr. * Tracking never throws. A blocked pixel or a failed request is recorded and reported in [SDK health](/developer-tools/headless-sdk/sdk-health), never surfaced to the visitor. * If your site sends a Content-Security-Policy, allow the pixel origins listed in [Content-Security-Policy](/developer-tools/headless-sdk/csp). *** ## Check that it works In the browser, `await tagada.track.health()` tells you what this page did: whether tracking is on, the funnel key, the pixels loaded, and what was blocked. ```typescript theme={null} const health = await tagada.track.health(); // { enabled: true, storeId: 'store_abc123', funnelKey: 'main', // sdk: { name: 'headless', version: '1.17.0' }, // manifestHash: '…', pixels: { loaded: true, providers: ['facebook', 'tiktok'] }, signals: [] } ``` From your terminal, `npx tagada funnel check` tells you what TagadaPay has seen from every visitor: steps never reached, events never received, pixels blocked, an outdated SDK, a wallet domain not registered. Each check is explained on [SDK health](/developer-tools/headless-sdk/sdk-health). *** ## The endpoints behind it The SDKs call these routes; you do not need to call them yourself. They are listed so you know what leaves your site. They are not in the API Reference tab. | Route | Called by | Auth | What it does | | - | - | - | - | | `PUT /api/public/v1/sdk/funnels/{key}` | `funnel push`, `funnels.declare()` | Secret API key | Declares the funnel and its steps. | | `PUT /api/public/v1/sdk/funnels/{key}/steps/{stepId}/image` | `funnel push`, `funnels.uploadStepImage()` | Secret API key | Uploads a step screenshot (base64 JSON). | | `GET /api/public/v1/sdk/health?storeId=&funnel=` | `funnel check`, `funnels.health()` | Secret API key | The health report. | | `GET /api/public/v1/sdk/config?storeId=&funnel=` | The browser, once per page | None | Which pixels to load and which events of each step they hear. Cached 60 seconds. | | `POST /api/public/v1/sdk/events` | The browser (`sendBeacon`) | None | Which steps were seen, which events arrived, which pixels were blocked. | The two browser routes take no API key and no custom header, so they work from any domain without a CORS preflight. They only accept data for hosts listed in `domains` (plus `localhost`), never carry a payment, and answer the same way for a store that does not exist. A request to them that carries an `Authorization` header is reported in SDK health as a secret key used from a browser. # Content-Security-Policy Source: https://docs.tagada.io/developer-tools/headless-sdk/csp The origins your CSP must allow for a TagadaPay checkout and for the pixels of a coded funnel # Content-Security-Policy If your site sends a Content-Security-Policy (a `Content-Security-Policy` header or `` tag), the browser refuses every script, request, frame or image from an origin the policy does not list. A Headless SDK checkout needs two sets of origins: 1. **The checkout itself** — TagadaPay, Basis Theory (card tokenization) and Stripe (express checkout). Always the same. 2. **The pixels of your [coded funnel](/developer-tools/headless-sdk/coded-funnels)** — Meta, TikTok, Snapchat, Google Tag Manager, Microsoft Clarity: only those you bound on the canvas are needed. They are listed per provider [below](#pixels). `npx tagada funnel csp` prints both. A site without a CSP has nothing to do. *** ## From the command line ```bash theme={null} npx tagada funnel csp --pixels=facebook,tiktok ``` ``` connect-src https://*.tagada.io https://*.tagada.dev https://*.tagadapay.com https://js.basistheory.com https://*.basistheory.com https://api.stripe.com https://r.stripe.com https://www.facebook.com https://analytics.tiktok.com script-src https://*.tagada.io https://*.tagada.dev https://*.tagadapay.com https://js.basistheory.com https://js.stripe.com https://*.js.stripe.com https://connect.facebook.net https://analytics.tiktok.com frame-src https://*.tagada.io https://*.tagada.dev https://*.tagadapay.com https://*.basistheory.com https://js.stripe.com https://*.js.stripe.com https://hooks.stripe.com img-src https://*.tagada.io https://*.tagadapay.com data: https://www.facebook.com https://analytics.tiktok.com ``` Each line is a directive: the checkout origins first, then those of the pixels. | Flag | What it does | | - | - | | `--pixels=facebook,tiktok` | Only the pixels named: `facebook` (Meta), `tiktok`, `snapchat`, `gtm` (Google Tag Manager), `clarity`. Without the flag, all five. `--pixels=` alone keeps the checkout origins only. An unknown name stops the command with an error. | | `--format=header` | One line, `;`-separated, ready to paste into a header value. | The command needs no API key. It requires `@tagadapay/node-sdk` 3.26.0 or later; earlier versions print the checkout origins only. ## From code `@tagadapay/node-sdk` (and `@tagadapay/node-sdk/edge`, for edge runtimes) exports the checkout origins as `CSP_ORIGINS`, and `withTagadaCsp(policy)` merges them into your own directives without duplicates. They do not include the pixels: add the rows of the [table below](#pixels) yourself. ```typescript theme={null} // next.config.ts import { withTagadaCsp } from '@tagadapay/node-sdk'; const directives = withTagadaCsp({ 'default-src': ["'self'"], 'script-src': ["'self'"], 'connect-src': ["'self'"], }); const csp = Object.entries(directives) .map(([directive, values]) => `${directive} ${values.join(' ')}`) .join('; '); export default { async headers() { return [{ source: '/(.*)', headers: [{ key: 'Content-Security-Policy', value: csp }] }]; }, }; ``` > [!NOTE] > > If you load the SDK with the CDN script tag, also allow `https://cdn.jsdelivr.net` in `script-src`: the SDK and its pixel file, `tagada-pixels.min.js`, are served from there. *** ## Pixels Add the rows of every provider you bound on the canvas: | Provider | `script-src` | `connect-src` | `img-src` | `frame-src` | | - | - | - | - | - | | Meta | `https://connect.facebook.net` | `https://www.facebook.com` | `https://www.facebook.com` | — | | TikTok | `https://analytics.tiktok.com` | `https://analytics.tiktok.com` | `https://analytics.tiktok.com` | — | | Snapchat | `https://sc-static.net` | `https://tr.snapchat.com` | `https://tr.snapchat.com` | — | | Google Tag Manager / GA4 / Google Ads | `https://www.googletagmanager.com` | `https://*.google-analytics.com` `https://*.analytics.google.com` `https://stats.g.doubleclick.net` | `https://www.googletagmanager.com` `https://*.google-analytics.com` `https://googleads.g.doubleclick.net` `https://www.google.com` | `https://www.googletagmanager.com` | | Microsoft Clarity | `https://www.clarity.ms` | `https://*.clarity.ms` `https://c.bing.com` | `https://c.clarity.ms` | — | Google Tag Manager loads whatever tags your container holds: if one of them calls another vendor, that vendor's origins are needed too. *** ## When something is still blocked A pixel the CSP blocks is reported by the SDK and shows up in [SDK health](/developer-tools/headless-sdk/sdk-health) as **Pixel blocked by your CSP**, with the provider and the domain it failed on. On the page itself, the browser console names the refused URL and the directive that refused it, and `await tagada.track.health()` lists the blocked pixels. # Customer Source: https://docs.tagada.io/developer-tools/headless-sdk/customer Customer profiles, order history, and subscription management # Customer The customer module gives you access to customer profiles, order history, and subscriptions. Use it to build account dashboards, order tracking pages, and subscription management UIs. > [!TIP] > > Building a full account area — email-code login, subscription changes, cancellation with retention offers, addresses, cards? See [Customer Portal](/developer-tools/headless-sdk/customer-portal). *** ## Get Customer Profile ```typescript theme={null} const customer = await tagada.customer.getProfile(customerId); ``` ### By Email Not available. No route finds a customer by email from a storefront: the only email search needs a secret API key of the whole account, which must never ship to a browser. From 1.18.0, `getByEmail()` rejects with a `TagadaError` of code `not_supported` without sending a request (before, it always returned `null`). For the logged-in customer, use [`portal.getMe()`](/developer-tools/headless-sdk/customer-portal#read-the-portal) or `getProfile(customerId)`. *** ## Update Email ```typescript theme={null} const updated = await tagada.customer.updateProfile(customerId, { email: 'jane@example.com', }); ``` This is the checkout's email step: only `email` is saved, other fields are ignored. To change the name and phone of a logged-in customer, use [`portal.updateProfile`](/developer-tools/headless-sdk/customer-portal#account). *** ## Orders ### List Orders ```typescript theme={null} const { orders, total } = await tagada.customer.getOrders(customerId, { limit: 10, offset: 0, }); ``` Newest first. It needs a session of that same customer: the checkout session, or a [portal login](/developer-tools/headless-sdk/customer-portal#log-in). Another customer's id rejects with `TagadaNotFoundError`. The route sends every order at once: `limit` and `offset` slice them in the SDK, and `total` counts them all. Works from 1.18.0; earlier versions called a route that does not exist. ### Get Single Order ```typescript theme={null} const order = await tagada.customer.getOrder(orderId); // order.items — line items on this order // order.relatedOrders — child orders from accepted upsells // (metadata.mainOrderId === order.id) ``` ### Get an Order on the Thank-You Page Accepted post-purchase offers create **separate child orders**, not extra lines on the main order — and they land **asynchronously**. The first fetch right after an accept usually misses them. Pass `waitForRelatedOrders: true` and the SDK polls for you: ```typescript theme={null} const order = await tagada.customer.getOrder(orderId, { waitForRelatedOrders: true, // polls until relatedOrders is non-empty timeoutMs: 8000, // optional, default 8000 intervalMs: 2000, // optional, default 2000 }); // Render one block per order: const allOrders = [order, ...(order.relatedOrders ?? [])]; ``` > [!NOTE] > > On timeout the latest snapshot is returned — it never throws. A customer who > declined every offer simply gets an order with an empty `relatedOrders` after > `timeoutMs`. In React, prefer the [`useOrder` hook](#useorder--thank-you-pages) > which renders the main order immediately and fills in the upsells in the > background. Worked example: [Basic post-purchase](/developer-tools/funnel-demos/basic-post-purchase#thank-you-related-orders). *** ## Subscriptions ### List Subscriptions ```typescript theme={null} const subscriptions = await tagada.customer.getSubscriptions(customerId); ``` The 20 most recent subscriptions of the logged-in customer. It needs the customer's [portal login](/developer-tools/headless-sdk/customer-portal#log-in); for any other customer id it returns `[]`. ### Get Single Subscription ```typescript theme={null} const subscription = await tagada.customer.getSubscription(subscriptionId); ``` Looks the id up among those 20, and rejects with `TagadaNotFoundError` when it is not there. Both work from 1.18.0; earlier versions called routes that do not exist. ### Manage a Subscription ```typescript theme={null} await tagada.customer.skipSubscription(subscriptionId); await tagada.customer.pauseSubscription(subscriptionId, { resumeAt: '2026-12-01' }); await tagada.customer.changeSubscriptionFrequency(subscriptionId, { optionId }); await tagada.customer.cancelSubscription(subscriptionId); // at the end of the paid period ``` Also `resumeSubscription`, `rescheduleSubscription`, `updateSubscriptionQuantity`, `swapSubscriptionProduct` and `updateSubscriptionPaymentMethod`. They act for the customer logged in with the emailed code, and each one can be turned off by the store. The full list, the permissions and the errors are on [Customer Portal](/developer-tools/headless-sdk/customer-portal#manage-a-subscription). *** ## React Hook ```tsx theme={null} import { useCustomer } from '@tagadapay/headless-sdk/react'; function CustomerDashboard({ customerId }: { customerId: string }) { const { customer, orders, subscriptions, isLoading, error, loadCustomer, loadOrders, loadSubscriptions, updateProfile, } = useCustomer(customerId); // auto-loads profile when customerId is provided useEffect(() => { if (customerId) { loadOrders(customerId); loadSubscriptions(customerId); } }, [customerId]); if (isLoading) return

Loading...

; if (error) return

Error: {error.message}

; return (

Welcome, {customer?.firstName}

Orders

{orders.map((order) => (
Order #{order.orderNumber} — {order.status}
))}

Subscriptions

{subscriptions.map((sub) => (
{sub.name} — {sub.status}
))}
); } ``` ### Full Hook API | Property / Method | Description | | - | - | | `customer` | Current customer profile (null until loaded) | | `orders` | Array of customer orders | | `subscriptions` | Array of customer subscriptions | | `isLoading` | True during any async operation | | `error` | Last error, if any | | `loadCustomer(customerId)` | Load customer profile (called automatically if `customerId` is passed to the hook) | | `loadOrders(customerId)` | Fetch all orders (needs that customer's session) | | `loadSubscriptions(customerId)` | Fetch all subscriptions | | `updateProfile(customerId, data)` | Update the customer's email (other fields are ignored) | *** ## `useOrder` — Thank-You Pages `useCustomer` is for account dashboards (you have a `customerId`). On a **thank-you page** you have an `orderId` from the URL — use `useOrder`. It loads the order, renders it immediately, and keeps watching in the background for the child orders created by accepted upsells: ```tsx theme={null} import { useOrder } from '@tagadapay/headless-sdk/react'; function ThankYouPage() { const orderId = new URLSearchParams(window.location.search).get('orderId'); const { order, relatedOrders, isLoading, error } = useOrder(orderId); if (isLoading || !order) return

Loading your order…

; if (error) return

Error: {error.message}

; return (

Thank you!

{/* Main order — the checkout purchase */} {/* One block per accepted upsell — appears automatically when it lands */} {relatedOrders.map((o) => ( ))}
); } ``` No manual polling: with the default `watchRelatedOrders: true`, the hook refetches every 2s for up to 8s while `relatedOrders` is empty, then stops. Upsell blocks pop in as soon as the child orders exist. ### `useOrder` API | Property / Method | Description | | - | - | | `order` | The order (null until loaded) | | `relatedOrders` | Child orders from accepted upsells (`[]` until they land) | | `isLoading` | True during the initial fetch only | | `error` | Last error, if any | | `refresh()` | Refetch the order once | | Option | Default | Description | | - | - | - | | `watchRelatedOrders` | `true` | Keep refetching while `relatedOrders` is empty | | `watchTimeoutMs` | `8000` | How long to keep watching | | `watchIntervalMs` | `2000` | Delay between refetches | # Customer Portal Source: https://docs.tagada.io/developer-tools/headless-sdk/customer-portal Build your own account area: email-code login, subscriptions, cancellation with retention offers, addresses, cards, credits and re-orders # Customer Portal `tagada.portal` lets you build the customer account area of your store in your own code: the customer logs in with a code sent by email, then sees their orders and subscriptions and manages them — skip, pause, change frequency, swap product, cancel with your retention offers, update addresses and cards, order again, spend credits. It is the same API as the portal TagadaPay hosts on `/account` of your checkout domain. Both read the portal you configure in the CRM under **Customer portal**: which actions are allowed, per store and per product, the cancellation reasons and the retention offer of each, the membership program. A rule you change there applies to your headless portal too. **Requirements** * `@tagadapay/headless-sdk` **1.17.0** or later. * A client created **without** `apiKey`. The SDK sends the API key in place of the customer's session when one is set, and the portal then refuses every call. *** ## Log in ```typescript theme={null} import { createHeadlessClient } from '@tagadapay/headless-sdk'; const tagada = createHeadlessClient({ storeId: 'store_abc123' }); await tagada.portal.requestCode('jane@example.com'); // emails a 6-digit code const { token } = await tagada.portal.verifyCode('jane@example.com', code); ``` After `verifyCode`, the client sends the session with every call. The session lives in the client only: keep `token` yourself (for example in `sessionStorage`) and give it back after a page reload with `tagada.setSessionToken(token)`. `requestCode` answers `404` when the store has no customer with that email. *** ## Read the portal ```typescript theme={null} const config = await tagada.portal.getConfig(); // no login needed const me = await tagada.portal.getMe(); ``` | Call | Returns | | - | - | | `getConfig()` | `store`, `portal` (the design you published), `retention` (cancellation reasons, offers, confirmation copy), `membership` (the program, or `null`), `products` (those the portal can offer: swaps, member products, credit prices, packs). | | `getMe()` | `customer`, `orders` (newest first), `subscriptions`, `membership`, `creditLedger`. | | `getCredits()` | The customer's credit balance and ledger. | *** ## Manage a subscription The everyday actions live on `tagada.customer` and return nothing; the newer ones live on `tagada.portal` and return `{ subscriptionId, status }`. Both need the logged-in session. | Call | What it does | | - | - | | `customer.skipSubscription(id)` | Defers the next charge by one billing period. Active or trialing subscriptions only. | | `portal.skipDate(id, 'YYYY-MM-DD')` / `portal.unskipDate(id, date)` | Skips one upcoming delivery date, or takes it back. Skipping the next date moves the next charge. | | `customer.pauseSubscription(id, { resumeAt? })` | Pauses billing; `resumeAt` (ISO date) resumes it that day, within the pause limit you set (90 days by default). | | `customer.resumeSubscription(id)` | Resumes a paused subscription, or one set to cancel at period end. | | `customer.rescheduleSubscription(id, date)` | Moves the next billing date, in the future and within a year. | | `customer.updateSubscriptionQuantity(id, n)` | Units per delivery, 1 to 100. | | `customer.changeSubscriptionFrequency(id, priceId \| { optionId })` | Another frequency of the same product: a recurring price id, or a purchase option. | | `customer.swapSubscriptionProduct(id, { productId, priceId } \| { productId, optionId, variantId? })` | Another product, at one of its recurring prices or purchase options. | | `portal.addToNextOrder({ subscriptionId, productId, variantId, quantity })` | Ships a one-time item with the next renewal, charged with it. `quantity: 0` takes it off. | | `portal.sendNow(id)` | Charges and ships the next order today. | | `portal.reactivateSubscription(id)` | Restarts a cancelled subscription. | | `portal.setSubscriptionCard(id, paymentMethodId)` | Bills the subscription on another saved card. | | `customer.updateSubscriptionPaymentMethod(id, tagadaToken)` | Bills it on a new card tokenized with `tagada.payment.tokenizeCard`. | | `portal.setSubscriptionAddress(id, addressId \| null)` | Ships it to an address of the book; `null` follows the default address. | | `portal.retryPayment(id)` | Charges a past-due subscription again now. | | `customer.cancelSubscription(id, { cancelAtPeriodEnd? })` | Cancels, at the end of the paid period by default. To offer your retention offers first, use the [cancel flow](#cancel-with-retention-offers) instead. | `sendNow` and `retryPayment` answer `status: 'past_due'` while the charge settles; read `getMe()` again to see the outcome. ### Permissions Every action can be turned off in the CRM, for the store or for one product; they are all on by default. A refused action throws `TagadaAuthError` with a message that says why ("This store does not offer this change for this product"). A missing or expired login throws the same class, so read `error.message` before sending the customer back to the login screen. A subscription with a minimum number of paid orders cannot be cancelled before it reaches it: ```typescript theme={null} import { TagadaValidationError } from '@tagadapay/headless-sdk'; try { await tagada.customer.cancelSubscription(subscriptionId); } catch (error) { if (error instanceof TagadaValidationError && error.appCode === 'MINIMUM_ORDERS_NOT_REACHED') { // error.message says how many paid orders the subscription still needs } } ``` *** ## Cancel with retention offers `getConfig().retention` holds the cancellation reasons you configured, and the retention offer mapped to each (a discount, a skip, a pause, another frequency, a product swap, a yearly plan). The flow is yours to draw; the SDK applies the outcome: ```typescript theme={null} const { reasons, offers } = (await tagada.portal.getConfig()).retention; const target = { type: 'subscription', subscriptionId } as const; // The customer picked a reason that has an offer, and took it: await tagada.portal.acceptCancelOffer({ target, reasonId: reason.id, offerId: reason.offerId! }); // Or they confirmed the cancellation: await tagada.portal.cancelFlow({ target, reasonId: reason.id }); ``` * `target` is `{ type: 'subscription', subscriptionId }` or `{ type: 'membership' }`. * `acceptCancelOffer` also takes what the customer chose inside the offer: `optionId`, `productId`, `variantId`, or `days` for a pause. * Both return `{ subscription, membership }` as they stand after the change. `portal.switchOption({ target, optionId })` moves a subscription to another purchase option, or the membership to `'monthly'` / `'yearly'`, **charged now**. It returns the `orderId` of that charge and `status: 'paid'` or `'requires_action'` (see [3D Secure](#3d-secure)); with `requires_action`, the subscription is unchanged until the customer completes it. *** ## Account | Call | What it does | | - | - | | `portal.updateProfile({ firstName, lastName, email, phone, emailCode? })` | Saves name, email and phone. `phone: null` keeps the one on file. To change the email, call `portal.requestEmailChangeCode(newEmail)` first and pass the code it emails as `emailCode`. | | `portal.saveAddress(address)` | Adds an address, or replaces the one with that `id`. `isDefault: true` makes it the default. Returns `{ addressId }`. | | `portal.removeAddress(id)` / `portal.setDefaultAddress(id)` | — | | `portal.addCard({ tagadaToken, makeDefault })` | Saves a card tokenized with `tagada.payment.tokenizeCard`. Returns `{ paymentMethodId }`. | | `portal.removeCard(id)` | Refused while a live subscription is paid with that card. | | `portal.setDefaultPaymentMethod(id)` | The default card also becomes the card of every live subscription. | *** ## Buy from the portal These charge the customer's default card and ship to their default address. | Call | What it does | | - | - | | `portal.buyAgain([{ variantId, quantity }])` | Orders products again at today's one-time price. | | `portal.buyNow(variantId, quantity?)` | One product, now. | | `portal.joinMembership('monthly' \| 'yearly')` | Buys the membership. | | `portal.redeemCredits({ productId, variantId, quantity })` | Pays a product with credits. Not enough credits: HTTP `402`. | | `portal.buyCreditPack({ packId })` | Buys a credit pack with the saved card. No saved card: `422`. | | `portal.getOffer(token)` / `portal.acceptOffer({ token })` | The upsell of a signed link from your emails (`/account/offer/`), paid with the card of the original order. Accepting twice charges once. | They return the `orderId` and a `status` of `'paid'` or `'requires_action'`. *** ## 3D Secure When the card asks for authentication, a charging call returns `status: 'requires_action'` and a `redirectUrl`. Send the customer there to complete it. ```typescript theme={null} const result = await tagada.portal.buyNow(variantId); if (result.status === 'requires_action' && result.redirectUrl) { window.location.href = result.redirectUrl; } ``` *** ## Errors | HTTP | Thrown as | Usually means | | - | - | - | | `401`, `403` | `TagadaAuthError` | Not logged in, session expired, or the action is turned off. Read `error.message`. | | `404` | `TagadaNotFoundError` | Unknown customer email, subscription, address or card. | | `422` | `TagadaValidationError` | A rule refused the change; `error.appCode` names it (`MINIMUM_ORDERS_NOT_REACHED`). | | `402` and others | `TagadaError` | `error.statusCode` and `error.message` say what happened (`402`: not enough credits). | # Emails Source: https://docs.tagada.io/developer-tools/headless-sdk/emails Customize transactional emails — order confirmations, subscription receipts, abandoned cart recovery, and more # Email Templates **Time**: \~10 minutes | **Difficulty**: Beginner TagadaPay sends transactional emails automatically when key events happen. You can customize every template per store — via the CRM dashboard **or** programmatically with the Node SDK and public API. ``` Event fires (order paid, subscription rebill, …) → TagadaPay picks the matching template for this store → Renders the body with real-time variables (customer name, amount, …) → Sends from your custom domain (or noreply@tagadapay.com) ``` > [!NOTE] > > **Zero code required for defaults.** If you create a template for a given event type, TagadaPay sends it automatically. No webhooks, no cron jobs — just create the template and it works. *** ## Supported Template Types | Type | Event | Fires when… | | - | - | - | | `order_paid` | Order confirmed | Customer completes a payment | | `order_refunded` | Refund processed | You issue a refund | | `subscription_rebill_succeeded` | Rebill receipt | Recurring payment succeeds | | `subscription_rebill_upcoming` | Upcoming rebill notice | 3 days before the next billing cycle | | `subscription_canceled` | Cancellation confirmation | Subscription is canceled | | `subscription_past_due` | Payment failed | Recurring payment declined | | `abandoned_checkout` | Cart recovery | Customer leaves checkout incomplete | | `customer_promotion_code` | Promo code delivery | Customer receives a discount code | | `club_membership_started` | Membership welcome | Customer joins a club | | `club_membership_deactivated` | Membership ended | Club membership is deactivated | > [!NOTE] > > `free_trial_expiration_incoming` is reserved for a future release (trial expiration reminders). All other types are fully supported today. *** ## Manage Templates with the Node SDK ```bash theme={null} npm install @tagadapay/node-sdk ``` ```ts theme={null} import Tagada from '@tagadapay/node-sdk'; const tagada = new Tagada('tgd_your_api_key'); ``` ### List Available Types ```ts theme={null} const types = await tagada.emailTemplates.listTypes(); // [ // { type: 'order_paid', label: 'Order Paid Confirmation', description: 'Sent when a customer successfully pays for an order' }, // { type: 'abandoned_checkout', label: 'Abandoned Checkout', description: 'Sent when a customer abandons their checkout' }, // ... // ] ``` ### Create a Template ```ts theme={null} const template = await tagada.emailTemplates.create({ storeId: 'store_xxx', type: 'order_paid', name: 'Order Confirmation', subject: { en: 'Your order #{{ orderNumber }} is confirmed — {{ storeName }}', fr: 'Votre commande #{{ orderNumber }} est confirmée — {{ storeName }}', }, active: true, params: { replyTo: 'support@your-store.com', }, templateVariables: { order_paid: { body: { en: `

Hi {{ customerFirstName }},

Thank you for your purchase! Your order has been confirmed.

Order: #{{ orderNumber }}
Total: {{ orderTotal }}
Date: {{ orderDate }}

`, fr: `

Bonjour {{ customerFirstName }},

Merci pour votre achat ! Votre commande a été confirmée.

Commande : #{{ orderNumber }}
Total : {{ orderTotal }}
Date : {{ orderDate }}

`, }, }, }, }); console.log(template.id); // 'et_...' ``` ### List Templates for a Store ```ts theme={null} const templates = await tagada.emailTemplates.list({ storeId: 'store_xxx' }); ``` ### Update a Template ```ts theme={null} await tagada.emailTemplates.update('et_xxx', { subject: { en: 'Thanks for your purchase, {{ customerFirstName }}!' }, active: true, }); ``` ### Send a Test Email ```ts theme={null} await tagada.emailTemplates.test({ templateId: 'et_xxx', to: 'test@example.com', locale: 'en', }); ``` > [!TIP] > > Always send a test email after creating or editing a template. TagadaPay renders the template with mock data so you can preview exactly what customers will receive. ### Delete a Template ```ts theme={null} await tagada.emailTemplates.del('et_xxx', 'store_xxx'); ``` *** ## Template Variables Reference Use `{{ variableName }}` in subjects and bodies. Variables are auto-populated from real-time event data when the email is sent. ### Common Variables (All Templates) | Variable | Description | Example | | - | - | - | | `customerFirstName` | Customer first name | John | | `customerLastName` | Customer last name | Doe | | `customerEmail` | Customer email | [john@example.com](mailto:john@example.com) | | `storeName` | Store name | My Store | ### `order_paid` | Variable | Description | Example | | - | - | - | | `orderNumber` | Order reference number | 1042 | | `orderTotal` | Formatted total (with currency) | \$149.99 | | `orderDate` | Formatted date | April 2, 2026 | | `orderItemsHtml` | HTML table of ordered items | `...
` | ### `order_refunded` | Variable | Description | Example | | - | - | - | | `orderNumber` | Order reference number | 1042 | | `refundAmount` | Formatted refund amount | \$149.99 | ### `subscription_rebill_succeeded` | Variable | Description | Example | | - | - | - | | `subscriptionName` | Plan/product name | VIP Club | | `subscriptionAmount` | Formatted recurring amount | \$19.99 | | `nextBillingDate` | Next billing date | May 2, 2026 | ### `subscription_rebill_upcoming` | Variable | Description | Example | | - | - | - | | `subscriptionName` | Plan/product name | VIP Club | | `subscriptionAmount` | Formatted recurring amount | \$19.99 | | `nextBillingDate` | Billing date | June 30, 2026 | | `customerPortalLink` | Link to the customer portal | https\://... | ### `subscription_canceled` | Variable | Description | Example | | - | - | - | | `subscriptionName` | Plan/product name | VIP Club | | `subscriptionAmount` | Formatted recurring amount | \$19.99 | ### `subscription_past_due` | Variable | Description | Example | | - | - | - | | `subscriptionName` | Plan/product name | VIP Club | | `subscriptionAmount` | Formatted recurring amount | \$19.99 | ### `abandoned_checkout` | Variable | Description | Example | | - | - | - | | `cartTotal` | Cart total | \$99.99 | | `checkoutUrl` | Return-to-cart link | https\://... | > [!NOTE] > > Abandoned checkout emails support a configurable **trigger delay** — how long after the customer leaves before the email fires. Set it via `params.specific.triggerDurationSinceLastActivity` with values like `10min`, `30min`, `1h`, `3h`, `6h`, `12h`, `24h`, or `48h`. ### `customer_promotion_code` | Variable | Description | Example | | - | - | - | | `promotionCode` | Discount code | SAVE20 | | `expiresAt` | Expiration date (if set) | 2026-12-31 | ### `club_membership_started` | Variable | Description | Example | | - | - | - | | `subscriptionName` | Club/membership name | VIP Club | | `subscriptionAmount` | Formatted membership amount | \$19.99 | | `nextBillingDate` | Next billing date | June 30, 2026 | | `customerPortalLink` | Link to the customer portal | https\://... | ### `club_membership_deactivated` | Variable | Description | Example | | - | - | - | | `subscriptionName` | Club/membership name | VIP Club | *** ## Template Data Structure The `templateVariables` field follows a specific nesting pattern: ```ts theme={null} templateVariables: { [templateType]: { // e.g. "order_paid" body: { [locale]: string // HTML body per language } } } ``` The `subject` field is simpler — a flat locale map: ```ts theme={null} subject: { en: 'Your order #{{ orderNumber }} is confirmed', fr: 'Votre commande #{{ orderNumber }} est confirmée', } ``` > [!NOTE] > > The key inside `templateVariables` must match the template `type`. For an `order_paid` template, use `templateVariables.order_paid.body`, not `templateVariables.body`. *** ## Multilingual Emails Set subjects and bodies per language. TagadaPay picks the locale from the checkout session or customer profile and falls back to `en` if the customer's locale isn't configured. Supported locales: `en`, `fr`, `de`, `es`, `it` (and any custom locale you define). ```ts theme={null} await tagada.emailTemplates.create({ storeId: 'store_xxx', type: 'subscription_rebill_succeeded', name: 'Subscription Receipt', subject: { en: 'Payment of {{ subscriptionAmount }} confirmed — {{ storeName }}', fr: 'Paiement de {{ subscriptionAmount }} confirmé — {{ storeName }}', de: 'Zahlung von {{ subscriptionAmount }} bestätigt — {{ storeName }}', es: 'Pago de {{ subscriptionAmount }} confirmado — {{ storeName }}', it: 'Pagamento di {{ subscriptionAmount }} confermato — {{ storeName }}', }, templateVariables: { subscription_rebill_succeeded: { body: { en: '

Hi {{ customerFirstName }}, your payment of {{ subscriptionAmount }} for {{ subscriptionName }} was successful. Next billing: {{ nextBillingDate }}.

', fr: '

Bonjour {{ customerFirstName }}, votre paiement de {{ subscriptionAmount }} pour {{ subscriptionName }} a été effectué. Prochain prélèvement : {{ nextBillingDate }}.

', }, }, }, active: true, }); ``` *** ## Custom Sender Domain By default, emails are sent from `noreply@tagadapay.com`. Set up a custom sender domain for branded emails: 1. Go to **Settings → Emails → Custom Domain** in the CRM 2. Add your domain (e.g., `your-store.com`) 3. Add the DNS records shown (SPF, DKIM, DMARC) 4. Once verified, emails send from `noreply@your-store.com` You can also set a per-template reply-to address: ```ts theme={null} await tagada.emailTemplates.create({ // ... params: { replyTo: 'support@your-store.com', }, }); ``` *** ## Full Example: Configure All Emails for a New Store This script creates the most common email templates in a single run: ```ts theme={null} import Tagada from '@tagadapay/node-sdk'; const tagada = new Tagada('tgd_your_api_key'); const storeId = 'store_xxx'; // ── 1. Order confirmation ──────────────────────────────────────────── await tagada.emailTemplates.create({ storeId, type: 'order_paid', name: 'Order Confirmation', subject: { en: 'Your order #{{ orderNumber }} is confirmed — {{ storeName }}' }, templateVariables: { order_paid: { body: { en: `

Hi {{ customerFirstName }},

Thank you for your purchase! Your order has been confirmed.

Order: #{{ orderNumber }}
Total: {{ orderTotal }}
Date: {{ orderDate }}

`, }, }, }, active: true, }); // ── 2. Refund notification ─────────────────────────────────────────── await tagada.emailTemplates.create({ storeId, type: 'order_refunded', name: 'Refund Confirmation', subject: { en: 'Your refund for order #{{ orderNumber }} has been processed' }, templateVariables: { order_refunded: { body: { en: '

Hi {{ customerFirstName }}, your refund of {{ refundAmount }} for order #{{ orderNumber }} has been processed. It may take 5–10 business days to appear on your statement.

', }, }, }, active: true, }); // ── 3. Subscription payment receipt ────────────────────────────────── await tagada.emailTemplates.create({ storeId, type: 'subscription_rebill_succeeded', name: 'Subscription Receipt', subject: { en: 'Payment of {{ subscriptionAmount }} confirmed — {{ storeName }}' }, templateVariables: { subscription_rebill_succeeded: { body: { en: '

Hi {{ customerFirstName }}, your payment of {{ subscriptionAmount }} for {{ subscriptionName }} was successful. Next billing date: {{ nextBillingDate }}.

', }, }, }, active: true, }); // ── 4. Upcoming rebill notice ──────────────────────────────────────── await tagada.emailTemplates.create({ storeId, type: 'subscription_rebill_upcoming', name: 'Upcoming Payment Notice', subject: { en: '{{ subscriptionAmount }} will be charged on {{ nextBillingDate }}' }, templateVariables: { subscription_rebill_upcoming: { body: { en: '

Hi {{ customerFirstName }}, your next payment of {{ subscriptionAmount }} for {{ subscriptionName }} is scheduled for {{ nextBillingDate }}.

', }, }, }, active: true, }); // ── 5. Failed payment alert ────────────────────────────────────────── await tagada.emailTemplates.create({ storeId, type: 'subscription_past_due', name: 'Payment Failed', subject: { en: 'Action required: payment failed for {{ subscriptionName }}' }, templateVariables: { subscription_past_due: { body: { en: '

Hi {{ customerFirstName }}, your payment of {{ subscriptionAmount }} for {{ subscriptionName }} could not be processed. Please update your payment method to avoid interruption.

', }, }, }, active: true, }); // ── 6. Cancellation confirmation ───────────────────────────────────── await tagada.emailTemplates.create({ storeId, type: 'subscription_canceled', name: 'Subscription Canceled', subject: { en: 'Your subscription to {{ subscriptionName }} has been canceled' }, templateVariables: { subscription_canceled: { body: { en: '

Hi {{ customerFirstName }}, your subscription to {{ subscriptionName }} has been canceled. If this was a mistake, you can resubscribe at any time from your account.

', }, }, }, active: true, }); // ── 7. Abandoned checkout recovery ─────────────────────────────────── await tagada.emailTemplates.create({ storeId, type: 'abandoned_checkout', name: 'Cart Recovery', subject: { en: 'You left items in your cart at {{ storeName }}' }, templateVariables: { abandoned_checkout: { body: { en: '

Hi {{ customerFirstName }}, you left {{ cartTotal }} worth of items in your cart. Click below to complete your purchase.

', }, }, }, params: { specific: { triggerDurationSinceLastActivity: '1h' } }, active: true, }); console.log('All email templates created!'); ``` *** ## CRM Dashboard You can also manage templates visually in the CRM without writing any code: ``` Stores → [Your Store] → Settings → Emails ``` The dashboard provides: * **Template editor** with live HTML preview * **Variable picker** — click to insert `{{ variableName }}` * **Multilingual editor** — tabs per language with independent subjects and bodies * **Send test email** — preview rendering with mock data sent to any address * **Enable/disable toggle** — per template, per store *** ## SDK Methods Reference | Method | Description | | - | - | | `emailTemplates.listTypes()` | List all available template types with labels and descriptions | | `emailTemplates.list({ storeId })` | List all templates for a store | | `emailTemplates.create({ ... })` | Create a new template | | `emailTemplates.update(id, { ... })` | Update an existing template | | `emailTemplates.del(id, storeId)` | Delete a template | | `emailTemplates.test({ templateId, to, locale })` | Send a test email | *** ## Next Steps > [card] [Webhooks & Events](/developer-tools/node-sdk/webhooks-events) > > Listen for the same events that trigger emails — order.paid, subscription.canceled, etc. > [card] [Subscriptions](/developer-tools/node-sdk/subscriptions) > > Set up recurring billing — the events that trigger subscription email templates > [card] [Build a Store with AI](/developer-tools/headless-sdk/build-store-with-ai) > > Full tutorial: AI-generated storefront + TagadaPay for payments and emails > [card] [Node SDK Quick Start](/developer-tools/node-sdk/quick-start) > > Install the SDK, authenticate, and explore all resources # Funnel Navigation Source: https://docs.tagada.io/developer-tools/headless-sdk/funnel-navigation Send shoppers into a TagadaPay funnel from your own cart # Funnel Navigation `tagada.funnel.navigate()` takes the cart from the loaded checkout session, bootstraps an anonymous CMS session, and returns a redirect URL into a specific funnel step. It's the JS equivalent of the WooCommerce / Shopify checkout plugins — one call from your own site, one URL to redirect to. > [!NOTE] > > **When to use it:** > > * The cart lives in your store (Shopify, WooCommerce, PrestaShop, custom) and you want to route the shopper into a TagadaPay marketing funnel. > * You want the shopper to enter at a specific funnel step (`step_xxx`) rather than the funnel default. > > **When NOT to use it:** > > * You're building a fully self-hosted checkout page — use [Checkout Flow](/developer-tools/headless-sdk/checkout-flow) directly. Do not follow `createSession().checkoutUrl`. > * You only need a one-shot **Tagada-hosted** checkout link without a funnel — use `tagada.checkout.createSession()` and follow its `checkoutUrl`. > * You need a self-hosted checkout URL with no funnel — use `tagada.checkout.createSessionUrl()` so the shopper stays on **your** origin. *** ## Prerequisites `accountId` is required on `createHeadlessClient()` — `funnel.navigate()` will throw `TagadaError('missing_account_id')` without it. A checkout session must be loaded first (`tagada.checkout.loadSession(...)`). The SDK sources the cart, currency, customer email, and promotion code from that session. > [!NOTE] > > **React provider:** `TagadaHeadlessProvider` only forwards `accountId` through the full `config` prop, not the individual named props. Pass `config={{ storeId, accountId, environment }}` if you need funnel navigation in React. *** ## Quick Start > [tab] Vanilla JavaScript > > ```typescript theme={null} > import { createHeadlessClient } from '@tagadapay/headless-sdk'; > > const tagada = createHeadlessClient({ > storeId: 'store_abc123', > accountId: 'acc_abc123', > environment: 'production', > }); > > // 1. Load (or create) a checkout session — populates the cart. > await tagada.checkout.loadSession(checkoutToken, sessionToken); > > // 2. Get a redirect URL into the funnel. > const { url } = await tagada.funnel.navigate({ > funnelId: 'fnlv2_abc123', > stepId: 'step_abc123', > returnUrl: 'https://merchant.com/thank-you', > }); > > // 3. Send the shopper there. > window.location.assign(url); > ``` > [tab] React > > ```tsx theme={null} > import { > TagadaHeadlessProvider, > useHeadlessClient, > } from '@tagadapay/headless-sdk/react'; > > function App() { > return ( > config={{ > storeId: 'store_abc123', > accountId: 'acc_abc123', > environment: 'production', > }} > > > > > ); > } > > function BuyNowButton() { > const sdk = useHeadlessClient(); > > const handleBuy = async () => { > await sdk.checkout.loadSession(checkoutToken, sessionToken); > const { url } = await sdk.funnel.navigate({ > funnelId: 'fnlv2_abc123', > stepId: 'step_abc123', > returnUrl: 'https://merchant.com/thank-you', > }); > window.location.assign(url); > }; > > return ; > } > ``` > [tab] CDN / Script Tag > > ```html theme={null} > > > ``` *** ## What Happens Under the Hood `navigate()` runs the same sequence the WooCommerce plugin does, with caching so repeat calls in the same page are cheap: 1. `POST /api/v1/cms/session/anonymous` — creates an anonymous CMS session, returns a token. 2. `POST /api/v1/cms/session/v2/init` — initializes the CMS session and binds a CMS customer id. 3. `POST /api/v1/funnel/initialize` — creates the funnel session for `funnelId` + `stepId`. 4. `POST /api/v1/funnel/navigate` — fires an `INIT_CHECKOUT` event with the cart and returns `{ url }`. The CMS token, session id, and customer id are cached on the module instance. Calling `navigate()` again in the same page skips steps 1–3. *** ## `navigate()` Input Reference | Field | Type | Required | Notes | | - | - | - | - | | `funnelId` | `string` | yes | Funnel to enter (e.g. `fnlv2_xxx`). | | `stepId` | `string` | yes | Funnel step to land on. Used for both `entryStepId` and `funnelStepId`. | | `returnUrl` | `string` | no | Where the funnel should send the shopper back to after checkout. | | `customer` | `{ email?, currency?, locale? }` | no | Overrides. Defaults to `session.customer.email` / `session.currency`. | | `discountCodes` | `string[]` | no | Defaults to `[session.promotionCode]` if a promo is applied, otherwise none. | | `metadata` | `Record` | no | Arbitrary metadata forwarded to the funnel-navigate event and stored on the checkout session. Reserved key: `lockShippingRate` (see below). | | `externalShipping` | `{ amount, currency }` | no | Shipping your storefront already settled on, in minor units. See below. | | `currentUrl` | `string` | no | Page URL recorded by the funnel. Defaults to `globalThis.location?.href` in browsers. | | `accountId` | `string` | no | Per-call override. Falls back to `HeadlessConfig.accountId`. | *** ## Carrying Your Own Shipping Amount If your storefront already charges its own shipping, pass `externalShipping` so the shopper is charged the amount they agreed to instead of whatever rate the platform would auto-select: ```ts theme={null} await sdk.funnel.navigate({ funnelId: 'fnlv2_xxx', stepId: 'step_xxx', externalShipping: { amount: 1200, currency: 'USD' }, // $12.00 }); ``` The checkout session starts on a rate matching that exact amount — an existing rate if one matches, otherwise a dynamically created one. > [!WARNING] > > Only send this once shipping is genuinely resolved. `{ amount: 0 }` means **free > shipping** and pins a free rate — it is not a stand-in for "not known yet". While > shipping is unresolved, omit the field entirely and the platform selects a rate as > before. ### Keeping your rate when the checkout re-evaluates shipping The hosted checkout re-evaluates shipping rates when the page loads, when the shopper changes country, and when discount codes move the cart across a rate's amount bracket. If the rate your storefront picked stops matching the store's rate conditions — for example a "$10 under $150" rate on a cart whose catalogue price is \$170 before the discount — the checkout swaps it for an eligible one. If your storefront is the authority on shipping, opt out of that re-selection by sending `lockShippingRate: true` in `metadata` alongside your pre-selected rate: ```ts theme={null} await sdk.funnel.navigate({ funnelId: 'fnlv2_xxx', stepId: 'step_xxx', externalShipping: { amount: 1000, currency: 'USD' }, // $10.00 metadata: { lockShippingRate: true }, }); ``` With the lock set: * The checkout keeps the pre-selected rate on load, on country changes and on discount changes; it never auto-selects another one. * The shipping selector shows that single rate and the shopper cannot change it. * The lock only applies once a rate is actually on the session (`externalShipping`, or a later `setShippingRate` call). With no rate yet, the checkout behaves as if the flag were absent. Leave the flag off when you want the platform's own rate rules — brackets, country restrictions, highlighted rate — to drive the selection. *** ## Return Value ```ts theme={null} { url: string; // Redirect destination. funnelSessionId: string; // From /funnel/initialize, useful for logging/debugging. } ``` The SDK does not perform the redirect — call `window.location.assign(url)`, `router.push(url)`, or whatever your framework uses. *** ## Errors > [!NOTE] > > `funnel.navigate()` throws typed `TagadaError`s: > > * **`no_cart_loaded`** — `sdk.checkout.loadSession(...)` was not called first. The SDK has no cart to send. > * **`missing_account_id`** — `accountId` was not provided on `createHeadlessClient()` and not passed per call. > > Network and validation failures throw the standard `TagadaNetworkError` / `TagadaValidationError`. *** ## SSR & Non-Browser Environments The SDK reads `globalThis.location?.href` for `currentUrl` when running in a browser. In SSR / Node contexts, pass `currentUrl` explicitly: ```ts theme={null} await sdk.funnel.navigate({ funnelId, stepId, currentUrl: 'https://merchant.com/products/foo', returnUrl: 'https://merchant.com/thank-you', }); ``` Because `navigate()` returns `{ url }` rather than redirecting, it composes cleanly with SPA routers (`react-router`, `next/router`) and server-side handoffs. *** > [!TIP] > > **Funnel navigation vs. `checkout.createSessionUrl()`:** Use `funnel.navigate()` to enter a marketing funnel (pre-checkout steps, upsell sequencing). Use `checkout.createSessionUrl()` when you just need a self-hosted checkout URL with no funnel logic in front of it. # Headless SDK Source: https://docs.tagada.io/developer-tools/headless-sdk/introduction Use TagadaPay as a headless checkout and CRM backend from any website # Headless SDK Build your own store with **any framework** (React, Vue, Svelte, plain HTML) or **AI tools** (Lovable, Claude, v0) and use TagadaPay as the headless backend for checkout, payments, pixel tracking, and CRM. > [!NOTE] > > **When to use this SDK:** > > * You're building a custom store on your own hosting (Vercel, Netlify, etc.) > * You want full control over the UI while TagadaPay handles payments, PSP routing, pixel tracking, and subscriptions > * An AI tool is generating your store code and needs a simple, self-documenting API > > **When NOT to use this SDK:** > > * You already have a cart / order and only need to charge — use [core-js + `payments.process`](/developer-tools/payments/core-js-payments) > * You want to deploy pages **on TagadaPay** — use the [Plugin SDK](/developer-tools/sdk/introduction) instead > * You only need a checkout link — use [Web Integration](/developer-tools/web-integration/trigger-checkout-from-website) > * You need server-side automation — use the [Node SDK](/developer-tools/node-sdk/quick-start) > * You're building a **payment platform that charges for many merchants** (white-label PSPs and marketplaces) — use the [Partners section](/developer-tools/partners/introduction) instead. Partner server-to-server deliberately avoids checkout sessions, which this SDK is built around. > [!TIP] > > **Not sure?** [Choose how you accept payments](/developer-tools/payments/choose-your-integration) first, then compare all five SDKs on [SDKs at a glance](/developer-tools/sdks-at-a-glance). > > `processPayment()` (browser, Headless) pays a **checkout session**. Node `payments.process()` (server) charges a **vaulted instrument**. They are not the same call. *** ## How It Works ``` Your Store (Vercel, Netlify, etc.) ├── Frontend (any framework) │ ├── @tagadapay/headless-sdk ← checkout, pixel tracking, offers, CRM │ └── @tagadapay/core-js ← card tokenization, 3DS (optional) └── Backend (API routes) └── @tagadapay/node-sdk ← server automation, webhooks ``` The headless SDK talks to TagadaPay's REST API from the browser. It's a **single import** that gives you these modules: | Module | What it does | | - | - | | **`tagada.checkout`** | Load sessions, update cart, apply promos, handle shipping | | **`tagada.payment`** | Discover APMs, tokenize cards, process payments, handle 3DS | | **`tagada.offers`** | Load upsells/downsells, accept/decline, order bumps | | **`tagada.catalog`** | Browse products, variants, and prices | | **`tagada.customer`** | Profile, orders, subscriptions | | **`tagada.funnel`** | Send shoppers into a TagadaPay funnel from your own cart | | **`tagada.track`** | Report the steps and events of a funnel you code, and fire the pixels bound to them — see [Coded Funnels](/developer-tools/headless-sdk/coded-funnels) | | **`tagada.portal`** | Build your own customer account area: login by email code, subscriptions, cancellation offers — see [Customer Portal](/developer-tools/headless-sdk/customer-portal) | | **`tagada.rx`** | Tagada Rx telehealth flows — see [Rx with the Headless SDK](/developer-tools/rx/headless-sdk) | > [!NOTE] > > **Pixel tracking** (Meta, TikTok, Snap, GTM, GA4) fires on its own on the pages TagadaPay hosts. On pages you code yourself, call `tagada.track.step()` on each step and TagadaPay loads the pixels you bind on the canvas — see [Coded Funnels](/developer-tools/headless-sdk/coded-funnels) and [Pixels](/developer-tools/headless-sdk/pixels). *** ## Install ```bash theme={null} npm install @tagadapay/headless-sdk # Optional: for client-side card tokenization npm install @tagadapay/core-js ``` | Import path | What you get | | - | - | | `@tagadapay/headless-sdk` | `createHeadlessClient` and every module | | `@tagadapay/headless-sdk/react` | `TagadaHeadlessProvider` and the hooks (`useCheckout`, `usePayment`, `useStep`, …) | | `@tagadapay/headless-sdk/stripe` | Stripe Express Checkout: `StripeExpressButton`, `useStripeExpress`, `StripeExpressCheckout`. Needs `@tagadapay/core-js`. | The client takes one more option for coded funnels: `funnel`, the key of the funnel declared in `tagada.funnel.ts` (default `'main'`). It is only read by `tagada.track`. *** ## Quick Start > [tab] Vanilla JavaScript > > ```typescript theme={null} > import { createHeadlessClient } from '@tagadapay/headless-sdk'; > > const tagada = createHeadlessClient({ > storeId: 'store_abc123', > environment: 'production', > }); > > // 1. Load checkout session (token from URL) > const session = await tagada.checkout.loadSession(checkoutToken, sessionToken); > > // 2. Set customer info + address > await tagada.checkout.updateCustomer(session.id, { > email: 'jane@example.com', > firstName: 'Jane', > lastName: 'Doe', > }); > await tagada.checkout.updateAddress(session.id, { > shippingAddress: { > line1: '123 Main St', > city: 'San Francisco', > postalCode: '94102', > country: 'US', > }, > }); > > // 3. Tokenize card + pay (3DS handled automatically) > const { tagadaToken } = await tagada.payment.tokenizeCard({ > cardNumber: '4242424242424242', > expiryDate: '12/28', > cvc: '123', > }); > > const result = await tagada.payment.processPayment({ > checkoutSessionId: session.id, > tagadaToken, > }); > > // 4. Handle result > if (result.status === 'succeeded') { > console.log('Paid!', result.order); > } else if (result.status === 'requires_redirect') { > window.location.href = result.redirectUrl; > } else if (result.status === 'failed') { > console.error(result.error); > } > ``` > [tab] React > > ```tsx theme={null} > import { > TagadaHeadlessProvider, > useCheckout, > usePayment, > } from '@tagadapay/headless-sdk/react'; > > function App() { > return ( > > > > ); > } > > function CheckoutPage() { > const { session, updateCustomer, updateAddress } = useCheckout(checkoutToken, sessionToken); > const { processPayment, isProcessing, tokenizeCard } = usePayment({ > onPaymentSuccess: (result) => router.push('/thank-you'), > onPaymentFailed: (result) => alert(result.error), > }); > > const handlePay = async () => { > await updateCustomer({ email, firstName, lastName }); > await updateAddress({ > shippingAddress: { line1, city, postalCode, country }, > }); > > const { tagadaToken } = await tokenizeCard({ cardNumber, expiryDate, cvc }); > await processPayment({ checkoutSessionId: session.id, tagadaToken }); > // 3DS redirects + polling handled automatically > // onPaymentSuccess / onPaymentFailed callbacks fire when done > }; > > return ( > > ); > } > ``` > [tab] CDN / Script Tag > > ```html theme={null} > > > ``` *** ## SDK Layers — Which Package Does What? TagadaPay has three npm packages. Most developers only need the Headless SDK: | Package | Runs in | Purpose | | - | - | - | | **`@tagadapay/headless-sdk`** | Browser | Checkout sessions, payments (tokenize + charge + 3DS), offers, CRM, catalog. **This is the main package.** | | **`@tagadapay/core-js`** | Browser | Low-level card tokenization, 3DS modal, Apple/Google Pay. **Optional peer dep** of headless-sdk — install it if you use `tagada.payment.tokenizeCard()`. | | **`@tagadapay/node-sdk`** | Server (Node.js) | Server automation: create stores, products, payment flows, webhooks, deploy to CDN, manage subscriptions. | ``` ┌───────────────────────────────────────────────────────────┐ │ Your Frontend (React, Vue, Svelte, HTML) │ │ │ │ @tagadapay/headless-sdk │ │ ├── checkout — sessions, cart, promos, shipping │ │ ├── payment — processPayment(), 3DS, APMs, express │ │ │ └── uses @tagadapay/core-js internally │ │ ├── offers — upsells, downsells, order bumps │ │ ├── customer — profile, orders, subscriptions │ │ ├── catalog — products, variants, prices │ │ ├── track — coded funnel steps, events, pixels │ │ └── portal — customer account area │ │ │ │ @tagadapay/core-js (optional) │ │ └── tokenizeCard(), useThreeds(), Apple/Google Pay │ └───────────────────────────────────────────────────────────┘ │ HTTPS ▼ ┌───────────────────────────────────────────────────────────┐ │ Your Backend (optional) │ │ @tagadapay/node-sdk — stores, webhooks, deploy, etc. │ └───────────────────────────────────────────────────────────┘ ``` > [!TIP] > > **When do you need `@tagadapay/core-js` separately?** Only if you're [accepting a payment with your own cart](/developer-tools/payments/core-js-payments) (or a mobile app, later charges) without the Headless SDK's session management. If you use `@tagadapay/headless-sdk`, just `npm install @tagadapay/core-js` as a peer dep — the Headless SDK calls it internally. *** ## Design Principles 1. **Zero dependencies** — core uses native `fetch`. No axios, no lodash. 2. **AI-first** — single import, minimal config, self-contained methods. LLMs generate working code on the first try. 3. **Full payment coverage** — same APMs, express checkout, 3DS, and PSP routing as the Plugin SDK. 4. **Automatic 3DS** — `processPayment()` handles redirects, iframe challenges, and polling out of the box. 5. **Tree-shakeable** — unused modules are eliminated by bundlers. 6. **TypeScript-first** — full type coverage, JSDoc on every method. *** ## Next Steps > [card] [Choose how you accept payments](/developer-tools/payments/choose-your-integration) > > Headless vs core-js vs Plugin vs `payments.process` — pick one path for the first payment > [card] [Payment Setup](/developer-tools/headless-sdk/payment-setup) > > Discover APMs, express checkout, and payment flows > [card] [Checkout Flow](/developer-tools/headless-sdk/checkout-flow) > > Sessions, cart, promo codes, and shipping > [card] [Funnel Navigation](/developer-tools/headless-sdk/funnel-navigation) > > Send shoppers into a TagadaPay funnel from your own cart > [card] [Emails](/developer-tools/headless-sdk/emails) > > Transactional emails — order confirmations, subscription receipts, cart recovery > [card] [Pixels](/developer-tools/headless-sdk/pixels) > > Client-side pixel tracking for Meta, TikTok, GA4, GTM, and more > [card] [Upsells & Offers](/developer-tools/headless-sdk/offers) > > Post-purchase offers and order bumps > [card] [Catalog](/developer-tools/headless-sdk/catalog) > > Browse products, variants, and prices > [card] [Customer](/developer-tools/headless-sdk/customer) > > Profiles, order history, and subscriptions > [card] [Customer Portal](/developer-tools/headless-sdk/customer-portal) > > Email-code login, subscription changes, retention offers > [card] [Coded Funnels](/developer-tools/headless-sdk/coded-funnels) > > Your own pages as cards on the canvas, with pixels fired for you # Upsells & Offers Source: https://docs.tagada.io/developer-tools/headless-sdk/offers Post-purchase offers, order bumps, and one-click upsells # Upsells & Offers Three different APIs. Use the one that matches the moment in the journey: | When | API | Creates a child order? | | - | - | - | | After checkout, one-click on the same card | `previewOffer` + **`processOfferPayment`** | Yes — `metadata.mainOrderId` = the checkout order | | On the checkout page, before pay | `toggleOrderBump` | No — adds a line to the cart | | Email / account “offers for this order” | `listPostPurchaseOffers` + accept / decline | Different surface — **not** the OTO page | For the [basic post-purchase funnel](/developer-tools/funnel-demos/basic-post-purchase), use the first row only. The finished app is [`basic-post-purchase`](https://github.com/TagadaPay/examples/tree/main/basic-post-purchase). > [!WARNING] > > `mainOrderId` is the **checkout order id** (`result.order.id` from `processPayment`), never a payment id. *** ## Get an Offer Pin IDs from the dashboard or `checkoutOffers.create` (Node SDK). Do not pick “the first upsell” from `listOffers` — a store can have many. ```typescript theme={null} const offer = await tagada.offers.getOffer('offer_xxx'); // offer.id -- offer ID // offer.title -- "Essential Cap — $19.99" // offer.type -- 'upsell' | 'orderbump' | 'downsell' // offer.lineItems -- products in the offer ``` ```typescript theme={null} const upsells = await tagada.offers.listOffers({ type: 'upsell' }); const orderBumps = await tagada.offers.listOffers({ type: 'orderbump' }); ``` > [!NOTE] > > `listOffers({ type })` only filters `upsell` and `orderbump`. A downsell created with `type: 'downsell'` will not appear. Load it with `getOffer(id)`. *** ## One-click upsell (this is the OTO) Preview the price, then charge the instrument stored on the **main order**. Prefer `processOfferPayment` — it runs 3DS / redirect / polling the same way `payment.processPayment` does. ```typescript theme={null} // orderId = processPayment() → result.order.id (the tee order) const preview = await tagada.offers.previewOffer({ offerId: 'offer_cap' }); // preview.items, preview.totalAmount, preview.currency const result = await tagada.offers.processOfferPayment({ offerId: 'offer_cap', mainOrderId: orderId, returnUrl: window.location.href, }); switch (result.status) { case 'succeeded': // Child order exists. Next OTO or thank you — your router. window.location.href = `/offer-tote?orderId=${orderId}`; break; case 'requires_redirect': window.location.href = result.redirectUrl; break; case 'failed': console.error(result.error); break; } ``` Decline is not an API call on this path. Send them to the next URL yourself (`/downsell?orderId=` or `/thank-you?orderId=`). ### Low-level: `payPreviewedOffer` Returns the raw `{ payment, order, preview, checkout }` and does **not** finish 3DS. Only use it if you handle `payment.requireAction` yourself. For a storefront, use `processOfferPayment`. *** ## Thank you: related orders The accept does **not** add a line to the tee order. It creates a **child order** — and it lands asynchronously, a couple of seconds after the redirect. The SDK handles the wait for you: ```typescript theme={null} // Vanilla — polls until the child orders exist (or 8s, whichever first) const order = await tagada.customer.getOrder(orderId, { waitForRelatedOrders: true }); // order.items → tee // order.relatedOrders → cap, tote, … one per accepted offer ``` ```tsx theme={null} // React — renders the tee immediately, upsells pop in when they land const { order, relatedOrders } = useOrder(orderId); ``` See [`useOrder`](/developer-tools/headless-sdk/customer#useorder--thank-you-pages) for the full thank-you page. Full graph: [Basic post-purchase](/developer-tools/funnel-demos/basic-post-purchase). *** ## Order Bumps Shown **on** checkout, before payment: ```typescript theme={null} await tagada.offers.toggleOrderBump({ checkoutSessionId: session.id, orderBumpOfferId: bumps[0].id, selected: true, }); ``` The parameter is `orderBumpOfferId` (not `offerId`). *** ## Post-purchase offer list (not the OTO page) `listPostPurchaseOffers` / `acceptPostPurchaseOffer` / `declinePostPurchaseOffer` are for “offers attached to this order” (account, email). They are **not** what the cap/tote pages in the basic funnel call. *** ## React Hook ```tsx theme={null} import { useOffers } from '@tagadapay/headless-sdk/react'; function UpsellPage({ offerId, orderId }: { offerId: string; orderId: string }) { const { offer, getOffer, previewOffer, processOfferPayment, isLoading } = useOffers(); useEffect(() => { getOffer(offerId); }, [offerId]); const accept = async () => { const result = await processOfferPayment({ offerId, mainOrderId: orderId, returnUrl: window.location.href, }); if (result.status === 'succeeded') { window.location.href = `/offer-tote?orderId=${orderId}`; } }; if (isLoading) return

Loading...

; return (

{offer?.title}

); } ``` ### Full Hook API | Method | Description | | - | - | | `getOffer(offerId)` | Load a single offer (sets `offer` state) | | `listOffers({ type? })` | List offers filtered by `'upsell'` or `'orderbump'` | | `previewOffer({ offerId })` | Preview pricing (sets `preview` state) | | `processOfferPayment({ offerId, mainOrderId, returnUrl? })` | One-click charge + 3DS / polling | | `payPreviewedOffer({ offerId, mainOrderId })` | Raw charge only — no 3DS handling | | `toggleOrderBump({ checkoutSessionId, orderBumpOfferId, selected })` | Toggle a bump on/off | | `listPostPurchaseOffers(orderId)` | List account-level post-purchase offers | | `acceptPostPurchaseOffer({ orderId, offerId })` | Accept one of those (not the OTO page) | | `declinePostPurchaseOffer({ orderId, offerId })` | Decline one of those | # Payment Setup Source: https://docs.tagada.io/developer-tools/headless-sdk/payment-setup Discover available payment methods, express checkout, and process payments # Payment Setup The payment module is the core of the Headless SDK. It lets you discover which payment methods are configured for a store, tokenize cards, and process payments with **automatic 3DS, redirect, and polling handling**. *** ## Discover Available Payment Methods Every store has a **payment setup config** — a map of payment methods (card, Apple Pay, Google Pay, Klarna, etc.) with their enabled/disabled state, processor IDs, and flow IDs. ```typescript theme={null} const setup = await tagada.payment.getPaymentSetup(checkoutSessionId); // Example response: // { // "card": { enabled: true, method: "card", paymentFlowId: "pf_xxx" }, // "apple_pay:stripe": { enabled: true, method: "apple_pay", express: true, processorId: "proc_xxx" }, // "google_pay:stripe": { enabled: true, method: "google_pay", express: true }, // "klarna:stripe": { enabled: true, method: "klarna", processorId: "proc_stripe" }, // } ``` Where the config comes from, in order: an explicit `paymentSetupConfig` you pass in, the config injected on Tagada-hosted pages, and otherwise the payment methods enabled on the store for that checkout session (resolved from the API). Keys are `method` or `method:provider` — so on a self-hosted page an Apple Pay integration shows up as `"apple_pay"`, the card form as `"card"`. An empty object means no payment method is enabled for the session's store/currency. ### Just the enabled method keys ```typescript theme={null} const methods = await tagada.payment.getEnabledMethods(checkoutSessionId); // ["card", "apple_pay:stripe", "google_pay:stripe"] ``` ### Express methods with browser availability ```typescript theme={null} const express = await tagada.payment.getExpressMethods(checkoutSessionId); // { // applePay: { available: true, processorId: "proc_xxx" }, // googlePay: { available: true }, // klarna: { available: true, processorId: "proc_stripe" }, // } ``` The SDK automatically checks `ApplePaySession.canMakePayments()` in the browser to determine Apple Pay availability. *** ## Card Payment Flow ### Recommended: `processPayment()` `processPayment()` is the **high-level orchestrator** that handles the entire payment lifecycle automatically: 1. Submits payment to the processor 2. If 3DS / bank auth is required → redirects the user and resumes on return 3. If the payment is async → polls until a terminal status 4. Returns a typed `ProcessPaymentResult` ```typescript theme={null} // 1. Tokenize const { tagadaToken } = await tagada.payment.tokenizeCard({ cardNumber: '4242424242424242', expiryDate: '12/28', cvc: '123', cardholderName: 'Jane Doe', }); // 2. Process payment (3DS, redirects, polling all handled) const result = await tagada.payment.processPayment({ checkoutSessionId: session.id, tagadaToken, }); // 3. Handle result switch (result.status) { case 'succeeded': console.log('Payment confirmed!', result.order); break; case 'requires_redirect': // In React, usePayment() handles this automatically. // In vanilla JS, redirect manually: window.location.href = result.redirectUrl; break; case 'failed': console.error('Payment failed:', result.error); break; case 'pending': console.log('Still processing...', result.paymentId); break; } ``` > [!NOTE] > > `tokenizeCard()` requires `@tagadapay/core-js` as an optional peer dependency. Install it: `npm install @tagadapay/core-js`. ### Return type: `ProcessPaymentResult` The return value is a **discriminated union** — check `result.status` for exhaustive handling: | Status | Fields | Meaning | | - | - | - | | `succeeded` | `payment`, `order` | Payment confirmed. Show success screen. | | `requires_redirect` | `redirectUrl`, `method?`, `postData?`, `paymentId` | User must visit a URL (3DS, bank auth, APM). | | `failed` | `error`, `payment?` | Payment declined or errored. | | `pending` | `paymentId` | Still processing (rare — polling timed out). | ### 3DS Return URL After a 3DS redirect, the bank sends the user back to your page with query parameters. The SDK auto-detects these and resumes the payment: * **React (`usePayment`)**: Handled automatically on mount — detects `?paymentAction=...` params, polls for result, fires callbacks. * **Vanilla JS**: Call `tagada.payment.maybeResumeFromUrl()` on page load. That is the one-liner. `resumeAfterRedirect(paymentId)` is the lower-level equivalent if you already parsed the query yourself. `returnUrl` passed to `processPayment()` (defaults to `window.location.href`) **must** be the page that runs this resume hook. After 3DS the bank sends the shopper back there. ```typescript theme={null} // Vanilla JS — first thing on page load const resumed = await tagada.payment.maybeResumeFromUrl(); if (resumed?.status === 'succeeded') { window.location.href = `/thank-you?orderId=${resumed.order?.id}`; } else if (resumed?.status === 'failed') { showError(resumed.error); } // null → no 3DS return, render the checkout as usual ``` ### Required actions (3DS, Stripe Radar) Some card payments pause before the charge and wait for the shopper's browser. The pay call then answers `payment.status: 'pending'` with `payment.requireAction` set and the action in `payment.requireActionData.type`. Such a payment has not failed: it goes on once the action is done. `processPayment()` (and `finalize()` for a raw pay result) runs the action for you: | `requireActionData.type` | What the SDK does | What your page needs | | - | - | - | | `threeds_auth` | Runs the 3DS challenge in a modal when `@tagadapay/core-js` is installed, otherwise returns `requires_redirect` to the bank page | The resume hook above on the `returnUrl` page | | `processor_auth`, `redirect_to_payment`, `redirect` | Returns `requires_redirect` | Redirect, then the resume hook | | `stripe_radar` | Loads Stripe.js, creates a Radar session with the key in `requireActionData.metadata.radar`, saves it, resumes the payment and polls. The result is `succeeded` or `failed` like any card payment | A browser (Radar cannot run on a server) and `https://js.stripe.com` allowed by your [CSP](/developer-tools/headless-sdk/csp) | Stripe Radar applies to Stripe processors with Radar turned on, the processor TagadaPay manages for you included. Apple Pay and Google Pay express payments and merchant-initiated rebills never pause for this step. A saved session, including a `FAILED` marker, lets the payment proceed. On Payments API stores, the legacy card pause is off by default (`PAYMENTS_V3_LEGACY_RADAR_PAUSE` must be `on` to enable it). When enabled, a checkout is asked at most once: if the page leaves the step unfinished and the buyer clicks Pay again, the server confirms without another pause. A failure preparing the pause also confirms without Radar. No merchant change enables this flag. If you call `pay()` (or any other raw pay method) yourself, pass its result to `tagada.payment.finalize(result)`: it runs these actions the same way. *** ## Express Checkout ### Apple Pay ```typescript theme={null} const result = await tagada.payment.processApplePay({ checkoutSessionId: session.id, applePayToken: applePayEvent.payment.token, }); ``` > [!NOTE] > > **Merchant-scoped Apple Pay domains.** When the checkout domain runs > merchant-scoped Apple Pay — either the merchant's own Apple certificates > (BYOK) or Tagada's platform-integrator registration — the backend attaches a > domain-keyed `applePayByok` map to the `apple_pay` method's metadata. The SDK > resolves the current hostname against that map automatically and sends the > matching `merchant_registration_id` to Basis Theory during tokenization, so no > code change is needed. Pass `merchantRegistrationId` explicitly on > `processApplePay` only to override the automatic resolution, or call > `tagada.payment.resolveApplePayRegistration()` yourself when minting the > Apple Pay merchant session (its `merchantRegistrationId` and `displayName` > must go into the Basis Theory `POST /apple-pay/session` call for these > domains). ### Google Pay ```typescript theme={null} const result = await tagada.payment.processGooglePay({ checkoutSessionId: session.id, googlePayToken: paymentData.paymentMethodData.tokenizationData.token, }); ``` ### Redirect APMs (Klarna, iDEAL, etc.) For the APM lifecycle rules (redirect → webhook, vouchers, recurring limits) see [Alternative payment methods](/developer-tools/payments/alternative-payment-methods). ```typescript theme={null} const result = await tagada.payment.processApm({ checkoutSessionId: session.id, paymentMethod: 'klarna', processorId: 'proc_stripe', // The page that runs maybeResumeFromUrl() after the redirect. Defaults to the current page; // a session with a live Tagada checkout page returns there instead. returnUrl: 'https://store.example/checkout', }); // Redirects the browser to Klarna, or resolves the payment if no redirect is needed. const outcome = await tagada.payment.finalize(result, { returnUrl: 'https://store.example/checkout' }); ``` ### Ocean Payment (your own Ocean account) Ocean Payment has its own card form and its own endpoints, so it does not go through `processPayment()`. `mountOceanPayment()` picks the same flow as the hosted checkout: * **Card form on your page**, when your Ocean integration in TagadaPay has Ocean's public key. * **Ocean's page**, when it has no public key, or when you pass `mode: 'redirect'`. Save the customer (email, first and last name) and the address on the session first: Ocean needs them. ```typescript theme={null} const ocean = await tagada.payment.mountOceanPayment({ checkoutSessionId: session.id, container: '#ocean-card', // an empty
, only used for the card form locale: 'en-US', }); payButton.onclick = async () => { const result = await ocean.pay(); if (result.status === 'requires_redirect') window.location.href = result.redirectUrl; // 3-D Secure or Ocean's page else if (result.status === 'succeeded') showThankYou(result.order); else if (result.status === 'failed') showError(result.error); // 'pending': Ocean has not confirmed yet; the order completes when it does. }; ``` On the page the shopper comes back to, load the session first (keep `checkoutToken` and `sessionToken` in the URL, as `createSessionUrl()` does), then call `tagada.payment.maybeResumeFromUrl()`, or use `usePayment()` in React, which does it for you. > [!WARNING] > > **Card form + 3-D Secure: your checkout page must accept a POST.** After 3-D Secure, Ocean sends the > shopper back to the exact page the card form was on with a form POST. Most static hosts answer 405 to > that and the shopper sees an error page. If your host only serves GET, either add a rule that serves the > checkout page on POST too, or use `mode: 'redirect'`: that return goes through TagadaPay first and > reaches your page as a normal GET. Only one Ocean card form can be on a page. In React, mount it in an effect and clean up with an `AbortController`: ```tsx theme={null} useEffect(() => { const controller = new AbortController(); let form: OceanPaymentForm | undefined; tagada.payment .mountOceanPayment({ checkoutSessionId, container: ref.current!, signal: controller.signal }) .then((f) => { form = f; setOcean(f); }) .catch((e) => { if (e.name !== 'AbortError') setError(e); }); return () => { controller.abort(); form?.unmount(); }; }, [checkoutSessionId]); ``` Ocean Payment is not offered on a cart with a subscription. *** ## React Hook ```tsx theme={null} import { usePayment } from '@tagadapay/headless-sdk/react'; function PaymentForm({ sessionId }) { const { processPayment, tokenizeCard, isProcessing, paymentSetup, loadPaymentSetup, } = usePayment({ onPaymentSuccess: (result) => { router.push(`/thank-you?orderId=${result.order?.id}`); }, onPaymentFailed: (result) => { setError(result.error); }, }); const handleSubmit = async () => { const { tagadaToken } = await tokenizeCard({ cardNumber, expiryDate, cvc }); await processPayment({ checkoutSessionId: sessionId, tagadaToken }); // 3DS redirects + return detection + polling all handled automatically }; return ( ); } ``` ### Full Hook API | Property / Method | Description | | - | - | | `processPayment(opts)` | High-level: tokenize → pay → 3DS → poll → callbacks. **Recommended.** | | `pay(opts)` | Low-level: submit payment, returns raw `PayResult`. No auto-redirect. | | `tokenizeCard(card)` | Tokenize card via `@tagadapay/core-js` | | `isProcessing` | True during payment processing | | `paymentSetup` | Cached payment method config | | `loadPaymentSetup(sessionId)` | Fetch available payment methods | | `getExpressMethods(sessionId)` | Check Apple Pay / Google Pay availability | | `onPaymentSuccess` | Callback when payment succeeds (including after 3DS return) | | `onPaymentFailed` | Callback when payment fails or is declined | *** ## Advanced API For advanced use cases, you can create instruments and process payments separately: ```typescript theme={null} // Create a reusable payment instrument const { paymentInstrument } = await tagada.payment.createInstrument({ tagadaToken, storeId: 'store_xxx', customerData: { email: 'jane@example.com' }, }); // Create 3DS session const threeds = await tagada.payment.create3dsSession({ paymentInstrumentId: paymentInstrument.id, sessionData: { sessionId: 'bt_session_xyz' }, }); // Process with instrument directly const result = await tagada.payment.payDirect({ checkoutSessionId: session.id, paymentInstrumentId: paymentInstrument.id, threedsSessionId: threeds.id, }); ``` ## Test your integration In sandbox, any 16-digit card works. Use this one: | | | | - | - | | Card | `4242 4242 4242 4242` | | Expiry | Any future date | | CVC | Any 3 digits | 1. Call `processPayment()` and confirm `result.status === 'succeeded'`. 2. Confirm `returnUrl` is the page that runs `maybeResumeFromUrl()` (vanilla) or `usePayment` (React). After a 3DS challenge the bank sends the shopper back there. Full sandbox setup: [Sandbox testing](/developer-tools/node-sdk/sandbox-testing). > [!NOTE] > > **Need even more control?** For instrument-level management, later charges (MIT — merchant-initiated, customer not present), auth+capture, or mobile apps, see [Accept a payment with your own cart](/developer-tools/payments/core-js-payments). # Pixels Source: https://docs.tagada.io/developer-tools/headless-sdk/pixels Client-side pixel tracking for Meta, TikTok, GA4, GTM, and more # Pixel Tracking TagadaPay handles **client-side pixel tracking** for your store. When you configure pixels in the dashboard, they're automatically loaded and fired at the right moments during the checkout flow — no extra code needed. > [!NOTE] > > Pixel tracking is **not** the same as analytics. Pixels fire client-side events to ad platforms (Meta, TikTok, etc.) for attribution and retargeting. Analytics (dashboards, reports, conversion metrics) is a separate feature in the TagadaPay CRM. *** ## How It Works 1. You configure pixel IDs in the TagadaPay dashboard (Settings → Integrations) 2. TagadaPay loads the pixel scripts and fires the events — on the pages it hosts by itself, on the pages you code once you report your steps 3. Each event reaches the pixels bound to that page on the [canvas](/developer-tools/funnels/canvas) There are two cases: * **Pages TagadaPay hosts** (checkout, offers, thank-you): no code at all. Pixels are platform-managed. * **Pages you code** with the Headless SDK: declare them as a [coded funnel](/developer-tools/headless-sdk/coded-funnels) and call `tagada.track.step()` on each one. The SDK loads the pixels you bind on the canvas and fires them; you never add a pixel script yourself. *** ## Supported Pixels | Platform | Config Key | What fires | | - | - | - | | **Meta (Facebook)** | Meta Pixel ID | PageView, ViewContent, AddToCart, InitiateCheckout, Purchase | | **TikTok** | TikTok Pixel ID | page, ViewContent, AddToCart, InitiateCheckout, Purchase | | **Google (GTM / GA4 / Google Ads)** | Container ID — `GTM-XXXXXX`, `G-XXXXXX`, or `AW-XXXXXX` | All events pushed to `dataLayer` (GTM) or via `gtag('event', …)` (GA4 / Google Ads) | | **Snapchat** | Snap Pixel ID | PAGE\_VIEW, VIEW\_CONTENT, ADD\_CART, START\_CHECKOUT, PURCHASE | | **Pinterest** | Pinterest Tag ID | pagevisit, viewcategory, addtocart, checkout, purchase | > [!NOTE] > > **One Google row, three products.** The "Google" pixel slot accepts any of three > ID formats — TagadaPay auto-detects which Google product to load based on the > prefix: > > * `GTM-XXXXXX` → Google Tag Manager. TagadaPay loads `gtm.js` and pushes events > to `dataLayer`. Configure GA4 / Ads conversion tags inside your GTM container. > * `G-XXXXXX` → Google Analytics 4. TagadaPay loads `gtag.js` directly and fires > events via `gtag('event', 'purchase', { value, currency, items })`. > * `AW-XXXXXX` → Google Ads. Same `gtag.js` loader; conversion `send_to` is > handled per-event when configured in the dashboard. > > No separate "GA4" or "Google Ads" provider exists — they all live behind the > same `gtm` config slot in the SDK. If you have both a GTM container and a > direct GA4 measurement ID, add them as two separate Google entries. *** ## Configure Pixels In the TagadaPay dashboard: ``` Settings → Integrations → Add pixel ``` Select the platform, paste your pixel ID, and save. TagadaPay handles the rest — script injection, event mapping, and deduplication. *** ## Event Mapping TagadaPay fires these standard e-commerce events and maps them to each pixel's native event format: | Event | When it fires | Meta (fbq) | TikTok (ttq) | GTM dataLayer | GA4 (gtag) | | - | - | - | - | - | - | | PageView | Every hosted page; every `track.step()` | `PageView` | `page()` | `PageView` | `page_view` | | ViewContent | `track.event('product_viewed')` in a coded funnel | `ViewContent` | `ViewContent` | `ViewContent` | `view_item` | | AddToCart | `track.event('added_to_cart')` in a coded funnel | `AddToCart` | `AddToCart` | `AddToCart` | `add_to_cart` | | InitiateCheckout | Hosted checkout page; `checkout.loadSession()` in a coded funnel | `InitiateCheckout` | `InitiateCheckout` | `InitiateCheckout` | `begin_checkout` | | AddPaymentInfo | Not fired today | `AddPaymentInfo` | `AddPaymentInfo` | `AddPaymentInfo` | `add_payment_info` | | Purchase | Hosted thank-you page; a payment that succeeds through the SDK in a coded funnel | `Purchase` | `Purchase` | `Purchase` | `purchase` | A coded funnel can also send `Lead` (`track.event('lead')`) and any custom event you declare. It loads Meta, TikTok, Snapchat, Google Tag Manager and Microsoft Clarity — not Pinterest. All purchase events are **deduplicated** — they won't fire twice for the same order, even if the customer refreshes the thank-you page. *** ## Funnel Step Tracking TagadaPay also tracks funnel step progression for conversion reporting in the CRM dashboard. This happens automatically when using TagadaPay-hosted funnels or the checkout session flow. *** ## Pixels on Pages You Code For a headless store, let the SDK fire the pixels: ```typescript theme={null} const tagada = createHeadlessClient({ storeId: 'store_abc123', funnel: 'main' }); tagada.track.step('product'); // PageView on the pixels bound to this step tagada.track.event('added_to_cart', { sku }); // AddToCart ``` Checkout and purchase events fire on their own, with the same event id as the server-side events TagadaPay sends, so Meta and TikTok count each conversion once. The whole setup — the manifest, the push, binding pixels on the canvas — is on [Coded Funnels](/developer-tools/headless-sdk/coded-funnels). > [!WARNING] > > Do not also add the same pixel to your page by hand: every event would count twice. [SDK health](/developer-tools/headless-sdk/sdk-health) reports it as **Pixel fired twice**. If your site sends a Content-Security-Policy, allow the [pixel origins](/developer-tools/headless-sdk/csp#pixels). The `CheckoutSession` returned by `loadSession()` does **not** contain pixel config — pixel IDs are a store-level setting, not a session-level one. # SDK Health Source: https://docs.tagada.io/developer-tools/headless-sdk/sdk-health What TagadaPay sees of your coded funnel: steps never reached, events that never arrive, blocked pixels, an outdated SDK — and how to fix each one # SDK Health A coded funnel fails quietly: a pixel blocked by your Content-Security-Policy, a step renamed in the code but not in the manifest, an Apple Pay domain never registered. The visitor sees nothing wrong and the numbers just drop. SDK health is the list of these silent failures, computed from what the Headless SDK reports from your visitors' browsers. It is one report, shown in three places: * on the [canvas](/developer-tools/funnels/canvas): the step cards and their drawer show the checks that concern them; * in your terminal: `npx tagada funnel check`; * in code: `tagada.funnels.health(storeId, funnelKey?)` from `@tagadapay/node-sdk`. A store with no [coded funnel](/developer-tools/headless-sdk/coded-funnels) has no report: it answers `ran: 0` and the canvas shows nothing. *** ## From the terminal ```bash theme={null} export TAGADA_API_KEY=sk_... export TAGADA_STORE_ID=store_abc123 npx tagada funnel check ``` ``` 🟡 Pixel blocked by your CSP tiktok never loaded on shop.example.com: csp. npx tagada funnel csp 🟡 Step declared but never reached upsell was declared on 2026-10-02 and nobody has landed on it. node:sdkstep_8f2c1a @tagadapay/headless-sdk … latest … … @tagadapay/core-js … latest … … @tagadapay/node-sdk … latest … … ran 12 checks ``` Each check prints its title, what was seen, and the fix. Then one line per package (`headless-sdk` and `core-js` as your visitors run them, `node-sdk` as it last pushed) with the latest version and how the two compare. | Flag | What it does | | - | - | | `--funnel=` | Only this funnel. Without it, every coded funnel of the store. | | `--json` | Prints the raw report instead, and always exits `0`. | | `--api-key=`, `--store=`, `--base-url=` | As for [`funnel push`](/developer-tools/headless-sdk/coded-funnels#5-push-the-manifest). | The command exits `1` when at least one check is an error, so you can run it in CI after a deploy. *** ## The report ```typescript theme={null} { status: 'error' | 'warning' | 'ok', // the worst severity present ran: number, // how many checks were evaluated checks: Array<{ id: string, // e.g. 'pixel-blocked' severity: 'error' | 'warning' | 'ok', title: string, detail: string, fix: { kind: 'command' | 'prompt' | 'canvas' | 'link', value: string }, scope: string, // what it is about, see below firstSeenAt: Date | null, lastSeenAt: Date | null, }>, packages: Array<{ name: string, version: string | null, latest: string, state: 'current' | 'recent' | 'outdated' | 'unknown' }>, } ``` * `fix.kind` says how to read `fix.value`: a command to run, an instruction to give your developer or your AI assistant, a place on the canvas (`node:`, `flow:`), or a CRM page. * `scope` is `sdk` (the whole funnel), `step:/`, `event://`, `destination:`, `wallet:applePay` or `wallet:googlePay`. * A check that cannot be evaluated — no data yet, a provider that did not answer — is left out, never reported as `ok`. * For packages, `current` is the latest release or any newer version, `outdated` is a major or three minors behind the latest, `recent` is anything in between, and `unknown` means no version was reported. *** ## The checks The signals behind these checks are what the SDK sends from your visitors' browsers, kept at most once a minute each. "Recently" means in the last 7 days. ### Errors | Check | What it means | Fix | | - | - | - | | `sdk-no-traffic` — SDK has never sent anything | The funnel is declared, and no browser has ever reported anything for this store. Either the site is not live yet, or the pages never call `track.step()`, or they run another store id. | Call `track.step()` on every step, deploy, open a page, and run `npx tagada funnel check` again. | | `sdk-version-unknown` — SDK version not reported | Signals arrive, but none carries an SDK version: the site runs a Headless SDK older than the `track` module. | Upgrade `@tagadapay/headless-sdk` to 1.16.0 or later and redeploy. | | `secret-key-in-browser` — Secret key used from a browser | A request from a browser carried an `Authorization` header. Your secret API key is in your front-end code. | Revoke the key in Settings → API keys now, then keep keys on your server only. | | `wallet-applepay-domain` — Apple Pay domain not registered | Apple Pay is on in the payment flow, and one of the manifest `domains` is not registered for it: the Apple Pay sheet fails on that domain. | Register the domain from the payment flow of the store. See [Wallets](/developer-tools/payments/wallets). | | `wallet-googlepay-domain` — Google Pay domain not registered | Google Pay runs through Stripe, and one of the manifest `domains` is not registered at Stripe. | Register the domain from the payment flow of the store. | | `checkout-no-processor` — Checkout has no active processor | The payment flow of the store has no enabled processor: nobody can pay. | Add or re-enable a processor in the payment flow. | ### Warnings | Check | What it means | Fix | | - | - | - | | `sdk-outdated` — Headless SDK is outdated | Your visitors run a version a major, or three minors, behind the latest. Not raised during the week after a release. | Upgrade `@tagadapay/headless-sdk` and redeploy. | | `manifest-drift` — Deployed manifest is not the declared one | The browsers recently reported a manifest TagadaPay was not given: the site was deployed without pushing. | `npx tagada funnel push` | | `origin-unknown` — Events from an undeclared domain | A host not listed in `domains` recently sent events. They were ignored. | Add the host to `domains`, then push. | | `wallet-unavailable` — Wallet button never appeared | Apple Pay, Google Pay or the express checkout is configured, and recently its button was never built on the checkout page. A visitor whose device does not offer a wallet does not count. | Check why the express button is not rendered on your checkout page. | | `step-never-seen` — Step declared but never reached | A step declared more than 24 hours ago has never been reached, while the funnel has traffic. Often a step id in the code that differs from the manifest. The card shows a **Never seen** pill. | Call `track.step('')` with the manifest id on that page. | | `step-undeclared` — Step seen but not declared | The code recently reported a step id that is not in the manifest. It is on no card. | Add the step to the manifest and push, or fix the id in the code. | | `event-never-received` — Declared event never arrives | An event declared in the manifest more than 24 hours ago has never fired, while its step is reached. | Call `tagada.track.event('')` on that step. | | `pixel-blocked` — Pixel blocked by your CSP | A bound pixel recently failed to load on your site: blocked by the Content-Security-Policy, a load error, or a timeout. | Allow the pixel's origins — see [Content-Security-Policy](/developer-tools/headless-sdk/csp). | | `pixel-duplicate` — Pixel fired twice | Your code loads a pixel that TagadaPay also loads, so events count twice. | Remove the tag from your code, or unbind that pixel on the canvas. | *** ## In the browser `tagada.track.health()` answers for the current page only, without asking the server: whether tracking is on, the funnel key, which pixels loaded, and what was blocked on this page. Use it while you develop; use `funnel check` for what happens across all visitors. # Host & A/B Test Any Page Source: https://docs.tagada.io/developer-tools/hosting/deploy-and-ab-test Deploy any HTML page or SPA onto TagadaPay and run geo or weighted A/B tests — no SDK required # Host & A/B Test Any Page > [!NOTE] > > **Advanced guide.** This walks through raw REST API calls. For most use cases, the [CLI](/developer-tools/cli/introduction) or [dashboard](https://app.tagada.io) is simpler. See the [Developer Tools overview](/developer-tools/index) if you're not sure this is what you need. TagadaPay can host **any static HTML page or single-page application** and serve it on a fast global CDN (\~10ms TTFB). You can then split traffic between variants using weighted or geo-based A/B testing — all through the REST API. *** ## Why Host on TagadaPay Instead of Your Own Servers? | Benefit | Details | | - | - | | **Edge-fast serving** | Pages are served from a global edge network (\~10 ms TTFB). A/B variant selection happens at the edge too — no extra round-trip to an origin server, so visitors never feel the split. | | **Same-URL A/B testing** | Both variants live on the **exact same URL**. The routing engine picks the right one transparently. This is critical for ad campaigns, email links, and SEO — you don't need separate URLs or client-side redirect hacks. | | **Custom domains & routing in one click** | Bring your own domain, point a CNAME, verify via API, done. TagadaPay handles TLS, routing, and CDN caching automatically. No nginx configs, no Cloudflare rules, no load balancers. | | **Free hosting for TagadaPay users** | Hosting is included at no extra cost when you use TagadaPay. No bandwidth bills, no storage fees, no infra to maintain. | ### Use Cases | Use case | Example | | - | - | | **Landing page testing** | Test two headline variants to see which converts better | | **Geo-targeted content** | Show a French page to EU visitors, English to US visitors | | **Gradual rollouts** | Send 10% of traffic to a new design before going 100% | | **External SPAs** | Host a React/Vue/Svelte app without managing your own infra | Every page you deploy gets: * A unique URL on `*.cdn.tagadapay.com` (or your own domain) * Instant global delivery via edge CDN * Built-in A/B split testing (weighted or geo) on the same URL * Sticky sessions so returning visitors see the same variant *** ## Prerequisites > [accordion] TagadaPay account > > Sign up at [app.tagada.io](https://app.tagada.io) and create a **store**. > [accordion] API key > > Go to **Settings → API Keys** in your dashboard and generate one. It looks like `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx`. > [accordion] curl (or any HTTP client) > > All examples use `curl`. You can use Postman, httpie, or any language's HTTP library. *** ## The 3-Step Flow Every deployment follows the same pattern: ``` Deploy → Instantiate → Mount ``` | Step | What it does | | - | - | | **Deploy** | Uploads your files (HTML, CSS, JS, images) to blob storage | | **Instantiate** | Creates a running instance of that deployment for a store | | **Mount** | Binds the instance to a URL so visitors can access it | After that, you can optionally **configure A/B split testing** on the mounted route. *** ## Step 1 — Deploy a Page Create a simple HTML file and deploy it via the API. Assets are sent as **base64-encoded** strings. **1. Prepare your HTML** Any valid HTML works. Here's a minimal example: ```html theme={null} My Landing Page

Welcome!

This page is hosted on TagadaPay.

``` **2. Base64-encode the file** ```bash theme={null} base64 -i index.html # Copy the output — you'll paste it in the next step ``` **3. Call the Deploy API** ```bash theme={null} curl -X POST https://api.tagada.io/api/public/v1/plugins/v2/deploy \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "storeId": "YOUR_STORE_ID", "manifest": { "name": "my-landing-page", "version": "1.0.0", "pages": [ { "id": "main", "path": "/", "name": "Landing Page" } ] }, "inlineAssets": [ { "path": "/index.html", "content": "PASTE_BASE64_HERE", "contentType": "text/html" } ] }' ``` Save the `pluginId` and `deploymentId` from the response — you'll need them next. > [!TIP] > > You can deploy **multiple files** (CSS, JS, images) by adding more entries to `inlineAssets`. Each file needs a `path`, base64 `content`, and `contentType`. *** ## Step 2 — Instantiate An instance is a "live copy" of a deployment, bound to a specific store. You can create multiple instances of the same deployment with different configurations. ```bash theme={null} curl -X POST https://api.tagada.io/api/public/v1/plugins/v2/instantiate \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "pluginId": "PLUGIN_ID_FROM_STEP_1", "deploymentId": "DEPLOYMENT_ID_FROM_STEP_1", "storeId": "YOUR_STORE_ID", "config": {} }' ``` Save the `instanceId` from the response. ### Instance Config The `config` object is optional but powerful. Whatever you pass here is **injected into the served HTML** as `window.__TAGADA_PLUGIN_CONFIG__`, making it available to your JavaScript at runtime. This lets you deploy **one set of files** and customize behavior per-instance without redeploying. ```bash theme={null} # Same deployment, different config per store/use case curl -X POST https://api.tagada.io/api/public/v1/plugins/v2/instantiate \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "pluginId": "PLUGIN_ID", "deploymentId": "DEPLOYMENT_ID", "storeId": "YOUR_STORE_ID", "config": { "theme": "dark", "headline": "Spring Sale — 30% Off!", "ctaUrl": "https://yourstore.com/checkout", "showTimer": true, "timerEnd": "2026-04-01T00:00:00Z" } }' ``` Then read it in your page: ```html theme={null} ``` > [!NOTE] > > **You don't have to read `window.__TAGADA_PLUGIN_CONFIG__` manually.** The [TagadaPay Plugin SDK](/developer-tools/sdk/introduction) reads it for you and exposes it via `tgd.config`. Using the SDK is the recommended approach — it also gives you session management, analytics, and funnel navigation out of the box. Reading the global directly is perfectly valid if you want zero dependencies, but for most use cases the SDK is simpler. > [!NOTE] > > Additional globals like `window.__TAGADA_STORE_ID__` and `window.__TAGADA_ACCOUNT_ID__` (and matching `x-plugin-*` meta tags) are always injected regardless of the config you pass. **Common use cases:** | Config field | Purpose | | - | - | | `theme`, `colors` | Brand customization without redeploying assets | | `headline`, `cta` | Copy testing across multiple instances | | `locale`, `currency` | Localization per region (combine with geo A/B) | | `featureFlags` | Gradual feature rollout | | `analyticsId` | Per-store tracking IDs | *** ## Step 3 — Mount Mounting binds your instance to a hostname so it becomes reachable by visitors. ```bash theme={null} curl -X POST https://api.tagada.io/api/public/v1/plugins/v2/mount \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "instanceId": "INSTANCE_ID_FROM_STEP_2", "storeId": "YOUR_STORE_ID", "hostname": "my-landing-page--YOUR_STORE_ID.cdn.tagadapay.com", "basePath": "/", "matcher": "/" }' ``` Save the `routeId` from the response — you'll need it if you set up A/B testing. Your page is now live at: ``` https://my-landing-page--YOUR_STORE_ID.cdn.tagadapay.com/ ``` *** ## Set Up A/B Testing You can split traffic on any mounted route. TagadaPay supports two split types: | Type | How it works | | - | - | | **weighted** | Split by percentage (e.g. 50/50, 90/10) | | **geo** | Split by visitor country (ISO country codes) | ### Create a Second Variant A variant is just another **instance**. There are two ways to create one: > [tab] Different deployment (different files) > > Deploy entirely different HTML/CSS/JS (Step 1), then instantiate it (Step 2). Each variant has its own build assets — useful when the pages are structurally different (e.g. a completely redesigned layout vs. the original). > > You'll get a separate `pluginId`, `deploymentId`, and `instanceId` for the variant. > [tab] Same deployment, different config > > Reuse the **same deployment** but create a second instance with a different `config`. The assets are identical — only the runtime configuration changes. This is faster and lighter: no need to re-upload files. > > ```bash theme={null} > curl -X POST https://api.tagada.io/api/public/v1/plugins/v2/instantiate \ > -H "Authorization: Bearer YOUR_API_KEY" \ > -H "Content-Type: application/json" \ > -d '{ > "pluginId": "SAME_PLUGIN_ID", > "deploymentId": "SAME_DEPLOYMENT_ID", > "storeId": "YOUR_STORE_ID", > "config": { > "headline": "Free Shipping Today!", > "theme": "light" > } > }' > ``` > > Same HTML, but `window.__TAGADA_PLUGIN_CONFIG__` will contain the new values — so the page renders differently at runtime. > [!NOTE] > > You do **not** mount the second variant separately. Both variants share the **same URL** — the split testing system decides which one to serve. ### Configure the Split Call the split endpoint with the `routeId` from Step 3 and both instance IDs: > [tab] Geo-based > > Route visitors to different variants based on their country. > > ```bash theme={null} > curl -X POST https://api.tagada.io/api/public/v1/plugins/v2/split \ > -H "Authorization: Bearer YOUR_API_KEY" \ > -H "Content-Type: application/json" \ > -d '{ > "routeId": "ROUTE_ID_FROM_STEP_3", > "storeId": "YOUR_STORE_ID", > "splitConfig": { > "type": "geo", > "instances": [ > { > "instanceId": "INSTANCE_A", > "deploymentId": "DEPLOYMENT_A", > "pluginId": "PLUGIN_A", > "regions": ["US", "CA", "MX", "BR"] > }, > { > "instanceId": "INSTANCE_B", > "deploymentId": "DEPLOYMENT_B", > "pluginId": "PLUGIN_B", > "regions": ["FR", "DE", "GB", "ES", "IT"] > } > ], > "stickyDuration": 604800 > } > }' > ``` > > Visitors from unlisted countries fall back to the first instance. > [tab] Weighted (percentage) > > Split traffic by percentage across variants. > > ```bash theme={null} > curl -X POST https://api.tagada.io/api/public/v1/plugins/v2/split \ > -H "Authorization: Bearer YOUR_API_KEY" \ > -H "Content-Type: application/json" \ > -d '{ > "routeId": "ROUTE_ID_FROM_STEP_3", > "storeId": "YOUR_STORE_ID", > "splitConfig": { > "type": "weighted", > "instances": [ > { > "instanceId": "INSTANCE_A", > "deploymentId": "DEPLOYMENT_A", > "pluginId": "PLUGIN_A", > "weight": 50 > }, > { > "instanceId": "INSTANCE_B", > "deploymentId": "DEPLOYMENT_B", > "pluginId": "PLUGIN_B", > "weight": 50 > } > ], > "stickyDuration": 604800 > } > }' > ``` > > Weights must sum to **100**. Adjust as needed (e.g. `90`/`10` for a gradual rollout). *** ## How Sticky Sessions Work When a visitor hits a split route for the first time, TagadaPay picks a variant and stores the choice in a **sticky session** cookie (`tgd-session-id`). On subsequent visits within `stickyDuration` seconds (default: 7 days), the same variant is served. This ensures a consistent experience — a visitor won't flip between variants mid-session. *** ## Update a Variant To push a new version of a variant, deploy with `"overwrite": true`: ```bash theme={null} curl -X POST https://api.tagada.io/api/public/v1/plugins/v2/deploy \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "storeId": "YOUR_STORE_ID", "manifest": { "name": "my-landing-page", "version": "1.1.0", "pages": [ { "id": "main", "path": "/", "name": "Landing Page" } ] }, "inlineAssets": [ { "path": "/index.html", "content": "NEW_BASE64_CONTENT", "contentType": "text/html" } ], "overwrite": true }' ``` The update propagates automatically to all routes using this deployment. No re-mount needed. *** ## Deploying a Full SPA TagadaPay can host any single-page application (React, Vue, Svelte, etc.). Build your app, then deploy all output files: ```bash theme={null} # Build your app npm run build # Encode each file and include in inlineAssets # Example for a Vite React app (dist/ folder): ``` ```json theme={null} { "storeId": "YOUR_STORE_ID", "manifest": { "name": "my-react-app", "version": "1.0.0", "pages": [ { "id": "main", "path": "/", "name": "App" } ] }, "inlineAssets": [ { "path": "/index.html", "content": "...", "contentType": "text/html" }, { "path": "/assets/index-abc123.js", "content": "...", "contentType": "application/javascript" }, { "path": "/assets/index-def456.css", "content": "...", "contentType": "text/css" } ] } ``` > [!TIP] > > All non-HTML paths (JS, CSS, images, fonts) are served with long-lived cache headers. HTML is served with `no-cache` for instant updates. *** ## Advanced: Large File Uploads (> 4 MB) > [!NOTE] > > The `inlineAssets` method shown above sends base64-encoded files inside the JSON body. This works well for small pages, but **serverless functions have a \~4.5 MB body limit**. If your SPA build output is larger — bundled JS, images, fonts — you need the **two-step blob upload** flow instead. > [accordion] How the blob upload flow works > > Instead of embedding assets in the request body, you: > > 1. **Upload a ZIP** of your build output to TagadaPay's blob storage, which supports **multipart uploads up to 50 MB**. > 2. **Deploy from the blob URL** — pass the returned URL to the deploy endpoint, which downloads and extracts the ZIP server-side. > > This is the same flow the [TagadaPay CLI](/developer-tools/cli/introduction) and Studio use under the hood. The CLI automatically switches to blob upload when a build exceeds 4 MB. > [accordion] Step-by-step with curl > > **1. ZIP your build output** > > ```bash theme={null} > cd dist/ # or build/, out/, etc. > zip -r ../my-app.zip . > cd .. > ``` > > **2. Get an upload token** > > The upload token endpoint implements a client upload protocol. You need to call it twice: once to get a token, then once more to confirm completion. In practice, use the `@vercel/blob` client library — it handles both calls for you. > > ```bash theme={null} > npm install @vercel/blob > ``` > > ```javascript theme={null} > import { upload } from '@vercel/blob/client'; > import { readFileSync } from 'fs'; > > const zipBuffer = readFileSync('my-app.zip'); > > const blob = await upload('my-app.zip', zipBuffer, { > access: 'public', > handleUploadUrl: 'https://api.tagada.io/api/public/v1/plugins/generate-upload-token', > multipart: true, > contentType: 'application/zip', > clientPayload: JSON.stringify({ apiKey: 'YOUR_API_KEY' }), > }); > > console.log('Uploaded to:', blob.url); > ``` > > **3. Deploy from the blob URL** > > Now pass the blob URL to the V2 deploy endpoint using the `zipUrl` parameter instead of `inlineAssets`: > > ```bash theme={null} > curl -X POST https://api.tagada.io/api/public/v1/plugins/v2/deploy \ > -H "Authorization: Bearer YOUR_API_KEY" \ > -H "Content-Type: application/json" \ > -d '{ > "storeId": "YOUR_STORE_ID", > "manifest": { > "name": "my-react-app", > "version": "1.0.0", > "pages": [ > { "id": "main", "path": "/", "name": "App" } > ] > }, > "zipUrl": "BLOB_URL_FROM_PREVIOUS_STEP" > }' > ``` > > The server downloads the ZIP, extracts all files, and uploads each one to blob storage — exactly like `inlineAssets`, but without the body size limit. > > **4. Continue as usual** > > From here, the flow is identical: **instantiate** → **mount** → optionally **configure A/B testing**. The `pluginId` and `deploymentId` from the response are the same as with inline assets. > [accordion] When to use which method > > | Method | Max size | Best for | > | - | - | - | > | `inlineAssets` (base64 in JSON) | \~4 MB total payload | Single HTML pages, small sites, quick tests | > | `zipUrl` (blob upload) | 50 MB | Full SPAs, sites with images/fonts, production builds | > > > [!TIP] > > > > If you use the [TagadaPay CLI](/developer-tools/cli/introduction), you don't need to think about this — it detects the file size and picks the right method automatically. *** ## Custom Domain By default your page is served on `*.cdn.tagadapay.com`. You can mount it on your own domain instead using the Domains API. **1. Register the domain** Call the domains API to add your domain to TagadaPay. This registers it with the edge network and returns a verification token. ```bash theme={null} curl -X POST https://api.tagada.io/api/public/v1/domains/add \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "domain": "landing.yourstore.com" }' ``` Response: ```json theme={null} { "success": true, "domain": { "id": "cdm_abc123", "domain": "landing.yourstore.com", "isVerified": false, "enabled": false, "verificationToken": "vrf_token_xyz" } } ``` Save the `id` — you'll use it to verify. **2. Configure DNS** Add the required DNS records at your registrar. You need a **CNAME** pointing to `cname.vercel-dns.com`: | Type | Name | Value | | - | - | - | | CNAME | `landing` | `cname.vercel-dns.com` | Wait for DNS propagation (usually a few minutes, can take up to 48h). **3. Verify the domain** Once DNS has propagated, call the verify endpoint: ```bash theme={null} curl -X POST https://api.tagada.io/api/public/v1/domains/verify \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "domainId": "cdm_abc123" }' ``` A successful response looks like: ```json theme={null} { "status": "Valid Configuration", "ownershipStatus": "Verified" } ``` **4. Mount on the custom domain** Once verified, mount your instance using the `customDomain` field: ```bash theme={null} curl -X POST https://api.tagada.io/api/public/v1/plugins/v2/mount \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "deploymentId": "YOUR_DEPLOYMENT_ID", "deploymentInstanceId": "YOUR_INSTANCE_ID", "storeId": "YOUR_STORE_ID", "customDomain": "landing.yourstore.com", "basePath": "/", "matcher": "/" }' ``` Your page is now live at `https://landing.yourstore.com/`. > [!TIP] > > HTTPS is provisioned automatically. A/B testing, sticky sessions, and all other features work identically on custom domains. You can also list and remove domains: ```bash theme={null} # List all your domains curl -X POST https://api.tagada.io/api/public/v1/domains/list \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{}' # Remove a domain curl -X POST https://api.tagada.io/api/public/v1/domains/remove \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "domainId": "cdm_abc123" }' ``` *** ## API Reference ### Write Operations | Endpoint | Method | Description | | - | - | - | | `/api/public/v1/plugins/v2/deploy` | POST | Upload files and create a deployment (`inlineAssets` or `zipUrl`) | | `/api/public/v1/plugins/generate-upload-token` | POST | Get a blob upload token for large files (multipart, up to 50 MB) | | `/api/public/v1/plugins/v2/instantiate` | POST | Create a live instance from a deployment | | `/api/public/v1/plugins/v2/mount` | POST | Bind an instance to a URL (hostname or custom domain) | | `/api/public/v1/plugins/v2/split` | POST | Configure A/B testing on a route | | `/api/public/v1/domains/add` | POST | Register a custom domain | | `/api/public/v1/domains/verify` | POST | Verify DNS configuration | | `/api/public/v1/domains/remove` | POST | Remove a custom domain | ### Read Operations | Endpoint | Method | Description | | - | - | - | | `/api/public/v1/plugins/v2/deployments/{deploymentId}` | GET | Get deployment details (version, pages) — no storeId required | | `/api/public/v1/plugins/v2/instances/{storeId}` | GET | List all instances for a store (optionally filter by `?deploymentId=`) | | `/api/public/v1/plugins/v2/instances/detail/{instanceId}` | GET | Get a single instance with its config and deployment data | | `/api/public/v1/plugins/v2/list/{storeId}` | GET | List all plugins for a store | | `/api/public/v1/plugins/v2/mount-points/{storeId}` | GET | List mount points for a store | | `/api/public/v1/plugins/v2/details/{pluginId}` | GET | Get plugin details | | `/api/public/v1/domains/list` | POST | List all custom domains | ### Funnel Operations | Endpoint | Method | Description | | - | - | - | | `/api/public/v1/funnels/{funnelId}` | GET | Get funnel config (nodes now include `deploymentId`) | | `/api/public/v1/funnels/{funnelId}` | PUT | Update funnel with automatic routing | | `/api/public/v1/funnels/{funnelId}/promote` | POST | Promote staging to production (handles prebuilds) | All endpoints require `Authorization: Bearer YOUR_API_KEY` and `Content-Type: application/json`. *** ## Troubleshooting > [accordion] 404 after mounting > > Make sure the `hostname` in the mount request matches the URL you're visiting. > Format: `{slug}--{storeId}.cdn.tagadapay.com` > > Double-check that `basePath` is `/` and `matcher` is `/`. > [accordion] A/B test always shows the same variant > > Sticky sessions may be pinning you to one variant. Clear your cookies or use incognito mode to get a fresh session. For geo testing, the system reads the visitor's country from the edge network — make sure you're testing from the expected country or use a VPN. > [accordion] Assets (CSS/JS) return 404 > > Ensure each asset's `path` in `inlineAssets` matches the path referenced in your HTML. > For example, if your HTML has ` ``` Its options, the npm build and the session rules are on the [External Page Tracker](/developer-tools/web-integration/external-page-tracker) page. Use the tracker for page views and the server route for anything involving an order. *** ## When it does not work | What you get | What it means | | - | - | | `401` — *Missing or invalid API key* | No `Authorization` header, an empty Bearer token, or a revoked key | | `403` — *You do not have access to this store* | The key's account does not own that `storeId` | | `400` with a zod issue list | A required field is missing, or `eventType` is not one of the four values | | `500` — *customEventName is required for custom events* | `eventType: 'custom'` with no `customEventName`. The SDK refuses this one before it leaves your process; the raw endpoint does not | > [!TIP] > > Send the same `stepId` on every call for a given page. It is the key everything else is grouped by: change it and you start a second block on the canvas with none of the history of the first. ## Next > [card] [Funnel Canvas](/developer-tools/funnels/canvas) > > The five commands, the exits, and the error catalogue. > [card] [External Page Tracker](/developer-tools/web-integration/external-page-tracker) > > The browser tracker in full. # Get an API key from code Source: https://docs.tagada.io/developer-tools/node-sdk/get-api-key Mint a Tagada API key in 30 seconds — from a script, an AI tool, or your terminal. No dashboard, no browser. # Get an API key from code > **TL;DR** — Run one command, paste a 6-digit code from your inbox, get an API key. No browser, no dashboard, no copy-pasting. ```bash theme={null} npx -p @tagadapay/node-sdk@latest tagada-init you@example.com ``` That's the whole onboarding. It mails you a code, verifies it, provisions a fresh sandbox account + a demo-seeded store, and writes `TAGADA_API_KEY`, `TAGADA_STORE_ID`, and `TAGADA_ACCOUNT_ID` into the `.env` of the directory you're in. > [!NOTE] > > **Why this exists.** AI coding tools (Claude, Cursor, Lovable, v0…) are great at writing storefront code, but they can't click through a signup form. So we exposed the same flow as a CLI command and a public SDK call — both end with a working API key in your hands. *** ## Pick your path | You're… | Use this | Why | | - | - | - | | Following a tutorial / hacking on your laptop | **`tagada-init` CLI** (below) | Interactive, writes `.env` for you | | Building an installer / scaffolding tool | **`Tagada.public()` SDK** (below) | Programmatic, no prompts | | Already have a Tagada account | **Dashboard → Settings → Access Tokens** | One-click new key for an existing account | All three end with the same thing: a UUID-shaped API key that works against `https://api.tagada.io`. *** ## Path 1 — The CLI (interactive) ```bash theme={null} npx -p @tagadapay/node-sdk@latest tagada-init you@example.com ``` What happens, step by step: **1. The CLI calls /api/public/onboarding/start** A 6-digit code lands in `you@example.com` within a few seconds. The email subject is **"Verify your TagadaPay account"** — the code is only inside the body, never in the subject or lock-screen preview. **2. You paste the code** The CLI prompts you. Type the 6 digits, hit enter. **3. The CLI calls /api/public/onboarding/verify** On success it gets back an `apiKey`, `storeId`, and `accountId`, and writes them to `.env` in the current directory: ```bash theme={null} # generated by tagada-init TAGADA_API_KEY=ed8a… TAGADA_STORE_ID=store_… TAGADA_ACCOUNT_ID=acc_… ``` It also writes framework-specific mirrors when relevant: | Framework | Variables added | | - | - | | **Vite** | `VITE_TAGADA_STORE_ID`, `VITE_TAGADA_ACCOUNT_ID` | | **Next.js** | `NEXT_PUBLIC_TAGADA_STORE_ID`, `NEXT_PUBLIC_TAGADA_ACCOUNT_ID` | | **Astro** | `PUBLIC_TAGADA_STORE_ID`, `PUBLIC_TAGADA_ACCOUNT_ID` | **4. A demo store seeds in the background** Sandbox processor, payment flow, 2 demo products (an *Essential Tee* in 3 colorways and an *Essential Cap*), one checkout upsell, and a default shipping rate. Takes \~10 seconds. Your API key is usable immediately — the catalog populates as the seeder runs. Want a richer 6-product apparel catalog? Examples like [`headless-react-store`](https://github.com/TagadaPay/examples/tree/main/headless-react-store) ship a `scripts/seed.ts` you can run with `pnpm seed $TAGADA_API_KEY` to extend the demo. > [!TIP] > > **Skip prompts entirely (CI, scripted demos, AI agents).** Because the user has to read the OTP from an inbox between the two API calls, the CLI exposes a **two-stage flow** so any orchestrator can drive it without a TTY: > > ```bash theme={null} > # 1. Mail the code (returns immediately, no prompt). > npx -p @tagadapay/node-sdk@latest tagada-init you@example.com --start-only > > # 2. After the user pastes the code into your agent / form / CI input: > npx -p @tagadapay/node-sdk@latest tagada-init you@example.com \ > --code=123456 --non-interactive > ``` > > | Flag | What it does | > | - | - | > | `--start-only` | Calls `/start` only — mails the OTP and exits with code 0. Re-invoke later with `--code` to verify. | > | `--code=NNNNNN` | Skips the `/start` call (assumes the code is already in flight) and calls `/verify` directly. Pair with `--non-interactive` to avoid any TTY fallback. | > | `--non-interactive` | Refuses to prompt. Fails fast (exit code `2`) if `--code` is missing. | > | `--source=` | Tags the onboarding attempt for analytics (`docs-llm-test`, `my-installer-v1`, etc.). | > > Three-line shell sketch for an LLM-mediated flow: > > ```bash theme={null} > npx -p @tagadapay/node-sdk@latest tagada-init you@example.com --start-only > read -p "Code from inbox: " CODE > npx -p @tagadapay/node-sdk@latest tagada-init you@example.com --code=$CODE --non-interactive > ``` *** ## Path 2 — The SDK (programmatic) If you're writing your own script (an AI agent, a CI step, an installer for your framework), call the SDK directly. `Tagada.public()` returns a *no-auth* client — its only job is to bootstrap a key for `new Tagada(apiKey)`: ```ts theme={null} import Tagada from '@tagadapay/node-sdk'; const onboarding = Tagada.public(); // hits api.tagada.io by default // 1. Mail a 6-digit code to the user. await onboarding.start({ email: 'you@example.com', source: 'my-installer-v1', }); // 2. Once you have the code (interactive prompt, query string, etc.): const result = await onboarding.verify({ email: 'you@example.com', code: '123456', }); console.log(result.apiKey); // ready to use console.log(result.storeId); // demo store created for you console.log(result.accountId); // 3. Drop it into the regular client: const tagada = new Tagada(result.apiKey); const store = await tagada.stores.retrieve(result.storeId); ``` The shape of `result`: ```ts theme={null} { ok: true, apiKey: string, // UUID, use immediately accountId: string, // 'acc_…' storeId: string, // 'store_…' — demo seeding starts in background clerkUserId: string, // 'user_…' clerkOrgId: string, // 'org_…' orgSlug: string | null, demoSeeding: 'pending', // poll tagada.stores.retrieve(...) if you need to wait } ``` ### Error handling `onboarding.start` and `onboarding.verify` throw an `OnboardingError` with a typed `code` field — no string-sniffing required: ```ts theme={null} import Tagada, { OnboardingError } from '@tagadapay/node-sdk'; try { await Tagada.public().verify({ email, code }); } catch (err) { if (!(err instanceof OnboardingError)) throw err; switch (err.code) { case 'invalid_code': /* user mistyped — let them retry */ break; case 'expired': /* code older than 5 minutes — call start again */ break; case 'no_pending_code': /* claim already used or never sent */ break; case 'too_many_attempts': /* 5 wrong tries on the same code */ break; case 'rate_limited': /* throttled — err.resetAt is a Date */ break; case 'email_send_failed': /* transient — retry start */ break; case 'provisioning_failed':/* server side — retry verify, claim auto-released */ break; case 'network_error': /* connection / timeout */ break; case 'invalid_request': /* bad payload (e.g. malformed email) */ break; } } ``` > [!NOTE] > > **Same email twice?** Both `tagada-init` and `Tagada.public()` mint a *fresh* sandbox account on every successful verify. If you re-run with an email that already has an account, the call will succeed and you'll get a brand-new account — keep track of the keys you've generated. *** ## Path 3 — The dashboard (existing account) If you already have a Tagada account and just need a new key: **1. Open Settings** Click your avatar (top-right) → **Settings**. ![Navigate to Settings from the user menu](https://mintcdn.com/tagadapay/TKkbuy8GaudqLW4Y/assets/images/api-key-menu.png?fit=max\&auto=format\&n=TKkbuy8GaudqLW4Y\&q=85\&s=5610f731f341dd04cbf426269c14398d) **2. Generate the key** Go to **Access Tokens** → **+ Create Access Token**. Copy the UUID. ![Access Tokens page in Settings](https://mintcdn.com/tagadapay/TKkbuy8GaudqLW4Y/assets/images/api-key-settings.png?fit=max\&auto=format\&n=TKkbuy8GaudqLW4Y\&q=85\&s=c6473adc09ba63dde29d03d9b7751d6a) *** ## What the API key gives you The key minted via `tagada-init` / `Tagada.public()` has **`org:admin`** scope on the new account — it can do everything the SDK exposes: | Surface | What you can call | | - | - | | Stores & products | `tagada.stores.*`, `tagada.products.*` | | Processors & flows | `tagada.processors.*`, `tagada.paymentFlows.*` | | Payments & orders | `tagada.payments.*`, `tagada.orders.*` | | Customers & subs | `tagada.customers.*`, `tagada.subscriptions.*` | | Webhooks | `tagada.webhooks.*`, `tagada.events.*` | | Plugins / pages | `tagada.plugins.*` | For multi-tenant setups that mint *per-merchant* keys from a partner account, see the [Partners tab](/developer-tools/partners/introduction). *** ## Security model — quick notes * **OTP delivery:** 6-digit, single-use, expires after 5 minutes. Generated with a CSPRNG (`crypto.randomInt`). * **Rate limits:** 3 sends / 10 min / IP and 5 sends / hour / email on `start`; 10 verifies / 10 min / IP on `verify` (fail-closed if our cache is unavailable, so brute-forcing isn't possible during outages). * **Lock-screen-safe email:** the subject is `"Verify your TagadaPay account"` and the lock-screen preview is `"Open this email to see your verification code."` — the code itself is only inside the email body. * **Single-claim provisioning:** even if `verify` is called twice in parallel with the same correct code, only one of the calls provisions an account — the other gets `no_pending_code`. *** ## Next steps > [card] [Build a store with AI](/developer-tools/headless-sdk/build-store-with-ai) > > Use Claude, Lovable, or v0 with the key you just minted. > [card] [Node SDK Quick Start](/developer-tools/node-sdk/quick-start) > > Create stores, products, and process payments from your server. # Merchant Quick Start Source: https://docs.tagada.io/developer-tools/node-sdk/merchant-quickstart Go from zero to a live checkout in 7 Node.js SDK calls # Merchant Quick Start **Time**: \~5 minutes | **Difficulty**: Beginner This guide walks you through the minimal steps to set up a complete, working checkout using the **TagadaPay Node.js SDK** (`@tagadapay/node-sdk`). Every step has been tested end-to-end on a live environment. *** ## Overview ``` 1. Create processor → Connect a payment gateway 2. Create payment flow → Define routing strategy 3. Create store → Your merchant storefront 4. Create product → What you're selling 5. Create funnel → Checkout + Thank You pages 6. Activate funnel → Routes are mounted, checkout is live 7. Create session → Generate a checkout link for your customer ``` > [!NOTE] > > **Native checkout is automatic.** When you create a funnel with `checkout` and `thankyou` steps, TagadaPay injects its built-in checkout UI automatically. No plugin deployment needed. *** ## Prerequisites | Requirement | How to get it | | - | - | | **Node.js 18+** | [nodejs.org](https://nodejs.org) | | **TagadaPay account** | Sign up at [app.tagada.io](https://app.tagada.io) | | **API key** | Dashboard → Settings → API Keys → Generate | ```bash theme={null} npm install @tagadapay/node-sdk ``` ```ts theme={null} import Tagada from '@tagadapay/node-sdk'; const tagada = new Tagada('your-api-key'); ``` *** ## Step 1: Create a Processor A processor is your connection to a payment gateway (Stripe, NMI, Checkout.com, etc.). For testing, use the `sandbox` type. ```ts theme={null} const { processor } = await tagada.processors.create({ processor: { name: 'Stripe US', type: 'stripe', enabled: true, supportedCurrencies: ['USD', 'EUR'], baseCurrency: 'USD', options: { secretKey: 'sk_live_...', publicKey: 'pk_live_...', webhookSecret: 'whsec_...', }, }, }); ``` > [!TIP] > > For testing without real credentials, use `type: 'sandbox'` with `options: { testMode: true }`. See the [Sandbox Testing Guide](/developer-tools/node-sdk/sandbox-testing) for details. > > Each processor type requires different credentials. See the [Processor Credentials Reference](/developer-tools/node-sdk/processor-credentials) for the exact `options` fields for Stripe, NMI, Checkout.com, Airwallex, and all other gateways. *** ## Step 2: Create a Payment Flow A payment flow defines how transactions are routed through your processors. A simple flow sends all traffic to one processor. ```ts theme={null} const flow = await tagada.paymentFlows.create({ data: { name: 'Default Flow', strategy: 'simple', fallbackMode: false, maxFallbackRetries: 0, threeDsEnabled: false, stickyProcessorEnabled: false, pickProcessorStrategy: 'weighted', processorConfigs: [ { processorId: processor.id, weight: 100, disabled: false, nonStickable: false }, ], fallbackProcessorConfigs: [], abuseDetectionConfig: null, }, }); ``` > [!NOTE] > > For production, consider using `strategy: 'cascade'` with multiple processors and fallback configs. See [Multi-Stripe Routing](/developer-tools/node-sdk/multi-stripe-routing) for advanced setups. *** ## Step 3: Create a Store The store represents your merchant storefront. Pass `selectedPaymentFlowId` to assign the payment flow at creation. ```ts theme={null} const store = await tagada.stores.create({ name: 'My Store', baseCurrency: 'USD', presentmentCurrencies: ['USD', 'EUR'], chargeCurrencies: ['USD'], selectedPaymentFlowId: flow.id, }); ``` *** ## Step 4: Create a Product Products define what you're selling, with multi-currency pricing and optional recurring billing. ```ts theme={null} const product = await tagada.products.create({ storeId: store.id, name: 'Premium Plan', active: true, variants: [{ name: 'Monthly', sku: 'premium-monthly', grams: 0, price: 2999, compareAtPrice: 0, active: true, default: true, prices: [{ currencyOptions: { USD: { amount: 2999 }, EUR: { amount: 2599 }, }, recurring: false, billingTiming: 'in_advance', default: true, }], }], }); const variantId = product.variants[0].id; console.log('Product:', product.id, '| Variant:', variantId); ``` > [!TIP] > > For subscriptions, set `recurring: true`, `interval: 'month'`, and `intervalCount: 1`. See [Subscriptions Guide](/developer-tools/node-sdk/subscriptions). *** ## Step 5: Create a Funnel A **funnel** is the sequence of pages your customer goes through. Think of it like a slideshow: ``` Page 1: Checkout (customer pays) → Page 2: Thank You (order confirmed) ``` You just tell TagadaPay what pages you want — it gives you a live URL. ```ts theme={null} const funnel = await tagada.funnels.create({ storeId: store.id, config: { id: 'my-checkout', name: 'My Checkout', version: '1.0.0', nodes: [ { id: 'step_checkout', name: 'Checkout', type: 'checkout', // ← tells TagadaPay this is a payment page kind: 'step', isEntry: true, // ← this is the first page position: { x: 0, y: 0 }, config: { path: '/checkout' }, }, { id: 'step_thankyou', name: 'Thank You', type: 'thankyou', // ← tells TagadaPay this is the confirmation page kind: 'step', position: { x: 300, y: 0 }, config: { path: '/thankyou' }, }, ], edges: [ { id: 'e1', source: 'step_checkout', target: 'step_thankyou' }, ], }, isDefault: true, }); ``` > [!NOTE] > > **You don't need to build a checkout page.** TagadaPay automatically injects its built-in checkout UI (the "native checkout") into `checkout` and `thankyou` steps. It always uses the latest version — no plugin deployment, no configuration needed. > > Want your own custom pages instead? See the [Funnel Pages](/developer-tools/node-sdk/custom-checkout) guide. *** ## Step 6: Activate the Funnel Creating a funnel saves it to the database, but it's not live yet. Calling `update` triggers the **routing engine** — this is the step that actually mounts your pages to a URL on TagadaPay's CDN. ```ts theme={null} const result = await tagada.funnels.update(funnel.id, { storeId: store.id, config: funnel.config, }); const checkoutNode = result.funnel.config.nodes .find(n => n.id === 'step_checkout'); console.log('Checkout live at:', checkoutNode.config.url); ``` After this call, your checkout has a real URL that customers can visit. > [!WARNING] > > **Don't skip this step.** Without `update`, the funnel exists in the database but has no routes — the checkout URL won't work. Think of `create` as saving a draft and `update` as publishing it. *** ## Step 7: Create a Checkout Session The funnel is live, but to send a customer to checkout you need a **checkout session**. This ties a specific cart (product + quantity + currency) to a unique session token. Use `tagada.checkout.createSession()` — it creates a session and returns the redirect URL with a checkout token: ```ts theme={null} const funnelCheckoutUrl = result.funnel.config.nodes .find(n => n.id === 'step_checkout').config.url; const session = await tagada.checkout.createSession({ storeId: store.id, items: [{ variantId, quantity: 1 }], currency: 'USD', checkoutUrl: funnelCheckoutUrl, }); console.log('Checkout token:', session.checkoutToken); console.log('Checkout link:', session.redirectUrl); ``` > [!TIP] > > The `variantId` is returned by `products.create()` in step 4. If you need it later, you can also retrieve the product with `tagada.products.retrieve(productId)`. The returned `redirectUrl` can be used as: * A **direct link** in emails, ads, or landing pages — the customer clicks it and lands on checkout with their cart pre-filled * A **redirect target** from your backend — embed it in a button or `` tag > [!NOTE] > > The `checkoutUrl` parameter is **critical** — it tells TagadaPay where to redirect the customer. Without it, the session redirects to the default CMS checkout instead of your funnel's deployed page. *** ## Complete Script Here's the full flow in one script: ```ts theme={null} import Tagada from '@tagadapay/node-sdk'; const tagada = new Tagada('your-api-key'); // 1. Processor const { processor } = await tagada.processors.create({ processor: { name: 'Sandbox', type: 'sandbox', enabled: true, supportedCurrencies: ['USD'], baseCurrency: 'USD', options: { testMode: true }, }, }); // 2. Payment flow const flow = await tagada.paymentFlows.create({ data: { name: 'Default', strategy: 'simple', fallbackMode: false, maxFallbackRetries: 0, threeDsEnabled: false, stickyProcessorEnabled: false, pickProcessorStrategy: 'weighted', processorConfigs: [{ processorId: processor.id, weight: 100, disabled: false, nonStickable: false }], fallbackProcessorConfigs: [], abuseDetectionConfig: null, }, }); // 3. Store const store = await tagada.stores.create({ name: 'My Store', baseCurrency: 'USD', presentmentCurrencies: ['USD', 'EUR'], chargeCurrencies: ['USD'], selectedPaymentFlowId: flow.id, }); // 4. Product const product = await tagada.products.create({ storeId: store.id, name: 'Premium Plan', active: true, variants: [{ name: 'Monthly', sku: 'premium-monthly', grams: 0, price: 2999, compareAtPrice: 0, active: true, default: true, prices: [{ currencyOptions: { USD: { amount: 2999 } }, recurring: false, billingTiming: 'in_advance', default: true }], }], }); const variantId = product.variants[0].id; // 5. Funnel const funnel = await tagada.funnels.create({ storeId: store.id, config: { id: 'my-checkout', name: 'My Checkout', version: '1.0.0', nodes: [ { id: 'step_checkout', name: 'Checkout', type: 'checkout', kind: 'step', isEntry: true, position: { x: 0, y: 0 }, config: { path: '/checkout' } }, { id: 'step_thankyou', name: 'Thank You', type: 'thankyou', kind: 'step', position: { x: 300, y: 0 }, config: { path: '/thankyou' } }, ], edges: [{ id: 'e1', source: 'step_checkout', target: 'step_thankyou' }], }, isDefault: true, }); // 6. Activate const result = await tagada.funnels.update(funnel.id, { storeId: store.id, config: funnel.config, }); const funnelCheckoutUrl = result.funnel.config.nodes .find(n => n.id === 'step_checkout').config.url; console.log('Funnel live at:', funnelCheckoutUrl); // 7. Checkout session — generate a link customers can open const session = await tagada.checkout.createSession({ storeId: store.id, items: [{ variantId, quantity: 1 }], currency: 'USD', checkoutUrl: funnelCheckoutUrl, }); console.log('Checkout link:', session.redirectUrl); ``` *** ## What Happens Under the Hood | Step | What it does | Side effects | | - | - | - | | `processors.create()` | Stores gateway credentials | None | | `paymentFlows.create()` | Defines routing rules | None | | `stores.create()` | Creates store, assigns flow | Seeds translations, order counter | | `products.create()` | Creates product + variants + prices | None | | `funnels.create()` | Saves funnel config, auto-injects native checkout | Creates plugin instance if needed | | `funnels.update()` | **Triggers routing engine** — mounts pages, creates CDN routes, builds prebuilt HTML | Pages go live | | `checkout.createSession()` | Creates a checkout session with cart items, returns redirect URL | Creates customer, session | *** ## Next Steps > [card] [Sandbox Testing](/developer-tools/node-sdk/sandbox-testing) > > Test payments without real money using the sandbox processor > [card] [Multi-PSP Routing](/developer-tools/node-sdk/multi-stripe-routing) > > Cascade across Stripe, Checkout.com, NMI with weighted distribution > [card] [Subscriptions](/developer-tools/node-sdk/subscriptions) > > Set up recurring billing with subscription products > [card] [Funnel Pages](/developer-tools/node-sdk/custom-checkout) > > Page types, custom pages, and deploy your own checkout, landing, or offer pages # Multi-PSP Routing & Vault Source: https://docs.tagada.io/developer-tools/node-sdk/multi-stripe-routing Connect Stripe, NMI, Checkout.com, Airwallex — vault cards once, route and cascade transactions automatically # Multi-PSP Routing & Vault **Time**: \~10 minutes | **Difficulty**: Intermediate *** ## The Problem You're locked into one payment processor. If it declines, you lose the sale: ``` Customer → Stripe → decline → lost sale ``` With TagadaPay, you connect **all your processors** and route intelligently: ``` Customer → TagadaPay → Stripe (40% traffic) → Checkout.com (30% traffic) → Airwallex (30% traffic) → NMI (fallback if all fail) ``` Card data is vaulted **once**. Transactions flow to the best processor automatically. If one declines, the next one picks up — **zero extra code on your side**. > [!NOTE] > > **TagadaPay sits above every PSP.** It's not a Stripe plugin or a Checkout.com add-on. You connect any combination of Stripe, NMI, Checkout.com, Airwallex, and [more](/developer-tools/payments/processors) — then define routing rules. Each processor is just a connection with API keys. *** ## How It Works ``` ┌─────────────────────────────────────────────────────────────┐ │ Your Checkout │ │ (Plugin SDK, headless, or any frontend) │ │ ↓ │ │ Card tokenized │ │ (PCI-compliant vault, one time) │ │ ↓ │ │ ┌──────── Payment Flow ─────────┐ │ │ │ strategy: cascade │ │ │ │ 40% → Stripe │ │ │ │ 30% → Checkout.com │ ← sticky: reuse │ │ │ 30% → Airwallex │ last successful │ │ │ fallback #1 → NMI │ processor for │ │ │ fallback #2 → Stripe (retry) │ returning │ │ └───────────────────────────────┘ customers │ │ ↓ │ │ Transaction OK │ └─────────────────────────────────────────────────────────────┘ ``` Three concepts to understand: | Concept | What it is | | - | - | | **Processor** | A PSP connection (Stripe, NMI, Checkout.com, Airwallex, etc.) with its own API keys | | **Payment Flow** | A routing rule: which processors to use, traffic weights, fallback order | | **Vault** | Card data is tokenized once and reusable across **all** processors — you never see raw card numbers | *** ## Step 1: Connect Your Processors Add each processor in the [TagadaPay dashboard](https://app.tagada.io) → Settings → Processors, or connect them via the SDK: | Processor | What you provide | | - | - | | **Stripe** | Secret key + Publishable key **or** use [Stripe Connect OAuth](#stripe-connect-via-api) | | **NMI** | API key (or username/password) | | **Checkout.com** | Secret key + Public key + Processing Channel ID | | **Airwallex** | Client ID + API Key | After connecting, list them via the SDK to get their IDs: ```ts theme={null} import Tagada from '@tagadapay/node-sdk'; const tagada = new Tagada('your-api-key'); const { processors } = await tagada.processors.list(); console.log(processors); // [ // { id: 'proc_s1', name: 'Stripe', type: 'stripe', enabled: true }, // { id: 'proc_nmi', name: 'NMI', type: 'nmi', enabled: true }, // { id: 'proc_cko', name: 'Checkout.com', type: 'checkout', enabled: true }, // { id: 'proc_aw', name: 'Airwallex', type: 'airwallex', enabled: true }, // ] ``` > [!TIP] > > You can connect **unlimited** processor accounts — even multiple Stripe accounts (US, EU, etc.). TagadaPay is fully gateway-agnostic. *** ## Step 2: Create a Payment Flow A payment flow defines **how** transactions are routed across your 4 processors: ```ts theme={null} const flow = await tagada.paymentFlows.create({ data: { name: 'Global 4-PSP Cascade', strategy: 'cascade', fallbackMode: true, maxFallbackRetries: 2, threeDsEnabled: true, stickyProcessorEnabled: true, pickProcessorStrategy: 'weighted', processorConfigs: [ { processorId: 'proc_s1', weight: 40, disabled: false, nonStickable: false }, // Stripe — 40% { processorId: 'proc_cko', weight: 30, disabled: false, nonStickable: false }, // Checkout.com — 30% { processorId: 'proc_aw', weight: 30, disabled: false, nonStickable: false }, // Airwallex — 30% ], fallbackProcessorConfigs: [ { processorId: 'proc_nmi', orderIndex: 0 }, // NMI — 1st fallback { processorId: 'proc_s1', orderIndex: 1 }, // Stripe — 2nd fallback (retry) ], }, }); console.log(flow.id); // 'flow_xyz' ``` Here's what each field does: | Field | What it does | | - | - | | `strategy: 'cascade'` | Use multiple processors (vs `'simple'` for one) | | `fallbackMode: true` | If the primary processor declines, try the next one | | `maxFallbackRetries: 2` | Try up to 2 fallback processors before giving up | | `pickProcessorStrategy: 'weighted'` | Distribute traffic by weight (40/30/30 split) | | `stickyProcessorEnabled: true` | Returning customers reuse their last successful processor | | `threeDsEnabled: true` | Enable 3D Secure when required by the card issuer | | `processorConfigs` | Primary processors with traffic weights | | `fallbackProcessorConfigs` | Backup processors tried in `orderIndex` order on decline | > [!NOTE] > > **Yes, a processor can appear in both lists.** Stripe is the primary at 40% *and* the 2nd fallback. If Checkout.com or Airwallex declines, NMI tries first, then Stripe retries — sometimes a retry on the same PSP with a fresh attempt succeeds. *** ## Step 3: Vault a Card (Tokenize Once) Card data is tokenized **client-side** via `@tagadapay/core-js`. The raw card number never reaches your server. ```ts theme={null} // Client-side (browser) import { useCardTokenization } from '@tagadapay/core-js/react'; const { tokenizeCard } = useCardTokenization({ environment: 'production' }); const { tagadaToken } = await tokenizeCard({ cardNumber: '4242424242424242', expiryDate: '12/28', cvc: '123', cardholderName: 'Jane Doe', }); // Send tagadaToken to your server → ``` Then, **server-side**, create a reusable payment instrument: ```ts theme={null} // Server-side (Node.js) const { paymentInstrument, customer } = await tagada.paymentInstruments.createFromToken({ tagadaToken: tagadaToken, // base64 string from client storeId: 'store_xxx', customerData: { email: 'jane@example.com', firstName: 'Jane', lastName: 'Doe', }, }); console.log(paymentInstrument.id); // 'pi_abc123' // This instrument is now vaulted — reusable across ALL processors ``` > [!NOTE] > > **One vault, all processors.** The payment instrument is PSP-agnostic. TagadaPay translates it to the right format for whichever processor the flow selects — Stripe, NMI, Checkout.com, Airwallex, or any other. You tokenize once, charge anywhere. *** ## Step 4: Charge — TagadaPay Routes Automatically ```ts theme={null} const { payment } = await tagada.payments.process({ amount: 4999, // $49.99 in cents currency: 'USD', storeId: 'store_xxx', paymentInstrumentId: paymentInstrument.id, paymentFlowId: flow.id, // uses the 4-PSP cascade flow initiatedBy: 'customer', mode: 'purchase', }); console.log(payment.status); // 'captured' console.log(payment.processorId); // 'proc_cko' (Checkout.com won the route) ``` What happened under the hood: 1. TagadaPay's weighted algorithm picked **Checkout.com** (30% weight, this time) 2. If Checkout.com declined → automatically retried on **NMI** (fallback #1) 3. If NMI also declined → retried on **Stripe** (fallback #2) 4. The winning processor is recorded in `payment.processorId` **You wrote zero retry logic. Zero PSP-specific code. One API call for 4 processors.** *** ## Routing Strategies Explained ### Weighted Distribution Split traffic by percentage. Great for load balancing or gradually migrating to a new processor. ```ts theme={null} processorConfigs: [ { processorId: 'proc_s1', weight: 40 }, // Stripe — 40% { processorId: 'proc_cko', weight: 30 }, // Checkout.com — 30% { processorId: 'proc_aw', weight: 30 }, // Airwallex — 30% ] ``` ### Lowest Capacity Sends traffic to whichever processor has processed the fewest transactions today. Auto-balances across all 4 PSPs. ```ts theme={null} pickProcessorStrategy: 'lowestCapacity', processorConfigs: [ { processorId: 'proc_s1' }, // Stripe { processorId: 'proc_cko' }, // Checkout.com { processorId: 'proc_aw' }, // Airwallex { processorId: 'proc_nmi' }, // NMI ] ``` ### Automatic (Round Robin) Equal distribution — each processor gets roughly the same number of transactions. ```ts theme={null} pickProcessorStrategy: 'automatic', ``` ### Sticky Processor When enabled, a returning customer is always routed to the processor that last succeeded for them. Reduces declines on stored-credential transactions. ```ts theme={null} stickyProcessorEnabled: true, ``` *** ## Multiple Flows for Different Scenarios You can create different flows for different situations. Example: a standard flow and a high-value flow using different processor mixes: ```ts theme={null} // Standard flow: spread across Stripe + Checkout.com, NMI as fallback const standardFlow = await tagada.paymentFlows.create({ data: { name: 'Standard', strategy: 'cascade', fallbackMode: true, maxFallbackRetries: 1, threeDsEnabled: true, stickyProcessorEnabled: true, pickProcessorStrategy: 'weighted', processorConfigs: [ { processorId: 'proc_s1', weight: 50, disabled: false, nonStickable: false }, // Stripe { processorId: 'proc_cko', weight: 50, disabled: false, nonStickable: false }, // Checkout.com ], fallbackProcessorConfigs: [ { processorId: 'proc_nmi', orderIndex: 0 }, ], }, }); // High-value flow: Airwallex primary (best rates for large amounts), // all others as fallbacks const highValueFlow = await tagada.paymentFlows.create({ data: { name: 'High Value (>$500)', strategy: 'cascade', fallbackMode: true, maxFallbackRetries: 3, threeDsEnabled: true, stickyProcessorEnabled: false, pickProcessorStrategy: 'weighted', processorConfigs: [ { processorId: 'proc_aw', weight: 100, disabled: false, nonStickable: false }, // Airwallex — all traffic ], fallbackProcessorConfigs: [ { processorId: 'proc_s1', orderIndex: 0 }, // Stripe — 1st fallback { processorId: 'proc_cko', orderIndex: 1 }, // Checkout.com — 2nd { processorId: 'proc_nmi', orderIndex: 2 }, // NMI — last resort ], }, }); // Route based on order amount const flowId = orderTotal > 50000 ? highValueFlow.id : standardFlow.id; await tagada.payments.process({ amount: orderTotal, currency: 'USD', storeId: 'store_xxx', paymentInstrumentId: 'pi_abc123', paymentFlowId: flowId, initiatedBy: 'customer', mode: 'purchase', }); ``` You can also override per funnel step — see the [Step Config Guide](/developer-tools/node-sdk/step-config-guide#payment-flow-override). *** ## Recurring Charges (MIT) For subscriptions and server-initiated charges, use `initiatedBy: 'merchant'`. The vaulted instrument works the same way — TagadaPay handles the stored-credential handshake with each PSP. ```ts theme={null} await tagada.payments.process({ amount: 2999, currency: 'USD', storeId: 'store_xxx', paymentInstrumentId: 'pi_abc123', paymentFlowId: flow.id, initiatedBy: 'merchant', reasonType: 'recurring', mode: 'purchase', }); ``` No customer present, no 3DS challenge, same routing intelligence. ### Cards first charged on another processor TagadaPay sends the card's network transaction id on every merchant-initiated charge. It takes it from the first customer payment made through TagadaPay. If that first payment was made on another processor (you are moving existing subscribers), pass its network transaction id once: ```ts theme={null} await tagada.payments.process({ amount: 2999, currency: 'USD', storeId: 'store_xxx', paymentInstrumentId: 'pi_abc123', initiatedBy: 'merchant', reasonType: 'recurring', mode: 'purchase', networkTransactionId: '586204110384522', // from your previous processor }); ``` It is saved on the payment instrument, so the card's later merchant-initiated charges send it without you passing it again. It is refused on customer-initiated charges. *** ## Comparison: Single PSP vs TagadaPay | | Single PSP (e.g. Stripe alone) | TagadaPay (Stripe + NMI + Checkout.com + Airwallex) | | - | - | - | | **Processors** | 1 | Unlimited, any combination | | **Add a new PSP** | New integration, new code | Dashboard → add API keys → done | | **Fallback on decline** | You build it | Automatic cascade | | **Traffic splitting** | You build it | `weight: 40` / `weight: 30` / `weight: 30` | | **Sticky routing** | You build it | `stickyProcessorEnabled: true` | | **Card vault** | PSP-specific tokens | PSP-agnostic, works across all processors | | **3DS** | Per-PSP implementation | Unified, automatic | | **Lines of code** | Hundreds (per PSP) | \~20 (for all PSPs combined) | *** ## Full Example: 4 PSPs, End to End ```ts theme={null} import Tagada from '@tagadapay/node-sdk'; const tagada = new Tagada('your-api-key'); // 1. List all connected processors const { processors } = await tagada.processors.list(); const stripe = processors.find(p => p.type === 'stripe')!; const nmi = processors.find(p => p.type === 'nmi')!; const checkout = processors.find(p => p.type === 'checkout')!; const airwallex = processors.find(p => p.type === 'airwallex')!; // 2. Create a 4-PSP cascade flow const flow = await tagada.paymentFlows.create({ data: { name: '4-PSP Global Cascade', strategy: 'cascade', fallbackMode: true, maxFallbackRetries: 2, threeDsEnabled: true, stickyProcessorEnabled: true, pickProcessorStrategy: 'weighted', processorConfigs: [ { processorId: stripe.id, weight: 40, disabled: false, nonStickable: false }, // Stripe — 40% { processorId: checkout.id, weight: 30, disabled: false, nonStickable: false }, // Checkout.com — 30% { processorId: airwallex.id, weight: 30, disabled: false, nonStickable: false }, // Airwallex — 30% ], fallbackProcessorConfigs: [ { processorId: nmi.id, orderIndex: 0 }, // NMI — 1st fallback { processorId: stripe.id, orderIndex: 1 }, // Stripe — 2nd fallback ], }, }); // 3. Vault a card (after client-side tokenization via @tagadapay/core-js) const { paymentInstrument } = await tagada.paymentInstruments.createFromToken({ tagadaToken: 'eyJ0eXBlIjoiY2FyZC...', // base64 from client storeId: 'store_xxx', customerData: { email: 'jane@example.com', firstName: 'Jane' }, }); // 4. Charge — TagadaPay picks the best processor from the flow const { payment } = await tagada.payments.process({ amount: 4999, currency: 'USD', storeId: 'store_xxx', paymentInstrumentId: paymentInstrument.id, paymentFlowId: flow.id, initiatedBy: 'customer', mode: 'purchase', }); console.log(`Payment ${payment.status} via ${payment.processorId}`); // → "Payment captured via proc_cko" (Checkout.com won this round) ``` *** ## Stripe Connect via API If your merchants use **Stripe**, you can programmatically connect their Stripe accounts via OAuth instead of manually entering API keys. ### How It Works ``` ┌────────────────────────────────────────────────────────────────┐ │ 1. Your server calls processors.initiateStripeConnect() │ │ → returns a Stripe OAuth URL │ │ │ │ 2. Redirect the merchant to that URL in their browser │ │ → merchant authorizes on Stripe │ │ │ │ 3. Stripe redirects to TagadaPay's callback │ │ → TagadaPay saves the connected account credentials │ │ → merchant is redirected to your redirectUrl │ │ │ │ 4. Processor is now live — ready to accept payments │ └────────────────────────────────────────────────────────────────┘ ``` ### Step-by-Step **1. Create a Stripe processor (placeholder)** ```ts theme={null} const { processor } = await tagada.processors.create({ processor: { name: 'Stripe EU (pending connect)', type: 'stripe', enabled: false, supportedCurrencies: ['EUR', 'GBP'], baseCurrency: 'EUR', }, }); ``` **2. Initiate the OAuth flow** ```ts theme={null} const { url } = await tagada.processors.initiateStripeConnect({ processorId: processor.id, }); // Redirect the merchant to `url` in their browser console.log('Send merchant to:', url); ``` TagadaPay handles the OAuth callback automatically — no URL configuration needed. You can optionally pass `redirectUrl` to control where the merchant lands after authorizing: ```ts theme={null} const { url } = await tagada.processors.initiateStripeConnect({ processorId: processor.id, redirectUrl: 'https://myapp.com/settings?stripe=connected', }); ``` **3. After the merchant authorizes**, TagadaPay automatically: * Exchanges the authorization code for access tokens * Saves the connected Stripe account ID and credentials on the processor * Enables the processor * Redirects the merchant to your `redirectUrl` (or the default processors page) **4. Verify the connection** ```ts theme={null} const proc = await tagada.processors.retrieve(processor.id); console.log(proc.enabled); // true console.log(proc.options); // { accountId: 'acct_...', ... } // Get full account details const details = await tagada.processors.getStripeAccountDetails( proc.options.accountId as string ); console.log(details.charges_enabled); // true console.log(details.country); // 'FR' ``` ### Disconnect a Stripe Account ```ts theme={null} await tagada.processors.disconnectStripe({ accountId: 'acct_1234567890', processorId: processor.id, }); // Processor is now disabled, OAuth access revoked ``` > [!TIP] > > **When to use Stripe Connect vs direct API keys?** > > * Use **Stripe Connect** when you're a platform onboarding merchants who have their own Stripe accounts > * Use **direct API keys** when you own the Stripe account and just need to plug it in *** ## Next Steps > [card] [Subscriptions & Rebilling](/developer-tools/node-sdk/subscriptions) > > Trials, auto-retry, manual rebill, processor migration for recurring billing > [card] [Node SDK Quick Start](/developer-tools/node-sdk/quick-start) > > Full SDK setup with stores, products, and funnels > [card] [core-js + REST](/developer-tools/payments/core-js-payments) > > Build your own checkout UI with client-side card tokenization and 3DS > [card] [Scripts & Pixels per Step](/developer-tools/node-sdk/step-config-guide) > > Add tracking pixels and custom scripts to funnel steps # Order Bumps Source: https://docs.tagada.io/developer-tools/node-sdk/order-bumps Add pre-payment offers on the checkout page to increase average order value # Order Bumps **Time**: \~5 minutes | **Difficulty**: Beginner Use the Node SDK to define **order bumps** — optional add-ons shown **on the checkout page before payment**. They lift average order value without changing your main line item. > [!NOTE] > > **Order bumps vs upsells**: Order bumps appear **before** the customer pays (same checkout session). **Upsell / post-purchase offers** run **after** payment on dedicated offer steps. See [Upsell & Downsell Funnel](/developer-tools/node-sdk/upsell-downsell-funnel) for post-checkout flows. *** ## Prerequisites | Requirement | Notes | | - | - | | Node.js 18+ | | | `@tagadapay/node-sdk` | `npm install @tagadapay/node-sdk` | | API key | Dashboard → Settings → API Keys | | Store + processor | [Merchant Quick Start](/developer-tools/node-sdk/merchant-quickstart) | ```ts theme={null} import Tagada from '@tagadapay/node-sdk'; const tagada = new Tagada('your-api-key'); const STORE_ID = 'store_...'; ``` *** ## 1. What order bumps are * Shown **on checkout** while the cart and payment form are visible. * Customer can opt in (or you can **pre-check** the bump). * Controlled by **triggers** (when to show) and optional **rules** (cart conditions). *** ## 2. Create an order bump product Create a normal product with variant(s) and prices — the bump sells that SKU. ```ts theme={null} const bumpProduct = await tagada.products.create({ storeId: STORE_ID, name: 'Extended Warranty', active: true, isShippable: false, isTaxable: false, variants: [{ name: 'Default', sku: 'BUMP-WARRANTY', grams: null, active: true, default: true, price: null, compareAtPrice: null, prices: [{ currencyOptions: { USD: { amount: 999 } }, recurring: false, billingTiming: 'usage', interval: null, intervalCount: 1, default: true, }], }], }); const v0 = bumpProduct.variants[0]; ``` *** ## 3. Create an order bump offer ```ts theme={null} const bump = await tagada.offers.create({ storeId: STORE_ID, offerTitle: 'Extended Warranty', enabled: true, type: 'orderbump', triggers: [{ type: 'any', productId: null }], offers: [], orderBumpOffers: [{ productId: bumpProduct.id, variantId: v0.id, priceId: v0.prices[0].id, type: 'primary', precheck: false, quantity: 1, titleTrans: { en: 'Add extended warranty' }, descriptionTrans: { en: '2 years of coverage — only $9.99' }, overrideImageUrl: null, displayPrice: true, displayCompareAtPrice: false, }], }); const bumpId = bump.id; ``` *** ## 4. Bump types (`orderBumpOffers[].type`) | Type | Role | | - | - | | `primary` | Main bump slot — highest visibility | | `secondary` | Additional bump row | | `vip` | Premium positioning / styling in checkout UI | | `non_interactive` | Shown without a toggle (informational / fixed presentation) | *** ## 5. Trigger types (`triggers[]`) | `type` | Behavior | | - | - | | `any` | Show for all checkouts (`productId: null`) | | `product` | Show when the cart matches a specific product (`productId: 'prod_...'`) | ```ts theme={null} triggers: [{ type: 'product', productId: 'prod_main_line_item' }], ``` *** ## 6. Attach to a funnel (checkout step) On **checkout** nodes, set `stepConfig.orderBumps`: ```ts theme={null} stepConfig: { orderBumps: { mode: 'custom', enabledOfferIds: [bumpId] }, } ``` | `mode` | Meaning | | - | - | | `custom` | Only bumps listed in `enabledOfferIds` apply on this step | | `inherit` | Use the store / default bump configuration ([Step config](/developer-tools/node-sdk/step-config-guide)) | *** ## 7. List, retrieve, update, delete ```ts theme={null} // List (response uses `upsells` array for all offer types) const { upsells, total } = await tagada.offers.list({ storeId: STORE_ID, type: 'orderbump' }); const one = await tagada.offers.retrieve(bumpId); await tagada.offers.update({ id: bumpId, data: { offerTitle: 'Extended Warranty — pre-checked', enabled: true, type: 'orderbump', triggers: [{ type: 'any', productId: null }], offers: [], orderBumpOffers: [/* same shape as create */], }, }); await tagada.offers.del([bumpId]); ``` *** ## 8. Order bump rules (optional) Per bump line, `rules` restrict when that line is eligible (evaluated against the **current cart**). | Rule `type` | Typical fields | | - | - | | `CartContainsProduct` | `productId` | | `CartTotalAbove` | `minimumAmount` (per-currency structure from API) | | `CartTotalBelow` | `minimumAmount` | | `CartItemCountAbove` | `itemCount` | | `CartItemCountBelow` | `itemCount` | ```ts theme={null} orderBumpOffers: [{ // ...productId, variantId, priceId, type, titleTrans, etc. rules: [ { type: 'CartContainsProduct', productId: 'prod_xxx' }, { type: 'CartItemCountAbove', itemCount: 1 }, ], }], ``` *** ## 9. SDK methods reference | Method | Description | | - | - | | `tagada.offers.create(params)` | Create upsell or order bump (`type: 'orderbump'`) | | `tagada.offers.list({ storeId, type: 'orderbump' })` | Paginate / filter bumps | | `tagada.offers.retrieve(id)` | Fetch one offer | | `tagada.offers.update({ id, data })` | Replace offer fields (omit `storeId` in `data`) | | `tagada.offers.del([ids])` | Delete one or more offers | | `tagada.products.create` / `update` | Manage bump SKUs and prices | | `tagada.funnels.create` / `update` | Set `stepConfig.orderBumps` on checkout steps | *** ## 10. Next steps > [card] [Step config (pixels & bumps)](/developer-tools/node-sdk/step-config-guide) > > `orderBumps`, scripts, pixels, and payment setup per funnel step > [card] [Upsell & downsell funnel](/developer-tools/node-sdk/upsell-downsell-funnel) > > Post-payment offers with conditional routing > [card] [Custom checkout & pages](/developer-tools/node-sdk/custom-checkout) > > Native, HTML, or Plugin SDK checkout surfaces > [card] [Merchant quick start](/developer-tools/node-sdk/merchant-quickstart) > > End-to-end store and processor setup # Apply for TagadaPay Processing Source: https://docs.tagada.io/developer-tools/node-sdk/processing-applications Submit a processing application — direct merchants use processing.applications.create(); CRM-only partners use partners.processing.applications.create({ accountId, … }) with the same payload. # Apply for TagadaPay Processing > [!NOTE] > > **Who this is for:** > > * **Direct merchants** — CRM key (`sk_crm_…`) → `processing.applications.create()`. Same flow as **Dashboard → New Request** at [dashboard.tagadapay.io](https://dashboard.tagadapay.io). > * **CRM-only partners** (no payfac white-label) — partner key → `partners.processing.applications.create({ accountId, … })` with the **same payload** below, on behalf of a sub-merchant. Or use [embed onboarding](/developer-tools/partners/embed-onboarding). > * **Payfac partners** (Suby, Xpage, …) — keep using `partners.processing.tpas.create()`; see [Processing provisioning](/developer-tools/partners/accounts). A **processing application** is how you ask TagadaPay to onboard a legal entity as a processor customer. It lands in our **review queue**, our team runs KYB, and provisions a TPA. The payload mirrors the dashboard **"New Request"** form 1:1 — the exact data our acquiring network runs KYB/KYC on. **The more complete and accurate it is, the faster you are approved.** > [!TIP] > > **Partners (CRM-only):** create the merchant first (`partners.crm.merchants.create`), then call `partners.processing.applications.create({ accountId: merchant.id, businessInfo, representative, … })`. After approval, mint a processing key with `partners.processing.enroll({ accountId, mode: 'live' })`. > > ```ts theme={null} > const partner = new Tagada({ apiKey: process.env.TAGADA_PARTNER_KEY! }); > const merchant = await partner.partners.crm.merchants.create({ legalName: 'Acme SAS', externalRef: 'm_42' }); > const application = await partner.partners.processing.applications.create({ > accountId: merchant.id, > businessInfo: { businessName: 'Acme SAS', country: 'FR' }, > representative: { firstName: 'Jeanne', lastName: 'Dupont', email: 'jeanne@example.com' }, > }); > // After Tagada promotes → TPA exists: > const { key } = await partner.partners.processing.enroll({ accountId: merchant.id, mode: 'live' }); > ``` *** ## What you're applying for: a TPA Approval gives you a **TagadaPay Account — a TPA** (id prefix `tpa_xxx`). The TPA, not your login and not your store, is the object that actually holds **one KYB-approved legal entity**, its **assigned acquirer**, its **settlement bank account**, and its own charging scope. It sits under your **merchant** account — the thing you log into and hold a single CRM key for: ``` Merchant (acc_xxx) your Tagada account: one login, one CRM key ├── TPA (tpa_xxx) an approved legal entity that can charge cards └── Store (store_xxx) checkout & payment routing (auto-created) ``` The important part: **one application provisions one TPA**, and a single merchant can own **many** of them (`acc_xxx` → 0..N `tpa_xxx`). See [One merchant, many TPAs](#one-merchant-many-tpas) for why you'd want that and how to do it. *** ## The three field tiers Every field is one of three tiers — the SDK types tag each one, and your editor autocompletes the full set: > [card] Required > > The API **rejects** the application without it (`400 missing_required_fields`). Non-optional in the types. > [card] Recommended > > Not enforced at intake, but acquirers **will** ask for it before activation. Omitting one only **delays** approval — `create()` echoes the gaps in `recommendations`, and the review queue flags every one. > [card] Optional > > Situational / nice-to-have. Improves risk underwriting but is never blocking. > [!WARNING] > > Only **5 fields are strictly required**: `businessInfo.businessName`, `businessInfo.country`, and the representative's `firstName`, `lastName`, `email`. Everything else is *recommended* or *optional* — but a 5-field application will bounce back from KYB. Send a complete one. *** ## Minimal vs complete ```ts theme={null} import { Tagada } from '@tagadapay/node-sdk'; const tagada = new Tagada({ apiKey: process.env.TAGADA_CRM_KEY }); // sk_crm_… // Minimal — passes intake, but our team will ask for more before activation. // NOTE: this is NOT idempotent. Each call submits a NEW application to the // review queue — keep `draft.id` and poll with retrieve(), don't blindly retry. const draft = await tagada.processing.applications.create({ businessInfo: { businessName: 'ACME COMMERCE', country: 'FR' }, representative: { firstName: 'Jeanne', lastName: 'Dupont', email: 'jeanne@example.com' }, }); console.log(draft.recommendations); // → ['businessInfo.email', 'businessInfo.website', 'businessInfo.registrationNumber', // 'businessInfo.mcc', 'representative.idNumber', 'bankAccount.iban', …] ``` A **complete** application — the shape you actually want to send. The payload is the same everywhere; only the **country-specific identifiers and settlement rail** change. Pick your jurisdiction: > [tab] France (SEPA) > > ```ts theme={null} > const application = await tagada.processing.applications.create({ > businessInfo: { > // ── Required ── > businessName: 'ACME COMMERCE', > country: 'FR', > // ── Recommended (acquirer KYB) ── > activityType: 'business', > legalEntityType: 'sas', > registrationNumber: '123456789', // SIREN / company number (from KBIS) > taxId: 'FR00123456789', // VAT number > website: 'https://example.com', > mcc: '5734', > email: 'ops@example.com', > phone: '+33123456789', > address: { > street: '1 Rue de l’Exemple', > city: 'Paris', > postalCode: '75001', > country: 'FR', > }, > // ── Optional (risk profile) ── > businessModel: 'SaaS (subscription)', > businessDescription: 'Online software platform (example.com).', > monthlyVolume: '10000', > desiredCurrencies: ['EUR'], > }, > representative: { > // ── Required ── > firstName: 'Jeanne', > lastName: 'Dupont', > email: 'jeanne@example.com', > // ── Recommended (KYC) ── > phone: '+33123456789', > title: 'signatory', > dateOfBirth: '1990-01-01', > nationality: 'FR', > idType: 'identityCard', > idNumber: 'X0000000', > idCountry: 'FR', > idExpiry: '2030-01-01', > residentialAddress: { > street: '2 Avenue Imaginaire', > city: 'Paris', > postalCode: '75002', > country: 'FR', > }, > }, > // ── Recommended: settlement account (holder MUST match the entity) ── > bankAccount: { > accountHolderName: 'SAS ACME COMMERCE', > iban: 'FR7630006000011234567890189', // SEPA rail > bic: 'AGRIFRPPXXX', > currency: 'EUR', > country: 'FR', > }, > documents: [], > }); > ``` > [tab] United States (ACH) > > ```ts theme={null} > const application = await tagada.processing.applications.create({ > businessInfo: { > // ── Required ── > businessName: 'ACME COMMERCE LLC', > country: 'US', > // ── Recommended (acquirer KYB) ── > activityType: 'business', > legalEntityType: 'llc', > registrationNumber: '98-1923816', // EIN — the US has no separate company number > taxId: '98-1923816', // EIN again — identical to registrationNumber > website: 'https://example.com', > mcc: '5734', > email: 'ops@example.com', > phone: '+12025550182', > address: { > street: '1 Market Street', > city: 'San Francisco', > state: 'CA', // US addresses need the state > postalCode: '94105', > country: 'US', > }, > // ── Optional (risk profile) ── > businessModel: 'SaaS (subscription)', > businessDescription: 'Online software platform (example.com).', > monthlyVolume: '10000', > desiredCurrencies: ['USD'], > }, > representative: { > // ── Required ── > firstName: 'John', > lastName: 'Smith', > email: 'john@example.com', > // ── Recommended (KYC) ── > phone: '+12025550182', > title: 'signatory', > dateOfBirth: '1985-03-14', > nationality: 'US', > idType: 'driversLicense', > idNumber: 'D1234567', > idCountry: 'US', > idState: 'CA', // issuing state, for US IDs > idExpiry: '2030-01-01', > ssnLast4: '6789', // US sole traders only > residentialAddress: { > street: '500 Howard Street', > city: 'San Francisco', > state: 'CA', > postalCode: '94105', > country: 'US', > }, > }, > // ── Recommended: settlement account (holder MUST match the entity) ── > bankAccount: { > accountHolderName: 'ACME COMMERCE LLC', > routingNumber: '021000021', // US ACH rail (instead of IBAN/BIC) > accountNumber: '1234567890', > currency: 'USD', > bankName: 'Example Bank, N.A.', > country: 'US', > }, > documents: [], > }); > ``` Either way, `create()` returns the same shape: ```ts theme={null} // → { // object: 'processing_application', // id: 'ent_xxx', // status: 'submitted', // accountId: 'acc_xxx', // tpaId: null, // set once our team provisions your TPA // kycStatus: null, // submittedAt: '2026-06-26T…', // recommendations: [] // empty → nothing left to fill // } ``` *** ## Field reference ### `businessInfo` | Field | Tier | Notes | | - | - | - | | `businessName` | **Required** | Legal entity name exactly as registered (or the person's full name for a sole trader). | | `country` | **Required** | Country of registration — ISO 3166-1 alpha-2 (`FR`). | | `activityType` | Recommended | `'business'` or `'individual'`. Drives the acquirer legal-entity type. | | `legalEntityType` | Recommended | Canonical code: `sas`, `sarl`, `sa`, `auto_entrepreneur`, `llc`, `ltd`, `inc`, `corporation`… | | `registrationNumber` | Recommended | Company registration number from the registration certificate / KBIS. FR: SIREN/SIRET, UK: Companies House no., **US: the 9-digit EIN** (see note below). | | `taxId` | Recommended | Tax identifier. EU: the VAT number, e.g. `FR00123456789`. **US: the federal EIN — the same value as `registrationNumber`.** | | `website` | Recommended | Public URL — also used for the statement descriptor & content review. | | `mcc` | Recommended | Merchant Category Code, e.g. `5734`. | | `address` | Recommended | Registered business address (`street`, `city`, `postalCode` recommended; `apartment`, `state`, `country` optional). | | `email` | Recommended | Business contact email (falls back to the representative's). | | `phone` | Recommended | Business phone, E.164 (`+33…`). | | `businessDescription` | Optional | Plain-language description of what is sold. | | `businessModel` | Optional | One-liner, e.g. `SaaS (subscription)`. | | `desiredCurrencies` | Optional | Settlement currencies — ISO 4217, e.g. `['EUR']`. | | `mccBreakdown` | Optional | Per-MCC volume split (`{ code, label?, volume?, averageTicket?, chargebackRatio?, refundRatio? }[]`). | | `monthlyVolume` | Optional | Expected monthly card volume, major units as a string (`'10000'`). | | `averageTicket` | Optional | Typical order value, major units as a string. | | `currentlyProcessing` | Optional | `boolean` — already processing elsewhere today? | | `currentProcessor` | Optional | Current/previous processor name. | | `previousMonthlyVolume` | Optional | Volume processed elsewhere last month, as a string. | | `expectedStartDate` | Optional | ISO date `YYYY-MM-DD`. | | `supportEmail` / `supportPhone` | Optional | Customer-support contacts shown to cardholders. | > [!NOTE] > > **US merchants — `registrationNumber` and `taxId` are the same EIN.** The US > has no separate company registration number, so the federal EIN (e.g. > `98-1923816`) is both your tax ID and your registration number. Send the same > 9-digit value in both fields. The acquirer requires both to be present. ### `representative` The legal representative — the UBO / authorised signer who is the KYC subject. | Field | Tier | Notes | | - | - | - | | `firstName` | **Required** | Given name. | | `lastName` | **Required** | Family name. | | `email` | **Required** | Contact email — also where the confirmation is sent. | | `phone` | Recommended | E.164 (`+33…`). | | `title` | Recommended | Role: `signatory`, `uboThroughOwnership`, `uboThroughControl`, `director`… | | `dateOfBirth` | Recommended | ISO `YYYY-MM-DD`. | | `nationality` | Recommended | ISO 3166-1 alpha-2. | | `idNumber` | Recommended | Government ID number. | | `idType` | Recommended | `passport` · `identityCard` · `driversLicense` · `nationalIdNumber`. | | `idCountry` | Recommended | Issuing country — ISO 3166-1 alpha-2. | | `idExpiry` | Recommended | ISO `YYYY-MM-DD`. | | `residentialAddress` | Recommended | Home address (`street`, `city`, `postalCode` recommended) — **not** the business seat. | | `idState` | Optional | Issuing state/province, where relevant (US). | | `ssnLast4` | Optional | Last 4 of SSN — US sole traders only. | ### `bankAccount` Settlement (payout) account. The **account holder must match the legal entity** — acquirers reject payouts to a mismatched name. Provide **one rail**. | Field | Tier | Notes | | - | - | - | | `accountHolderName` | Recommended | Must equal the legal entity name. | | `currency` | Recommended | Settlement currency — ISO 4217 (`EUR`). | | `iban` + `bic` | Recommended | SEPA rail. | | `routingNumber` + `accountNumber` | — | US ACH rail (use instead of IBAN). | | `bsbNumber` + `accountNumber` | — | Australian BSB rail. | | `bankName` / `country` | Optional | Bank name and country (ISO 3166-1 alpha-2). | ### `documents` Optional at submit, but they satisfy KYB requirements early. Each entry is metadata referencing a file you've already uploaded to storage: ```ts theme={null} documents: [ { type: 'national_id', fileKey: 'kyc/loic-id.pdf', fileUrl: 'https://…', fileName: 'id.pdf' }, { type: 'business_registration', fileKey: 'kyb/kbis.pdf', fileUrl: 'https://…' }, { type: 'bank_statement', fileKey: 'kyb/rib.pdf', fileUrl: 'https://…' }, ] ``` Accepted `type` values: `passport`, `drivers_license`, `national_id`, `proof_of_national_id`, `proof_of_address`, `business_registration`, `bank_statement`, `processing_history`, `id_scan`, `other`. *** ## How `recommendations` works `create()` never fails on a missing *recommended* field. Instead it returns them so you can surface them in your own UI or fill them later: ```ts theme={null} const app = await tagada.processing.applications.create({ businessInfo, representative }); if (app.recommendations?.length) { console.warn('Acquirer KYB will need these before activation:', app.recommendations); } ``` The same gaps appear as **"Missing"** pills in the TagadaPay dashboard once your application is in review. *** ## Pre-submission document audit The #1 reason an application is **not** accepted by the acquirer on the first try is a mismatch between an uploaded document and the declared data — a passport whose name differs from `representative`, an ID issued by a different country than `nationality`, a registration document for another company name, or a file uploaded under the wrong `type`. The SDK can catch these **before** you submit. ### Audit each document right after upload ```ts theme={null} const audit = await tagada.processing.applications.auditDocument({ kind: 'passport', fileUrl: uploadedUrl, // the public URL of the file you already uploaded // declared data to cross-check against (same shape as create()) representative: { firstName: 'Loïc', lastName: 'Delobel', nationality: 'FR' }, }); for (const issue of audit.issues) { console.warn(`[${issue.code}] ${issue.message}`); if (issue.suggestion) console.warn(` → ${issue.suggestion}`); } ``` `auditDocument` reads the file (SumSub's validated read for identity documents when available, otherwise an AI document analysis), extracts the key fields, and compares them to what you declared. It returns: ```ts theme={null} { kind: 'passport', detectedKind: 'passport', fields: { personName: 'LOIC DELOBEL', country: 'FR', /* … */ }, issues: [ { code: 'name_mismatch', severity: 'warning', documentType: 'passport', message: 'The name on the ID ("Loic Delobel") does not match the declared representative ("Loic Dupont").', suggestion: "Make sure the representative's first/last name exactly matches their photo ID.", confidence: 0.92, }, ], source: 'llm', } ``` Everything is **advisory and non-blocking** — `issues: []` means the document looks consistent. It is best-effort: an unreadable file returns `{ issues: [], source: 'none' }`. ### `documentWarnings` on submit `create()` runs the same audit across all uploaded documents and echoes any findings in `documentWarnings` (present only when something was found): ```ts theme={null} const app = await tagada.processing.applications.create({ businessInfo, representative, documents }); if (app.documentWarnings?.length) { console.warn('Fix these before the application can be accepted:'); for (const w of app.documentWarnings) console.warn(`- [${w.code}] ${w.message}`); } ``` Common `code` values: `doc_type_mismatch`, `name_mismatch`, `issuer_country_mismatch`, `company_name_mismatch`, `registration_number_mismatch`, `cross_border_residency`, `missing_for_declared`. > [!NOTE] > > **Bank statements too.** Pass the declared `bankAccount` alongside a > `kind: 'bank_statement'` audit and it also verifies the account holder, the > account identifier (masking-aware — `****6789` matches a declared number > ending in `6789`) and the statement freshness (must be under 12 months): the > exact checks acquirers run on the settlement document. Codes: > `bank_holder_mismatch`, `bank_account_mismatch`, `bank_routing_mismatch`, > `bank_doc_stale`. *** ## Why the SDK asks for less than the dashboard "requires" The dashboard form *visually* marks \~15 fields as required (red pills). Only 5 are hard gates; the rest are the **Recommended** tier above. A complete SDK application and a complete dashboard application carry **identical** data. *** ## Track the application ```ts theme={null} const status = await tagada.processing.applications.retrieve('ent_xxx'); // { status: 'submitted' | 'in_review' | 'approved' | 'rejected' | …, tpaId, kycStatus } ``` Once approved and your TPA is provisioned, `tpaId` is populated. Then [enroll](#after-approval-one-key-for-all-your-tpas) to mint a processing key and start charging. *** ## Identity verification (KYC) in your own flow Every application requires an **identity check of the representative** (ID + selfie, via SumSub) before it can be approved. By default that step happens on the TagadaPay dashboard — which your merchant may never open. The SDK lets you run it **inside your own journey** instead, exactly like the identity step of the TagadaPay application form: ```ts theme={null} // 1. Right after create() — while the merchant is still in front of you: const session = await tagada.processing.applications.createKycSession(app.id); if (session.configured && session.sdkToken) { // 2. Mount the SumSub WebSDK with the token (web or mobile — same token). // npm i @sumsub/websdk — the merchant does ID + selfie in your UI. launchSumsubWebSdk(session.sdkToken); } ``` * The **verdict is asynchronous** and never blocks the application — don't make the merchant wait for it. Track it with `retrieveKycStatus()`: ```ts theme={null} const kyc = await tagada.processing.applications.retrieveKycStatus(app.id); // { kycStatus: 'pending' | 'in_progress' | 'approved' | 'rejected' | 'skipped', // applicantId, review: { reviewStatus }, fixableReasons: [] } ``` * `review.reviewStatus` of `pending` or `completed` means the documents are **in** — use it to mark your identity step complete when a merchant resumes an interrupted session. * On rejection, `fixableReasons` lists what the applicant can fix alone when SumSub asks them to submit again, as SumSub labels about the photo (`UNSATISFACTORY_PHOTOS`, `SCREENSHOTS`, `DIGITAL_DOCUMENT`), the document (`DOCUMENT_PAGE_MISSING`, `DOCUMENT_DAMAGED`, `INCOMPLETE_DOCUMENT`, `INCOMPATIBLE_LANGUAGE`, `EXPIRATION_DATE`, `BAD_PROOF_OF_IDENTITY`) or the selfie (`BAD_SELFIE`, `BAD_FACE_MATCHING`, `BAD_VIDEO_SELFIE`). Call `createKycSession()` again to let them retry (SumSub reopens recoverable rejections). * An empty `fixableReasons` is not a final word: why else a check was refused is not returned, and the SumSub WebSDK shows the applicant its own message. * `configured: false` means there is nothing to do — verification is not enabled, was skipped by the review team, or is not required for this application. > [!TIP] > > **Partners:** the same pair exists on the partner surface — > `partner.partners.processing.applications.createKycSession(id)` / > `.retrieveKycStatus(id)` — scoped to your own sub-merchants. Your merchant > completes the whole onboarding, identity included, without ever leaving your > product or receiving TagadaPay credentials. *** ## One merchant, many TPAs A TPA is scoped to **one legal entity with one settlement setup**. That is deliberate: KYB is run per entity, and an acquirer is assigned per entity. So whenever your reality has more than one of those, you want more than one TPA — all owned by your single merchant account. Common reasons to run several: | You have… | TPAs you'd open | | - | - | | **Several legal entities** (a holding with multiple LLCs, one company per brand) | One TPA per entity — each passes its own KYB | | **The same entity selling in several regions** | One TPA per settlement region (e.g. an EU TPA settling in EUR, a US TPA settling in USD) | | **Risk or volume you want to split** | Several TPAs so traffic and exposure spread across different acquirers | > [!NOTE] > > **One application = one TPA.** You don't get multiple TPAs from a single submission — you get them by submitting **one application per entity (or region)**. Every application you send with the **same CRM key** attaches to the **same merchant** (`acc_xxx`), so they all collect under one account you manage with one key. ### Example: three LLCs, one merchant Say you operate three US LLCs. Each is a separate legal entity, so each needs its own application — but you submit them all from the same CRM key: ```ts theme={null} import { Tagada } from '@tagadapay/node-sdk'; const tagada = new Tagada({ apiKey: process.env.TAGADA_CRM_KEY }); // one CRM key // Three LLCs you operate. Each is its own legal entity → its own TPA. const entities = [ { businessName: 'NORTHWIND APPAREL LLC', ein: '88-1112221', mcc: '5651', website: 'https://northwind.example', rep: { firstName: 'John', lastName: 'Smith', email: 'john@northwind.example' }, accountNumber: '1000000001', }, { businessName: 'CINDER SUPPLEMENTS LLC', ein: '88-3334441', mcc: '5499', website: 'https://cinder.example', rep: { firstName: 'John', lastName: 'Smith', email: 'john@cinder.example' }, accountNumber: '1000000002', }, { businessName: 'HARBOR SAAS LLC', ein: '88-5556661', mcc: '5734', website: 'https://harbor.example', rep: { firstName: 'John', lastName: 'Smith', email: 'john@harbor.example' }, accountNumber: '1000000003', }, ]; // One application per LLC. They all attach to the SAME merchant (acc_xxx) // and each provisions its own TPA once approved. for (const e of entities) { const app = await tagada.processing.applications.create({ businessInfo: { businessName: e.businessName, country: 'US', activityType: 'business', legalEntityType: 'llc', registrationNumber: e.ein, // US: EIN is both… taxId: e.ein, // …registrationNumber and taxId mcc: e.mcc, website: e.website, address: { street: '1 Market Street', city: 'San Francisco', state: 'CA', postalCode: '94105', country: 'US' }, }, representative: e.rep, bankAccount: { accountHolderName: e.businessName, // holder MUST match each entity routingNumber: '021000021', accountNumber: e.accountNumber, currency: 'USD', country: 'US', }, }); console.log(`${e.businessName} → application ${app.id}, merchant ${app.accountId}`); // Same app.accountId (acc_xxx) for all three — one merchant, three applications. } ``` > [!TIP] > > **Same entity, several regions?** Use the exact same loop, but vary `businessInfo.country` and the settlement rail per region — e.g. one application with `country: 'FR'` + an EUR `iban`/`bic`, and another with `country: 'US'` + a USD `routingNumber`/`accountNumber`. You'll end up with an EU TPA and a US TPA under the same merchant. ### After approval: one key for all your TPAs Once your applications are approved and their TPAs are provisioned, call **`enroll()` once**. It mints a **merchant-scoped** processing key (`tp_sk_…`) that can see and manage **every** TPA under your account — you do not enroll per TPA. ```ts theme={null} // Build a client with your CRM key, then enroll → processing key. // NOTE: not idempotent. One call = one NEW key. Enroll ONCE and store the // secret; calling again just mints extra live keys you'll have to revoke. const { key } = await tagada.processing.enroll({ mode: 'live' }); // key.secret = 'tp_sk_live_…' (plaintext, returned ONLY here — store it) const merchant = new Tagada({ apiKey: key.secret }); // tp_sk_live_… // This one key lists all of your TPAs. const { data: tpas } = await merchant.processing.tpas.list(); // → [ { id: 'tpa_aaa', … }, { id: 'tpa_bbb', … }, { id: 'tpa_ccc', … } ] // one TPA per approved LLC, all under your single merchant account // Optional: mint a key scoped to a SINGLE TPA — e.g. to isolate one brand's // charging, or hand one brand's key to a teammate. // Also not idempotent: each call mints another key. Mint one per consumer // (per service / per teammate) on purpose, and revoke them when unused. const northwindKey = await merchant.processing.tpas.keys.create('tpa_aaa'); // northwindKey.secret = 'tp_sk_live_…' scoped to tpa_aaa only ``` > [!NOTE] > > **`enroll()` is activation without leaving your code.** It does the same thing as going to the TagadaPay dashboard, activating processing, and copying your key — the SDK just lets you do it (and the whole apply → KYB → charge flow) end to end, without ever opening the CRM or the dashboard. > > Because of that, treat key minting as a **one-time setup step, not application code**: run `enroll()` once in a bootstrap script (or grab the key from the dashboard), store `key.secret` in your secrets manager, and have your app read it from the environment. Minting a key inside your request path is the equivalent of re-running a seeding script on every request. ```ts theme={null} // ── setup.ts — run ONCE ──────────────────────────────────────────────────── const { key } = await tagada.processing.enroll({ mode: 'live' }); // → store key.secret as TAGADA_PROCESSING_KEY in your secret manager // ── app.ts — every request ───────────────────────────────────────────────── const tp = new Tagada({ apiKey: process.env.TAGADA_PROCESSING_KEY! }); // read it await tp.payments.process({ /* … */ }); ``` So the key model mirrors the entity model: | Key | Scope | Minted by | Sees | | - | - | - | - | | **CRM key** (`sk_crm_…`) | the merchant | `tagada-init` / dashboard | CRM data + apply + `enroll()` | | **Merchant processing key** (`tp_sk_…`) | the merchant | `processing.enroll()` | **all** your TPAs | | **Per-TPA key** (`tp_sk_…`) | one TPA | `processing.tpas.keys.create(tpaId)` | that one TPA | > [!NOTE] > > `enroll()`'s `mode` defaults to `'test'` server-side, so a fresh enrollment can never touch live processing by accident. Pass `mode: 'live'` once you're ready to charge real cards. > [!WARNING] > > **`enroll()` is not idempotent — call it once and store the secret.** Every call mints a **brand-new** merchant key; it does **not** return or rotate a previous one. Calling it repeatedly doesn't break anything (older keys keep working), but you pile up live credentials you then have to track and revoke. Treat `key.secret` like a password: persist it on first enroll, reuse it, and if you ever lose or leak one, revoke that key and enroll again. For narrower, disposable credentials, mint a per-TPA key with `processing.tpas.keys.create(tpaId)` instead. *** ## Calling things more than once Networks time out and retries happen, so it pays to know what each call does the **second** time. The rule of thumb: **reads are safe to repeat, and every write here creates a new resource — none of them silently de-duplicate.** Know which is which before you wrap anything in a retry loop. | Call | What it does | Safe to repeat? | A second call… | | - | - | - | - | | `processing.applications.create()` | Submits a processing application | **No** | …files a **second application** in the review queue. Duplicates slow KYB and can provision an extra TPA. | | `processing.enroll()` | Mints your **merchant** processing key | **No** | …mints **another** live key. Old ones keep working — you just accumulate secrets to track and revoke. | | `processing.tpas.keys.create()` | Mints a **per-TPA** key | **No** | …mints **another** key. Great on purpose (one per service), a liability by accident. | | `processing.tpas.list()` / `retrieve()` | Reads your TPA(s) | **Yes** | …returns the same data. Repeat freely. | | `payments.process()` | Charges a card | **Only with an idempotency key** | …can **double-charge** without one; with the same UUID key it returns the original payment. | ### Retry a charge safely `payments.process()` is the one write you legitimately need to retry (timeouts mid-charge). Pass an `idempotencyKey`: the first call charges, any repeat with the same key returns that same payment instead of charging again. A repeat sent while the first call is still running gets HTTP 409 `idempotent_request_in_progress`: wait and retry with the same key. * Use a UUID. A key that is not a UUID is honoured only on an account with a store on Payments API V3 (there, a repeat sent while the first call runs waits up to 20 seconds for its answer). Elsewhere it is ignored without an error, and each call charges. * A key is kept for 24 hours, per account, method and path. * Create the key once per payment, store it with the order, and reuse it on every retry. * A `5xx` response releases the key, so a retry after a `5xx` can charge again. ```ts theme={null} import { randomUUID } from 'node:crypto'; const tp = new Tagada({ apiKey: key.secret }); // your stored tp_sk_… const idempotencyKey = randomUUID(); // store it with the order, reuse it on retry await tp.payments.process( { paymentInstrumentId, paymentFlowId, amount: 4999, currency: 'EUR', paymentMethod: 'card', mode: 'purchase' }, { idempotencyKey }, // same key on retry => one charge, unless the first call got a 5xx ); ``` ### Don't re-submit an application `applications.create()` has **no** server-side de-dup, so a retry creates a duplicate dossier. Keep your own "already applied?" guard, and once you have an id, **poll** instead of re-submitting: ```ts theme={null} const app = await tagada.processing.applications.create({ businessInfo, representative }); // From here on, track it — never call create() again for the same entity. const status = await tagada.processing.applications.retrieve(app.id); ``` *** ## Common errors | HTTP | Code | When | | - | - | - | | 400 | `missing_required_fields` | One of the 5 required fields is empty (`missing` lists them). | | 400 | `invalid_request` | Body failed schema validation (`issues` has details). | | 401 | `invalid_api_key` | Not a valid CRM key (`sk_crm_…`) or partner key. | | 403 | `use_applications_api` | A direct merchant tried `tpas.create()` — use this endpoint instead. | | 403 | `payfac_required` | A CRM-only partner tried `tpas.create()` — use `partners.processing.applications.create({ accountId, … })` or [embed](/developer-tools/partners/embed-onboarding). | | 403 | `merchant_access_denied` | Partner `accountId` is not owned by that partner. | *** ## Next steps > [card] [Node SDK Quick Start](/developer-tools/node-sdk/quick-start) > > CRM setup — stores, products, funnels, payment flows > [card] [Partners — processing provisioning](/developer-tools/partners/accounts) > > CRM-only: `applications.create({ accountId })`. Payfac: `tpas.create()`. See the capability matrix. # Processor Credentials Source: https://docs.tagada.io/developer-tools/node-sdk/processor-credentials Required credentials and options for each payment gateway # Processor Credentials Each processor type requires different credentials in the `options` object when calling `tagada.processors.create()`. This page documents the exact fields for every supported gateway. *** ## Supported Gateways > [card] [Stripe](#stripe) > > Cards, wallets, APMs > [card] [NMI](#nmi) > > Direct gateway > [card] [Checkout.com](#checkoutcom) > > Global payments > [card] [Airwallex](#airwallex) > > Multi-currency > [card] [Mastercard](#mastercard-gateway) > > Enterprise gateway > [card] [Authorize.Net](#authorizenet) > > US gateway > [card] [Finix](#finix) > > Platform payments > [card] [N-Genius](#network-ngenius) > > Middle East > [card] [CCAvenue](#ccavenue) > > India gateway > [card] [Ovri](#ovri) > > EU gateway > [card] [KessPay](#kesspay) > > Alt. gateway > [card] [ConvesioPay](#convesiopay) > > WordPress payments > [card] [Tap](#tap) > > MENA payments > [card] [TagadaPay](#tagadapay) > > Managed payments > [card] [Sandbox](#sandbox) > > Testing *** ## Common Structure All processors share the same creation format — only the `options` differ: ```ts theme={null} const { processor } = await tagada.processors.create({ processor: { name: 'My Gateway', type: 'stripe', // ← processor type enabled: true, supportedCurrencies: ['USD', 'EUR'], baseCurrency: 'USD', options: { /* credentials — see below */ }, }, }); ``` *** ## ![Sandbox](https://mintcdn.com/tagadapay/Qw6kVeL1g4c_2DvI/assets/images/processors/sandbox.svg?fit=max\&auto=format\&n=Qw6kVeL1g4c_2DvI\&q=85\&s=76f4c561354a792ca05ac729b00275ff)Sandbox **Type**: `sandbox` | **Use for**: Testing and development No real credentials required — the sandbox processor simulates a payment gateway. ```ts theme={null} options: { testMode: true, } ``` For which operations and payment methods each processor supports, see the [capability matrix](/developer-tools/payments/processors#capability-matrix). | Field | Type | Required | Description | | - | - | - | - | | `testMode` | boolean | No | Always treated as test mode | | `forceDecline` | boolean | No | Force all payments to decline | | `targetApprovalRate` | number | No | Simulate a specific approval rate (0–100) | | `simulatedDelay` | number | No | Add artificial latency in milliseconds | > [!TIP] > > See the [Sandbox Testing Guide](/developer-tools/node-sdk/sandbox-testing) for a full walkthrough. *** ## ![Stripe](https://mintcdn.com/tagadapay/Qw6kVeL1g4c_2DvI/assets/images/processors/stripe.svg?fit=max\&auto=format\&n=Qw6kVeL1g4c_2DvI\&q=85\&s=ad2d1fbfbbb9b461dce3fe17a132be2a)Stripe **Type**: `stripe` | **Where to find credentials**: [Stripe Dashboard → Developers → API Keys](https://dashboard.stripe.com/apikeys) ```ts theme={null} options: { secretKey: 'sk_live_...', publicKey: 'pk_live_...', webhookSecret: 'whsec_...', } ``` | Field | Type | Required | Description | | - | - | - | - | | `secretKey` | string | **Yes** | Stripe secret key (`sk_live_...` or `sk_test_...`) | | `publicKey` | string | Recommended | Stripe publishable key (`pk_live_...`) | | `webhookSecret` | string | Recommended | Webhook signing secret (`whsec_...`) | | `testMode` | boolean | No | Use Stripe test mode | | `sendReceiptEmail` | boolean | No | Let Stripe send payment receipt emails | | `descriptor` | object | No | Statement descriptor override (see [Descriptor Fields](#descriptor-fields)) | | `radar` | object | No | Enable Stripe Radar: `{ enabled: true, publishableKey: 'pk_...' }` | | `apmSettings` | object | No | Alternative payment methods (Apple Pay, Google Pay, etc.) | > [!NOTE] > > **Stripe Connect**: If you're connecting via OAuth instead of API keys, Stripe provides an `accountId` (e.g. `acct_...`). In this case you don't need `secretKey` — TagadaPay handles the authentication. This is typically done through the TagadaPay dashboard, not the API. *** ## ![NMI](https://mintcdn.com/tagadapay/Qw6kVeL1g4c_2DvI/assets/images/processors/nmi.png?fit=max\&auto=format\&n=Qw6kVeL1g4c_2DvI\&q=85\&s=2b09cce47a2c522fa1f1cb3722c0bf1c)NMI **Type**: `nmi` | **Where to find credentials**: NMI Merchant Portal → Settings → Security Keys ```ts theme={null} options: { apiKey: 'your-nmi-security-key', } ``` | Field | Type | Required | Description | | - | - | - | - | | `apiKey` | string | **Yes** | NMI Security Key | | `username` | string | No | NMI username (for certain integrations) | | `password` | string | No | NMI password | | `testMode` | boolean | No | Use NMI test mode | | `merchantName` | string | No | Merchant name for 3DS | | `merchantUrl` | string | No | Merchant URL for 3DS | | `merchantCountryCode` | string | No | ISO country code for 3DS | | `enable3DS` | boolean | No | Enable 3D Secure authentication | | `useProcessorToken` | boolean | No | Use NMI's tokenization | | `descriptor` | object | No | Statement descriptor override | | `acquirerBinVisa` | string | No | Acquirer BIN for Visa 3DS | | `acquirerBinMastercard` | string | No | Acquirer BIN for Mastercard 3DS | | `acquirerBinAmex` | string | No | Acquirer BIN for Amex 3DS | | `acquirerBinDiscover` | string | No | Acquirer BIN for Discover 3DS | | `acquirerBinJcb` | string | No | Acquirer BIN for JCB 3DS | | `acquirerBinDinersClub` | string | No | Acquirer BIN for Diners Club 3DS | | `acquirerBinCB` | string | No | Acquirer BIN for Carte Bancaire 3DS | | `amexRequestorType` | string | No | Amex 3DS requestor type | | `cbSiretNumber` | string | No | SIRET number for Carte Bancaire | | `discoverClientId` | string | No | Discover 3DS client ID | *** ## ![Checkout.com](https://mintcdn.com/tagadapay/Qw6kVeL1g4c_2DvI/assets/images/processors/checkout.svg?fit=max\&auto=format\&n=Qw6kVeL1g4c_2DvI\&q=85\&s=169c48f1b3bf3b6c150bf94cf265aaf9)Checkout.com **Type**: `checkout` | **Where to find credentials**: [Checkout.com Dashboard → Developers → Keys](https://dashboard.checkout.com) Supports two authentication modes: > [tab] Secret Key (recommended) > > ```ts theme={null} > options: { > apiKey: 'sk_...', > } > ``` > > | Field | Type | Required | Description | > | - | - | - | - | > | `apiKey` | string | **Yes** | Checkout.com secret key | > | `sandboxed` | boolean | No | Use sandbox environment | > [tab] OAuth > > ```ts theme={null} > options: { > clientId: 'ck_...', > clientSecret: 'sk_...', > } > ``` > > | Field | Type | Required | Description | > | - | - | - | - | > | `clientId` | string | **Yes** | OAuth client ID | > | `clientSecret` | string | **Yes** | OAuth client secret | > | `sandboxed` | boolean | No | Use sandbox environment | *** ## ![Airwallex](https://mintcdn.com/tagadapay/Qw6kVeL1g4c_2DvI/assets/images/processors/airwallex.svg?fit=max\&auto=format\&n=Qw6kVeL1g4c_2DvI\&q=85\&s=25f56d8ac6c0d739eceac7acddceb625)Airwallex **Type**: `airwallex` | **Where to find credentials**: [Airwallex Dashboard → Developer → API Keys](https://www.airwallex.com) ```ts theme={null} options: { clientId: 'your-client-id', clientApiKey: 'your-api-key', webhookSecret: 'your-webhook-secret', } ``` | Field | Type | Required | Description | | - | - | - | - | | `clientId` | string | **Yes** | Airwallex client ID | | `clientApiKey` | string | **Yes** | Airwallex API key | | `webhookSecret` | string | **Yes** | Webhook signing secret | | `testMode` | boolean | No | Use Airwallex demo environment | | `descriptor` | object | No | Statement descriptor override | | `apmSettings` | object | No | APM config (Klarna, Afterpay, PayPal, etc.) | *** ## ![Mastercard](https://mintcdn.com/tagadapay/Qw6kVeL1g4c_2DvI/assets/images/processors/mastercard.svg?fit=max\&auto=format\&n=Qw6kVeL1g4c_2DvI\&q=85\&s=e356c2ad1c351d07e1b855520d9bc57a)Mastercard Gateway **Type**: `mastercard` | **Where to find credentials**: Mastercard Gateway Merchant Administration portal ```ts theme={null} options: { merchantId: 'your-merchant-id', password: 'your-api-password', gatewayUrl: 'https://your-gateway.mastercard.com/api/rest', } ``` | Field | Type | Required | Description | | - | - | - | - | | `merchantId` | string | **Yes** | Merchant ID from your Mastercard Gateway account | | `password` | string | **Yes** | API password (not your login password) | | `gatewayUrl` | string | **Yes** | Your gateway API URL (region-specific) | | `apiVersion` | string | No | API version (defaults to latest) | | `testMode` | boolean | No | Use test mode | | `descriptor` | object | No | Statement descriptor override | | `acquirerBinVisa` | string | No | Acquirer BIN for Visa 3DS | | `acquirerBinMastercard` | string | No | Acquirer BIN for Mastercard 3DS | *** ## Authorize.Net **Type**: `authorizenet` | **Where to find credentials**: [Authorize.Net Merchant Interface → Account → API Credentials & Keys](https://account.authorize.net) ```ts theme={null} options: { apiLoginId: 'your-api-login-id', transactionKey: 'your-transaction-key', } ``` | Field | Type | Required | Description | | - | - | - | - | | `apiLoginId` | string | **Yes** | API Login ID | | `transactionKey` | string | **Yes** | Transaction Key | | `clientKey` | string | No | Public client key (for Accept.js tokenization) | | `testMode` | boolean | No | Use sandbox environment | *** ## ![Finix](https://mintcdn.com/tagadapay/Qw6kVeL1g4c_2DvI/assets/images/processors/finix.jpg?fit=max\&auto=format\&n=Qw6kVeL1g4c_2DvI\&q=85\&s=deec27300f2623f80dcb48b4604304eb)Finix **Type**: `finix` | **Where to find credentials**: Finix Dashboard → Settings → API Keys ```ts theme={null} options: { username: 'your-finix-username', password: 'your-finix-password', merchantId: 'your-merchant-id', } ``` | Field | Type | Required | Description | | - | - | - | - | | `username` | string | **Yes** | Finix API username | | `password` | string | **Yes** | Finix API password | | `merchantId` | string | **Yes** | Finix merchant identity ID | | `sandboxed` | boolean | No | Use sandbox environment | | `webhookSecret` | string | No | Webhook signing secret | *** ## ![N-Genius](https://mintcdn.com/tagadapay/Qw6kVeL1g4c_2DvI/assets/images/processors/ngenius.png?fit=max\&auto=format\&n=Qw6kVeL1g4c_2DvI\&q=85\&s=678b919d05025ce88eb45d7296117efd)Network Ngenius **Type**: `ngenius` | **Where to find credentials**: N-Genius Online Portal → Settings → API Keys ```ts theme={null} options: { apiKey: 'your-api-key', outlet: 'your-outlet-reference', apiUrl: 'https://api-gateway.ngenius-payments.com', } ``` | Field | Type | Required | Description | | - | - | - | - | | `apiKey` | string | **Yes** | N-Genius API key | | `outlet` | string | **Yes** | Outlet reference ID | | `apiUrl` | string | **Yes** | API gateway URL (must end with a lowercase letter, no trailing slash) | | `sandboxed` | boolean | No | Use sandbox environment | *** ## ![CCAvenue](https://mintcdn.com/tagadapay/Qw6kVeL1g4c_2DvI/assets/images/processors/ccavenue.png?fit=max\&auto=format\&n=Qw6kVeL1g4c_2DvI\&q=85\&s=98fa0196400fb3c213c32d19ef041d0a)CCAvenue **Type**: `ccavenue` | **Where to find credentials**: CCAvenue Merchant Portal → Settings → API Keys ```ts theme={null} options: { accessCode: 'your-access-code', workingKey: 'your-working-key', merchantId: 'your-merchant-id', } ``` | Field | Type | Required | Description | | - | - | - | - | | `accessCode` | string | **Yes** | CCAvenue access code | | `workingKey` | string | **Yes** | CCAvenue working (encryption) key | | `merchantId` | string | **Yes** | CCAvenue merchant ID | | `testMode` | boolean | No | Use test mode | *** ## ![Ovri](https://mintcdn.com/tagadapay/Qw6kVeL1g4c_2DvI/assets/images/processors/ovri.png?fit=max\&auto=format\&n=Qw6kVeL1g4c_2DvI\&q=85\&s=7a3733aa86b2693eca3fb6490ec4d3b1)Ovri **Type**: `ovri` | **Where to find credentials**: Ovri Back Office → Configuration → API ```ts theme={null} options: { apiKey: 'your-api-key', websiteKey: 'your-website-key', secretKeyPos: 'your-secret-pos-key', } ``` | Field | Type | Required | Description | | - | - | - | - | | `apiKey` | string | **Yes** | Ovri API key | | `websiteKey` | string | **Yes** | Ovri website key | | `secretKeyPos` | string | **Yes** | Ovri secret POS key | | `testMode` | boolean | No | Use test mode | *** ## ![KessPay](https://mintcdn.com/tagadapay/Qw6kVeL1g4c_2DvI/assets/images/processors/kesspay.png?fit=max\&auto=format\&n=Qw6kVeL1g4c_2DvI\&q=85\&s=7523ccbc1c9c5db6cd33b4641de946ea)KessPay **Type**: `kesspay` | **Where to find credentials**: KessPay Merchant Portal ```ts theme={null} options: { clientId: 'your-client-id', clientSecret: 'your-client-secret', username: 'your-username', password: 'your-password', sellerCode: 'your-seller-code', apiSecretKey: 'your-api-secret', publicKey: 'your-public-key', } ``` | Field | Type | Required | Description | | - | - | - | - | | `clientId` | string | **Yes** | KessPay client ID | | `clientSecret` | string | **Yes** | KessPay client secret | | `username` | string | **Yes** | KessPay API username | | `password` | string | **Yes** | KessPay API password | | `sellerCode` | string | **Yes** | Seller code | | `apiSecretKey` | string | **Yes** | API secret key | | `publicKey` | string | **Yes** | Public key | | `testMode` | boolean | No | Use test mode | | `notifyUrl` | string | No | Webhook notification URL | *** ookSecret`| string | No | Webhook signing secret | |`testMode\` | boolean | No | Use test mode | *** ## Tap **Type**: `tap` | **Where to find credentials**: [Tap Dashboard → goSell → API Keys](https://dashboard.tap.company) ```ts theme={null} options: { apiKey: 'sk_live_...', merchantId: 'your-merchant-id', } ``` | Field | Type | Required | Description | | - | - | - | - | | `apiKey` | string | **Yes** | Tap secret API key | | `merchantId` | string | **Yes** | Tap merchant ID | | `testMode` | boolean | No | Use test mode | | `descriptor` | object | No | Statement descriptor override | | `threeDSecure` | boolean | No | Enable 3D Secure | | `saveCard` | boolean | No | Allow saving cards for future payments | | `receiptEmail` | boolean | No | Send receipt email via Tap | | `receiptSms` | boolean | No | Send receipt SMS via Tap | *** ## Paysafe **Type**: `paysafe` | **Where to find credentials**: Paysafe Merchant Portal | Field | Type | Required | Description | | - | - | - | - | | `apiKey` | string | **Yes** | API key (Base64-encoded `user:password` pair from the portal) | | `accountId` | string | **Yes** | Card-payments account ID the charges run on | ## ![TagadaPay](https://mintcdn.com/tagadapay/Qw6kVeL1g4c_2DvI/assets/images/processors/tagadapay.png?fit=max\&auto=format\&n=Qw6kVeL1g4c_2DvI\&q=85\&s=4a5371f4dc887f9bac77936716b3f7fc)TagadaPay **Type**: `tagadapay-router` | **How it works**: Managed payment processing by TagadaPay. The processor is provisioned for you when your processing account is approved — you never enter credentials for it. ```ts theme={null} options: { accountId: 'acct_...', } ``` | Field | Type | Required | Description | | - | - | - | - | | `accountId` | string | **Yes** | Your TagadaPay account ID | | `testMode` | boolean | No | Use test mode | | `descriptor` | object | No | Statement descriptor override | > [!NOTE] > > Contact TagadaPay support to enable this processor and get your account ID. *** ## Descriptor Fields Several processors support a `descriptor` object for customizing the statement descriptor shown on customer bank statements: ```ts theme={null} descriptor: { descriptor: 'MYCOMPANY', descriptor_suffix: 'Order', phone: '+1-555-0100', address: '123 Main St', city: 'New York', state: 'NY', postal: '10001', country: 'US', mcc: '5411', merchantId: 'MERCH001', url: 'https://mycompany.com', } ``` All descriptor fields are optional. Not all processors support all fields — check your gateway's documentation for supported descriptor options. *** ## Full Example Here's a complete example connecting Stripe with all common options: ```ts theme={null} import Tagada from '@tagadapay/node-sdk'; const tagada = new Tagada('your-api-key'); const { processor } = await tagada.processors.create({ processor: { name: 'Stripe US', type: 'stripe', enabled: true, supportedCurrencies: ['USD', 'EUR', 'GBP'], baseCurrency: 'USD', options: { secretKey: 'sk_live_...', publicKey: 'pk_live_...', webhookSecret: 'whsec_...', descriptor: { descriptor: 'MYSHOP', }, radar: { enabled: true, publishableKey: 'pk_live_...', }, }, }, }); console.log('Created:', processor.id); ``` *** ## Next Steps > [card] [Merchant Quick Start](/developer-tools/node-sdk/merchant-quickstart) > > Full 7-step setup from processor to live checkout > [card] [Multi-PSP Routing](/developer-tools/node-sdk/multi-stripe-routing) > > Connect multiple processors and cascade transactions > [card] [Sandbox Testing](/developer-tools/node-sdk/sandbox-testing) > > Test payments without real money # Promotions & Discount Codes Source: https://docs.tagada.io/developer-tools/node-sdk/promotions Create percentage and fixed-amount discounts, coupon codes, and conditional promotions # Promotions & Discount Codes **Time**: \~10 minutes | **Difficulty**: Intermediate Use the Node SDK to define **promotions** (automatic or code-based discounts) with **rules** (when they apply) and **actions** (what they do). Attach human-readable **promotion codes** so customers can enter coupons at checkout. > [!NOTE] > > Promotions are scoped to a **store** (`storeId`). Amounts in money fields are typically in the **smallest currency unit** (e.g. cents for USD) unless noted otherwise in your dashboard. *** ## Prerequisites | Requirement | How to get it | | - | - | | Node.js 18+ | [nodejs.org](https://nodejs.org) | | `@tagadapay/node-sdk` | `npm install @tagadapay/node-sdk` | | API key | Dashboard → Settings → API Keys | | A store | [Merchant Quick Start](/developer-tools/node-sdk/merchant-quickstart) | ```ts theme={null} import Tagada from '@tagadapay/node-sdk'; const tagada = new Tagada('your-api-key'); const STORE_ID = 'store_...'; ``` *** ## Initialize and (optional) create a target product Line-item discounts often reference a **product id**. For a store-wide percentage off, you can skip this. ```ts theme={null} const product = await tagada.products.create({ storeId: STORE_ID, name: 'Promo target product', active: true, isShippable: false, isTaxable: false, variants: [{ name: 'Default', sku: 'PROMO-001', grams: null, active: true, default: true, price: null, compareAtPrice: null, prices: [{ currencyOptions: { USD: { amount: 5000 } }, recurring: false, billingTiming: 'usage', interval: null, intervalCount: 1, default: true, }], }], }); ``` > [!TIP] > > `5000` in `currencyOptions` = **\$50.00** when the currency is USD (cents). *** ## Create a percentage order discount (20% off) Apply a percentage to the **whole order** with `OrderAdjustment` and `adjustmentType: 'percentage'`. ```ts theme={null} const promotion = await tagada.promotions.create({ storeId: STORE_ID, name: '20% off entire order', enabled: true, automatic: true, actions: [{ type: 'OrderAdjustment', adjustmentType: 'percentage', adjustmentPercentage: 20, }], }); ``` > [!NOTE] > > `automatic: true` means the promotion can apply without a coupon when your rules (if any) are satisfied. Set `automatic: false` when you only want it to apply via a **promotion code**. *** ## Create a fixed line-item discount (\$10 off a specific product) Use `LineItemAdjustment` with `adjustmentType: 'amount'` and `adjustmentAmount` in the **full currency object** shape (not just `{ USD: 1000 }`). ```ts theme={null} const lineItemPromo = await tagada.promotions.create({ storeId: STORE_ID, name: '$10 off selected product', enabled: true, automatic: false, actions: [{ type: 'LineItemAdjustment', adjustmentType: 'amount', adjustmentAmount: { USD: { amount: 1000, // $10.00 in cents rate: 1, lock: false, date: '2026-01-01', }, }, targetProductId: product.id, targetVariantIds: null, maxQuantityDiscounted: null, appliesOnEachItem: false, }], }); ``` > [!NOTE] > > **`adjustmentAmount` format:** each currency key maps to `{ amount, rate, lock, date }`. Use an ISO date string (or timestamp) for `date` as required by your environment. `rate`, `lock`, and `date` participate in currency conversion and locking behavior on the platform. *** ## Conditional promotion: free shipping over \$30 Combine **`OrderAmountMinimum`** in `rules` with **`ShippingAdjustment`** in `actions`. ```ts theme={null} const freeShippingPromo = await tagada.promotions.create({ storeId: STORE_ID, name: 'Free shipping on orders $30+', enabled: true, automatic: true, rules: [{ type: 'OrderAmountMinimum', minimumAmount: { USD: { amount: 3000, // $30.00 rate: 1, lock: false, date: '2026-01-01', }, }, }], actions: [{ type: 'ShippingAdjustment', freeShipping: true, }], }); ``` *** ## Create a promotion code (coupon) Link a reusable **code** to an existing promotion. Customers enter the code at checkout; the promotion’s rules and actions then apply. ```ts theme={null} const promotionCode = await tagada.promotionCodes.create({ promotionId: lineItemPromo.id, code: 'SAVE10', active: true, }); ``` > [!TIP] > > Create the **promotion** first, then call `promotionCodes.create` with its `promotionId`. You can attach multiple codes to the same promotion if your workflow allows it. *** ## List, retrieve, update, and delete promotions ### List ```ts theme={null} const listResult = await tagada.promotions.list({ storeId: STORE_ID }); // Shape may include `promotions`, `items`, or a raw array — normalize in your app ``` ### Retrieve `storeId` is **required** for a reliable lookup in multi-store accounts. ```ts theme={null} const one = await tagada.promotions.retrieve(promotion.id, STORE_ID); ``` ### Update Updates are wrapped in a **`data`** object alongside `id`. ```ts theme={null} const updated = await tagada.promotions.update({ id: promotion.id, data: { storeId: STORE_ID, name: '25% off entire order', enabled: true, automatic: true, actions: [{ type: 'OrderAdjustment', adjustmentType: 'percentage', adjustmentPercentage: 25, }], }, }); ``` ### Delete Pass an **array of ids** and `storeId`. ```ts theme={null} await tagada.promotions.del([promotion.id, lineItemPromo.id], STORE_ID); ``` > [!NOTE] > > Some API responses nest the resource under `promotion` or `promotionCode`. When creating resources, read `result.id` or `result.promotion?.id` depending on the payload shape. *** ## Promotion rules reference | Rule type | Purpose | | - | - | | `ContainsProduct` | Order must include specific product(s) / variant(s) | | `OrderAmountMinimum` | Subtotal (or qualifying amount) must meet a minimum, using currency objects | | `OrderMinQuantity` | Minimum total line-item quantity on the order | | `OrderMaxQuantity` | Maximum total line-item quantity on the order | | `MaxProductQuantity` | Cap quantity eligible for the discount per product | | `PaymentIntegrationSelected` | Restrict to orders using a specific processor / payment integration | *** ## Promotion actions reference | Action type | What it does | Common fields | | - | - | - | | `LineItemAdjustment` | Discount specific lines | `adjustmentType`: `'percentage'` \| `'amount'`; `adjustmentPercentage` or `adjustmentAmount`; optional `targetProductId`, `targetVariantIds`, `maxQuantityDiscounted`, `appliesOnEachItem` | | `OrderAdjustment` | Discount the whole order | `adjustmentType`: `'percentage'` \| `'amount'`; `adjustmentPercentage` or order-level `adjustmentAmount` | | `ShippingAdjustment` | Change shipping charges | e.g. `freeShipping: true` | | `CreateLineItem` | Add a line item when the promotion fires | Product / variant / quantity configuration (per your store setup) | | `SubscriptionLineItemFreeTrial` | Apply a free trial on subscription line items | Trial duration / terms as supported by the platform | *** ## SDK methods: `tagada.promotions` | Method | Signature (conceptual) | Description | | - | - | - | | `create` | `promotions.create({ storeId, name, enabled, automatic, actions, rules, ... })` | Create a promotion | | `list` | `promotions.list({ storeId })` | List promotions for a store | | `retrieve` | `promotions.retrieve(id, storeId)` | Get one promotion; **`storeId` required** | | `update` | `promotions.update({ id, data: { storeId, name, ... } })` | Update fields inside **`data`** | | `del` | `promotions.del(ids[], storeId)` | Delete one or more promotions | *** ## SDK methods: `tagada.promotionCodes` | Method | Signature (conceptual) | Description | | - | - | - | | `create` | `promotionCodes.create({ promotionId, code, active })` | Create a coupon linked to a promotion | | `list` | `promotionCodes.list()` | List promotion codes | | `update` | `promotionCodes.update({ ... })` | Update an existing code (e.g. deactivate) | | `del` | `promotionCodes.del(ids[])` | Delete codes by id | *** ## Currency amount shape Whenever the API expects a **currency map** (e.g. `adjustmentAmount`, `minimumAmount`), use: ```ts theme={null} { USD: { amount: 1000, // smallest unit (e.g. cents) rate: 1, lock: false, date: '2026-01-01', // ISO date string }, } ``` Repeat keys (`EUR`, `GBP`, …) for multi-currency stores as needed. *** ## Next steps > [card] [Merchant Quick Start](/developer-tools/node-sdk/merchant-quickstart) > > Store, product, funnel, and checkout session setup > [card] [Upsell & Downsell Funnel](/developer-tools/node-sdk/upsell-downsell-funnel) > > Post-purchase offers and conditional funnel routing > [card] [Custom Checkout](/developer-tools/node-sdk/custom-checkout) > > Advanced checkout flows with the Node SDK > [card] [API Reference](/api-reference/introduction) > > Full REST API documentation # Node SDK Quick Start Source: https://docs.tagada.io/developer-tools/node-sdk/quick-start Create stores, deploy pages, and process payments from your server in 5 minutes # Node SDK Quick Start **Time**: \~5 minutes | **Difficulty**: Beginner > [!NOTE] > > **When to use this SDK:** > > * Server automation: AI agents, CI/CD pipelines, batch jobs > * Programmatically managing stores, products, payments, customers, subscriptions > * Verifying webhook signatures > * **Provisioning sub-merchants and minting per-merchant API keys** (`tagada.partners.*` — see the [Partners section](/developer-tools/partners/introduction)) > > **When NOT to use this SDK:** > > * Anything that runs in a browser — tokenization, 3DS challenges, wallet sheets → use [`@tagadapay/core-js`](/developer-tools/payments/core-js-payments) or the [Headless SDK](/developer-tools/headless-sdk/introduction) > * Custom checkout UI on your own domain where TagadaPay manages the cart → pair this SDK with the [Headless SDK](/developer-tools/headless-sdk/introduction) > * Paying a Headless checkout session with `payments.process()` → that session must be paid with `processPayment()` in the browser. See [Choose how you accept payments](/developer-tools/payments/choose-your-integration) > [!TIP] > > **Want TagadaPay to process your cards?** (direct merchant, not a partner platform) See [Apply for TagadaPay Processing](/developer-tools/node-sdk/processing-applications) — `processing.applications.create()` with your CRM key. > [!TIP] > > **Building a payment platform that charges for MANY merchants?** Jump straight to the [Partners tab](/developer-tools/partners/introduction) — it walks through the full multi-tenant flow with sub-keys, auto-provisioned stores, and APMs. *** ## What Is the Node SDK? The Node SDK lets you control TagadaPay **from your server**. Think of it as the backend counterpart to the Plugin SDK — while the Plugin SDK builds the checkout UI, the Node SDK manages everything behind it. ``` ┌──────────────────────────────────────────────┐ │ Your server / script / CI pipeline │ │ ↓ │ │ @tagadapay/node-sdk │ │ ↓ │ │ TagadaPay REST API │ │ • Create stores & products │ │ • Deploy checkout pages │ │ • Set up multi-step funnels │ │ • Process & route payments across PSPs │ │ • Manage subscriptions & customers │ └──────────────────────────────────────────────┘ ``` > [!NOTE] > > **Why use the Node SDK?** If you're an AI agent, a CI/CD pipeline, a custom backend, or just prefer code over dashboards — this is how you talk to TagadaPay programmatically. *** ## Prerequisites * **Node.js 18+** ([nodejs.org](https://nodejs.org) — run `node --version` to check) * **A TagadaPay API key** — get one in 30 seconds (next section) *** ## Get an API key in 30 seconds You have three options. The first one is what AI coding tools / installers should use; the last one is what you'd do if you already have an account. > [tab] CLI (interactive) > > Run this in the directory where you want your `.env`: > > ```bash theme={null} > npx -p @tagadapay/node-sdk@latest tagada-init you@example.com > ``` > > Paste the 6-digit code from your inbox when prompted. Done — `TAGADA_API_KEY`, `TAGADA_STORE_ID`, and `TAGADA_ACCOUNT_ID` are now in `.env`. > [tab] SDK (programmatic) > > For scripts, AI agents, or framework installers: > > ```ts theme={null} > import Tagada from '@tagadapay/node-sdk'; > > const onboarding = Tagada.public(); > > await onboarding.start({ email: 'you@example.com' }); > > // ...prompt the user / read from a query string... > const { apiKey, storeId } = await onboarding.verify({ > email: 'you@example.com', > code: '123456', > }); > > const tagada = new Tagada(apiKey); // ready to call any resource > ``` > [tab] Dashboard (existing account) > > 1. Click your avatar (top-right) → **Settings** > > ![Navigate to Settings from the user menu](https://mintcdn.com/tagadapay/TKkbuy8GaudqLW4Y/assets/images/api-key-menu.png?fit=max\&auto=format\&n=TKkbuy8GaudqLW4Y\&q=85\&s=5610f731f341dd04cbf426269c14398d) > > 2. **Access Tokens** → **+ Create Access Token** → copy the UUID. > > ![Access Tokens page in Settings](https://mintcdn.com/tagadapay/TKkbuy8GaudqLW4Y/assets/images/api-key-settings.png?fit=max\&auto=format\&n=TKkbuy8GaudqLW4Y\&q=85\&s=c6473adc09ba63dde29d03d9b7751d6a) > [!TIP] > > Full guide with error-handling, security notes, and the framework-specific env-var mirrors `tagada-init` writes (Vite / Next / Astro): [Get an API key from code](/developer-tools/node-sdk/get-api-key). *** ## Install ```bash theme={null} npm install @tagadapay/node-sdk ``` *** ## Initialize ```ts theme={null} import Tagada from '@tagadapay/node-sdk'; const tagada = new Tagada('your-api-key'); ``` That's it. Every resource is now available via `tagada.`. *** ## Example: Full Checkout Setup in 7 Steps This script creates a processor, payment flow, store, product, and funnel — activates the checkout — then generates a checkout session link. No plugin deployment needed; TagadaPay's native checkout is auto-injected. ```ts theme={null} import Tagada from '@tagadapay/node-sdk'; const tagada = new Tagada('your-api-key'); // 1. Create a sandbox processor (or use 'stripe', 'nmi', etc.) const { processor } = await tagada.processors.create({ processor: { name: 'Sandbox', type: 'sandbox', enabled: true, supportedCurrencies: ['USD'], baseCurrency: 'USD', options: { testMode: true }, }, }); // 2. Create a payment flow const flow = await tagada.paymentFlows.create({ data: { name: 'Default', strategy: 'simple', fallbackMode: false, maxFallbackRetries: 0, threeDsEnabled: false, stickyProcessorEnabled: false, pickProcessorStrategy: 'weighted', processorConfigs: [{ processorId: processor.id, weight: 100, disabled: false, nonStickable: false }], fallbackProcessorConfigs: [], abuseDetectionConfig: null, }, }); // 3. Create a store with the payment flow const store = await tagada.stores.create({ name: 'My Store', baseCurrency: 'USD', presentmentCurrencies: ['USD', 'EUR'], chargeCurrencies: ['USD'], selectedPaymentFlowId: flow.id, }); // 4. Create a product const product = await tagada.products.create({ storeId: store.id, name: 'Premium Plan', active: true, variants: [{ name: 'Monthly', sku: 'premium-monthly', grams: 0, price: 2999, compareAtPrice: 0, active: true, default: true, prices: [{ currencyOptions: { USD: { amount: 2999 } }, recurring: false, billingTiming: 'in_advance', default: true }], }], }); const variantId = product.variants[0].id; // 5. Create a funnel (native checkout auto-injected) const funnel = await tagada.funnels.create({ storeId: store.id, config: { id: 'my-checkout', name: 'My Checkout', version: '1.0.0', nodes: [ { id: 'step_checkout', name: 'Checkout', type: 'checkout', kind: 'step', isEntry: true, position: { x: 0, y: 0 }, config: { path: '/checkout' } }, { id: 'step_thankyou', name: 'Thank You', type: 'thankyou', kind: 'step', position: { x: 300, y: 0 }, config: { path: '/thankyou' } }, ], edges: [{ id: 'e1', source: 'step_checkout', target: 'step_thankyou' }], }, isDefault: true, }); // 6. Activate (mounts routes, checkout goes live) const result = await tagada.funnels.update(funnel.id, { storeId: store.id, config: funnel.config, }); const funnelCheckoutUrl = result.funnel.config.nodes .find(n => n.id === 'step_checkout').config.url; console.log('Funnel live at:', funnelCheckoutUrl); // 7. Create a checkout session — shareable link with pre-loaded cart const session = await tagada.checkout.createSession({ storeId: store.id, items: [{ variantId, quantity: 1 }], currency: 'USD', checkoutUrl: funnelCheckoutUrl, }); console.log('Checkout link:', session.redirectUrl); ``` > [!TIP] > > For a detailed walkthrough of each step, see the [Merchant Quick Start](/developer-tools/node-sdk/merchant-quickstart). For deploying your own pages (checkout, landing, offers) instead of the native checkout, see [Funnel Pages](/developer-tools/node-sdk/custom-checkout). *** ## Available Resources Every resource follows the same patterns: `list`, `retrieve`, `create`, `update`, `del`. | Resource | Examples | | - | - | | **`tagada.stores`** | `.list()`, `.create(...)`, `.retrieve(id)` | | **`tagada.products`** | `.list(...)`, `.create(...)`, `.update(...)` | | **`tagada.payments`** | `.list(...)`, `.process(...)`, `.refund(...)`, `.void(...)` | | **`tagada.paymentFlows`** | `.create(...)`, `.listWithProcessors()` — define how payments cascade across PSPs | | **`tagada.funnels`** | `.create(...)`, `.update(id, ...)`, `.promote(id, ...)` — multi-step flows with auto-routing | | **`tagada.shopify`** | `.checkScript(storeId)`, `.updateScript(storeId, ...)`, `.removeScript(storeId)`, `.audit(storeId)` — [Shopify checkout script](/developer-tools/shopify/checkout-script) | | **`tagada.plugins`** | `.deployDirectory(...)` (recommended), `.deploy(...)`, `.instantiate(...)`, `.mount(...)`, `.configureSplit(...)` — host pages on TagadaPay's CDN with A/B testing | | **`tagada.subscriptions`** | `.create(...)`, `.cancel(...)`, `.rebill(id)`, `.changeProcessor(...)` | | **`tagada.customers`** | `.list(...)`, `.retrieve(id)` | | **`tagada.orders`** | `.list(...)`, `.retrieve(id)` | | **`tagada.webhooks`** | `.create(...)`, `.list(...)`, `.del(id)` | | **`tagada.events`** | `.recent(...)`, `.list(...)`, `.statistics(...)` — event log and audit trail | | **`tagada.emailTemplates`** | `.create(...)`, `.list(...)`, `.update(...)`, `.test(...)`, `.del(...)` — [Emails guide](/developer-tools/headless-sdk/emails) | | **`tagada.promotions`** | `.create(...)`, `.list(...)`, `.update(...)` — discounts | | **`tagada.promotionCodes`** | `.create(...)`, `.list(...)` — discount codes | | **`tagada.offers`** | `.list(...)`, `.create(...)` — upsells, downsells, order bumps | | **`tagada.blockRules`** | `.create(...)`, `.list(...)`, `.del(...)` — fraud prevention | | **`tagada.paymentInstruments`** | `.createFromToken(...)`, `.list(...)`, `.retrieve(id)`, `.del(id)` — stored payment methods | | **`tagada.checkoutOffers`** | `.list(...)`, `.create(...)`, `.update(...)`, `.del(...)` — checkout-scoped offers | | **`tagada.checkout`** | `.createSession(...)`, `.pay(...)` — create checkout links and process payments server-side | | **`tagada.processors`** | `.list()`, `.create(...)`, `.retrieve(id)`, `.update(...)`, `.del([ids])` — manage PSP connections | | **`tagada.domains`** | `.add(...)`, `.list(...)`, `.verify(...)`, `.remove(...)`, `.getConfig(...)`, `.getDnsLookup(...)` — [Custom Domains guide](/developer-tools/node-sdk/custom-checkout#custom-domains) | *** ## Payment Flows: The Core of TagadaPay TagadaPay is **PSP-agnostic**. You connect multiple processors (Stripe, Checkout.com, NMI, etc.) and define **payment flows** that route transactions intelligently. ```ts theme={null} const flow = await tagada.paymentFlows.create({ data: { name: 'US Primary', strategy: 'cascade', // 'simple' = single processor, 'cascade' = fallback chain fallbackMode: true, maxFallbackRetries: 3, threeDsEnabled: false, stickyProcessorEnabled: true, pickProcessorStrategy: 'weighted', // 'weighted' | 'lowestCapacity' | 'automatic' processorConfigs: [ { processorId: 'proc_stripe', weight: 60, disabled: false, nonStickable: false }, { processorId: 'proc_checkout', weight: 40, disabled: false, nonStickable: false }, ], fallbackProcessorConfigs: [ { processorId: 'proc_nmi', orderIndex: 0 }, ], }, }); ``` 60% of traffic goes to Stripe, 40% to Checkout.com. If both fail, NMI picks up the payment. All automatic. *** ## Error Handling The SDK throws typed errors you can catch individually: ```ts theme={null} import Tagada, { TagadaNotFoundError, TagadaValidationError, TagadaAuthenticationError, TagadaRateLimitError, } from '@tagadapay/node-sdk'; try { await tagada.payments.retrieve('pay_nonexistent'); } catch (err) { if (err instanceof TagadaNotFoundError) { // 404 — resource doesn't exist } else if (err instanceof TagadaValidationError) { console.log(err.errors); // [{ field: 'amount', message: 'Required' }] } else if (err instanceof TagadaRateLimitError) { console.log(`Retry after ${err.retryAfter}s`); } } ``` Retries on `429`, `5xx`, and network errors are automatic (configurable via `maxRetries`). *** ## Configuration ```ts theme={null} const tagada = new Tagada({ apiKey: 'your-api-key', baseUrl: 'https://api.tagada.io/api/public/v1', // default timeout: 30_000, // request timeout maxRetries: 2, // auto-retry on failure apiVersion: '2025-01-01', }); ``` > [!TIP] > > Pass an `idempotencyKey` to safely retry mutations. Use a UUID: create it once per operation (for a payment, once per payment) and reuse it on every retry. A key is kept for 24 hours, per account, method and path. A key that is not a UUID is honoured only on an account with a store on Payments API V3; elsewhere it is ignored without an error. A `5xx` response releases the key, so a retry after a `5xx` can charge again. > > ```ts theme={null} > import { randomUUID } from 'node:crypto'; > > const idempotencyKey = randomUUID(); // store it with the order, reuse it on retry > await tagada.payments.process(params, { idempotencyKey }); > ``` *** ## TypeScript Fully typed. Import any type you need: ```ts theme={null} import type { Payment, Customer, Subscription, TagadaList } from '@tagadapay/node-sdk'; ``` *** ## Next Steps > [card] [Email Templates](/developer-tools/headless-sdk/emails) > > Create and customize transactional emails — order confirmations, subscription receipts, cart recovery > [card] [Webhooks & Events](/developer-tools/node-sdk/webhooks-events) > > Real-time notifications and event log for payments, subscriptions, and more > [card] [Subscriptions](/developer-tools/node-sdk/subscriptions) > > Recurring billing, trials, retries, processor migration > [card] [Multi-Stripe Routing & Vault](/developer-tools/node-sdk/multi-stripe-routing) > > Connect multiple Stripe accounts, vault cards, and cascade transactions > [card] [Funnel Orchestrator](/developer-tools/funnels/funnel-orchestrator) > > Deep dive into multi-step funnels with routing, A/B testing, and analytics > [card] [API Reference](/api-reference/introduction) > > Full REST API documentation # Sandbox Testing Source: https://docs.tagada.io/developer-tools/node-sdk/sandbox-testing Test payments end-to-end without real money using the sandbox processor # Sandbox Testing **Time**: \~10 minutes | **Difficulty**: Beginner The sandbox processor lets you test the full payment flow — checkout, payment processing, order creation, webhooks — without connecting a real payment gateway or charging real cards. *** ## How the Sandbox Processor Works The sandbox processor simulates a payment gateway. When a customer submits payment on a checkout that uses a sandbox processor: 1. The payment is **always approved** (no real card validation) 2. An order is created in TagadaPay 3. Webhooks fire as if a real payment occurred 4. Subscriptions are created and can be billed This makes it perfect for: * Testing your checkout flow end-to-end * Verifying webhook integrations * Testing subscription billing cycles * QA before going live with a real processor *** ## Step 1: Create a Sandbox Processor > [tab] Node SDK > > ```ts theme={null} > import Tagada from '@tagadapay/node-sdk'; > const tagada = new Tagada('your-api-key'); > > const { processor } = await tagada.processors.create({ > processor: { > name: 'Test Sandbox', > type: 'sandbox', > enabled: true, > supportedCurrencies: ['USD', 'EUR', 'GBP'], > baseCurrency: 'USD', > options: { > testMode: true, > }, > }, > }); > > console.log('Sandbox processor:', processor.id); > ``` > [tab] cURL > > ```bash theme={null} > curl -X POST https://api.tagada.io/api/public/v1/processors/create \ > -H "Authorization: Bearer your-api-key" \ > -H "Content-Type: application/json" \ > -d '{ > "processor": { > "name": "Test Sandbox", > "type": "sandbox", > "enabled": true, > "supportedCurrencies": ["USD", "EUR", "GBP"], > "baseCurrency": "USD", > "options": { "testMode": true } > } > }' > ``` *** ## Step 2: Create a Payment Flow Create a payment flow that routes all traffic to your sandbox processor: ```ts theme={null} const flow = await tagada.paymentFlows.create({ data: { name: 'Sandbox Flow', strategy: 'simple', fallbackMode: false, maxFallbackRetries: 0, threeDsEnabled: false, stickyProcessorEnabled: false, pickProcessorStrategy: 'weighted', processorConfigs: [ { processorId: processor.id, weight: 100, disabled: false, nonStickable: false, }, ], fallbackProcessorConfigs: [], abuseDetectionConfig: null, }, }); ``` *** ## Step 3: Assign to Your Store Assign the sandbox payment flow to your store. You can pass it at store creation: ```ts theme={null} const store = await tagada.stores.create({ name: 'Test Store', baseCurrency: 'USD', presentmentCurrencies: ['USD', 'EUR'], chargeCurrencies: ['USD'], selectedPaymentFlowId: flow.id, }); ``` Or if your store already exists, assign it via the dashboard: **Store Settings → Payments → Select Payment Flow**. *** ## Step 4: Complete the Setup Follow the [Merchant Quick Start](/developer-tools/node-sdk/merchant-quickstart) to create a product and funnel. Once your checkout is live, any payment submitted will go through the sandbox processor. *** ## Testing Payments ### On the Checkout Page 1. Open your checkout URL in a browser 2. Fill in any email and shipping details 3. Enter **any card number** — the sandbox accepts everything: * `4242 4242 4242 4242` (or any 16 digits) * Any future expiry date * Any 3-digit CVC 4. Submit payment 5. The order is created and you're redirected to the thank you page ### Via the Headless API You can also create a checkout session programmatically and share the link: ```ts theme={null} const session = await tagada.checkout.createSession({ storeId: store.id, items: [{ variantId: 'variant_...', quantity: 1 }], currency: 'USD', checkoutUrl: 'https://your-funnel-checkout-url.cdn.tagadapay.com/checkout', }); console.log('Test checkout:', session.redirectUrl); ``` *** ## Verifying Results After a sandbox payment, verify everything worked: ### Check Orders ```ts theme={null} const orders = await tagada.orders.list({ storeId: store.id, page: 1, per_page: 5, }); console.log('Latest orders:', orders.data); ``` ### Check Payments ```ts theme={null} const payments = await tagada.payments.list({ pagination: { page: 1, pageSize: 5 }, filters: { storeIds: [store.id] }, }); console.log('Latest payments:', payments.data); ``` ### Check Webhooks If you've configured webhooks, they fire for sandbox payments exactly as they would for real ones: ```ts theme={null} const webhooks = await tagada.webhooks.list(store.id); console.log('Configured webhooks:', webhooks); ``` *** ## Testing Subscriptions The sandbox processor fully supports subscription billing. Create a recurring product and test the billing cycle: ```ts theme={null} // Create a subscription product await tagada.products.create({ storeId: store.id, name: 'Monthly Membership', active: true, variants: [{ name: 'Standard', sku: 'membership-monthly', grams: 0, price: 1999, compareAtPrice: 0, active: true, default: true, prices: [{ currencyOptions: { USD: { amount: 1999 } }, recurring: true, interval: 'month', intervalCount: 1, billingTiming: 'in_advance', default: true, }], }], }); ``` When a customer subscribes through the checkout: * The initial payment is processed through the sandbox * The subscription is created in TagadaPay * Rebilling occurs on schedule (processed through the sandbox) * You can manage the subscription via the API or dashboard *** ## Sandbox vs Production | Behavior | Sandbox | Production | | - | - | - | | Card validation | Accepts any card | Real card validation | | Charges | No real money | Real charges | | Orders | Created normally | Created normally | | Webhooks | Fire normally | Fire normally | | Subscriptions | Created and billed | Created and billed | | 3D Secure | Skipped | Enforced if enabled | | Refunds | Simulated | Real refunds | *** ## Going Live When you're ready for production: 1. Create a real processor (Stripe, NMI, Checkout.com, etc.) with production credentials 2. Create a new payment flow using the real processor 3. Update your store's payment flow assignment 4. Your checkout now processes real payments ```ts theme={null} // 1. Real processor const { processor: stripeProcessor } = await tagada.processors.create({ processor: { name: 'Stripe Production', type: 'stripe', enabled: true, supportedCurrencies: ['USD', 'EUR'], baseCurrency: 'USD', options: { secretKey: 'sk_live_...', publicKey: 'pk_live_...', webhookSecret: 'whsec_...', }, }, }); // 2. Production flow const prodFlow = await tagada.paymentFlows.create({ data: { name: 'Production Flow', strategy: 'simple', fallbackMode: false, maxFallbackRetries: 0, threeDsEnabled: true, stickyProcessorEnabled: false, pickProcessorStrategy: 'weighted', processorConfigs: [ { processorId: stripeProcessor.id, weight: 100, disabled: false, nonStickable: false }, ], fallbackProcessorConfigs: [], abuseDetectionConfig: null, }, }); // 3. To switch a store's payment flow, update it in the dashboard // or recreate the store with the new flow ID ``` > [!TIP] > > You can keep the sandbox processor and flow around for ongoing testing. Just create a separate test store that uses the sandbox flow. *** ## Cleanup When done testing, archive the sandbox processor: ```ts theme={null} await tagada.processors.del([processor.id]); ``` *** ## Next Steps > [card] [Merchant Quick Start](/developer-tools/node-sdk/merchant-quickstart) > > Complete setup from zero to live checkout > [card] [Multi-PSP Routing](/developer-tools/node-sdk/multi-stripe-routing) > > Set up cascade routing across multiple processors > [card] [core-js + REST](/developer-tools/payments/core-js-payments) > > Build your own checkout UI with client-side card tokenization > [card] [Webhooks](/api-reference/introduction) > > Configure webhooks to receive payment events # Scripts & Pixels per Step Source: https://docs.tagada.io/developer-tools/node-sdk/step-config-guide Inject tracking pixels, custom scripts, and payment config into individual funnel steps # Scripts & Pixels per Step **Time**: \~10 minutes | **Difficulty**: Intermediate *** ## What Is Step Config? Every step in a funnel can have its own **runtime configuration** — tracking pixels, custom scripts, payment flow overrides, and order bumps. This is set inside `node.config.stepConfig`. ``` Funnel ├── step-landing → stepConfig: { pixels: { facebook: [...] } } ├── step-checkout → stepConfig: { pixels: {...}, scripts: [...], paymentSetupConfig: { card: { paymentFlowId: "..." } } } └── step-thankyou → stepConfig: { pixels: { facebook: [...] }, scripts: [...] } ``` > [!NOTE] > > **Why per-step?** Different steps fire different events. Your landing page tracks `PageView`, your checkout tracks `InitiateCheckout` and `Purchase`, and your thank-you page tracks the conversion. Each step can have completely different pixels and scripts. *** ## Step Config Structure ```ts theme={null} node.config.stepConfig = { // Tracking pixels (Meta, TikTok, Snapchat, GTM, etc.) pixels: { ... }, // Custom script injection (any JS) scripts: [ ... ], // Payment methods displayed at checkout (cards, wallets, APMs) paymentSetupConfig: { card: { enabled: true, method: 'card', provider: 'tagada', paymentFlowId: 'flow_xxx' }, apple_pay: { enabled: true, method: 'apple_pay', provider: 'stripe', express: true, processorId: 'processor_xxx' }, // ...more methods }, // Order bumps (checkout steps only) orderBumps: { mode: 'inherit' | 'custom', enabledOfferIds: [...] }, }; ``` *** ## Tracking Pixels Pixels are keyed by provider. Each provider can have **multiple pixels** (array). ### Meta / Facebook Pixel ```ts theme={null} stepConfig: { pixels: { facebook: [ { enabled: true, pixelId: '123456789012345', events: { PageView: true, ViewContent: true, AddToCart: true, InitiateCheckout: true, Purchase: true, }, }, ], }, } ``` ### Meta Conversion API (server-side) ```ts theme={null} stepConfig: { pixels: { metaConversion: [ { enabled: true, pixelId: '123456789012345', accessToken: 'EAABsbCS...', publishPurchaseIfNewCustomerOnly: false, }, ], }, } ``` ### TikTok Pixel ```ts theme={null} stepConfig: { pixels: { tiktok: [ { enabled: true, pixelId: 'CTJDE3RC77U...', events: { PageView: true, ViewContent: true, AddToCart: true, InitiateCheckout: true, Purchase: true, }, }, ], }, } ``` ### Snapchat Pixel ```ts theme={null} stepConfig: { pixels: { snapchat: [ { enabled: true, pixelId: 'abc123...', events: { PageView: true, InitiateCheckout: true, Purchase: true, AddToCart: true, ViewContent: true, }, }, ], }, } ``` ### Google Tag Manager ```ts theme={null} stepConfig: { pixels: { gtm: [ { enabled: true, containerId: 'GTM-XXXXXXX', events: { PageView: true, InitiateCheckout: true, Purchase: true, AddToCart: true, ViewContent: true, }, googleAdsConversionId: 'AW-123456789', googleAdsConversionLabel: 'abcDEF123', }, ], }, } ``` *** ## Custom Scripts Inject any JavaScript into funnel pages. Each script has a name, content, and injection position. ```ts theme={null} stepConfig: { scripts: [ { name: 'Hotjar', enabled: true, content: `(function(h,o,t,j,a,r){h.hj=h.hj||function(){(h.hj.q=h.hj.q||[]).push(arguments)};h._hjSettings={hjid:12345,hjsv:6};a=o.getElementsByTagName('head')[0];r=o.createElement('script');r.async=1;r.src=t+h._hjSettings.hjid+j+h._hjSettings.hjsv;a.appendChild(r);})(window,document,'https://static.hotjar.com/c/hotjar-','.js?sv=');`, position: 'head-end', }, { name: 'Custom conversion', enabled: true, content: `console.log('Step loaded:', window.__TGD_FUNNEL_STEP_ID__);`, position: 'body-end', }, ], } ``` | Position | Where it's injected | | - | - | | `head-start` | First thing inside `` | | `head-end` | Last thing inside `` (default) | | `body-start` | First thing inside `` | | `body-end` | Last thing inside `` | *** ## Full Example: 3-Step Funnel with Tracking Here's a complete Node SDK example that creates a funnel with Meta Pixel + TikTok on every step, plus GTM on checkout only. ```ts theme={null} import Tagada from '@tagadapay/node-sdk'; const tagada = new Tagada('your-api-key'); const META_PIXEL = '123456789012345'; const TIKTOK_PIXEL = 'CTJDE3RC77U...'; const GTM_CONTAINER = 'GTM-XXXXXXX'; const storeId = 'store_xxx'; const pluginId = 'my-checkout-plugin'; const instanceId = 'my-instance-id'; // Helper: Meta pixel config for a step const metaPixel = (events: Record) => ({ facebook: [{ enabled: true, pixelId: META_PIXEL, events: { PageView: false, InitiateCheckout: false, Purchase: false, ...events }, }], }); // Helper: TikTok pixel config for a step const tiktokPixel = (events: Record) => ({ tiktok: [{ enabled: true, pixelId: TIKTOK_PIXEL, events: { PageView: false, InitiateCheckout: false, Purchase: false, ...events }, }], }); const funnel = await tagada.funnels.create({ storeId, config: { id: 'my-tracked-funnel', name: 'Tracked Checkout Funnel', version: '1.0.0', nodes: [ { id: 'step-landing', name: 'Landing Page', type: 'landing', isEntry: true, isDefault: true, position: { x: 0, y: 0 }, config: { pluginId, instanceId, pagePath: '/', path: '/', stepConfig: { pixels: { ...metaPixel({ PageView: true }), ...tiktokPixel({ PageView: true }), }, }, }, }, { id: 'step-checkout', name: 'Checkout', type: 'checkout', isConversion: true, position: { x: 300, y: 0 }, config: { pluginId, instanceId, pagePath: '/checkout', path: '/checkout', stepConfig: { pixels: { ...metaPixel({ InitiateCheckout: true, Purchase: true }), ...tiktokPixel({ InitiateCheckout: true, Purchase: true }), gtm: [{ enabled: true, containerId: GTM_CONTAINER, events: { PageView: true, InitiateCheckout: true, Purchase: true, AddToCart: true, ViewContent: true, }, }], }, paymentSetupConfig: { card: { enabled: true, method: 'card', provider: 'tagada', paymentFlowId: 'flow_xxx' }, }, scripts: [ { name: 'Checkout analytics', enabled: true, content: `console.log('Checkout step loaded');`, position: 'body-end', }, ], }, }, }, { id: 'step-thankyou', name: 'Thank You', type: 'thankyou', position: { x: 600, y: 0 }, config: { pluginId, instanceId, pagePath: '/thankyou', path: '/thankyou', stepConfig: { pixels: { ...metaPixel({ Purchase: true }), ...tiktokPixel({ Purchase: true }), }, }, }, }, ], edges: [ { id: 'e1', source: 'step-landing', target: 'step-checkout' }, { id: 'e2', source: 'step-checkout', target: 'step-thankyou' }, ], }, isDefault: true, }); // Activate routing await tagada.funnels.update(funnel.id, { storeId, config: funnel.config, }); console.log('Funnel created with per-step tracking!'); ``` *** ## Pixel Event Reference | Event | When it fires | Typical steps | | - | - | - | | `PageView` | Page loads | All steps | | `InitiateCheckout` | Customer starts checkout | Checkout | | `Purchase` | Payment succeeds | Checkout, Thank You | | `AddToCart` | A landing page button clicked that opens the checkout or continues to the next step, or an order bump added on a checkout page | Landing, Checkout | | `ViewContent` | Landing or offer page viewed | Landing, Offer | Every provider (Meta, TikTok, Snapchat, GTM, Clarity) offers these five events. Entries saved with the old Snapchat-only `Search`, `AddToWishlist` or `CompleteRegistration` keys keep loading, but nothing fires them. *** ## Supported Providers | Provider Key | Pixel Type | Config Fields | | - | - | - | | `facebook` | Meta Pixel (client-side) | `pixelId`, `events` | | `metaConversion` | Meta Conversion API (server-side) | `pixelId`, `accessToken`, `publishPurchaseIfNewCustomerOnly` | | `tiktok` | TikTok Pixel | `pixelId`, `events` | | `snapchat` | Snap Pixel | `pixelId`, `events` (extended) | | `gtm` | Google Tag Manager | `containerId`, `events`, `googleAdsConversionId`, `googleAdsConversionLabel` | > [!TIP] > > You can attach **multiple pixels of the same provider** to a single step. For example, two Facebook pixels for different ad accounts — just add more entries to the array. *** ## Payment Setup Config `paymentSetupConfig` controls which payment methods are displayed on a checkout step and how each method is routed. It's a key-value map where keys are method identifiers. ### Structure ```ts theme={null} stepConfig: { paymentSetupConfig: { card: { enabled: true, method: 'card', provider: 'tagada', paymentFlowId: 'flow_xxx', }, 'apple_pay:stripe': { enabled: true, method: 'apple_pay', provider: 'stripe', express: true, processorId: 'processor_xxx', }, 'google_pay:stripe': { enabled: true, method: 'google_pay', provider: 'stripe', express: true, processorId: 'processor_xxx', }, 'klarna:airwallex': { enabled: false, method: 'klarna', provider: 'airwallex', processorId: 'processor_yyy', }, }, } ``` ### Fields | Field | Type | Description | | - | - | - | | `enabled` | boolean | Whether this payment method is shown at checkout | | `method` | string | Payment method: `card`, `apple_pay`, `google_pay`, `paypal`, `klarna`, `ideal`, etc. | | `provider` | string | Processor family: `tagada`, `stripe`, `airwallex`, etc. | | `express` | boolean | Render as an express checkout button above the form | | `paymentFlowId` | string | Route this method through a specific payment flow (cascade, weighted, etc.) | | `processorId` | string | Route directly to a specific processor (for APMs and express methods) | | `integrationId` | string | TagadaPay native integration ID (for Apple Pay via Basis Theory, etc.) | ### Key Format Keys follow the pattern `{method}` or `{method}:{provider}`: * `card` — card payments (routed via payment flow) * `apple_pay:stripe` — Apple Pay via Stripe * `google_pay:stripe` — Google Pay via Stripe * `klarna:airwallex` — Klarna via Airwallex * `paypal:airwallex` — PayPal via Airwallex ### Payment Flow Resolution Order When processing a card payment, the `paymentFlowId` is resolved in this order: ``` 1. paymentSetupConfig.card.paymentFlowId ← most specific (recommended) 2. payment.paymentFlowId ← per-step fallback (legacy) 3. Store's default payment flow ← if neither is set ``` > [!WARNING] > > The `payment: { paymentFlowId }` key is **legacy**. Use `paymentSetupConfig.card.paymentFlowId` instead — it's more explicit and supports per-method routing. ### Example: Different Flow for High-Value Orders ```ts theme={null} stepConfig: { paymentSetupConfig: { card: { enabled: true, method: 'card', provider: 'tagada', paymentFlowId: 'flow_high_value', }, }, } ``` ### Example: Cards + Apple Pay + Google Pay ```ts theme={null} stepConfig: { paymentSetupConfig: { card: { enabled: true, method: 'card', provider: 'tagada', paymentFlowId: 'flow_default', }, 'apple_pay:stripe': { enabled: true, method: 'apple_pay', provider: 'stripe', express: true, processorId: 'processor_stripe_us', }, 'google_pay:stripe': { enabled: true, method: 'google_pay', provider: 'stripe', express: true, processorId: 'processor_stripe_us', }, }, } ``` *** ## Next Steps > [card] [Node SDK Quick Start](/developer-tools/node-sdk/quick-start) > > Get started with the Node SDK > [card] [Funnel Orchestrator](/developer-tools/funnels/funnel-orchestrator) > > Deep dive into funnel routing, A/B testing, and navigation > [card] [core-js + REST](/developer-tools/payments/core-js-payments) > > Build your own checkout UI with client-side card tokenization and 3DS > [card] [Deploy & A/B Test](/developer-tools/hosting/deploy-and-ab-test) > > Deploy pages and run split tests # Subscriptions & Rebilling Source: https://docs.tagada.io/developer-tools/node-sdk/subscriptions Create subscriptions, handle trials, manual rebills, processor changes, and the full subscription lifecycle # Subscriptions & Rebilling **Time**: \~10 minutes | **Difficulty**: Intermediate *** ## What Are Subscriptions in TagadaPay? TagadaPay manages the entire recurring billing lifecycle — creation, automatic rebills, retries on failure, pause/resume, cancellation, and processor changes. It's **PSP-agnostic**: the same subscription can be billed through Stripe today and NMI tomorrow, without touching your code. ``` ┌────────────┐ ┌─────────────┐ ┌──────────────┐ ┌──────────┐ │ Customer │────▶│ Subscribe │────▶│ Auto-rebill │────▶│ Renew │ │ pays once │ │ (active) │ │ every cycle │ │ forever │ └────────────┘ └─────────────┘ └──────────────┘ └──────────┘ │ │ │ ┌─────┴──────┐ │ │ Declined? │ │ │ → Retry │ │ │ → Past due │ │ │ → Cancel │ │ └────────────┘ │ ┌────┴────┐ │ Trial? │ │ 7 days │ │ free │ └─────────┘ ``` > [!NOTE] > > **Subscriptions are vaulted.** The customer's card is tokenized once. TagadaPay charges it automatically each cycle — through whichever processor your payment flow selects. You never handle raw card data or PSP-specific recurring APIs. *** ## Subscription Lifecycle | Status | Meaning | | - | - | | `trialing` | Free trial period, no charges yet | | `active` | Recurring charges are running | | `past_due` | Last rebill failed, retrying automatically | | `paused` | Billing suspended, can be resumed | | `canceled` | Terminated (immediately or at period end) | ``` create → trialing → active ⟲ (rebill each cycle) ↓ past_due → retry → active (success) ↓ → canceled (max retries) ↓ paused → resume → active ↓ canceled ``` *** ## Create a Subscription ```ts theme={null} import Tagada from '@tagadapay/node-sdk'; const tagada = new Tagada('your-api-key'); const { subscription } = await tagada.subscriptions.create({ customerId: 'cus_abc123', priceId: 'price_monthly_2999', storeId: 'store_xxx', currency: 'USD', quantity: 1, defaultPaymentInstrumentId: 'pi_abc123', }); console.log(subscription.id); // 'sub_xyz789' console.log(subscription.status); // 'active' console.log(subscription.nextBillingDate); // '2026-04-19T00:00:00Z' ``` | Parameter | Required | Description | | - | - | - | | `customerId` | Yes | The customer to bill | | `priceId` | Yes | A recurring price (from a product variant) | | `storeId` | Yes | Your store | | `currency` | Yes | ISO currency code | | `defaultPaymentInstrumentId` | No | Card to charge (uses customer's default if omitted) | | `quantity` | No | Number of units (default: 1) | | `paymentId` | No | Link to the initial payment | | `billingCycleAnchor` | No | First billing date as Unix milliseconds in a string of digits, e.g. `String(Date.UTC(2026, 10, 1))`; fixes the billing day (e.g. always the 1st). Date strings are rejected | | `initiatePayment` | No | Deprecated: the API rejects it with a `400`. Use `billingCycleAnchor` to schedule the first charge | *** ## Create with a Free Trial ```ts theme={null} const { subscription } = await tagada.subscriptions.create({ customerId: 'cus_abc123', priceId: 'price_monthly_2999', storeId: 'store_xxx', currency: 'USD', defaultPaymentInstrumentId: 'pi_abc123', trialSettings: { trialPeriodDuration: 7, trialPeriodDurationType: 'day', }, }); console.log(subscription.status); // 'trialing' console.log(subscription.trial); // true ``` The customer isn't charged until the trial ends. TagadaPay automatically transitions to `active` and triggers the first rebill. | Trial Duration Type | Examples | | - | - | | `day` | 3 days, 7 days, 14 days | | `week` | 1 week, 2 weeks | | `month` | 1 month, 3 months | *** ## Manual Rebill Trigger an immediate charge on any `active` or `past_due` subscription — useful for dashboards, support tools, or retry scripts. ```ts theme={null} const result = await tagada.subscriptions.rebill('sub_xyz789'); console.log(result.success); // true console.log(result.message); // 'Rebill triggered successfully' ``` > [!NOTE] > > **What happens under the hood:** > > 1. TagadaPay loads the subscription's price, currency, and payment instrument > 2. Routes the charge through your payment flow (cascade, weighted, fallback — all automatic) > 3. On success → updates `nextBillingDate`, status stays `active` > 4. On decline → enters retry logic (see below) ### When to Use Manual Rebill | Scenario | Example | | - | - | | **Customer updated card** | They fixed their card details, you want to charge immediately instead of waiting for auto-retry | | **Support request** | "Please charge me now" | | **Retry script** | Batch-retry all `past_due` subscriptions | | **Testing** | Verify billing works end-to-end | ### Batch Retry All Past-Due Subscriptions ```ts theme={null} const { data: subscriptions } = await tagada.subscriptions.list({ per_page: 100, filters: { 'subscriptions.status': ['past_due'], storeIds: ['store_xxx'], }, }); console.log(`Found ${subscriptions.length} past-due subscriptions`); for (const sub of subscriptions) { try { await tagada.subscriptions.rebill(sub.id); console.log(`Rebilled ${sub.id}`); } catch (err) { console.log(`Failed ${sub.id}: ${err.message}`); } } ``` *** ## Automatic Retry on Failure When a rebill is declined, TagadaPay doesn't immediately cancel. It retries automatically: ``` Rebill declined → Wait 24h → Retry #1 → Wait 48h → Retry #2 → Wait 96h → Retry #3 → Wait 168h → Retry #4 → Wait 168h → Retry #5 → Cancel subscription ``` | Retry | Delay | Total elapsed | | - | - | - | | 1 | 24 hours | 1 day | | 2 | 48 hours | 3 days | | 3 | 96 hours | 7 days | | 4 | 168 hours | 14 days | | 5 | 168 hours | 21 days | During retries, the subscription status is `past_due`. After max retries, it's automatically canceled. > [!TIP] > > **Smart retry** is also available — it uses failure codes (e.g. "insufficient funds"), velocity limits, and even payroll-day heuristics to pick the optimal retry time. Contact support to enable it. *** ## Cancel a Subscription ### Cancel Immediately ```ts theme={null} await tagada.subscriptions.cancel({ subscriptionIds: ['sub_xyz789'], }); // Status → 'canceled' right now ``` ### Cancel at Period End ```ts theme={null} await tagada.subscriptions.cancel({ subscriptionIds: ['sub_xyz789'], cancelAtPeriodEnd: true, }); // Stays 'active' until currentPeriodEnd, then auto-cancels ``` The customer keeps access until their billing period ends. TagadaPay handles the scheduled cancellation automatically. ### Cancel a trial at its end By default, cancelling a trial ends it immediately, even with `cancelAtPeriodEnd: true`. Opt in per request to keep access until the trial ends, then cancel without a first charge: ```ts theme={null} await tagada.subscriptions.cancel({ subscriptionIds: ['sub_trial'], cancelAtPeriodEnd: true, keepTrialUntilEnd: true, }); // Response status: 'cancel_scheduled'. The subscription stays 'trialing'. ``` The subscription keeps its trial and billing dates, with `cancelAtPeriodEnd: true`. Call `tagada.subscriptions.resume({ subscriptionIds: ['sub_trial'] })` before the end to clear the flag without converting the trial to an active subscription. At `nextBillingDate`, Tagada cancels it with reason `scheduled_period_end` before any charge. The option is ignored for immediate cancellations and non-trialing subscriptions. Grouped, PayPal-billed or draft trials, legacy trials with an unknown draft flag, and trials without `nextBillingDate` still end immediately because the scheduled reaper does not cover them. Existing callers keep their current behavior unless they pass `keepTrialUntilEnd: true`. The `subscription/cancelScheduled` webhook keeps its existing keys and also includes `status` and `nextBillingDate` (ISO timestamp or `null`). For a trial without `currentPeriodEnd`, that field falls back to `nextBillingDate`, when access ends. ### Bulk Cancel ```ts theme={null} await tagada.subscriptions.cancel({ subscriptionIds: ['sub_001', 'sub_002', 'sub_003'], cancelAtPeriodEnd: true, }); ``` *** ## Resume a Subscription Resume a `paused` or `past_due` subscription, or undo a cancellation scheduled at period end. A `canceled` subscription cannot be resumed (HTTP 409): ```ts theme={null} await tagada.subscriptions.resume({ subscriptionIds: ['sub_xyz789'], }); // Status → 'active', billing resumes ``` If the subscription had `cancelAtPeriodEnd: true` but hasn't reached the end yet, resuming clears the cancellation flag. *** ## Pause a Subscription Pausing stops billing without canceling — the subscription stays on file and can be resumed at any time. Useful for customer-portal self-serve, seasonal accounts, or account-recovery flows where you don't want to lose the vaulted card. ```ts theme={null} await tagada.subscriptions.pause({ subscriptionIds: ['sub_xyz789'], }); // Status → 'paused', billing suspended until resume ``` ### Bulk Pause ```ts theme={null} await tagada.subscriptions.pause({ subscriptionIds: ['sub_001', 'sub_002', 'sub_003'], }); ``` Only subscriptions belonging to the authenticated account are affected — ids you don't own are silently ignored (no error). Response shape: `{ success: true }`. ### Pause vs. Cancel at Period End | Scenario | Use | | - | - | | Customer explicitly wants to keep the sub, just skip billing for a while | `pause` | | Customer wants to end the sub but keep it running through the current cycle | `cancel({ cancelAtPeriodEnd: true })` | | Customer wants to end the sub immediately | `cancel({ cancelAtPeriodEnd: false })` | To undo `cancel({ cancelAtPeriodEnd: true })` before the period ends, call `tagada.subscriptions.resume({ subscriptionIds: [...] })`. Once a subscription is `canceled`, resume answers HTTP 409. *** ## Move the Next Billing Date (Skip a Month) `updateBillingCycle` moves the next charge to a new date. The subscription stays `active`, so there is nothing to resume afterwards: to skip a month, move the next billing date one month later. ```ts theme={null} const results = await tagada.subscriptions.updateBillingCycle({ subscriptionIds: ['sub_xyz789'], billingCycleAnchor: Date.UTC(2026, 11, 1), // 1 December 2026 }); // [{ subscriptionId: 'sub_xyz789', status: 'success' }] ``` `billingCycleAnchor` is Unix milliseconds, as a number or a string of digits. A date string is rejected. By default the subscription keeps its usual time of day and only the date moves, so pass midnight UTC of the target day. To bill at an exact instant, which must be in the future, add `timeOfDay: 'exact'`. A date before today is refused. The answer has one result per id: | `status` | Meaning | | - | - | | `success` | The next billing date moved | | `skipped` | `skipReason: 'not_found_or_trialing_or_canceled'`: the id is not on your account, or the subscription is trialing or canceled | | `failed` | The date was refused, `error` says why | *** ## Change Processor Move a subscription from one processor to another — for example, migrating from Stripe to Checkout.com, or clearing a stuck processor. ### Assign a Specific Processor ```ts theme={null} const { subscription } = await tagada.subscriptions.changeProcessor( 'sub_xyz789', 'proc_cko', // Checkout.com ); console.log(subscription.processorId); // 'proc_cko' ``` The next rebill will use Checkout.com instead of the previous processor. ### Let TagadaPay Auto-Select ```ts theme={null} const { subscription } = await tagada.subscriptions.changeProcessor('sub_xyz789'); // No processorId → TagadaPay uses the payment flow strategy ``` This removes the sticky processor, so the next rebill will be routed by your payment flow (weighted, cascade, etc.). ### Use Case: Migrate All Subscriptions from Stripe to NMI ```ts theme={null} const { data: subscriptions } = await tagada.subscriptions.list({ per_page: 100, filters: { 'subscriptions.status': ['active'], processorIds: ['proc_s1'], // current: Stripe }, }); for (const sub of subscriptions) { await tagada.subscriptions.changeProcessor(sub.id, 'proc_nmi'); console.log(`Migrated ${sub.id} to NMI`); } ``` > [!TIP] > > **This is a TagadaPay superpower.** With a traditional PSP, migrating subscriptions between processors means re-collecting card details. With TagadaPay's PSP-agnostic vault, you just change the processor ID — the vaulted card works across all processors. *** ## List & Filter Subscriptions ```ts theme={null} const { data, total, hasMore } = await tagada.subscriptions.list({ page: 1, per_page: 50, sort: 'createdAt', sort_order: 'desc', filters: { storeIds: ['store_xxx'], 'subscriptions.status': ['active', 'trialing'], }, }); for (const sub of data) { console.log(`${sub.id} — ${sub.status} — next bill: ${sub.nextBillingDate}`); } ``` ### Available Filters | Filter | Type | Example | | - | - | - | | `subscriptions.status` | `string[]` | `['active', 'past_due']` | | `subscriptions.trial` | `boolean` | `true` | | `storeIds` | `string[]` | `['store_xxx']` | | `processorIds` | `string[]` | `['proc_s1', 'proc_nmi']` | | `currency` | `string` | `'USD'` | | `customerEmail` | `string` | `'jane@example.com'` | | `price` | `{ condition, value }` | `{ condition: 'gte', value: [1000] }` | | `date` | `{ condition, value }` | `{ condition: 'between', value: ['2026-01-01', '2026-03-01'] }` | | `nextBillingDate` | `{ condition, value }` | `{ condition: 'lte', value: ['2026-03-25'] }` | *** ## Retrieve a Subscription ```ts theme={null} const { subscription } = await tagada.subscriptions.retrieve('sub_xyz789'); console.log(subscription.status); // 'active' console.log(subscription.currentPeriodStart); // '2026-03-01T00:00:00Z' console.log(subscription.currentPeriodEnd); // '2026-04-01T00:00:00Z' console.log(subscription.nextBillingDate); // '2026-04-01T00:00:00Z' console.log(subscription.processorId); // 'proc_s1' console.log(subscription.paymentInstrumentId); // 'pi_abc123' console.log(subscription.cancelAtPeriodEnd); // false ``` *** ## Webhook Events Listen for subscription events via [webhooks](/api-reference/introduction) to keep your system in sync: | Event | When it fires | | - | - | | `subscription/created` | New subscription created | | `subscription/rebillSucceeded` | Recurring charge succeeded | | `subscription/rebillDeclined` | Recurring charge failed | | `subscription/pastDue` | Subscription entered past\_due after decline | | `subscription/paused` | Subscription paused | | `subscription/resumed` | Subscription resumed | | `subscription/canceled` | Subscription canceled immediately | | `subscription/cancelScheduled` | Cancel scheduled for period end | | `subscription/rebillUpcoming` | Upcoming rebill (advance notice) | *** ## Full Example: Subscription with Trial, Rebill, and Processor Migration ```ts theme={null} import Tagada from '@tagadapay/node-sdk'; const tagada = new Tagada('your-api-key'); const storeId = 'store_xxx'; // ── 1. Create a subscription with 14-day trial ────────────────────── const { subscription } = await tagada.subscriptions.create({ customerId: 'cus_abc123', priceId: 'price_monthly_2999', storeId, currency: 'USD', defaultPaymentInstrumentId: 'pi_abc123', trialSettings: { trialPeriodDuration: 14, trialPeriodDurationType: 'day', }, }); console.log(`Created: ${subscription.id} — ${subscription.status}`); // → "Created: sub_xyz789 — trialing" // ── 2. Later: trial ends, auto-rebill runs ────────────────────────── // (TagadaPay handles this automatically — no code needed) // ── 3. Manual rebill (e.g. customer updated their card) ───────────── const rebillResult = await tagada.subscriptions.rebill(subscription.id); console.log(`Rebill: ${rebillResult.message}`); // ── 4. Move subscription from Stripe to Checkout.com ──────────────── const { subscription: updated } = await tagada.subscriptions.changeProcessor( subscription.id, 'proc_cko', ); console.log(`Processor changed to: ${updated.processorId}`); // ── 5. Customer wants to cancel at period end ─────────────────────── await tagada.subscriptions.cancel({ subscriptionIds: [subscription.id], cancelAtPeriodEnd: true, }); console.log('Cancel scheduled at period end'); // ── 6. Customer changes their mind — resume ───────────────────────── await tagada.subscriptions.resume({ subscriptionIds: [subscription.id], }); console.log('Subscription resumed!'); ``` *** ## Next Steps > [card] [Multi-PSP Routing & Vault](/developer-tools/node-sdk/multi-stripe-routing) > > Connect Stripe, NMI, Checkout.com, Airwallex and route payments intelligently > [card] [core-js + REST](/developer-tools/payments/core-js-payments) > > Build your own checkout UI with client-side card tokenization and 3DS > [card] [Node SDK Quick Start](/developer-tools/node-sdk/quick-start) > > Get started with stores, products, and funnels > [card] [API Reference](/api-reference/introduction) > > Full REST API documentation # Upsell & Downsell Funnel Source: https://docs.tagada.io/developer-tools/node-sdk/upsell-downsell-funnel Build a checkout flow with conditional offer routing — upsell on accept, downsell on decline # Upsell & Downsell Funnel **Time**: \~10 minutes | **Difficulty**: Intermediate > [!NOTE] > > The 6-step version of this type (landing + second OTO + thank-you `relatedOrders`) is the runnable [`basic-post-purchase`](https://github.com/TagadaPay/examples/tree/main/basic-post-purchase) example. Build a complete post-purchase offer flow using the Node SDK. Customers check out, see an upsell offer, and either accept it (→ thank you) or decline it (→ cheaper downsell offer → thank you). ![Upsell and downsell funnel: checkout, 99 upsell, 19 downsell, thank you](https://mintcdn.com/tagadapay/kGWh0luIQjcrt2Rd/assets/images/funnel-demos/upsell-downsell-graph.png?fit=max\&auto=format\&n=kGWh0luIQjcrt2Rd\&q=85\&s=3a4f6954e68a74870c02f3c5349ece6a) > [!NOTE] > > This tutorial uses **native checkout pages** — no custom HTML or Plugin SDK deployment needed. TagadaPay auto-injects checkout, offer, and thank you pages when no plugin is assigned to a step. *** ## Prerequisites | Requirement | How to get it | | - | - | | Node.js 18+ | [nodejs.org](https://nodejs.org) | | `@tagadapay/node-sdk` | `npm install @tagadapay/node-sdk` | | API key | Dashboard → Settings → API Keys | | A store with at least one payment processor | [Merchant Quick Start](/developer-tools/node-sdk/merchant-quickstart) | *** ## What You'll Build A 4-step funnel with **conditional routing** based on offer acceptance: | Step | Type | Purpose | | - | - | - | | Checkout | `checkout` | Payment page — collects card info, processes the initial order | | Upsell | `offer` | Post-purchase offer — VIP Coaching Pack (\$99) | | Downsell | `offer` | Fallback offer if upsell is declined — Quick-Start Guide (\$19) | | Thank You | `thankyou` | Order confirmation — fires conversion events | The edges between steps use **conditions** to route the customer: * `{ when: 'offer.accepted' }` — customer accepted the offer * `{ when: 'offer.declined' }` — customer declined the offer *** ## Step 1: Initialize the SDK ```ts theme={null} import Tagada from '@tagadapay/node-sdk'; const tagada = new Tagada('your-api-key'); const STORE_ID = 'store_...'; ``` *** ## Step 2: Create products You need three products — one for the main checkout, one for the upsell, one for the downsell. ```ts theme={null} const mainProduct = await tagada.products.create({ storeId: STORE_ID, name: 'Premium Course', description: 'The main product customers purchase at checkout.', active: true, isShippable: false, isTaxable: false, variants: [{ name: 'Default', sku: 'COURSE-001', grams: null, active: true, default: true, price: null, compareAtPrice: null, prices: [{ currencyOptions: { USD: { amount: 4900 } }, recurring: false, billingTiming: 'usage', interval: null, intervalCount: 1, default: true, }], }], }); const upsellProduct = await tagada.products.create({ storeId: STORE_ID, name: 'VIP Coaching Pack', active: true, isShippable: false, isTaxable: false, variants: [{ name: 'Default', sku: 'VIP-001', grams: null, active: true, default: true, price: null, compareAtPrice: null, prices: [{ currencyOptions: { USD: { amount: 9900 } }, recurring: false, billingTiming: 'usage', interval: null, intervalCount: 1, default: true, }], }], }); const downsellProduct = await tagada.products.create({ storeId: STORE_ID, name: 'Quick-Start Guide', active: true, isShippable: false, isTaxable: false, variants: [{ name: 'Default', sku: 'GUIDE-001', grams: null, active: true, default: true, price: null, compareAtPrice: null, prices: [{ currencyOptions: { USD: { amount: 1900 } }, recurring: false, billingTiming: 'usage', interval: null, intervalCount: 1, default: true, }], }], }); ``` > [!TIP] > > Prices are in **cents** — `4900` = \$49.00. The `currencyOptions` object lets you define amounts per currency. *** ## Step 3: Create checkout offers Checkout offers are standalone resources that you bind to funnel steps. Each offer references product line items via their `priceId`. Use `tagada.checkoutOffers.create()` — this creates offers in the checkout offers table, which the native offer page can render. ```ts theme={null} const upsellOffer = await tagada.checkoutOffers.create({ storeId: STORE_ID, type: 'upsell', titleTrans: { en: 'Upgrade to VIP Coaching Pack' }, lineItems: [{ priceId: upsellProduct.variants[0].prices[0].id, quantity: 1, }], }); const downsellOffer = await tagada.checkoutOffers.create({ storeId: STORE_ID, type: 'upsell', titleTrans: { en: 'Get the Quick-Start Guide instead' }, lineItems: [{ priceId: downsellProduct.variants[0].prices[0].id, quantity: 1, }], }); ``` ### Verify and list offers ```ts theme={null} // Retrieve a single offer const offer = await tagada.checkoutOffers.retrieve(upsellOffer.id); console.log('Offer title:', offer.offer.titleTrans.en); // List all offers for the store const allOffers = await tagada.checkoutOffers.list({ storeId: STORE_ID }); console.log('Total offers:', allOffers.offers.length); ``` > [!NOTE] > > Both upsell and downsell use `type: 'upsell'` — they are post-purchase offers. For order bumps shown **on** the checkout page (before payment), use `tagada.offers.create()` with `type: 'orderbump'`. *** ## Step 4: Create the funnel with conditional edges This is where the magic happens. Define four nodes and five edges with `conditions.when` to control the flow. ```ts theme={null} const funnel = await tagada.funnels.create({ storeId: STORE_ID, config: { name: 'Upsell/Downsell Flow', version: '1.0.0', nodes: [ { id: 'step_checkout', name: 'Checkout', kind: 'step', type: 'checkout', isEntry: true, position: { x: 0, y: 150 }, index: 0, config: { pagePath: '/checkout', metadata: { internalPath: '/checkout' }, stepConfig: { orderBumps: { mode: 'inherit' }, }, }, }, { id: 'step_upsell', name: 'Upsell — VIP Coaching', kind: 'step', type: 'offer', position: { x: 300, y: 150 }, index: 1, config: { pagePath: '/upsell', metadata: { internalPath: '/offer' }, stepConfig: { resources: { offer: upsellOffer.id }, }, }, }, { id: 'step_downsell', name: 'Downsell — Quick-Start Guide', kind: 'step', type: 'offer', position: { x: 600, y: 300 }, index: 2, config: { pagePath: '/downsell', metadata: { internalPath: '/offer' }, stepConfig: { resources: { offer: downsellOffer.id }, }, }, }, { id: 'step_thankyou', name: 'Thank You', kind: 'step', type: 'thankyou', position: { x: 900, y: 150 }, index: 3, config: { pagePath: '/thankyou/:orderId', metadata: { internalPath: '/thankyou/:orderId' }, }, }, ], edges: [ // Checkout → Upsell (always, after payment) { id: 'e_checkout_to_upsell', source: 'step_checkout', target: 'step_upsell', label: 'After payment', }, // Upsell accepted → Thank You { id: 'e_upsell_accepted', source: 'step_upsell', target: 'step_thankyou', label: 'Offer accepted', conditions: { when: 'offer.accepted' }, }, // Upsell declined → Downsell { id: 'e_upsell_declined', source: 'step_upsell', target: 'step_downsell', label: 'Offer declined', conditions: { when: 'offer.declined' }, }, // Downsell accepted → Thank You { id: 'e_downsell_accepted', source: 'step_downsell', target: 'step_thankyou', label: 'Downsell accepted', conditions: { when: 'offer.accepted' }, }, // Downsell declined → Thank You { id: 'e_downsell_declined', source: 'step_downsell', target: 'step_thankyou', label: 'Downsell declined', conditions: { when: 'offer.declined' }, }, ], }, isDefault: false, }); ``` ### How conditional edges work Each offer step has two possible outcomes: **accepted** or **declined**. The orchestrator checks the edge conditions to decide where to send the customer: ``` step_upsell ├── conditions: { when: 'offer.accepted' } → step_thankyou (customer took the VIP pack) └── conditions: { when: 'offer.declined' } → step_downsell (show cheaper alternative) ``` If both edges point to the same target (e.g., downsell → thank you regardless of outcome), the customer always moves forward but the system still tracks what they chose. *** ## Step 5: Activate the funnel Creating a funnel defines the structure. **Updating** it triggers the routing engine — routes get mounted to CDN, pages become reachable. ```ts theme={null} const result = await tagada.funnels.update(funnel.id, { storeId: STORE_ID, config: funnel.config, }); // The checkout URL is now live const checkoutUrl = result.funnel.config.nodes .find(n => n.id === 'step_checkout').config.url; console.log('Checkout live at:', checkoutUrl); ``` > [!NOTE] > > TagadaPay detects that your nodes have no `pluginId` and automatically injects the **native checkout** plugin. The offer pages show the bound offer product, and the thank you page shows the order confirmation — no setup needed. *** ## Step 6: Verify and manage the funnel ### Retrieve a funnel ```ts theme={null} const retrieved = await tagada.funnels.retrieve(funnel.id); const nodes = retrieved.config.nodes; const edges = retrieved.config.edges; const upsellNode = nodes.find(n => n.id === 'step_upsell'); console.log('Upsell offer:', upsellNode.config.stepConfig.resources.offer); const downsellNode = nodes.find(n => n.id === 'step_downsell'); console.log('Downsell offer:', downsellNode.config.stepConfig.resources.offer); ``` ### List all funnels ```ts theme={null} const funnels = await tagada.funnels.list(STORE_ID); console.log(`${funnels.funnels.length} funnels in store`); ``` ### Delete a funnel ```ts theme={null} await tagada.funnels.del(funnel.id, STORE_ID); console.log('Funnel deleted'); ``` ### Delete checkout offers ```ts theme={null} await tagada.checkoutOffers.del({ offerIds: [upsellOffer.id, downsellOffer.id], storeId: STORE_ID, }); ``` *** ## Complete Flow Diagram ``` ┌──────────────┐ ┌────────────────────┐ ┌──────────────┐ │ Checkout │────▶│ Upsell ($99) │────▶│ Thank You │ │ ($49.00) │ │ VIP Coaching │ │ │ └──────────────┘ └─────────┬──────────┘ └──────▲───────┘ declined│ │ ▼ │ ┌────────────────────┐ │ │ Downsell ($19) │────────────┘ │ Quick-Start Guide │ └────────────────────┘ ``` **Customer paths:** 1. **Checkout → Accept upsell → Thank You** — Customer pays $49 + $99 = \$148 2. **Checkout → Decline upsell → Accept downsell → Thank You** — Customer pays $49 + $19 = \$68 3. **Checkout → Decline upsell → Decline downsell → Thank You** — Customer pays \$49 *** ## Edge Conditions Reference The funnel orchestrator supports a rich set of conditions you can attach to edges via `conditions.when`. Use **string** format for simple conditions, or **object** format for conditions that take parameters. ### Offer Conditions | Condition | Format | Description | | - | - | - | | `offer.accepted` | `string` | Customer accepted the offer | | `offer.declined` | `string` | Customer declined the offer | | `offer.acceptedWithId` | `object` | Customer accepted a specific offer | ```ts theme={null} // Simple: any offer accepted conditions: { when: 'offer.accepted' } // Parameterized: specific offer accepted conditions: { when: { 'offer.acceptedWithId': { offerId: 'offer_xxx' } } } ``` ### Payment Conditions | Condition | Format | Params | Description | | - | - | - | - | | `payment.success` | `string` | — | Payment succeeded | | `payment.failed` | `string` | — | Payment failed (error, declined, rejected) | | `payment.amountGreaterThan` | `object` | `amount` (cents) | Payment amount exceeds threshold | ```ts theme={null} conditions: { when: 'payment.success' } conditions: { when: 'payment.failed' } conditions: { when: { 'payment.amountGreaterThan': { amount: 5000 } } } // > $50 ``` ### Main Order Conditions Evaluate the **initial checkout order** (the first order in the funnel). | Condition | Format | Params | Description | | - | - | - | - | | `mainOrder.exists` | `string` | — | Main order was created | | `mainOrder.hasProduct` | `object` | `productId` or `variantIds` | Order contains a specific product | | `mainOrder.totalGreaterThan` | `object` | `amount` (cents) | Order total exceeds threshold | ```ts theme={null} conditions: { when: 'mainOrder.exists' } conditions: { when: { 'mainOrder.hasProduct': { productId: 'prod_xxx' } } } conditions: { when: { 'mainOrder.totalGreaterThan': { amount: 10000 } } } // > $100 ``` ### Last Order Conditions Evaluate the **most recent order** (from the current or previous step — could be an upsell or downsell order). | Condition | Format | Params | Description | | - | - | - | - | | `lastOrder.exists` | `string` | — | Last order exists | | `lastOrder.hasProduct` | `object` | `productId` or `variantIds` | Last order contains a product | | `lastOrder.totalGreaterThan` | `object` | `amount` (cents) | Last order total exceeds threshold | ```ts theme={null} conditions: { when: 'lastOrder.exists' } conditions: { when: { 'lastOrder.hasProduct': { productId: 'prod_xxx' } } } conditions: { when: { 'lastOrder.totalGreaterThan': { amount: 2000 } } } // > $20 ``` ### Customer Tag Conditions Route based on tags attached to the customer (set via API or automations). | Condition | Format | Params | Description | | - | - | - | - | | `customer.hasTag` | `object` | `tag` | Customer has an exact tag | | `customer.hasTagPrefix` | `object` | `prefix` | Customer has a tag starting with prefix | | `customer.hasAnyTag` | `object` | `tags` (comma-separated) | Customer has at least one of the tags | | `customer.hasAllTags` | `object` | `tags` (comma-separated) | Customer has all of the tags | ```ts theme={null} conditions: { when: { 'customer.hasTag': { tag: 'vip' } } } conditions: { when: { 'customer.hasTagPrefix': { prefix: 'plan' } } } conditions: { when: { 'customer.hasAnyTag': { tags: 'vip,premium,whale' } } } conditions: { when: { 'customer.hasAllTags': { tags: 'active,verified' } } } ``` ### Customer Geo Conditions Route based on the customer's geographic location (detected automatically from IP). | Condition | Format | Params | Description | | - | - | - | - | | `customer.fromCountry` | `object` | `country` (ISO code) | Customer is from a specific country | | `customer.fromContinent` | `object` | `continent` (code) | Customer is from a continent (EU, NA, SA, AS, AF, OC, AN) | | `customer.fromEU` | `string` | — | Customer is from the European Union | ```ts theme={null} conditions: { when: { 'customer.fromCountry': { country: 'US' } } } conditions: { when: { 'customer.fromContinent': { continent: 'EU' } } } conditions: { when: 'customer.fromEU' } ``` ### Customer Device & Browser Conditions Route based on the customer's device, browser, or display mode. | Condition | Format | Params | Description | | - | - | - | - | | `customer.onMobile` | `string` | — | Customer is on a mobile device | | `customer.withBrowser` | `object` | `browser` | Browser name (chrome, firefox, safari, edge) | | `customer.withLocale` | `object` | `locale` | Browser locale (e.g., en-US, fr-FR) | | `customer.isChromeFamily` | `string` | — | Chrome, Edge, Brave, or Opera | | `customer.isStandalonePWA` | `string` | — | Installed PWA (standalone mode) | | `customer.isAppleSilicon` | `string` | — | Apple Silicon Mac (M1/M2/M3) | ```ts theme={null} conditions: { when: 'customer.onMobile' } conditions: { when: { 'customer.withBrowser': { browser: 'safari' } } } conditions: { when: { 'customer.withLocale': { locale: 'fr-FR' } } } conditions: { when: 'customer.isChromeFamily' } ``` ### Traffic & Bot Conditions Route based on traffic source or bot detection. | Condition | Format | Params | Description | | - | - | - | - | | `customer.fromUtmSource` | `object` | `source` | UTM source (facebook, google, email, etc.) | | `customer.isBot` | `string` | — | Detected as a bot or crawler | ```ts theme={null} conditions: { when: { 'customer.fromUtmSource': { source: 'facebook' } } } conditions: { when: 'customer.isBot' } ``` ### Generic Conditions | Condition | Format | Description | | - | - | - | | `always` | `string` | Always evaluates to true — use as fallback | ```ts theme={null} conditions: { when: 'always' } ``` ### Edge Priority When multiple edges leave the same node, use `priority` to control evaluation order. Higher priority edges are checked first: ```ts theme={null} edges: [ { id: 'e_vip_path', source: 'step_checkout', target: 'step_vip_offer', conditions: { when: { 'customer.hasTag': { tag: 'vip' } }, priority: 10 }, }, { id: 'e_default_path', source: 'step_checkout', target: 'step_standard_offer', conditions: { when: 'always', priority: 1 }, }, ] ``` *** ## Going Further ### Add an order bump on the checkout step Order bumps appear **on** the checkout page, before payment. Use `stepConfig.orderBumps` with `mode: 'custom'` to pick specific bumps: ```ts theme={null} { id: 'step_checkout', type: 'checkout', config: { stepConfig: { orderBumps: { mode: 'custom', enabledOfferIds: ['upsell_xxx'], }, }, }, } ``` ### Chain multiple offers Add more offer steps between checkout and thank you. Each can have independent accept/decline routing: ![Chained offers: checkout, offer A, offer B or offer C, thank you](https://mintcdn.com/tagadapay/kGWh0luIQjcrt2Rd/assets/images/funnel-demos/offer-chain-graph.png?fit=max\&auto=format\&n=kGWh0luIQjcrt2Rd\&q=85\&s=84d3575b72eed927a200002d9a9743f7) ### Geo-based routing Show different offers based on customer location: ```ts theme={null} edges: [ { id: 'e_eu_offer', source: 'step_checkout', target: 'step_eu_offer', conditions: { when: 'customer.fromEU', priority: 10 }, }, { id: 'e_us_offer', source: 'step_checkout', target: 'step_us_offer', conditions: { when: { 'customer.fromCountry': { country: 'US' } }, priority: 10 }, }, { id: 'e_default_offer', source: 'step_checkout', target: 'step_global_offer', conditions: { when: 'always', priority: 1 }, }, ] ``` ### Generate a checkout link Use checkout sessions to create pre-loaded cart links: ```ts theme={null} const session = await tagada.checkout.createSession({ storeId: STORE_ID, items: [{ variantId: mainProduct.variants[0].id, quantity: 1 }], currency: 'USD', checkoutUrl, }); console.log('Share this link:', session.redirectUrl); ``` *** ## SDK Methods Reference ### Funnels | Method | Description | | - | - | | `tagada.funnels.create(params)` | Create a funnel with nodes and edges | | `tagada.funnels.update(id, params)` | Update config and activate routing | | `tagada.funnels.retrieve(id)` | Get a funnel by ID | | `tagada.funnels.list(storeId)` | List all funnels for a store | | `tagada.funnels.del(id, storeId)` | Delete a funnel and its routes | ### Checkout Offers | Method | Description | | - | - | | `tagada.checkoutOffers.create(params)` | Create a post-purchase offer | | `tagada.checkoutOffers.retrieve(id)` | Get a checkout offer by ID | | `tagada.checkoutOffers.list(params)` | List offers for a store | | `tagada.checkoutOffers.del(params)` | Delete one or more offers | *** ## Next Steps > [card] [Finished project on GitHub](https://github.com/TagadaPay/examples/tree/main/basic-post-purchase) > > Clone the 6-step Headless app for this funnel type > [card] [Basic post-purchase demo](/developer-tools/funnel-demos/basic-post-purchase) > > Same type with a landing, a second OTO, and related orders on thank you > [card] [Funnel Orchestrator](/developer-tools/funnels/funnel-orchestrator) > > Deep dive into funnel concepts — nodes, edges, routing, analytics > [card] [Step Config Guide](/developer-tools/node-sdk/step-config-guide) > > Configure payment methods, pixels, scripts, and order bumps per step > [card] [Funnel Pages](/developer-tools/node-sdk/custom-checkout) > > Three ways to build pages: native, custom HTML, or Plugin SDK > [card] [Merchant Quick Start](/developer-tools/node-sdk/merchant-quickstart) > > Full setup from processor configuration to live checkout # Webhooks & Events Source: https://docs.tagada.io/developer-tools/node-sdk/webhooks-events Receive real-time notifications and monitor platform events # Webhooks & Events **Time**: \~10 minutes | **Difficulty**: Beginner Use the TagadaPay Node SDK to register HTTPS endpoints for real-time notifications, verify deliveries cryptographically, and query the event log for debugging and analytics. *** ## What webhooks are (and why use them) **Webhooks** are HTTP callbacks TagadaPay sends to your server when something happens on the platform — for example, a successful payment or a subscription change. Your endpoint receives a JSON payload so you can update your database, trigger fulfillment, notify internal tools, or sync with Zapier/n8n without polling the API. > [!NOTE] > > Webhooks run **asynchronously** after the triggering action. Design your handler to respond quickly (e.g. validate the signature, enqueue work, return `2xx`). Heavy work should happen in a background job. *** ## Create a webhook Register a URL and the event types you care about. The API returns the endpoint id, URL, **signing secret**, subscribed types, and whether the endpoint is enabled. ```ts theme={null} import Tagada from '@tagadapay/node-sdk'; const tagada = new Tagada('your-api-key'); const webhook = await tagada.webhooks.create({ storeId: 'store_...', url: 'https://api.example.com/webhooks/tagada', eventTypes: ['order/paid', 'subscription/created', 'subscription/canceled'], description: 'Production notifications', }); // { id, url, secret, eventTypes, enabled, storeId, createdAt, ... } console.log(webhook.id, webhook.secret); ``` > [!TIP] > > Store `webhook.secret` securely (environment variable or secrets manager). It is returned when you create the endpoint and is required to verify that payloads really came from TagadaPay. *** ## The signing secret Each webhook endpoint has a unique **secret**. TagadaPay uses it to compute an **HMAC-SHA256** signature over the **raw JSON body** of each delivery. Your server must verify that signature before trusting the payload. > [!NOTE] > > Event type strings in `eventTypes` must **exactly match** the names listed below (slash format like `order/paid`). The SDK validates event types at build time via TypeScript and at runtime — passing an invalid type will throw an error immediately. *** ## Payload envelope Every delivery is a JSON object with the same top-level shape: ```json theme={null} { "id": "8f1c04b1-3a2e-4a6a-9a63-2b0c5f7a3f7b", "type": "order/paid", "createdAt": "2026-08-27T14:22:41.812Z", "data": { "accountId": "acc_9e8d7c6b5a4f", "storeId": "store_1a2b3c4d5e6f", "orderId": "order_5f8ec3a7b2d1", "paymentId": "pay_7c2e9a41d0b3", "lineItems": [ { "productId": "product_3b8f1c2a9e7d", "productName": "Starter Kit", "variantId": "variant_6a1d4e8b2c9f", "variantName": "Default", "sku": "starter-kit", "unitAmount": 4990, "quantity": 1 } ], "cartToken": null, "isReturning": "false", "draft": true, "v3Simulated": true, "user_data": { "external_id": "cus_2f9b7d4e1a6c", "client_ip_address": "203.0.113.24", "client_user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36", "gclid": "", "gbraid": "", "wbraid": "" }, "order_metadata": null, "customer": { "id": "cus_2f9b7d4e1a6c", "email": "grace@example.com", "firstName": "Grace", "lastName": "Hopper", "phone": "+15550100", "locale": "en", "acceptsMarketing": true, "tags": ["segment:vip"] }, "order": { "status": "paid", "orderNumber": 1042, "currency": "USD", "paidAmount": 4990, "paidAt": "2026-08-27T14:22:39.950Z", "createdAt": "2026-08-27T14:22:31.402Z", "checkoutSessionId": "cs_8d1f2a7c4b9e", "billingAddress": { "firstName": "Grace", "lastName": "Hopper", "company": "", "address1": "1 Navy Yard", "address2": "", "city": "Arlington", "state": "VA", "country": "US", "postal": "22202", "phone": "+15550100", "email": "grace@example.com" }, "shippingAddress": { "firstName": "Grace", "lastName": "Hopper", "company": "", "address1": "1 Navy Yard", "address2": "", "city": "Arlington", "state": "VA", "country": "US", "postal": "22202", "phone": "+15550100", "email": "grace@example.com" }, "requiresShipping": true, "externalOrderId": null, "subtotalAmount": 4990, "totalPromotionAmount": 0, "totalTaxAmount": 0, "shippingCost": 0, "totalAmount": 4990, "totalAdjustedAmount": 4990 }, "timestamp": "2026-08-27T14:22:40.104Z" }, "metadata": { "source": "tagadapay", "version": "1.0", "accountId": "acc_9e8d7c6b5a4f", "storeId": "store_1a2b3c4d5e6f" } } ``` > [!WARNING] > > The top-level **`id` is the event's own UUID** — not the id of the order, subscription or payment it describes. The resource's id lives inside `data` (`data.orderId`, `data.subscriptionId`, `data.paymentId`, etc., depending on the event). Reading `payload.id` as an order id will return the event UUID and fail every downstream lookup. > [!WARNING] > > Every order, payment and subscription webhook carries `data.draft`. `data.draft` is `true` for a test purchase: do not ship it. It is `false` on a live purchase. `data.v3Simulated` is present, and `true`, only when the purchase went through the CRM V3 payment simulator; it is absent on every other purchase. ### Buyer, order and cart fields `order/paid` and `checkout/abandonedCart` carry what you need to contact the buyer and see what they bought or left, with no follow-up API call. Amounts are in minor units (cents). * `data.customer`: `id`, `email`, `firstName`, `lastName`, `phone`, `locale`, `acceptsMarketing`, `tags`. `phone` is the first number the buyer typed: on this checkout or order first, then on an earlier purchase. It is `null` when the buyer never gave one. * `data.order` (`order/paid` only): `status`, `orderNumber`, `currency`, `paidAmount`, `paidAt`, `createdAt`, `checkoutSessionId`, `billingAddress`, `shippingAddress`, `requiresShipping`, `externalOrderId`, and the totals: `subtotalAmount`, `totalPromotionAmount` (the discount, positive), `totalTaxAmount`, `shippingCost`, `totalAmount` (before discounts) and `totalAdjustedAmount` (what the buyer is charged). An address the buyer never filled in comes with every key set to an empty string, as in the `payment/*` events. * `data.lineItems` (`checkout/abandonedCart`, same shape as `order/paid`): `productId`, `productName`, `variantId`, `variantName`, `sku`, `unitAmount`, `quantity` for each product left in the cart. * `data.checkout` (`checkout/abandonedCart` only): `status`, `currency`, the same totals as `data.order`, `billingAddress` and `shippingAddress` (`null` until the buyer typed one), `createdAt`, and `lastActiveAt`, the buyer's last action on the checkout. A `checkout/abandonedCart` delivery looks like this: ```json theme={null} { "id": "2c7d9e10-6b4f-4f1e-9a3d-7e5c1b8a0f42", "type": "checkout/abandonedCart", "createdAt": "2026-08-27T15:31:02.118Z", "data": { "storeId": "store_1a2b3c4d5e6f", "accountId": "acc_9e8d7c6b5a4f", "checkoutSessionId": "cs_8d1f2a7c4b9e", "customerId": "cus_7a3e1c9b5d2f", "checkoutUrl": "https://checkout.example.com/checkout?checkoutToken=…", "draft": false, "customer": { "id": "cus_7a3e1c9b5d2f", "email": "ada@example.com", "firstName": "Ada", "lastName": "Lovelace", "phone": "+33612345678", "locale": "fr", "acceptsMarketing": false, "tags": [] }, "lineItems": [ { "productId": "product_3b8f1c2a9e7d", "productName": "Collagen Boost", "variantId": "variant_6a1d4e8b2c9f", "variantName": "30 sachets", "sku": "COL-30", "unitAmount": 3900, "quantity": 2 } ], "checkout": { "status": "address_entered", "currency": "EUR", "subtotalAmount": 7800, "totalPromotionAmount": 0, "totalTaxAmount": 0, "shippingCost": 490, "totalAmount": 8290, "totalAdjustedAmount": 8290, "billingAddress": null, "shippingAddress": { "firstName": "Ada", "lastName": "Lovelace", "address1": "12 rue de Rivoli", "city": "Paris", "country": "FR", "postal": "75001", "phone": "+33612345678" }, "createdAt": "2026-08-27T14:18:44.530Z", "lastActiveAt": "2026-08-27T14:26:10.007Z" }, "timestamp": "2026-08-27T15:31:02.101Z" }, "metadata": { "source": "tagadapay", "version": "1.0", "accountId": "acc_9e8d7c6b5a4f", "storeId": "store_1a2b3c4d5e6f" } } ``` `checkoutUrl` reopens the buyer's checkout with their cart: it is the link of the abandoned-cart e-mail. Use `id` as the deduplication key (see [Delivery contract](#delivery-contract) below). Use `type` to route the handler. The exact contents of `data` depend on the event type — inspect a real delivery in the [Delivery history](#delivery-history) view of the CRM to see what your subscriptions actually receive. *** ## Delivery contract TagadaPay `POST`s each event to your endpoint with a strict, bounded delivery contract. Design your handler to fit inside it. ### Timeout **10 seconds per attempt.** If your endpoint has not returned a response within 10 seconds, TagadaPay aborts the connection and treats the attempt as failed. The abort does **not** cancel any work already running on your side, so an aborted attempt that keeps processing can end up finishing twice — one on the aborted call, one on the retry. Handlers must be idempotent (see below). ### Retry schedule Up to **6 attempts** per event over about **1 h 15** (about **1 h 25** when your endpoint answers HTTP 409). The first attempt fires immediately when the event is emitted; later attempts use smart backoff based on the failure type: timeouts, `5xx`, `408` and `429` retry quickly; HTTP 409 / Woo sync lag waits longer. | Attempt | Delay after previous failure | Delay after an HTTP 409 | | - | - | - | | 1 | Immediate | Immediate | | 2 | Immediate | \~30 seconds | | 3 | \~4 seconds | \~2 minutes | | 4 | \~1 minute | \~5 minutes | | 5 | \~10 minutes | \~15 minutes | | 6 | \~1 hour | \~1 hour | Retries are picked up by a job that runs every minute, so each retry can arrive up to about one minute later than the delay above. Permanent client errors (`401`, `404`, `400`, `403`) stop retrying immediately — they will not consume later attempts. After attempt 6 fails, the delivery moves to a dead-letter state. You can replay it manually from the CRM once the endpoint is fixed. ### Ack fast, process async Return a 2xx (typically `200`) **as soon as possible after verifying the signature** — ideally within 2 seconds. Do the actual work (fulfilment, database writes, calls to Shopify, e-mails) in a background job. If your handler takes longer than 10 seconds because it processes synchronously, every attempt for that event will time out, be retried, and you will run the same work up to three times in parallel. > [!TIP] > > The right shape for a webhook handler:\ >   1. Verify the signature.\ >   2. Enqueue a background job with the event.\ >   3. Respond `200 OK`.\ > Everything else — database writes, external API calls, e-mails — happens in the worker. ### Idempotency (dedupe by `event.id`) The same event can reach you more than once — an aborted attempt that kept processing, an attempt-2 landing while attempt-1 completes late, or a manual replay from the CRM. Use the top-level `id` as your deduplication key: record each `id` you have processed and short-circuit if you see it again. Two deliveries with the same `id` describe the same event and must produce the same side effect only once. ### Auto-disable of dead endpoints An endpoint that goes **3 continuous days without a single successful delivery** is disabled automatically, so a URL that has stopped answering does not silently consume your allowance. A badge shows the auto-disabled state in the CRM, and one click re-enables it once you have fixed the endpoint. *** ## List webhooks ```ts theme={null} const endpoints = await tagada.webhooks.list('store_...'); // Webhook[] ``` *** ## Delete a webhook ```ts theme={null} const { success, id } = await tagada.webhooks.del('wh_...'); ``` *** ## Available event types All webhook event types use the **slash format** (`category/event`). These are the only valid values accepted by the `eventTypes` field. ### Order events | Event type | Description | | - | - | | `order/paid` | Order successfully paid — trigger fulfillment or CRM updates. Carries the buyer (`customer`) and the order's addresses and totals (`order`), see [Buyer, order and cart fields](#buyer-order-and-cart-fields). An accepted post-purchase upsell is its own order and sends its own `order/paid`, with the main order's id in `order_metadata.mainOrderId` | | `order/created` | Order record created | | `order/refunded` | Order refunded. Sent once per refund: `refundAmount` is this refund, in minor units of `currency`, the order currency. Events fired from the event simulator may leave `refundAmount` out | | `order/failed` | Order payment failed | | `order/upsellStarted` | Post-purchase upsell flow initiated | | `order/paymentInitiated` | Payment process started for an order | | `order/syncFailed` | Storefront sync to Shopify/Woo failed (paid order may be unfulfilled) | ### Checkout events | Event type | Description | | - | - | | `checkout/initiated` | Checkout session started | | `checkout/emailValidated` | Customer email validated during checkout | | `checkout/abandonedCart` | A buyer who entered their email left the checkout without paying. Sent about one hour after their last action, or at the delay of each active abandoned-cart email of the store. Not sent when the buyer has paid an order in the store since. Carries the buyer, the products left in the cart and its totals, see [Buyer, order and cart fields](#buyer-order-and-cart-fields) | ### Payment events | Event type | Description | | - | - | | `payment/created` | Payment record created | | `payment/succeeded` | Payment completed successfully | | `payment/failed` | Payment attempt failed | | `payment/refunded` | Payment refunded, from the API, the CRM or on the TagadaPay processor. A refund issued automatically for a chargeback alert carries `source: "payfac_auto_refund"`; one made outside Tagada carries `source: "external_payfac_refund"`. Sent once per refund: `refundAmount` is this refund, `totalRefundedAmount` everything refunded on the payment so far, this refund included, both in minor units. `isPartialRefund` is `true` while part of the payment is left to refund, and `false` once `totalRefundedAmount` reaches the payment amount | | `payment/authorized` | Payment authorized (not yet captured) | | `payment/rejected` | Payment rejected by processor or fraud rules | ### Subscription events | Event type | Description | | - | - | | `subscription/created` | New subscription started | | `subscription/canceled` | Subscription canceled | | `subscription/paused` | Subscription paused | | `subscription/resumed` | Subscription resumed | | `subscription/pastDue` | Subscription payment past due. Carries the declined charge's `paymentId` when there is one: a rebill billed by an external store platform, or the failed capture of an authorized rebill, carries none. Not sent when the decline ends the retries and cancels or pauses the subscription: that decline sends `subscription/rebillDeclined` and `subscription/canceled` or `subscription/paused` instead | | `subscription/rebillUpcoming` | Upcoming rebill notification | | `subscription/rebillSucceeded` | Rebill charge succeeded. Carries the charge's `paymentId`, and the renewal order's `orderId` when the order is created with the charge (a price set to rebill with an order, or items added to the next order). A rebill authorized first and captured later gets its order at capture, so its event carries no `orderId`. Subscriptions billed together in one charge each get their own event, with the same `paymentId` and `orderId`, and `groupShareAmount`: that subscription's own part of the charge in minor units, add-ons included, the group's delivery excluded | | `subscription/rebillDeclined` | Rebill charge declined | | `subscription/cancelScheduled` | Cancellation scheduled for end of period | | `subscription/rebillCaptureFailed` | Rebill capture failed | ### Funnel events | Event type | Description | | - | - | | `funnel/sessionStarted` | Funnel session started | | `funnel/sessionCompleted` | Funnel session completed | | `funnel/stepEntered` | Visitor entered a funnel step | | `funnel/stepViewed` | Funnel step viewed | | `funnel/stepExited` | Visitor exited a funnel step | | `funnel/converted` | Funnel conversion recorded | | `funnel/customEvent` | Custom funnel event fired | | `funnel/sessionAbandoned` | Funnel session abandoned | ### Club events | Event type | Description | | - | - | | `club/membershipActivated` | Club membership activated | | `club/membershipDeactivated` | Club membership deactivated | ### Security events | Event type | Description | | - | - | | `security/abuseDetected` | Abuse or fraud detected | > [!WARNING] > > The SDK and API **reject** any event type not in this list. If you pass an invalid type like `order.paid` (dot format) or `s_order_paid` (internal format), you will receive a validation error. *** ## Events API (query & analytics) Use the **Events** resource to audit activity, build dashboards, or debug webhook payloads. ### Recent events ```ts theme={null} const recent = await tagada.events.recent(25); // AppEvent[] — includes eventType, createdAt, payload, storeId, ... ``` ### Statistics ```ts theme={null} const stats = await tagada.events.statistics({ storeId: 'store_...' }); // { totalEvents, eventsByType, processedCount, unprocessedCount } ``` ### List with filters and pagination Pages are numbered from **0**: `page: 0` is the first page and the last one is `totalPages - 1`. Starting at `page: 1` silently skips the first `pageSize` events. ```ts theme={null} const { data, total, totalPages } = await tagada.events.list({ pagination: { page: 0, pageSize: 50 }, sortBy: { field: 'appEvents.createdAt', direction: 'desc' }, filters: { 'stores.id': ['store_...'], // Event types here are often internal analytics ids (e.g. s_order_paid) — see Note below 'appEvents.eventType': ['s_order_paid'], }, }); ``` Optional filters include date ranges on `appEvents.createdAt` / `appEvents.processedAt`, `customer.email`, `appEvents.draft`, and free-text `search`. > [!NOTE] > > **Webhook subscriptions** use slash-format names like `order/paid` and `subscription/created`. The **Events list** API may return internal `eventType` strings (for example `s_order_paid`) — these are for internal analytics and should not be used when creating webhooks. *** ## Webhook signature verification (HMAC-SHA256) TagadaPay signs the **exact JSON string** sent as the request body. 1. Read the raw body as a **string** (do not parse JSON before verifying). 2. Compute `HMAC-SHA256(secret, rawBody)` and hex-encode the digest. 3. Compare to the `X-TagadaPay-Signature` header value after the `sha256=` prefix. ```ts theme={null} import crypto from 'crypto'; function verifyTagadaWebhook(rawBody: string, secret: string, signatureHeader: string | null) { if (!signatureHeader?.startsWith('sha256=')) return false; const expected = signatureHeader.slice('sha256='.length); const hmac = crypto.createHmac('sha256', secret).update(rawBody, 'utf8').digest('hex'); try { return crypto.timingSafeEqual(Buffer.from(expected, 'hex'), Buffer.from(hmac, 'hex')); } catch { return false; } } ``` Every delivery also carries the following headers: | Header | Value | | - | - | | `User-Agent` | `TagadaPay-Webhooks/1.0` | | `X-TagadaPay-Timestamp` | Delivery time as a Unix timestamp in **milliseconds** (`Date.now()`) | | `X-TagadaPay-Event-Type` | The event type, e.g. `order/paid` | | `X-TagadaPay-Event-Id` | The event UUID — same value as the top-level `id` in the JSON body | | `X-TagadaPay-Delivery-Attempt` | `1` through `6` — which attempt this delivery is | Use `X-TagadaPay-Delivery-Attempt` to log or alert on retries. > [!WARNING] > > The signature covers the body only. `X-TagadaPay-Timestamp` is not signed, so do not use it for replay protection. Use the signed body instead: > > * Dedupe on the body `id`, as described in **Idempotency** above. This is the main protection. > * To reject old events, check the body `createdAt` with a tolerance longer than the [retry schedule](#retry-schedule) (about 1 h 25 at most), for example 2 hours. A manual replay from the CRM keeps the original `createdAt`, so a strict limit also rejects those replays. *** ## Delivery history Every delivery attempt is recorded — the exact payload sent, the headers, the HTTP status returned, the response body, the outcome — and stays available for audit and debugging. Open it in the CRM under **Integrations → Webhooks → Deliveries** (per endpoint). Each row is one attempt: successful attempts appear with the response code, failed ones with the error, and a timed-out attempt shows the `No response` badge. > [!NOTE] > > When something looks wrong — an event you expected did not fire, a `4xx` your endpoint should have accepted — the Deliveries view is the source of truth. It shows exactly what left our side and what your endpoint answered, byte for byte. *** ## SDK methods reference | Resource | Method | Description | | - | - | - | | `webhooks` | `create(params)` | Create endpoint; params: `storeId`, `url`, `eventTypes`, optional `description` | | `webhooks` | `list(storeId)` | List all webhooks for a store | | `webhooks` | `del(id)` | Delete webhook; returns `{ success, id }` | | `events` | `recent(limit?)` | Most recent events | | `events` | `statistics(params?)` | Aggregates; optional `storeId`, `startDate`, `endDate` | | `events` | `list(params?)` | Filtered list with `filters`, `pagination`, `sortBy`, `search` | | `events` | `retrieve(eventId)` | Single event by id | *** ## Next steps > [card] [Node SDK Quick Start](/developer-tools/node-sdk/quick-start) > > Install the SDK, authenticate, and explore core resources > [card] [Sandbox Testing](/developer-tools/node-sdk/sandbox-testing) > > Exercise payments and webhook-style flows without live processors > [card] [Merchant Quick Start](/developer-tools/node-sdk/merchant-quickstart) > > End-to-end store, funnel, and checkout setup > [card] [Subscriptions](/developer-tools/node-sdk/subscriptions) > > Recurring billing and subscription lifecycle # Alternative payment methods Source: https://docs.tagada.io/developer-tools/payments/alternative-payment-methods Klarna, iDEAL, PayPal, BLIK and the rest — which processor charges them, and how the redirect lifecycle works. # Alternative payment methods An **alternative payment method** (APM) is anything that is not a card and not a wallet: bank redirects, buy-now-pay-later, e-wallets and vouchers. They all share one property that shapes your integration: > [!WARNING] > > **APMs are asynchronous.** The charge call does not return a final result — it returns a redirect > URL. The shopper authorises on the provider's page, comes back, and the real outcome arrives on a > webhook. Never treat the charge response as a completed payment. ## Availability | Method | `code` | TagadaPay | Stripe | Airwallex | Coverage | | - | - | :-: | :-: | :-: | - | | iDEAL | `ideal` | ✓ | ✓ | ✓ | NL · EUR | | Bancontact | `bancontact` | ✓ | ✓ | ✓ | BE · EUR | | Klarna | `klarna` | ✓ | ✓ | ✓ | EU · US · AU · CA | | Afterpay / Clearpay | `afterpay` | ✓ | ✓ | ✓ | AU · CA · NZ · US · GB | | Affirm | `affirm` | ✓ | ✓ | — | US · CA · GB | | PayPal | `paypal` | ✓ | — | ✓ | Worldwide | | TWINT | `twint` | ✓ | ✓ | ✓ | CH · CHF | | BLIK | `blik` | ✓ | ✓ | — | PL · PLN | | EPS | `eps` | ✓ | — | — | AT · EUR | | Przelewy24 | `p24` | ✓ | — | — | PL · PLN | | Multibanco | `multibanco` | ✓ | — | — | PT · EUR | | KNET | `knet` | ✓ | — | — | KW · KWD | | Fawry | `fawry` | ✓ | — | — | EG · EGP | | Sofort | `sofort` | ✓ | — | — | DE · AT · BE · NL · GB | | Skrill | `skrill` | ✓ | — | ✓ | EU · GB · US | > [!NOTE] > > The **TagadaPay** column is the managed catalogue. Which of those methods your specific account > can charge depends on your configuration and region — resolve it at runtime with `paymentSetup`, > never from this table. ### Not supported These come up often enough to be worth stating plainly. There is no integration for them today: Alipay, WeChat Pay, GrabPay, Swish, Vipps, MobilePay, Satispay, Trustly, MB WAY, Cash App Pay, Giropay and Neteller. **Bank debits are also not available.** SEPA Direct Debit and ACH appear in some older material and in our internal type definitions, but no processor can charge them today — treat them as unsupported until this page says otherwise. > [!NOTE] > > Giropay and Sofort are being retired by their own schemes across the industry. Sofort remains > chargeable on the managed catalogue; Giropay is not. ## The three shapes of an APM Not all APMs behave the same once the shopper commits. > [card] Bank redirect > > iDEAL, Bancontact, EPS, Przelewy24, Sofort. The shopper authorises in their bank. Funds are > guaranteed on confirmation. > [card] Buy now, pay later > > Klarna, Afterpay, Affirm. The provider underwrites the shopper. Usually needs line items and a > billing address to get approved. > [card] Voucher > > Multibanco, Fawry. The shopper gets a reference and pays later, in cash or at a bank. Settlement > can take days — the order stays pending. > [!WARNING] > > **Vouchers do not settle at checkout.** A Fawry or Multibanco order is unpaid until the shopper > goes and pays it, which may never happen. Do not fulfil on the redirect — fulfil on the webhook. ## The redirect lifecycle **1. Charge with an explicit method** Send `paymentMethod` + `processorId` + `customerId` + `returnUrl`, and **no** `paymentInstrumentId` — the absence of an instrument is what makes it a redirect APM charge. ```ts theme={null} const { payment } = await tagada.payments.process({ amount: 4999, currency: 'EUR', storeId: 'store_xxx', customerId: 'cus_xxx', paymentMethod: 'ideal', processorId: 'proc_xxx', returnUrl: 'https://store.example/checkout/return', }); ``` **2. Handle requireAction** A successful APM charge comes back **pending**, carrying a redirect. ```ts theme={null} const redirectUrl = payment.requireActionData?.metadata?.redirect?.redirectUrl; if (redirectUrl) { // Hand this URL to the shopper's browser. } ``` **3. The shopper returns to your returnUrl** Treat this as "the shopper came back", not "the payment succeeded". They may have abandoned, failed, or simply hit the back button. **4. Confirm on the webhook** The provider's confirmation is the only authoritative result. Fulfil there. ```ts theme={null} // payment.succeeded / payment.failed ``` See [Webhooks & events](/developer-tools/node-sdk/webhooks-events). ### BLIK needs a code BLIK is the exception to "redirect and wait". The shopper generates a six-digit code in their banking app and types it into your checkout, and you send it with the charge. The code rides the checkout-session pay path (plugin-sdk shown): ```ts theme={null} await tagada.payments.processPaymentDirect(checkoutSessionId, paymentInstrumentId, undefined, { paymentMethod: 'blik', processorId: 'proc_xxx', blikCode: '123456', }); ``` ### Fawry needs a basket Fawry is a cash voucher, so the shopper has to be reachable and the basket itemised. A charge without `lineItems`, an email and a phone number is rejected before it leaves us. ## Discovery Do not hard-code the table above into a checkout. Ask what the store has enabled: ```ts core-js (browser) theme={null} import { getStorePaymentSetup } from '@tagadapay/core-js'; const setup = await getStorePaymentSetup({ storeId: 'store_xxx', apiKey: 'tp_pk_live_***', }); const apms = Object.values(setup.config).filter((m) => m.type === 'apm' && m.enabled); ``` ```ts node-sdk (server) theme={null} const setup = await tagada.paymentSetup.get('store_xxx'); const apms = Object.values(setup.config).filter((m) => m.type === 'apm' && m.enabled); ``` ### The config shape Keys are **two-dimensional**. A method routed through exactly one provider is keyed by its own name; a method available through several is keyed `method:provider`. ```jsonc theme={null} { "klarna": { "enabled": true, "method": "klarna", "provider": "tagada", "type": "apm" }, "klarna:stripe": { "enabled": true, "method": "klarna", "provider": "stripe", "type": "apm", "processorId": "proc_xxx", "publishableKey": "pk_live_***" }, "ideal": { "enabled": false, "method": "ideal", "provider": "tagada", "type": "apm" } } ``` | Field | Meaning | | - | - | | `enabled` | Whether the shopper can pick it right now | | `method` | The logical method (`klarna`, `ideal`, …) | | `provider` | Which infrastructure charges it | | `type` | `card`, `apm` or `wallet` — use it to group your UI | | `processorId` | Pass this back on the charge to pin the route | | `publishableKey` | Present when the method needs a client-side SDK | ## Recurring payments > [!WARNING] > > **Do not build a subscription on an APM.** Almost every APM here authorises one specific amount, > once. There is no stored credential to rebill against, so the second charge has nothing to use. If a funnel mixes a subscription product with an APM, either hide the APM for that cart or collect a card for the renewals. Cards and wallets are the reusable instruments — see [Wallets](/developer-tools/payments/wallets#recurring-and-wallets). ## Refunds Refunds are issued against the **processor**, not the method: ```ts theme={null} await tagada.payments.refund({ paymentIds: ['pay_xxx'], amount: 1999 }); ``` Two caveats worth designing around: * A voucher that has not settled yet cannot be refunded — there is no money to return. * Some BNPL providers reverse the shopper's instalment plan on their own schedule, so the shopper may see the refund later than your dashboard does. ## Next > [card] [Support matrix](/developer-tools/payments/support-matrix) > > Filter every method by processor. > [card] [Apple Pay & Google Pay](/developer-tools/payments/wallets) > > Wallets follow different rules. > [card] [From the SDKs](/developer-tools/payments/sdk-usage) > > `processApm`, `payments.process` and friends. # Choose how you accept payments Source: https://docs.tagada.io/developer-tools/payments/choose-your-integration Four ways to accept a payment with TagadaPay. This page picks the right one in under a minute. # Choose how you accept payments > [!NOTE] > > **Payments V2.** This page documents V2 payments (`pay-v2`, `payments/process`, `threeds/*` on the Commerce API). V2 is the reference for every live integration today. The new [Payments API (V3)](/payments-api/overview) is in preview: see [V2 or V3: which one should I use?](/payments-api/v2-or-v3) Four ways to accept a payment. They are not interchangeable. Combining two paths on the same customer-initiated payment (CIT — your customer is present) is the most common integration mistake. ```mermaid theme={null} flowchart TD start[What are you building] start --> ownOrder[You already have the order] start --> tagadaCart[TagadaPay should manage cart and upsells] start --> hosted[You want a TagadaPay-hosted page] start --> later[Charge a saved card later] start --> pci[You already hold the card number] ownOrder --> coreJs[core-js plus payments.process] tagadaCart --> headless[Headless SDK] hosted --> plugin[Plugin SDK or funnel] later --> mit[Node payments.process] pci --> rawCard[Node createFromCard - on request only] ``` | What you want | Use | | - | - | | Accept a payment when you already have the order (Medusa, WooCommerce, a custom order API) | [`@tagadapay/core-js`](/developer-tools/payments/core-js-payments) in the browser + Node [`tagada.payments.process()`](/developer-tools/node-sdk/quick-start) on the server | | Build a checkout where TagadaPay manages the cart, upsells, and funnel — on your domain | [`@tagadapay/headless-sdk`](/developer-tools/headless-sdk/introduction) (install `@tagadapay/core-js` as a peer for cards) | | Use a TagadaPay-hosted checkout page | [`@tagadapay/plugin-sdk`](/developer-tools/sdk/introduction) | | Charge a saved card later — subscriptions, retries, metered billing (MIT — merchant-initiated, customer not present) | Node [`tagada.payments.process()`](/developer-tools/node-sdk/quick-start), regardless of which path created the instrument | | You are **already PCI-DSS compliant** and hold the card number yourself — no browser step at all | Node [`tagada.paymentInstruments.createFromCard()`](/developer-tools/partners/payments#alternative-you-already-hold-the-card-server-side-tokenization). ⚠️ **Off by default — TagadaPay must enable it on your account first** | Working Headless example: [headless-vanilla](https://github.com/TagadaPay/examples/tree/main/headless-vanilla). *** ## The fifth path: raw card data (on request only) Almost every integration should tokenize in the browser with `@tagadapay/core-js`, which keeps the card number out of your servers and your PCI scope at SAQ-A. One exception: merchants who are **already PCI-DSS compliant** and hold card numbers in their own environment — typically because they use several PSPs and collect cards themselves. Those can send the card straight from their server with `paymentInstruments.createFromCard()`. > [!WARNING] > > **TagadaPay has to switch this on for your account. It is off by default, for everyone.** > > Until we do, the call fails with `Please contact support to ask for raw card data enablement`. > Ask your account manager or contact support, and be ready to evidence your PCI-DSS compliance. > Do not plan an integration around this path before it has been granted. The card goes from your server directly to TagadaPay's PCI vault; only the resulting vault token reaches the TagadaPay API. Full walkthrough in [Server-to-server payments](/developer-tools/partners/payments#alternative-you-already-hold-the-card-server-side-tokenization). *** ## Same name, different call | Call | Where | What it does | | - | - | - | | `tagada.payment.processPayment()` | Browser, Headless SDK | Pays a **checkout session**. Handles 3DS, redirects, polling. | | `tagada.payment.pay()` | Browser, Headless SDK | Lower-level session pay. Prefer `processPayment()`. | | `tagada.payments.process()` | Server, Node SDK | Charges a **vaulted instrument**. No checkout session required. | *** ## What not to do > [accordion] Do combine Headless with core-js as a peer > > Headless dynamically imports `@tagadapay/core-js` for `tokenizeCard()`. Install both. That is the intended pairing, not two competing checkouts. > [accordion] Do charge later with payments.process after any first payment > > First payment (customer present) with Headless `processPayment()` **or** core-js + `/payments/process`. Later charges use Node `payments.process()` against the saved instrument. Same card, two different moments. > [accordion] Do not create a Headless session and then charge with payments.process > > A checkout session is not a payment. If you `createSession()` and then call `/payments/process` without paying that session, the cart is left unpaid, 3DS returns to the wrong page, and the hosted checkout link often points to a placeholder. Pick **one** path for the first payment. *** ## Headless `returnUrl` vs `checkoutUrl` On a **self-hosted** Headless checkout: * `returnUrl` is the page that hosts `usePayment` / `maybeResumeFromUrl`. After 3DS the bank sends the shopper back **there**. * `checkoutUrl` is generated by TagadaPay. Headless **cannot set it**. Do not redirect the shopper to `session.checkoutUrl` when you are rendering checkout yourself. * To hop from a cart page to your own checkout path, use `tagada.checkout.createSessionUrl()` — it builds a URL on **your** origin with `checkoutToken` + `sessionToken`. `checkoutUrl` is for TagadaPay-hosted checkouts only. *** ## Next steps > [card] [What can you accept?](/developer-tools/payments/support-matrix) > > Every card, wallet and APM, per processor — the support matrix > [card] [Accept a payment with your own cart](/developer-tools/payments/core-js-payments) > > Tokenize in the browser, charge with payments.process > [card] [Headless SDK](/developer-tools/headless-sdk/introduction) > > Custom UI, TagadaPay manages the cart > [card] [Plugin SDK](/developer-tools/sdk/introduction) > > Pages hosted on TagadaPay > [card] [Node SDK](/developer-tools/node-sdk/quick-start) > > Server charges, including later rebills # Accept a payment with your own cart Source: https://docs.tagada.io/developer-tools/payments/core-js-payments Tokenize a card in the browser with @tagadapay/core-js, then charge it from your server. Use this when you already have the order. # Accept a payment with your own cart > [!NOTE] > > **Payments V2.** This page documents V2 payments (`pay-v2`, `payments/process`, `threeds/*` on the Commerce API). V2 is the reference for every live integration today. The new [Payments API (V3)](/payments-api/overview) is in preview: see [V2 or V3: which one should I use?](/payments-api/v2-or-v3) > [!WARNING] > > This page is **not** the Headless SDK. Use it when **you already have the order** (Medusa, WooCommerce, a custom order API) and only need to tokenize and charge. Native apps and partner server-to-server flows live here too. > > If TagadaPay should manage the cart, upsells, and funnel, use the [Headless SDK](/developer-tools/headless-sdk/introduction) instead (`processPayment()`, not this page). > > Not sure? [Choose how you accept payments](/developer-tools/payments/choose-your-integration). ## Which Approach Should I Use? | | [Headless SDK](/developer-tools/headless-sdk/payment-setup) | This page (core-js + REST) | | - | - | - | | **Package** | `@tagadapay/headless-sdk` (+ `core-js` peer for cards) | `@tagadapay/core-js` + REST / Node `payments.process` | | **Who owns the cart?** | Tagada checkout session | You (Medusa, Woo, your backend) | | **Pay** | `tagada.payment.processPayment({ checkoutSessionId, tagadaToken })` | Tokenize → instrument → 3DS → `POST /payments/process` | | **Checkout sessions** | Built-in (`useCheckout()`, cart, promos, shipping) | Not used — you already have an order | | **3DS handling** | Automatic inside `processPayment()` | Manual (create session + start challenge) | | **Best for** | Custom UI, TagadaPay manages the cart | Your own commerce backend, mobile, later charges (MIT), platforms | > [!TIP] > > **Rule of thumb:** You already have the order → this page. TagadaPay manages the cart → Headless. Hosted on TagadaPay → Plugin SDK. Charge a saved card later → Node `payments.process()`. See [Choose how you accept payments](/developer-tools/payments/choose-your-integration). *** ## When to Use This | Use case | Example | | - | - | | **Own commerce backend** | Medusa, custom Woo, your own order API — tokenize in the browser, charge with `/payments/process` | | **Mobile apps** | Native iOS/Android apps that collect card data via your own UI | | **Embedded checkout** | Injecting a payment form into a third-party page or iframe | | **Marketplace / platform** | Collecting card details on behalf of sub-merchants | | **Later charges (MIT)** | Subscription renewals, metered billing, retries — merchant-initiated, customer not present | | **Auth + capture** | Authorize now, capture later (hotels, car rentals, pre-orders) | ### When NOT to Use This | Instead of... | Use... | | - | - | | Building a web checkout where TagadaPay manages the cart | [Headless SDK](/developer-tools/headless-sdk/payment-setup) — sessions, APMs, 3DS | | You just want a hosted checkout page | [Merchant Quick Start](/developer-tools/node-sdk/merchant-quickstart) — 7 API calls, zero frontend code | | You want a custom-branded page (HTML or Plugin SDK) | [Funnel Pages](/developer-tools/node-sdk/custom-checkout) — deploy pages as plugins | | You need server-side recurring billing | [Subscriptions Guide](/developer-tools/node-sdk/subscriptions) — managed subscription lifecycle | *** ## The Flow Every payment follows 4 steps: ``` 1. Tokenize card → Client-side, via @tagadapay/core-js 2. Create instrument → Server-side, POST to TagadaPay API 3. 3DS authenticate → Client + Server (if required by the card issuer) 4. Process payment → Server-side, POST to TagadaPay API ``` ``` ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │ 1. Tokenize │────▶│ 2. Instrument│────▶│ 3. 3DS │────▶│ 4. Charge │ │ (client) │ │ (server) │ │ (client+srv) │ │ (server) │ └──────────────┘ └──────────────┘ └──────────────┘ └──────────────┘ Card details TagadaToken Challenge if Amount + currency → Secure Vault → Payment Inst. required → PSP routing → TagadaToken + Customer → Transaction ``` *** ## Prerequisites * A TagadaPay account with an **API key** (Bearer token) * A **store** with at least one **payment flow** configured (connects to your PSP: Stripe, NMI, Airwallex, etc.) * Install the tokenization SDK: ```bash theme={null} npm install @tagadapay/core-js ``` > [!NOTE] > > The tokenization SDK runs **client-side** (browser). Steps 2–4 happen **server-side** with your API key. Never expose your API key in the browser. *** ## Step 1: Tokenize the Card (Client-Side) The card number never touches your server. It goes directly to a PCI-compliant secure vault (BasisTheory) and returns a token. > [!NOTE] > > **Already PCI-DSS compliant and holding the card number yourself?** There is a server-side > equivalent, `paymentInstruments.createFromCard()`, that skips the browser entirely — see > [Server-to-server payments](/developer-tools/partners/payments#alternative-you-already-hold-the-card-server-side-tokenization). > > ⚠️ **It is off by default and TagadaPay has to enable it on your account first**, otherwise the call > fails with `Please contact support to ask for raw card data enablement`. Ask your account manager > before building against it. If you are not already PCI-compliant, stay on this page: tokenizing in > the browser is what keeps the card number out of your scope. > [tab] React > > ```typescript theme={null} > import { useCardTokenization } from '@tagadapay/core-js/react'; > > function CheckoutForm() { > const { tokenizeCard, isLoading, error } = useCardTokenization({ > environment: 'production', // 'production' | 'development' | 'local' > }); > > async function handleSubmit() { > const { tagadaToken, rawToken } = await tokenizeCard({ > cardNumber: '4242424242424242', > expiryDate: '12/28', > cvc: '123', > cardholderName: 'Jane Doe', > }); > > // tagadaToken → base64 string, send to your server > // rawToken.metadata.auth.scaRequired → true if 3DS is needed > await sendToServer(tagadaToken, rawToken); > } > } > ``` > [tab] Vanilla JavaScript > > ```javascript theme={null} > import { Tokenizer } from '@tagadapay/core-js'; > > const tokenizer = new Tokenizer({ environment: 'production' }); > await tokenizer.initialize(); > > const tagadaToken = await tokenizer.tokenizeCard({ > cardNumber: '4242424242424242', > expiryDate: '12/28', > cvc: '123', > cardholderName: 'Jane Doe', > }); > > // tagadaToken → base64 string, send to your server > ``` > > For the raw token with SCA metadata: > > ```javascript theme={null} > const rawToken = await tokenizer.tokenizeCardRaw({ > cardNumber: '4242424242424242', > expiryDate: '12/28', > cvc: '123', > }); > > if (rawToken.metadata?.auth?.scaRequired) { > console.log('3DS will be required'); > } > ``` > [tab] Apple Pay / Google Pay > > ```typescript theme={null} > import { useCardTokenization } from '@tagadapay/core-js/react'; > > const { tokenizeApplePay, tokenizeGooglePay } = useCardTokenization({ > environment: 'production', > }); > > // Apple Pay > const appleResult = await tokenizeApplePay(applePayToken); > > // Google Pay > const { tagadaToken } = await tokenizeGooglePay(googlePayToken); > ``` > > **Apple Pay runs through TagadaPay's platform integration:** we hold the Apple > certificates and register your checkout domains under them — you never manage a > certificate or an Apple Developer account. Each registered domain has its own > `merchantRegistrationId`, and Apple encrypts the wallet token to that > registration's certificate, so the id must reach **both** the merchant session > and the tokenize call. > > The simplest integration never touches it: give `startApplePaySession` your > store id and a public key, and it resolves the registration for the current > domain itself while the sheet is opening. > > ```typescript theme={null} > import { startApplePaySession } from '@tagadapay/core-js'; > > button.addEventListener('click', () => { > startApplePaySession( > { > basisTheoryApiKey: 'key_***', > storeId: 'store_xxx', > tagadaApiKey: 'tp_pk_live_***', > countryCode: 'FR', > storeName: 'My Store', > }, > { totalAmountMinor: 4999, currency: 'EUR' }, > { > // The sheet stays open until this returns, and shows what it returns. > onSuccess: async (token, contacts) => { > const approved = await chargeOnYourServer(token, contacts); > return { status: approved ? 'success' : 'failure' }; > }, > }, > ); > }); > ``` > > When you drive the sheet yourself, resolve it in one call and pass it to both > Basis Theory calls: > > ```typescript theme={null} > import { resolveApplePayRegistration } from '@tagadapay/core-js'; > > // Before the click — one fetch, cache it. > const registration = await resolveApplePayRegistration({ > storeId: 'store_xxx', > apiKey: 'tp_pk_live_***', > }); > > // Merchant session (inside onvalidatemerchant) > const session = await validateApplePayMerchant( > registration?.displayName ?? storeName, > window.location.host, > registration?.merchantRegistrationId, > ); > > // Tokenization (inside onpaymentauthorized) > const appleResult = await tokenizeApplePay(applePayToken, registration?.merchantRegistrationId); > ``` > > A `null` result means the domain uses the store's default platform > configuration — omit the argument and behavior is unchanged. Either way, **the > domain must be registered with TagadaPay first**: an unregistered domain fails > at merchant validation before the sheet ever opens. Enable it from the CRM > (Store → Integrations → Apple Pay), which registers the checkout domain for > you, and repeat it for every hostname that serves your checkout, CDN aliases > included. > > > [!NOTE] > > > > `resolveApplePayByok(metadata, hostname)` still works and is unchanged, but it > > only reads the metadata bag you already fetched and misses the binding when > > the config entry is keyed `apple_pay:`. Prefer > > `resolveApplePayRegistration` (fetches for you) or `findApplePayRegistration` > > (a config you already hold). > > See the [Apple & Google Pay example](https://github.com/TagadaPay/examples/tree/main/apple-google-tokenization) for the full integration including wallet button setup. > The canonical wallet reference (processor support, platform registration, recurring rules) is > [Apple Pay & Google Pay](/developer-tools/payments/wallets). **What's in a TagadaToken?** It's a base64-encoded JSON envelope containing the provider token, card metadata (last4, brand, BIN, expiry), SCA flags, and issuer information. It's safe to send over the network — no raw card data. *** ## Step 2: Create a Payment Instrument (Server-Side) Send the `tagadaToken` from your client to your server, then call TagadaPay to create a reusable payment instrument: ```bash theme={null} curl -X POST https://api.tagada.io/api/public/v1/payment-instruments/create-from-token \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "tagadaToken": "eyJ0eXBlIjoiY2FyZC...", "storeId": "store_abc123", "customerData": { "email": "jane@example.com", "firstName": "Jane", "lastName": "Doe" }, "customer": { "ipAddress": "203.0.113.9", "userAgent": "Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1" } }' ``` `customer` is the shopper as seen by **your** server (IP and `User-Agent`), not your server's own address — see [Pass the shopper's IP](#pass-the-shoppers-ip-and-user-agent). It is kept on the customer so later charges carry it. Response: ```json theme={null} { "paymentInstrument": { "id": "pi_a1b2c3d4", "type": "card", "customerId": "cus_x1y2z3", "card": { "last4": "4242", "brand": "visa", "expMonth": 12, "expYear": 2028 } }, "customer": { "id": "cus_x1y2z3", "email": "jane@example.com" } } ``` > [!TIP] > > `customerData` reuses the store's customer with the same email (case-insensitive, surrounding spaces ignored), creating one only when none exists; you can also pass `customerId` explicitly. Save the `paymentInstrument.id` — you'll use it for every charge on this card. The instrument is reusable for future payments (subscriptions, repeat purchases). *** ## Step 3: 3DS Authentication (If Required) 3DS (3D Secure) is required by many card issuers, especially in Europe (SCA regulation). The tokenization step tells you if it's needed via `rawToken.metadata.auth.scaRequired`. 3DS has two parts: creating a session (server + client) and handling the challenge (client). ### 3a. Create a 3DS Session **Client-side:** Create a local session with the 3DS provider SDK: ```typescript theme={null} import { useThreeds } from '@tagadapay/core-js/react'; const { createSession, startChallenge } = useThreeds({ environment: 'production', }); const session = await createSession( { id: paymentInstrument.id, token: rawToken.id, type: 'card', card: { last4: '4242', bin: '424242', expirationMonth: 12, expirationYear: 2028, }, }, { amount: 2999, // in cents currency: 'USD', customerInfo: { name: 'Jane Doe', email: 'jane@example.com', }, }, ); ``` **Server-side:** Persist the session to TagadaPay so the payment processor can use it: ```bash theme={null} curl -X POST https://api.tagada.io/api/public/v1/threeds/create-session \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "provider": "basis_theory", "storeId": "store_abc123", "paymentInstrumentId": "pi_a1b2c3d4", "sessionData": { "sessionId": "bt_session_xyz", "metadata": {} } }' ``` Response: ```json theme={null} { "id": "threeds_abc123", "externalSessionId": "bt_session_xyz", "provider": "basis_theory", "status": "created", "paymentInstrumentId": "pi_a1b2c3d4" } ``` ### 3b. Handle the Challenge (After Payment — See Step 4) If the issuer requires a challenge (password, SMS, biometric), it comes back in the payment response. You handle it client-side — see Step 4b below. *** ## Step 4: Process the Payment (Server-Side) ### 4a. Send the charge request ```bash theme={null} curl -X POST https://api.tagada.io/api/public/v1/payments/process \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "amount": 2999, "currency": "USD", "storeId": "store_abc123", "paymentInstrumentId": "pi_a1b2c3d4", "threedsSessionId": "threeds_abc123", "initiatedBy": "customer", "mode": "purchase" }' ``` | Field | Type | Description | | - | - | - | | `amount` | `number` | Amount in **cents** (2999 = \$29.99) | | `currency` | `string` | ISO currency code (USD, EUR, GBP, etc.) | | `storeId` | `string` | Your store ID | | `paymentInstrumentId` | `string` | From Step 2 | | `threedsSessionId` | `string` | From Step 3 (optional if 3DS not required) | | `returnUrl` | `string` | Where the shopper comes back after a 3DS page hosted by the processor. Pass it on every customer-initiated payment (see "If the processor runs 3DS itself" below) | | `initiatedBy` | `string` | `"customer"` (CIT) or `"merchant"` (MIT) | | `mode` | `string` | `"purchase"` (charge immediately), `"auth"` (authorize only), `"capture"` (capture a previous auth), or `"verify"` (\$0 card verification that saves the card, see below) | | `reasonType` | `string` | For MIT only: `"recurring"`, `"unscheduled"`, or `"installment"` | | `paymentFlowId` | `string` | Optional — forces a specific payment flow (PSP routing rule) | | `threeDSecure` | `string` | Optional — `"challenge"` asks the card issuer to challenge the customer on this payment (see [Request a 3DS challenge](#request-a-3ds-challenge)) | | `customer` | `object` | Strongly recommended — `{ ipAddress, userAgent }` of the shopper as seen by **your** server (see [Pass the shopper's IP](#pass-the-shoppers-ip-and-user-agent)) | **If payment succeeds immediately:** ```json theme={null} { "payment": { "id": "pay_xyz789", "amount": 2999, "currency": "USD", "status": "succeeded", "requireAction": "none" } } ``` **If 3DS challenge is required:** ```json theme={null} { "payment": { "id": "pay_xyz789", "status": "pending", "requireAction": "threeds_auth", "requireActionData": { "type": "threeds_auth", "metadata": { "threedsSession": { "externalSessionId": "bt_session_xyz", "acsChallengeUrl": "https://acs.issuer.com/challenge", "acsTransID": "acs_trans_123", "messageVersion": "2.2.0" } } } } } ``` **If the processor runs 3DS itself (Stripe, Adyen and other processors that host the challenge):** ```json theme={null} { "payment": { "id": "pay_xyz789", "status": "pending", "requireAction": "redirect", "requireActionData": { "type": "processor_auth", "metadata": { "type": "redirect", "redirect": { "redirectUrl": "https://processor.example/3ds/authenticate/...", "returnUrl": "https://your-site.com/return" } } } } } ``` Send the shopper to `requireActionData.metadata.redirect.redirectUrl`. They authenticate on the processor's page and come back to your `returnUrl`. Then poll for the final status (4c). > [!WARNING] > > This needs a `returnUrl` on the charge. Without one there is no page to send the shopper to, so on Stripe a card that needs 3DS is declined straight away, not left pending: `status` is `declined`, `error.code` is `authentication_required` and `error.processorCode` is `authentication_not_handled`. To keep those sales, pass `returnUrl` on every customer-initiated payment and handle `requireAction: "redirect"`. A merchant-initiated payment (`initiatedBy: "merchant"`) does not need it. ### 4b. Handle the 3DS Challenge (Client-Side) When the payment response has `requireAction: "threeds_auth"`, show the challenge to the customer: ```typescript theme={null} const challengeResult = await startChallenge({ sessionId: threedsSession.externalSessionId, acsChallengeUrl: threedsSession.acsChallengeUrl, acsTransactionId: threedsSession.acsTransID, threeDSVersion: threedsSession.messageVersion, }); if (challengeResult.success) { // 3DS passed — poll for final payment status } ``` The SDK opens a modal with the issuer's authentication page. Once the customer completes it, poll for the final status. ### 4c. Poll for Final Status After 3DS completes, the PSP processes the payment asynchronously. Poll until you get a terminal status: ```bash theme={null} curl https://api.tagada.io/api/public/v1/payments/pay_xyz789 \ -H "Authorization: Bearer YOUR_API_KEY" ``` Poll every 1–2 seconds. Terminal statuses: `succeeded`, `failed`, `declined`. *** ## CIT vs MIT (Customer vs Merchant Initiated) | | CIT (Customer Initiated) | MIT (Merchant Initiated) | | - | - | - | | **When** | Customer is present and clicks "Pay" | Server charges without customer present | | **Examples** | First purchase, one-click reorder | Subscription renewal, metered billing, retry | | **3DS** | Required if issuer demands it | Typically exempt (uses stored credential) | | **`initiatedBy`** | `"customer"` | `"merchant"` | | **`reasonType`** | Not needed | `"recurring"`, `"unscheduled"`, or `"installment"` | ### CIT Example (Customer Paying Now) ```json theme={null} { "amount": 2999, "currency": "USD", "storeId": "store_abc123", "paymentInstrumentId": "pi_a1b2c3d4", "initiatedBy": "customer", "mode": "purchase" } ``` ### MIT Example (Subscription Renewal) ```json theme={null} { "amount": 2999, "currency": "USD", "storeId": "store_abc123", "paymentInstrumentId": "pi_a1b2c3d4", "initiatedBy": "merchant", "reasonType": "recurring", "mode": "purchase" } ``` ### MIT Example (Auth + Capture) ```json theme={null} // Step 1: Authorize { "amount": 2999, "currency": "USD", "storeId": "store_abc123", "paymentInstrumentId": "pi_a1b2c3d4", "initiatedBy": "merchant", "reasonType": "unscheduled", "mode": "auth" } // Step 2: Capture later { "paymentId": "pay_xyz789", "mode": "capture" } ``` ### Save a Card Without Charging (\$0 Verification) For pay-as-you-go, save the card while the customer is present (3DS runs if the issuer asks for it), then charge it off-session later. ```json theme={null} // Step 1: Verify and save the card (customer present) { "amount": 0, "currency": "USD", "storeId": "store_abc123", "customerId": "cus_abc123", "paymentInstrumentId": "pi_a1b2c3d4", "initiatedBy": "customer", "reasonType": "unscheduled", "mode": "verify", "returnUrl": "https://your-site.com/return" } // Step 2: Charge later (customer not present) { "amount": 1999, "currency": "USD", "storeId": "store_abc123", "customerId": "cus_abc123", "paymentInstrumentId": "pi_a1b2c3d4", "initiatedBy": "merchant", "reasonType": "unscheduled", "mode": "purchase" } ``` * `mode: "verify"` requires `amount: 0` and `initiatedBy: "customer"`. `orderId`, `subscriptionId` and `paymentMethod` are not accepted. Any other mode still requires `amount > 0`. * If the response has `requireAction`, send the customer through it exactly as for a payment. The verification completes when they return. * Use the same `customerId` and `paymentInstrumentId` for the later charges. That is how they are linked to the verification. ### Pass the Shopper's IP and User Agent On this path your server is the caller, so Tagada sees your datacenter, not the shopper. Processors weigh the shopper IP heavily (Stripe Radar, Adyen risk, issuer scoring). Forward the shopper's IP and the browser's `User-Agent`, as your server received them, in `customer` — on `create-from-token` (kept on the customer for later charges) and on every `payments/process` you can. ```json theme={null} { "amount": 2999, "currency": "USD", "storeId": "store_abc123", "paymentInstrumentId": "pi_a1b2c3d4", "initiatedBy": "customer", "mode": "purchase", "customer": { "ipAddress": "203.0.113.9", "userAgent": "Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1" } } ``` ```ts theme={null} // Node SDK — Express behind a trusted proxy (`app.set('trust proxy', true)`) await tagada.payments.process({ // ... customer: { ipAddress: req.ip, userAgent: req.get('user-agent') }, }); ``` * Never your own server's address. Tagada never substitutes it either: a charge without `customer` and without a known device simply carries no IP. * `ipAddress` must be a valid public IPv4 or IPv6; anything else is refused with `400`. Behind a proxy, take the first entry of `X-Forwarded-For`. * On merchant-initiated charges (rebills) the shopper is not present: omit `customer`, the IP kept on the customer from the original purchase is used. ### Request a 3DS Challenge By default, whether 3DS runs depends on your payment setup and on the card. To ask for a challenge on one payment while the customer is present, add `threeDSecure: "challenge"`. ```json theme={null} { "amount": 2999, "currency": "EUR", "storeId": "store_abc123", "customerId": "cus_abc123", "paymentInstrumentId": "pi_a1b2c3d4", "initiatedBy": "customer", "mode": "purchase", "threeDSecure": "challenge", "returnUrl": "https://your-site.com/return" } ``` * The issuer makes the final call. The response has either a `requireAction` (send the customer through it, as for any 3DS payment) or a final status straight away: the issuer authenticated the customer without a challenge, and the payment still counts as 3DS-authenticated. * Card payments with `initiatedBy: "customer"` only. The request is refused on merchant-initiated charges and on redirect payment methods. * It also works with `mode: "auth"` and `mode: "verify"`. *** ## Void and Refund ### Void (Cancel an Authorization) ```bash theme={null} curl -X POST https://api.tagada.io/api/public/v1/payments/void \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "paymentId": "pay_xyz789", "storeId": "store_abc123" }' ``` ### Refund (Full or Partial) ```bash theme={null} curl -X POST https://api.tagada.io/api/public/v1/payments/refund \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "paymentIds": ["pay_xyz789"], "amount": 1000 }' ``` Omit `amount` for a full refund. *** ## What TagadaPay Does Under the Hood When you call `/payments/process`, TagadaPay: 1. **Routes to the right PSP** — based on your payment flow rules (card brand, currency, amount, BIN range, etc.) 2. **Attaches 3DS data** — if a `threedsSessionId` is provided, the authentication result is forwarded to the PSP 3. **Handles retries** — if the primary PSP declines, the payment flow can cascade to a backup PSP 4. **Normalizes the response** — regardless of which PSP handled it, you get the same response format 5. **Records the transaction** — for analytics, dispute management, and reconciliation You don't need to integrate with Stripe, NMI, Airwallex, etc. individually. Configure the PSP connections in the [CRM dashboard](https://app.tagada.io), set up payment flow routing rules, and TagadaPay handles the rest. *** ## API Reference | Endpoint | Method | Purpose | | - | - | - | | [`/payment-instruments/create-from-token`](/api-reference/payment-instruments/create-payment-instrument-from-tagadatoken) | POST | Create instrument from TagadaToken | | [`/payment-instruments/{id}`](/api-reference/payment-instruments/get-payment-instrument-details) | GET | Get instrument details | | [`/customers/{id}/payment-instruments`](/api-reference/payment-instruments/list-customer-payment-instruments) | GET | List customer's instruments | | [`/threeds/create-session`](/api-reference/3ds-authentication/create-3ds-authentication-session) | POST | Create 3DS session | | [`/payments/process`](/api-reference/payments/process-a-payment) | POST | Process a payment (CIT or MIT) | | [`/payments/{id}`](/api-reference/payments/get-payment-by-id) | GET | Get payment status | | [`/payments/void`](/api-reference/payments/void-a-payment) | POST | Void an authorization | | [`/payments/refund`](/api-reference/payments/refund-a-payment) | POST | Full or partial refund | *** ## Working Examples Complete working examples with React, TypeScript, and Tailwind CSS are available on GitHub: > [card] [Card Tokenization + Payment](https://github.com/TagadaPay/examples/tree/main/core-js-tokenization) > > Full 4-step payment flow with 3DS > [card] [Apple Pay & Google Pay](https://github.com/TagadaPay/examples/tree/main/apple-google-tokenization) > > Wallet tokenization integration **Test card:** `4242 4242 4242 4242` (any future expiry, any CVC) *** ## SDK Reference ### `@tagadapay/core-js` Package | Export | Import Path | What it provides | | - | - | - | | **Core** | `@tagadapay/core-js` | `Tokenizer` class, `createTagadaToken`, `decodeTagadaToken` | | **React** | `@tagadapay/core-js/react` | `useCardTokenization`, `useThreeds` hooks | | **3DS** | `@tagadapay/core-js/threeds` | `ThreedsManager`, `ThreedsModal` for manual 3DS | ### Key Types ```typescript theme={null} interface CardPaymentMethod { cardNumber: string; expiryDate: string; // "MM/YY" cvc: string; cardholderName?: string; } interface CardTokenResponse { id: string; type: string; data: { number?: string; expiration_month?: number; expiration_year?: number }; metadata?: { auth?: { scaRequired?: boolean }; tokenizedAt?: string; }; } interface TagadaToken { type: 'card' | 'apple_pay' | 'google_pay'; token: string; provider: string; nonSensitiveMetadata: { last4?: string; brand?: string; bin?: string; expiryMonth?: number; expiryYear?: number; funding?: string; fingerprint?: string; authentication?: 'sca_required' | 'optional'; issuer?: { name?: string; country?: string }; }; } ``` ## Test your integration In sandbox, any 16-digit card works. Use this one: | | | | - | - | | Card | `4242 4242 4242 4242` | | Expiry | Any future date | | CVC | Any 3 digits | Confirm the payment succeeds, then list it with `tagada.payments.list()`. To exercise a 3DS return, use a card your processor flags for authentication and confirm the shopper lands back on the `returnUrl` you passed. Full sandbox setup (processor, payment flow, store): [Sandbox testing](/developer-tools/node-sdk/sandbox-testing). > [card] [npm Package](https://www.npmjs.com/package/@tagadapay/core-js) > > @tagadapay/core-js on npm > [card] [API Reference](/api-reference/introduction) > > Full REST API documentation # Processors Source: https://docs.tagada.io/developer-tools/payments/processors Every processor TagadaPay can charge through, and which operations each one supports. # Processors A **processor** is the connection between TagadaPay and the party that actually moves the money. Every store points at one or more processors, and every charge is executed by exactly one of them. ## Two ways to get paid > [card] TagadaPay (managed) > > We are your payment provider. You hold no processor credentials — onboarding, underwriting, > acquiring, settlement, payouts and disputes all run through TagadaPay. Configured as a single > processor of type `tagadapay-router`. > [card] Bring your own processor > > You already have a merchant account. You give us the credentials and we drive it through a > connector. You keep the acquiring relationship, the settlement and the risk. > [!NOTE] > > With **TagadaPay managed**, the underlying acquiring is arranged for you and can differ by > account, currency and region. You integrate against `tagadapay-router` and never against a > specific acquirer — which methods your account can charge is answered at runtime by > [`paymentSetup`](/developer-tools/payments/support-matrix#discovering-what-a-store-can-actually-charge). ## The operation contract Every processor implements the same seven operations. Your integration calls the same API regardless of who is behind it. | Operation | What it does | | - | - | | `purchase` | Authorize and capture in one call. The default for most checkouts. | | `authorize` | Reserve funds without taking them. | | `capture` | Take previously authorized funds. | | `void` | Cancel an authorization before capture. | | `refund` | Return captured funds, in full or in part. | | `verify` | Validate an instrument without charging it (zero-amount / account check). | | `retrieve` | Re-read a transaction's current state from the processor. | > [!NOTE] > > Not every processor exposes all seven. Where a cell is `—` below, the operation is not available > through that connector — calling it returns an `unsupported_feature` error rather than failing > silently. Design your flows around `purchase` and `refund`, which are the most widely supported. ## Capability matrix > [!TIP] > > Looking for **which payment methods** each processor can charge rather than which operations? > That is the [support matrix](/developer-tools/payments/support-matrix). | Processor | `type` | Purchase | Authorize | Capture | Void | Refund | Verify | Retrieve | | - | - | :-: | :-: | :-: | :-: | :-: | :-: | :-: | | **TagadaPay** (managed) | `tagadapay-router` | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | | Airwallex | `airwallex` | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | | Authorize.Net | `authorizenet` | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | | CCAvenue | `ccavenue` | ✓ | ✓ | — | — | — | ✓ | — | | Checkout.com | `checkout` | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | — | | ConvesioPay | `convesio` | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | | Finix | `finix` | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | | KessPay | `kesspay` | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | | Mastercard MPGS | `mastercard` | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | — | | Network N-Genius | `ngenius` | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | — | | NMI | `nmi` | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | — | | Ovri | `ovri` | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | | Paysafe | `paysafe` | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | — | | Stripe | `stripe` | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | — | | Tap Payments | `tap` | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | > [!WARNING] > > **Availability in the integration is not commercial availability.** This table says the connector > exists and what it can do. It does not mean the processor is offered, contracted or supported for > your account. Confirm with your account manager before designing around one. ### Worth knowing > [accordion] CCAvenue cannot capture, void or refund > > CCAvenue exposes no capture, void or refund API to us — it can purchase, authorize and verify, > but everything after the charge has to be issued from CCAvenue's own back office, and TagadaPay > will not know about it unless you record it. > [accordion] Retrieve is not universal > > Re-reading a transaction's live state from the processor is only available on some connectors. > Where `retrieve` is `—`, rely on our stored transaction record and the > [webhooks](/developer-tools/node-sdk/webhooks-events) instead. > [accordion] Testing without a real acquirer > > Use sandbox credentials on your processor, or the built-in simulator — see > [Sandbox testing](/developer-tools/node-sdk/sandbox-testing). ## Configuring a processor Credentials are stored per processor and never leave the backend. ```ts theme={null} import { Tagada } from '@tagadapay/node-sdk'; const tagada = new Tagada({ apiKey: process.env.TAGADA_API_KEY }); await tagada.processors.create({ processor: { name: 'Stripe — EU entity', type: 'stripe', enabled: true, baseCurrency: 'EUR', supportedCurrencies: ['EUR', 'USD'], options: { secretKey: 'sk_live_***', publicKey: 'pk_live_***', }, }, }); ``` Field names differ per processor — see [Processor credentials](/developer-tools/node-sdk/processor-credentials). ## Routing across several processors A store can hold more than one processor and route between them — for load balancing, for per-currency routing, or to retry a declined card on a second acquirer. That is configured as a **payment flow**: ```ts theme={null} await tagada.paymentFlows.create({ data: { name: 'EU cascade', strategy: 'cascade', pickProcessorStrategy: 'weighted', fallbackMode: true, maxFallbackRetries: 3, threeDsEnabled: true, stickyProcessorEnabled: true, processorConfigs: [ { processorId: 'proc_primary', weight: 70, disabled: false, nonStickable: false }, { processorId: 'proc_secondary', weight: 30, disabled: false, nonStickable: false }, ], fallbackProcessorConfigs: [{ processorId: 'proc_backup', orderIndex: 0 }], }, }); ``` See [Multi-processor routing](/developer-tools/node-sdk/multi-stripe-routing) for cascade rules and retry semantics. ## Next > [card] [Support matrix](/developer-tools/payments/support-matrix) > > Which methods each processor can charge. > [card] [Alternative payment methods](/developer-tools/payments/alternative-payment-methods) > > Klarna, iDEAL, PayPal and the redirect lifecycle. > [card] [From the SDKs](/developer-tools/payments/sdk-usage) > > Charging any of this from our packages. # Using payment methods from the SDKs Source: https://docs.tagada.io/developer-tools/payments/sdk-usage Which package to reach for, and the exact call that charges a card, a wallet or an APM. # Using payment methods from the SDKs > [!NOTE] > > **Payments V2.** This page documents V2 payments (`pay-v2`, `payments/process`, `threeds/*` on the Commerce API). V2 is the reference for every live integration today. The new [Payments API (V3)](/payments-api/overview) is in preview: see [V2 or V3: which one should I use?](/payments-api/v2-or-v3) Four packages can charge a payment. They differ in where they run and how much they do for you. | Package | Runs in | Reach for it when | | - | - | - | | [`@tagadapay/headless-sdk`](/developer-tools/headless-sdk/introduction) | Browser | You are building a custom storefront and want one call that handles 3DS, redirects and polling | | [`@tagadapay/core-js`](/developer-tools/payments/core-js-payments) | Browser | You need the low-level primitives — tokenization, wallet sheets, 3DS | | [`@tagadapay/plugin-sdk`](/developer-tools/sdk/introduction) | Browser | You are building a storefront plugin on TagadaPay hosting | | [`@tagadapay/node-sdk`](/developer-tools/node-sdk/quick-start) | Server | You are charging server-to-server, or orchestrating a backend flow | > [!TIP] > > If you are unsure, start with `headless-sdk`'s `processPayment()`. It is the one function that > covers cards, wallets and APMs, and it handles the parts people get wrong. ## The one call that handles everything `processPayment()` charges, detects `requireAction`, runs the 3DS challenge, follows APM redirects and polls until the payment reaches a terminal status. ```ts theme={null} import { createHeadlessClient } from '@tagadapay/headless-sdk'; const tagada = createHeadlessClient({ storeId: 'store_xxx' }); const result = await tagada.payment.processPayment({ checkoutSessionId: 'cs_xxx', paymentInstrumentId: 'pi_xxx', }); if (result.status === 'succeeded') fulfil(); ``` Everything below is the same flow taken apart, for when you need control over a step. ## Discovering what you can offer Always render your payment UI from the store's configuration, not from a hard-coded list. ```ts headless-sdk theme={null} const setup = await tagada.payment.getPaymentSetup('cs_xxx'); const methods = await tagada.payment.getEnabledMethods('cs_xxx'); const express = await tagada.payment.getExpressMethods('cs_xxx'); ``` ```ts core-js theme={null} import { getStorePaymentSetup } from '@tagadapay/core-js'; const setup = await getStorePaymentSetup({ storeId: 'store_xxx', apiKey: 'tp_pk_live_***', }); ``` ```ts node-sdk theme={null} const setup = await tagada.paymentSetup.get('store_xxx'); ``` Group the result by `type` — `card`, `wallet`, `apm` — to build your UI sections. See [the config shape](/developer-tools/payments/alternative-payment-methods#the-config-shape). ## Cards **1. Tokenize in the browser** Raw card data never reaches your server or ours unvaulted. ```ts theme={null} const { tagadaToken } = await tagada.payment.tokenizeCard({ cardNumber: '4242424242424242', expiryDate: '12/2030', cvc: '123', }); ``` **2. Pay with the token** `processPayment` creates the instrument from the token for you: ```ts theme={null} await tagada.payment.processPayment({ checkoutSessionId: 'cs_xxx', tagadaToken, }); ``` To store the instrument first (e.g. to reuse it), call `const { paymentInstrument } = await tagada.payment.createInstrument({ tagadaToken })` and pass `paymentInstrumentId: paymentInstrument.id` instead. Server-side, the equivalent is `tagada.payments.process({ amount, currency, storeId, paymentInstrumentId })` — the Node SDK charges vaulted instruments directly and takes no checkout session. ## Wallets ```ts headless-sdk theme={null} // You open the sheet (core-js or your own ApplePaySession); headless-sdk // tokenizes the authorized wallet payload and charges the session. // Inside session.onpaymentauthorized: await tagada.payment.processApplePay({ checkoutSessionId: 'cs_xxx', applePayToken: event.payment.token, }); // Google Pay — inside the paymentsClient callback: await tagada.payment.processGooglePay({ checkoutSessionId: 'cs_xxx', googlePayToken: paymentData.paymentMethodData.tokenizationData.token, }); ``` ```ts core-js theme={null} import { isApplePayAvailable, startApplePaySession } from '@tagadapay/core-js'; if (await isApplePayAvailable()) { button.addEventListener('click', () => { startApplePaySession(config, request, { onSuccess: async (token) => { const approved = await chargeOnYourServer(token); // the sheet waits for this return { status: approved ? 'success' : 'failure' }; }, onError: (msg) => console.error(msg), }); }); } ``` > [!WARNING] > > The wallet sheet must be opened from a real user gesture. Do not `await` anything between the > click and `startApplePaySession` — resolve your configuration beforehand. Full detail in > [Apple Pay & Google Pay](/developer-tools/payments/wallets). ## Alternative payment methods APMs need an explicit `paymentMethod` and a `processorId`, and they always come back with a redirect rather than a final status. ```ts headless-sdk theme={null} const result = await tagada.payment.processApm({ checkoutSessionId: 'cs_xxx', paymentMethod: 'ideal', processorId: 'proc_xxx', // The page that calls maybeResumeFromUrl() after the bank. Defaults to the current page; // a session with a live Tagada checkout page returns there instead. returnUrl: 'https://store.example/checkout', }); // finalize() resolves the action: it redirects the browser for APMs, // runs 3DS challenges, and polls to a terminal status otherwise. const outcome = await tagada.payment.finalize(result, { returnUrl: 'https://store.example/checkout' }); if (outcome.status === 'succeeded') fulfil(); ``` ```ts node-sdk theme={null} const { payment } = await tagada.payments.process({ amount: 4999, currency: 'EUR', storeId: 'store_xxx', customerId: 'cus_xxx', paymentMethod: 'klarna', processorId: 'proc_xxx', returnUrl: 'https://store.example/checkout/return', }); ``` ### Coming back from the redirect When the shopper returns to your `returnUrl`, resume the payment rather than assuming it worked: ```ts theme={null} const resumed = await tagada.payment.maybeResumeFromUrl(); if (resumed?.status === 'succeeded') fulfil(); ``` > [!WARNING] > > The redirect return is not proof of payment. Fulfil on the > [webhook](/developer-tools/node-sdk/webhooks-events), which is the authoritative result. ## Server-side payment operations ```ts theme={null} import { Tagada } from '@tagadapay/node-sdk'; const tagada = new Tagada({ apiKey: process.env.TAGADA_API_KEY }); await tagada.payments.process({ amount, currency, storeId, paymentInstrumentId }); await tagada.payments.retrieve('pay_xxx'); await tagada.payments.refund({ paymentIds: ['pay_xxx'], amount: 1999 }); await tagada.payments.void({ paymentId: 'pay_xxx' }); await tagada.payments.continue('pay_xxx'); await tagada.payments.currencies(); await tagada.payments.processors(); ``` > [!NOTE] > > `payments.refund()` and `payments.void()` are subject to what the underlying processor supports — > CCAvenue, notably, cannot refund through us at all. Check the > [capability matrix](/developer-tools/payments/processors#capability-matrix) before you rely on one. ## Choosing a package > [accordion] I'm building a custom storefront > > `headless-sdk`. Use `processPayment()` for cards and wallets, `processApm()` for redirects, and > `getEnabledMethods()` to decide what to render. > [accordion] I only need to tokenize > > `core-js`. It is the smallest surface — `Tokenizer`, the wallet session helpers and 3DS, with no > checkout opinions attached. > [accordion] I'm charging from a backend > > `node-sdk`. Never put a secret key in a browser — use a restricted publishable key > (`tp_pk_*`) client-side and keep `tp_sk_*` on the server. > [accordion] I'm building a plugin on TagadaPay hosting > > `plugin-sdk`. It has the richest React surface — `usePayment`, wallet hooks and the full > payment-action handler. ## Next > [card] [Support matrix](/developer-tools/payments/support-matrix) > > What each processor can charge. > [card] [Headless SDK](/developer-tools/headless-sdk/checkout-flow) > > The full checkout flow. > [card] [Node SDK](/developer-tools/node-sdk/quick-start) > > Server-side quick start. # Payment method support matrix Source: https://docs.tagada.io/developer-tools/payments/support-matrix Every card, wallet and alternative payment method TagadaPay can charge, and which processor each one runs on. # Payment method support matrix Filter by method type, by processor, or search for a scheme by name or code. > [!NOTE] > > A method listed here is **supported by the integration**. Whether it is available on *your* > store also depends on your account, your currency and what your acquirer has enabled — resolve > that at runtime with [`paymentSetup`](#discovering-what-a-store-can-actually-charge) rather than > hard-coding this table. ## How to read this TagadaPay charges money through two different arrangements, and the matrix mixes both: > [card] TagadaPay (managed) > > We are your payment provider. You hold no processor credentials — onboarding, acquiring, > settlement and payouts run through TagadaPay. This is the widest method catalogue. > [card] Bring your own processor > > You hold the merchant account and give us the credentials. The method catalogue is whatever > that processor supports through our connector. Every method in the matrix falls into one of three families, which behave very differently at checkout: | Family | What the shopper does | What your integration does | | - | - | - | | **Card** | Enters a card number (Visa, Mastercard, American Express, Discover, JCB, Diners Club — per acquirer) | Tokenize in the browser, then charge server-to-server | | **Wallet** | Confirms in a native sheet (Touch ID, Face ID, screen lock) | Open the sheet, receive a token, charge server-to-server | | **APM** | Is redirected to the provider, authorises, comes back | Charge, receive a redirect URL, send the browser there, wait for the webhook | > [!WARNING] > > APMs are **redirect-based and asynchronous**. The charge call does not return a final status — it > returns a `requireAction` with a redirect URL. The real outcome arrives on a webhook after the > shopper returns. Never treat the charge response as a completed payment for an APM. ## Recurring and subscriptions The `Recurring` column means the method can be charged again later without the shopper present (a merchant-initiated transaction). * **Cards, Apple Pay and Google Pay** are reusable. On the native path the wallet is stored as a network token and rebilled on the card rails, so a subscription started with Apple Pay keeps billing after the sheet is gone. Link is Express-only and single-use — hence its `—` in the Recurring column. * **Most APMs are single-use.** The shopper authorises one specific amount on the provider's page. If your funnel has a subscription or a post-purchase upsell, an APM will not silently rebill — design for it. ## Discovering what a store can actually charge The matrix tells you what the platform supports. It does not tell you what *your* store has switched on. That answer is per-store and lives behind one call: ```ts core-js (browser) theme={null} import { getStorePaymentSetup } from '@tagadapay/core-js'; const setup = await getStorePaymentSetup({ storeId: 'store_xxx', apiKey: 'tp_pk_live_***', }); if (setup.config.apple_pay?.enabled) renderApplePayButton(); if (setup.config.klarna?.enabled) renderKlarnaButton(); ``` ```ts node-sdk (server) theme={null} import { Tagada } from '@tagadapay/node-sdk'; const tagada = new Tagada({ apiKey: process.env.TAGADA_API_KEY }); const setup = await tagada.paymentSetup.get('store_xxx'); const enabled = Object.values(setup.config).filter((m) => m.enabled); ``` Keys in `config` are two-dimensional — `""` when there is one provider for that method, and `":"` when the same method is routed through more than one. Read [Alternative payment methods](/developer-tools/payments/alternative-payment-methods#discovery) for the full shape. ## What this matrix does not tell you > [accordion] Whether a method is commercially available to you > > Support in the integration is not the same as a signed agreement. Some methods need a separate > contract with the scheme, or underwriting on your account. Talk to your account manager. > [accordion] Per-country and per-currency limits > > The Coverage column is indicative. Real availability is decided by your acquirer per market, > and some methods have amount floors and ceilings. `paymentSetup` reflects what is actually > switched on. > [accordion] Refund behaviour per method > > Refunds go through the processor, not the method. Some APMs settle asynchronously (vouchers in > particular) and cannot be refunded before they settle. Check the specific scheme's rules. ## Next > [card] [Processors](/developer-tools/payments/processors) > > Every processor, and which operations each one supports. > [card] [Alternative payment methods](/developer-tools/payments/alternative-payment-methods) > > The redirect lifecycle, per-processor APM detail. > [card] [Apple Pay & Google Pay](/developer-tools/payments/wallets) > > Native vault vs through-processor wallets. # Apple Pay & Google Pay Source: https://docs.tagada.io/developer-tools/payments/wallets Which processors accept wallets, the two integration paths, and what you must configure before the sheet will open. # Apple Pay & Google Pay Wallets sit between cards and APMs. The shopper confirms in a native sheet instead of typing a card number, but what comes out the other side is a **network token that rides the card rails** — so unlike an APM, a wallet payment can be stored and rebilled. ## Availability | Processor | Apple Pay | Google Pay | Notes | | - | :-: | :-: | - | | **TagadaPay** (managed) | ✓ | ✓ | Nothing to configure beyond your domains | | Stripe | ✓ | ✓ | Also exposes Link and Klarna through Express Checkout | | Checkout.com | ✓ | ✓ | | | NMI | ✓ | ✓ | | | Mastercard MPGS | ✓ | — | Apple Pay only | Every other processor charges a wallet-sourced card as a plain card if it gets one, with no cryptogram and no wallet indicator — which usually means worse authorisation rates and no liability shift. Treat the table above as the real list. ## Two integration paths > [card] Native (vault tokenization) > > You open the sheet yourself. The encrypted wallet payload is decrypted inside TagadaPay's PCI > vault and turned into a Tagada token you charge like any other instrument. > **Works with every processor in the table.** > [card] Through-processor (Express) > > The processor's own element renders the button and confirms the payment. Less code, but you > inherit that processor's rules — and the instrument can be charged again only in the cases > listed [below](#express-checkout-stripe). > [!NOTE] > > Prefer the **native** path when you want one code path across processors, a reusable credential > on every cart, or control over the sheet. Prefer **Express** when you want the shortest possible > integration on Stripe or TagadaPay: it can start a subscription with Apple Pay or Google Pay, but > a one-time Express payment leaves nothing to charge later. ## Native wallets with core-js **1. Check the device can pay** Both checks are async and must run before you render a button. Never render an Apple Pay button on a device that cannot use it. ```ts theme={null} import { isApplePayAvailable, isGooglePayAvailable } from '@tagadapay/core-js'; const canApple = await isApplePayAvailable(); const canGoogle = await isGooglePayAvailable(); ``` **2. Open the sheet from a user gesture** Apple Pay **must** be started synchronously inside a click handler. Any `await` before `startApplePaySession` and the browser will refuse to open the sheet. Pass your `storeId` and a public-restricted key: Apple Pay runs through **TagadaPay's platform integration** (we hold the Apple certificates and register your checkout domains under them), and each registered domain has its own registration id. The session resolves the one for the current domain by itself, during merchant validation — after the sheet has opened, so it costs nothing at gesture time and there is no lookup code to write. ```ts theme={null} import { startApplePaySession, applePayTokenToTagadaToken } from '@tagadapay/core-js'; button.addEventListener('click', () => { startApplePaySession( { basisTheoryApiKey: 'key_***', storeId: 'store_xxx', tagadaApiKey: 'tp_pk_live_***', countryCode: 'FR', storeName: 'My Store', }, { totalAmountMinor: 4999, currency: 'EUR' }, { onSuccess: async (token, contacts) => { const tagadaToken = applePayTokenToTagadaToken(token); const approved = await chargeOnYourServer(tagadaToken, contacts); return { status: approved ? 'success' : 'failure' }; }, onError: (msg) => console.error(msg), }, ); }); ``` The sheet stays open while `onSuccess` runs, and shows what it returns (core-js 3.5.0 and later; earlier versions closed the sheet as a success before calling it): | `onSuccess` returns | The sheet shows | | - | - | | `{ status: 'success' }`, or nothing | The checkmark and "Done" | | `{ status: 'failure' }` | "Payment Not Completed". `onError` is not called: you already have the reason | | `{ status: 'unknown' }` | Nothing: the sheet is dismissed. Use it when the charge is still pending or needs a redirect | | it throws | "Payment Not Completed", then `onError` | Apple abandons the sheet 30 seconds after the shopper authorizes. If `onSuccess` has not returned after 25 seconds, the sheet is dismissed as for `unknown`, and your code keeps running. Only when you mint the Basis Theory merchant session yourself do you need the id in hand — one call, before the click: ```ts theme={null} import { resolveApplePayRegistration } from '@tagadapay/core-js'; const registration = await resolveApplePayRegistration({ storeId: 'store_xxx', apiKey: 'tp_pk_live_***', }); // registration?.merchantRegistrationId → `merchant_registration_id` // registration?.displayName → `display_name` ``` `null` means the domain uses the store's default platform configuration — that is normal, not an error: send no `merchant_registration_id` and behavior is unchanged. **3. Charge server-side** The browser never charges. Send the token to your backend and create the payment there. ```ts theme={null} const { paymentInstrument } = await tagada.paymentInstruments.createFromToken({ tagadaToken, storeId: 'store_xxx', customerData: { email: 'shopper@example.com' }, }); await tagada.payments.process({ amount: 4999, currency: 'EUR', storeId: 'store_xxx', paymentInstrumentId: paymentInstrument.id, }); ``` Google Pay is the same shape with `startGooglePaySession` and a `GooglePayServiceConfig`. > [!WARNING] > > `startApplePaySession` and `startGooglePaySession` take `(config, request, callbacks)` and return > `void` — they are **not** promises. The token arrives in `callbacks.onSuccess`. ## Express Checkout (Stripe) Stripe's Express Checkout Element renders Apple Pay, Google Pay, Link and Klarna as one row of buttons. TagadaPay pins the intent to exactly the wallet the shopper pressed. You discover it through `paymentSetup` — an `express_checkout:` entry carries the Stripe `publishableKey` and the per-method `methods` map — and confirm it with the headless SDK's `tagada.payment.processStripeExpress({ checkoutSessionId, processorId, paymentMethod })`, which returns the `clientSecret` for `stripe.confirmPayment()`. Supported express methods are `apple_pay`, `google_pay`, `link` and `klarna_express`. Anything else the Stripe account has switched on is deliberately refused rather than half-handled. ### Can an Express payment be charged again? An Express payment records an instrument with no card token of its own. Whether it can be charged later without the shopper (a subscription renewal, a one-click upsell) depends on the cart and the method, the same way on Stripe and on TagadaPay: | Express payment | Charged again later? | | - | - | | Apple Pay or Google Pay, cart with a subscription item | **Yes.** TagadaPay attaches the payment to a Stripe customer and asks Stripe to keep the payment method (`setup_future_usage: off_session`), stores it on the instrument, and charges renewals on it. | | Apple Pay or Google Pay, one-time cart | **No.** Nothing is kept: the instrument settles that order only. | | Link or Klarna, any cart | **No.** Nothing is kept. Do not sell a subscription through them. | > [!WARNING] > > When a cart has a subscription item and Stripe cannot keep the payment method (no shopper email, > or Stripe refuses to create the customer), the Apple Pay or Google Pay payment is refused before > any charge, and the shopper is asked to pay by card. Subscriptions > started with an Express payment before 7 September 2026, 09:00 UTC have no kept payment method: > their renewals are declined with `payment_instrument_invalid`. ## What you must configure > [accordion] Apple Pay — register every checkout domain with us > > Apple Pay runs through TagadaPay's **platform integration**: we hold the Apple certificates and > register your domains under them. You never create an Apple Developer account, host a > verification file, or manage a certificate. > > What you must do is register **every domain** that will show an Apple Pay button — checkout > subdomains and any CDN alias you serve checkout from included. Do it yourself from the CRM, > under **Store → Integrations → Apple Pay**: it picks up the store's checkout domain, checks > the association file, registers it with Apple and switches it on. An unregistered domain fails > at merchant validation, before the sheet ever opens, and the failure is silent to the shopper > (the button simply does not work). Registration is per-domain: a store served from two > hostnames needs both registered. > > At runtime nothing is left for you to configure. `startApplePaySession` resolves the > registration for the current domain from `storeId` + `tagadaApiKey`; when you drive the sheet > yourself, `resolveApplePayRegistration({ storeId, apiKey })` returns the same thing in one > call (`findApplePayRegistration(config, hostname)` if you already hold the payment setup). > [accordion] Google Pay — merchant id > > Google Pay needs your Google merchant id for production, and the button will render in test mode > without it. The gateway side is handled by TagadaPay. > [accordion] Both — HTTPS and a real user gesture > > Wallets need HTTPS and a genuine click or tap to open the sheet. Apple Pay additionally refuses > `localhost` — test it through an HTTPS tunnel. Google Pay tolerates `localhost` in test mode. ## Recurring and wallets Unlike APMs, wallets **can** be rebilled. On the native path the wallet gives you a network token that is stored like a card, so a subscription started with Apple Pay keeps billing after the sheet is long gone. On the Express path, see [which payments can be charged again](#can-an-express-payment-be-charged-again). Two rules make the difference between a working rebill and a decline: * **The cryptogram is single-use.** It authenticates the first, shopper-present charge only. Replaying it on a later merchant-initiated charge gets the charge declined. * **Later charges are merchant-initiated.** They carry the stored credential and the network transaction id from the first payment instead. TagadaPay does this for you on the native path. > [!NOTE] > > This is the practical reason to prefer native tokenization for anything with a subscription, a > rebill or a post-purchase upsell: it keeps a reusable credential on every processor and every > cart, while Express keeps one only for Apple Pay or Google Pay on a cart with a subscription item. ## Next > [card] [Support matrix](/developer-tools/payments/support-matrix) > > Every method and processor in one filterable view. > [card] [Card tokenization](/developer-tools/examples/card-tokenization) > > The same vault flow for plain cards. > [card] [From the SDKs](/developer-tools/payments/sdk-usage) > > Wallet helpers in each package. # API & events reference Source: https://docs.tagada.io/developer-tools/rx/api-reference Every Tagada Rx endpoint and case event in one page — storefront, merchant, portal, and clinical webhooks. # API & events reference The compact map of the whole Rx surface. Full request/response shapes live in the [OpenAPI reference](/api-reference/introduction) and the per-SDK pages. *** ## Storefront endpoints (public — no API key) Base: `/api/public/v1/rx`. Case routes authorize with the `(orderId, checkoutToken)` ownership proof. | Method | Path | Purpose | | - | - | - | | `GET` | `/required-for-product?productId=…` | Is this product Rx-gated? Returns clinical requirements | | `POST` | `/cases/submit` | Submit patient + intake after payment (PHI pass-through) | | `POST` | `/cases/lookup` | Public-safe case statuses for an order (thank-you polling) | | `POST` | `/intake/context` | Resume an unfinished intake: Rx line + basics on the order, or `caseExists: true` | | `GET` | `/activation-status?storeId=…` | Steps, missing items and `payments: setting_up \| ready` (no payout or partner items) | ## Merchant endpoints (Tagada API key) Base: `/api/v1/rx` — Node SDK namespace `tagada.rx.*`. | Method | Path | Purpose | | - | - | - | | `GET` | `/integration/status` | Activation state for a store | | `GET` | `/activation-status` | Steps, missing items and `payments: setting_up \| ready` | | `GET` | `/statement-descriptor` | Brand statement descriptor (`TGDCARE*`) and its review state | | `POST` | `/statement-descriptor` | Submit the brand descriptor (reviewed by Tagada before use) | | `POST` | `/integration/activate` | Request activation (creates pending setup fee) | | `POST` | `/integration/confirm-setup-fee` | Flip to active once the fee is captured | | `GET` | `/networks` | Clinical networks available to the account | | `GET` | `/brand` | Brand clinical config (+ affiliate terms) | | `POST` | `/brand-clinical-config` | Wire network credentials | | `POST` | `/affiliate-terms` | Version commission terms (account managers) | | `POST` | `/product-offerings` | Map product ↔ network offering | | `GET` | `/cases` | List cases | | `GET` | `/cases/{caseId}` | Case + event timeline | | `POST` | `/cases` | Submit a case server-side | | `POST` | `/cases/{caseId}/refill` | Manual refill trigger | ## Patient portal endpoints (customer CMS session) Base: `/api/v1/rx/portal` — authenticated with the customer's `x-cms-token` (email OTP login). | Method | Path | Purpose | | - | - | - | | `GET` | `/cases` | The customer's cases | | `GET` | `/cases/{caseId}` | One case + lifecycle timeline | | `GET` | `/cases/{caseId}/messages` | Patient ↔ care-team thread (relayed) | | `POST` | `/cases/{caseId}/messages` | Send message (text + attachments) | | `POST` | `/cases/{caseId}/identity` | Upload photo ID | ## Clinical webhooks (network → Tagada) `POST /api/public/webhooks/rx/{networkSlug}` (e.g. `/rx/mdi`) — HMAC-SHA256 signed, processed asynchronously and idempotently. **You don't consume these**; they drive the case state you read from the APIs above. *** ## Case statuses | Status | Terminal? | Rebills? | | - | - | - | | `requested` | no | no | | `submitted` | no | no | | `in_review` | no | no | | `approved` | no | no | | `shipped` | no | **yes** | | `delivered` | yes (resting) | **yes** | | `declined` | yes | no | | `cancelled` | yes | no | | `error` | yes | no | ## Case events Append-only, exposed on `GET /rx/cases/{caseId}` and the portal timeline: | Event | Status after | | - | - | | `case.requested` | `requested` | | `case.submitted` | `submitted` | | `case.in_review` | `in_review` | | `case.approved` | `approved` | | `case.declined` | `declined` | | `case.cancelled` | `cancelled` | | `case.error` | `error` | | `shipment.shipped` | `shipped` | | `shipment.delivered` | `delivered` | | `message.created` | *(no change — portal thread + patient notification)* | | `refill.requested` | *(no change — rebill cycle)* | | `affiliate.commission.accrued` | *(no change — MoR ledger)* | | `affiliate.commission.reversed` | *(no change — MoR ledger)* | *** ## Key objects at a glance | Object | Id prefix | Notes | | - | - | - | | Rx case | `rxcase_` | Non-PHI: statuses, network ids, amounts, timestamps | | Case event | — | Append-only timeline rows | | Product offering | — | The product ↔ network SKU mapping (the "requires Rx" signal) | | Affiliate terms | — | Versioned commission contract (MoR mode) | | Integration | — | `provider: tagada_rx`, gated by the setup fee | # Building blocks Source: https://docs.tagada.io/developer-tools/rx/building-blocks The decoupled Rx architecture: every storefront — Tagada-hosted template, headless site, or partner infrastructure — is a facade over the same small set of Rx bricks. # The Rx building blocks Tagada Rx is **decoupled by design**. The clinical flow is a small set of backend bricks — products, quizzes, orders, intakes, patients, cases, portal, refills — and every storefront is just a *facade* that calls them in some order. The [Tagada-hosted templates](/developer-tools/rx/storefront-templates) use the exact same bricks as a fully headless integration on your own infrastructure: nothing in the clinical layer is template-only. ```mermaid theme={null} flowchart TB subgraph FACADES["Facades (pick any — or several)"] direction LR F1["Tagada-hosted template
(Plugin SDK)"] F2["Your own site / funnel builder
(Headless SDK)"] F3["Your backend or a partner platform
(Node SDK / REST)"] end subgraph BRICKS["Rx bricks (invariant)"] direction LR B1[Products &
offerings] B2[Checkout &
orders] B3[Medical intake
questions] B4[Patients &
cases] B5[Patient
portal] B6[Refills &
ship-day rebill] end F1 --> BRICKS F2 --> BRICKS F3 --> BRICKS BRICKS --> NET["Clinical network + pharmacy
(Tagada-owned integration)"] ``` > [!NOTE] > > **Why this matters:** you can start on a hosted template today, move to a > headless build on your own funnel infrastructure next quarter, and keep the > same store, products, cases, and patient history. Switching facades is a > frontend rewrite, never a data migration. *** ## The matrix: every brick, every surface | Brick | What it is | Storefront (browser) | Server (API key) | Endpoint | | - | - | - | - | - | | **Product ↔ offering mapping** | "This product requires a prescription" — links a Tagada product to a clinical-network offering, with flags (`requiresIdVerification`, `requiresLabs`, `isDeaControlled`, `allowedStates`) | `rx.isRequiredForProduct(productId)` | `tagada.rx.setProductOffering(...)` to write it | `GET /api/public/v1/rx/required-for-product` | | **Marketing quiz** | Pre-payment qualification: vertical, goals, preferences. **Zero medical questions, zero PHI.** Lives in your storefront (template config or your own code) | Template quiz engine / your own UI — outputs product selection + tags | — (it's yours) | — | | **Checkout & order** | Standard Tagada commerce: session, payment, order, subscription | Plugin SDK `useCheckout`/`usePayment`, or Headless SDK `tagada.checkout` + `tagada.payment` | Node SDK `tagada.orders`, `tagada.subscriptions` | Standard checkout API | | **Medical intake questions** | Network-authored clinical questionnaire for a product, rendered verbatim post-payment | `rx.getQuestionsForProduct(productId)` | same via `tagada.rx` | `GET /api/public/v1/rx/questions-for-product` | | **Patient** | Identity + demographics. **Pass-through only** — transits to the clinical network, never persisted by Tagada | Part of the `submitCase` payload | Part of `tagada.rx.cases.submit` | — | | **Case** | The clinical unit of work (`rxcase_xxx`): submit → review → approve/decline → ship → deliver, with an append-only event timeline | `rx.submitCase({ orderId, checkoutToken, productId, patient, intakeAnswers })` | `tagada.rx.cases.submit / list / retrieve` | `POST /api/public/v1/rx/cases/submit` | | **Case status** | Authoritative status for the thank-you page and order tracking, proven by `(orderId, checkoutToken)` | `rx.getCasesForOrder({ orderId, checkoutToken })` — poll until terminal | `tagada.rx.cases.retrieve(caseId)` for the full timeline | `POST /api/public/v1/rx/cases/lookup` | | **Patient portal** | Case list, secure messaging, photo-ID upload. Auth = customer CMS session (email OTP) | Portal client over `/api/v1/rx/portal/*` (see [Patient portal](/developer-tools/rx/patient-portal)) | — | `/api/v1/rx/portal/*` | | **Refills & rebilling** | Ship-day rebill engine: next charge scheduled at `ship day + cycle`, automatically | — (invisible to the storefront) | `tagada.rx.cases.requestRefill(...)` for manual ops | `POST /api/v1/rx/cases/:id/refill` | | **Activation & config** | Integration lifecycle: activate, setup fee, clinical credentials, operating mode | — | `tagada.rx.requestActivation / confirmSetupFeePaid / configureBrandClinical / integrationStatus` | `/api/v1/rx/integration/*` | | **Affiliate terms** | Versioned commission contract (MoR mode); accruals post/reverse automatically | `accrualAmountMinor` returned by `submitCase` | `tagada.rx.setAffiliateTerms` (account-manager-restricted) | `/api/v1/rx/affiliate-terms` | Three auth models, one per column: * **Storefront calls** need no key — the case routes prove ownership with the `(orderId, checkoutToken)` pair your checkout already holds. * **Server calls** use a Tagada API key (`tagada.rx.*` in the [Node SDK](/developer-tools/rx/node-sdk)). * **Portal calls** ride the customer's CMS session (email OTP login). *** ## The same flow, on any facade Whatever the facade, a sale always executes the bricks in this order: ```mermaid theme={null} sequenceDiagram participant S as Storefront (any facade) participant T as Tagada participant N as Clinical network / pharmacy S->>T: required-for-product? (at product load) S->>S: marketing quiz (no PHI) S->>T: checkout + payment T-->>S: orderId + checkoutToken S->>T: questions-for-product S->>T: submitCase(patient, intakeAnswers) T->>N: create patient + case N-->>T: review / approve / ship (webhooks) S->>T: cases/lookup (poll) T->>T: schedule rebill at ship day + cycle ``` Two hard rules survive every facade: 1. **The marketing quiz and the medical intake are two different objects.** The quiz sells before payment and contains no medical questions; the network-authored intake runs after the card hold. If the clinician declines, the hold is voided — money never left the card. 2. **PHI is pass-through.** `patient` and `intakeAnswers` go from the browser through Tagada to the clinical network in one request. Never store them in your own database or queue them "for later". *** ## Funnel orchestration (Tagada-hosted facades) On Tagada infrastructure, each step of the journey is a **box in the Tagada funnel system** — a funnel step with its own `RuntimeStepConfig` (`resources`, `checkoutOffers`, `orderBumps`, `upsellOffers`, `pixels`, `paymentSetupConfig`), A/B-testable per step. The plugin manifest declares the remappable pages (`/`, `/checkout`, `/offer`, `/thank-you`) and the funnel engine drives transitions (`useFunnel().next`). Headless facades keep the same *logical* steps but orchestrate them themselves — the bricks don't care who drives navigation. See [Storefront templates](/developer-tools/rx/storefront-templates) for how the hosted templates arrange the boxes, and [With the Headless SDK](/developer-tools/rx/headless-sdk) for the self-orchestrated version. *** ## Where to go next > [card] [Storefront templates](/developer-tools/rx/storefront-templates) > > The hosted template catalog: three archetypes, one skeleton, live demos. > [card] [Headless SDK](/developer-tools/rx/headless-sdk) > > The same bricks from your own infrastructure — `tagada.rx` in the browser. > [card] [Node SDK](/developer-tools/rx/node-sdk) > > Server-side: activation, config, product mapping, case ops. > [card] [Platform partners](/developer-tools/rx/platform-partners) > > Running Rx for a fleet of merchants under your own brand. # Activate in the CRM Source: https://docs.tagada.io/developer-tools/rx/crm-activation Apply for TagadaRx, unlock the store, and map your products — from the Tagada dashboard or the API. # Activating Tagada Rx Tagada Rx is activated **per store**. On TagadaRx there is **no setup fee** — you apply, we review, and we unlock the store (invite code or your account manager). Until the store is active, case submission is rejected. Sold price on TagadaRx: **6.9% of GMV**, processing included. Clinician and pharmacy costs pass through at cost — never marked up. There is no per-prescription fee. ``` not_requested ──► pending_payment ──► active (apply) (under review / (Rx menu appears, invite unlock) cases can flow) ``` *** ## From the CRM (recommended) **1. Open the Rx page of your store** In the CRM, navigate to **your store → Tagada Rx** (`/stores/{storeId}/rx`). Before activation the page shows the activation card. **2. Pick how you run the brand** **Your brand on TagadaRx** is open now — 6.9% of GMV, $0 setup, processing and LegitScript included, min $200k GMV / month. **Standalone** (same stack, you are MoR — 4.9% + \$4,980 setup) is coming soon. **3. Apply** Click **Apply to launch on TagadaRx**. The page switches to *Application under review*. **4. Unlock** We review every application. If you already have an invite code, enter it on that page. Your account manager can also unlock the store. **5. The Rx menu appears** Once active, a **Tagada Rx** section appears in the store sidebar with six tabs: **Overview**, **Cases**, **Products**, **Storefront**, **Commission**, and **Settings**. On **Products** you make exactly two decisions per treatment — sell it or not, and your retail price; the medical questionnaire, clinician review, and pharmacy routing are pre-configured by Tagada (the questionnaire is viewable read-only from each treatment card). > [!NOTE] > > On TagadaRx, unlocking the store also provisions the Rx processing account behind the scenes — no extra onboarding on your side. *** ## Wire the clinical configuration After activation, the store needs its clinical-network configuration before cases can flow. This is done once, usually together with your account manager during onboarding: * **Network credentials** — issued by the clinical network for your brand (client id/secret, environment id, webhook secret). * **Brand clinical config** — flips from `draft` to active once credentials are verified. From the CRM this lives under **Tagada Rx → Settings**. From the API: ```ts theme={null} await tagada.rx.configureBrandClinical({ storeId: 'store_xxx', credentials: { clientId: '…', clientSecret: '…', webhookSecret: '…', externalEnvironmentId: '…', }, }); ``` *** ## Map products to treatments A product only triggers the Rx flow once it's mapped to a clinical-network **offering** (the network's SKU for a treatment): **1. CRM** **Tagada Rx → Products** → pick a product → set its **Treatment ID** (the network offering id) and the clinical requirements. **2. Or via API / Node SDK** ```ts theme={null} await tagada.rx.setProductOffering({ storeId: 'store_xxx', productId: 'product_xxx', externalOfferingId: '', requiresLabs: false, requiresIdVerification: true, isDeaControlled: false, }); ``` **3. Verify from the storefront side** ```bash theme={null} curl "https://api.tagada.io/api/public/v1/rx/required-for-product?productId=product_xxx" # → { "required": true, "requiresIdVerification": true, ... } ``` > [!WARNING] > > `isDeaControlled: true` products are **rejected at case submission in affiliate mode**. Direct mode only. *** ## Launch your storefront Once active, **Tagada Rx → Storefront** offers two paths: > [card] Use a template (fastest) > > Pick a [storefront template](/developer-tools/rx/storefront-templates) > (multi-vertical, plan-first, or quiz-first), add your logo, brand name, > colors, and subdomain — publishing **clones the plugin instance and > installs a Funnel v2** on `your-brand.tgdcare.com`. Each step (landing, > quiz, checkout, offer, thank-you, portal) shows up in the CRM funnel > builder. Your product catalog and payment flow are wired automatically. > [card] Build your own (Headless SDK) > > Build the storefront on your own stack with the > [Headless SDK](/developer-tools/rx/headless-sdk), following the > compliance directives. **The build is still deployed on your Tagada > subdomain** — LegitScript certification is tied to Tagada-hosted > domains. Deploying on your own root domain is coming soon (direct > mode). Switching templates later is safe: republishing swaps the facade on the same subdomain, same funnel, same cases and patient history. *** ## Checking the state programmatically ```ts theme={null} const status = await tagada.rx.integrationStatus('store_xxx'); // { state: 'not_requested' | 'pending_payment' | 'active', operatingMode, ... } ``` The same endpoint powers the CRM activation card, so what you see in the dashboard is exactly what the API returns. Once approved, the Rx overview shows a **Rx payments: Setting up / Ready** badge. There is no step behind it: Tagada opens the brand's payment account (affiliate mode, Tagada is merchant of record) and the badge flips to Ready when the account is live and its payment flow is bound. Read it with `tagada.rx.activationStatus('store_xxx')` (`payments`), or from a storefront with the Headless SDK `tagada.rx.getActivationStatus()`. The **Card statement name** card on the storefront page is where the brand enters the `` part of `TGDCARE*`. Tagada staff approve or reject it from the same card; until it is approved, statements show a line built from the store name. *** ## Full activation via API only Everything above the CRM does is available on the merchant API — useful for partners provisioning many brands: | Step | Endpoint | Node SDK | | - | - | - | | Request activation | `POST /api/v1/rx/integration/activate` | `tagada.rx.requestActivation()` | | Confirm setup fee (admin) | `POST /api/v1/rx/integration/confirm-setup-fee` | `tagada.rx.confirmSetupFeePaid()` | | Clinical config | `POST /api/v1/rx/brand-clinical-config` | `tagada.rx.configureBrandClinical()` | | Product mapping | `POST /api/v1/rx/product-offerings` | `tagada.rx.setProductOffering()` | | Status | `GET /api/v1/rx/integration/status` | `tagada.rx.integrationStatus()` | | Activation + payments status | `GET /api/v1/rx/activation-status` | `tagada.rx.activationStatus()` | | Statement descriptor | `POST /api/v1/rx/statement-descriptor` | `tagada.rx.setStatementDescriptor()` | | Available networks | `GET /api/v1/rx/networks` | `tagada.rx.listNetworks()` | # With the Headless SDK Source: https://docs.tagada.io/developer-tools/rx/headless-sdk Add the Rx clinical flow to any external site — React, Vue, plain HTML, or AI-generated — with tagada.rx. # Tagada Rx with the Headless SDK Running your storefront on your own hosting (Vercel, Netlify, Shopify headless, an AI-generated site)? The [Headless SDK](/developer-tools/headless-sdk/introduction) ships a first-class **`tagada.rx`** module that mirrors the public storefront endpoints — no API key in the browser, ever. ```bash theme={null} npm install @tagadapay/headless-sdk ``` ```ts theme={null} import { createHeadlessClient } from '@tagadapay/headless-sdk'; const tagada = createHeadlessClient({ storeId: 'store_xxx' }); // tagada.rx is ready — no extra config ``` > [!NOTE] > > **Auth model:** there is no key. `isRequiredForProduct` is public; the case routes prove ownership with the `(orderId, checkoutToken)` pair your checkout flow already holds. PHI transits to the clinical network and is never persisted by Tagada. > [!WARNING] > > **Hosting rule in affiliate (MoR) mode:** you build headless on your own > stack, but the resulting storefront must be **deployed on your Tagada > subdomain** (`your-brand.tgdcare.com`) — LegitScript certification is tied > to Tagada-hosted domains. Reserve the subdomain in the CRM storefront > wizard, then work with your account manager to wire the deploy of your > build onto it. Serving the storefront from your own root domain is a > direct-mode capability — **coming soon**. *** ## The calls ### 1. Is this an Rx product? ```ts theme={null} const check = await tagada.rx.isRequiredForProduct(productId); if (check.required) { // Rx product: check the patient before payment (step 2), // then show the network questionnaire after payment (step 3) // check.requiresIdVerification → plan for photo-ID upload post-purchase // check.requiresLabs → surface lab expectations in the copy } ``` ### 2. Check the patient before payment The clinical network only accepts US patients: an address in one of the 50 states or DC, a US phone number, a 5 digit ZIP, an adult. Check it before taking the payment, so a card is never held for a patient who cannot be treated: ```ts theme={null} const pre = await tagada.rx.validateIntake({ productId, patient: { phone: '+1 512 555 0100', dateOfBirth: '1990-04-12', // YYYY-MM-DD sexAtBirth: 'female', address: { state: 'TX', zip: '78701', country: 'US' }, }, }); if (!pre.valid) showErrors(pre.issues); // [{ field: 'patient.phone', message: '…' }] ``` ### 3. Show the network questionnaire, then submit Run your normal headless checkout (`tagada.checkout` + `tagada.payment`). Once the order is paid, render the questionnaire written by the clinical network **as is**: it includes the questions the clinician needs on the patient profile (height, weight, allergies, medications, conditions, pregnancy). Two helpers make it plug and play: * `isQuestionActive(question, answers, { state, sexAtBirth })` tells you which questions to show right now (hidden clinician questions never, "Drug Allergies" only after "Yes", pregnancy only for women, state rules). * `toIntakeAnswers(questions, answers, context)` builds the `intakeAnswers` to send. ```ts theme={null} import { isQuestionActive, toIntakeAnswers } from '@tagadapay/headless-sdk'; const { questions } = await tagada.rx.getQuestionsForProduct(productId, variantId); const ctx = { state: patient.address.state, sexAtBirth: patient.sexAtBirth }; const visible = questions.filter((q) => isQuestionActive(q, answers, ctx)); // re-run on every answer // answers: Record, one per visible question. // select / multiselect: only the option values offered. const result = await tagada.rx.submitCase({ orderId, // from the paid order checkoutToken, // from your checkout session productId, patient: { firstName: 'Jane', lastName: 'Doe', email: 'jane@example.com', phone: '+1 512 555 0100', dateOfBirth: '1990-04-12', sexAtBirth: 'female', address: { line1: '1 Main St', city: 'Austin', state: 'TX', zip: '78701', country: 'US' }, }, intakeAnswers: toIntakeAnswers(questions, answers, ctx), }); // result.rxCaseId → 'rxcase_xxx' // result.status → 'submitted' // result.accrualAmountMinor → your commission (affiliate mode; 0 in direct mode) ``` > [!NOTE] > > The server enforces these rules on every submit, whatever the integration. A patient or intake that does not > meet them fails with **422** and the list of fields to fix; nothing reaches the clinician and the same order > can be resubmitted. `validateIntake` with `intakeAnswers` returns the same list before you submit. > Never replace the network questionnaire with your own quiz: an empty `questions` list means the product has none. > [!WARNING] > > Submit **synchronously after payment, from the browser**. Do not stash `patient` / `intakeAnswers` in your own database or queue "for later" — that would make *you* a PHI processor. If the call fails, keep the data in memory and offer a retry button. ### 4. Poll status on the thank-you page ```ts theme={null} const { cases } = await tagada.rx.getCasesForOrder({ orderId, checkoutToken }); const status = cases[0]?.status; // 'submitted' → "Sent to a licensed clinician" // 'in_review' → "A clinician is reviewing your information" // 'approved' → "Approved — preparing your shipment" // 'shipped' → "On its way" (lastShipmentShippedAt is set) ``` Poll every \~10 seconds while the tab is open; the statuses come from the processed clinical webhooks, so they're authoritative. ### Resume an unfinished intake The patient paid (card on hold) but closed the tab before sending the questionnaire, or opens the "finish your consultation" email link (`/thank-you?orderId=…&checkoutToken=…&resume=1`) on another device. Your checkout data is gone; the order still holds the basics: ```ts theme={null} const ctx = await tagada.rx.getIntakeContext({ orderId, checkoutToken }); if (ctx.caseExists) { // A case is already in: show its status (getCasesForOrder). } else { // ctx.productId, ctx.variantId: the Rx line of the order. // ctx.patient: name, email, phone, shipping address (prefill these). // Ask again: date of birth, sex at birth (never returned), a US phone if missing, // and confirm the patient lives in the shipping state. Then step 3 as usual. } ``` A wrong `checkoutToken` (or an unknown order) fails with **401**, an order without an Rx line with **404**. Tagada emails the patient a resume link 30 minutes after the hold, one reminder after 24 hours, and releases the hold after 5 days if no case was submitted. ### Before checkout: are Rx payments ready? ```ts theme={null} const status = await tagada.rx.getActivationStatus(); // defaults to the client's storeId if (status.payments === 'setting_up') { // Tagada is still opening the brand's payment account. Show // "Payments are being set up" instead of the pay button. } // status.steps → [{ key: 'application' | 'approval' | 'statement_descriptor' | 'storefront', done }] // status.missing → e.g. ['storefront'] // status.descriptorStatus → 'none' | 'pending' | 'approved' | 'rejected' ``` `payments` is `'ready'` once the brand's Rx payment account is live and its payment flow is bound. It is a status, not a step: the brand has nothing to do while it reads `'setting_up'`. An Rx checkout attempted before that is refused server-side with "Payments for this treatment are being set up". This public call leaves out payout verification and partner contract items; the Node SDK `rx.activationStatus()` returns them. Available since `@tagadapay/headless-sdk` 1.16.0. *** ## Full example: React thank-you page ```tsx theme={null} function RxStatus({ orderId, checkoutToken }: Props) { const [status, setStatus] = useState(null); useEffect(() => { const tick = async () => { const { cases } = await tagada.rx.getCasesForOrder({ orderId, checkoutToken }); if (cases[0]) setStatus(cases[0].status); }; tick(); const id = setInterval(tick, 10_000); return () => clearInterval(id); }, [orderId, checkoutToken]); const copy: Record = { submitted: 'Your information was sent to a licensed clinician.', in_review: 'A clinician is reviewing your information.', approved: 'Approved! Your treatment is being prepared.', shipped: 'Your treatment is on its way.', declined: 'A clinician determined this treatment isn’t right for you — the hold on your card has been released.', }; return

{status ? copy[status] ?? status : 'Submitting…'}

; } ``` *** ## Install the same Funnel v2 (CRM canvas) A headless build still needs the six-step Funnel v2 so operators see landing, quiz, checkout, offer, thank-you, and portal in the CRM. Create it with the [Node SDK](/developer-tools/rx/node-sdk) (API key, server-side) — the browser SDK only runs the bricks. Working example: [`rx-storefront/`](https://github.com/TagadaPay/examples/tree/main/rx-storefront) in [tagada-examples](https://github.com/TagadaPay/examples). `pnpm seed` calls `tagada.funnels.create` with this graph; you can also import [`funnel.bundle.json`](https://github.com/TagadaPay/examples/blob/main/rx-storefront/funnel.bundle.json) from **Funnels → Import bundle**. ```ts theme={null} import { Tagada } from '@tagadapay/node-sdk'; const tagada = new Tagada(process.env.TAGADA_API_KEY!); await tagada.funnels.create({ storeId: 'store_xxx', isDefault: true, config: { id: 'rx-storefront', name: 'Harbor Clinic storefront', version: '1.0.0', metadata: { rxStorefront: true }, nodes: [ { id: 'rx_landing', name: 'Landing', kind: 'step', type: 'landing', isEntry: true, isDefault: true, position: { x: 0, y: 0 }, config: { path: '/' } }, { id: 'rx_quiz', name: 'Marketing quiz', kind: 'step', type: 'custom', position: { x: 280, y: 0 }, config: { path: '/quiz', matchSubPaths: true } }, { id: 'rx_checkout', name: 'Checkout', kind: 'step', type: 'checkout', position: { x: 560, y: 0 }, config: { path: '/checkout' } }, { id: 'rx_offer', name: 'Offer', kind: 'step', type: 'offer', position: { x: 840, y: 0 }, config: { path: '/offer' } }, { id: 'rx_thankyou', name: 'Thank you', kind: 'step', type: 'thankyou', isConversion: true, position: { x: 1120, y: 0 }, config: { path: '/thank-you' } }, { id: 'rx_portal', name: 'Patient portal', kind: 'step', type: 'custom', position: { x: 1400, y: 0 }, config: { path: '/portal', matchSubPaths: true } }, ], edges: [ { id: 'edge_rx_landing_quiz', source: 'rx_landing', target: 'rx_quiz' }, { id: 'edge_rx_quiz_checkout', source: 'rx_quiz', target: 'rx_checkout' }, { id: 'edge_rx_checkout_offer', source: 'rx_checkout', target: 'rx_offer', conditions: { when: 'payment.success' } }, { id: 'edge_rx_offer_thankyou', source: 'rx_offer', target: 'rx_thankyou' }, { id: 'edge_rx_thankyou_portal', source: 'rx_thankyou', target: 'rx_portal' }, ], }, }); ``` Your router must serve those exact paths. Medical intake stays on `/thank-you` **after** payment (`getQuestionsForProduct` → `submitCase` → poll). The marketing quiz on `/quiz` has no medical questions. > [!WARNING] > > Reserve `your-brand.tgdcare.com` in the CRM, then deploy this build onto > that subdomain (LegitScript). Own root domain is coming soon (direct mode). ## What the headless module does *not* cover | Need | Where it lives | | - | - | | Creating the Funnel v2 graph | Node SDK `tagada.funnels.create` — see above, or the [rx-storefront example](https://github.com/TagadaPay/examples/tree/main/rx-storefront) | | Patient portal (messaging, ID upload) | Portal endpoints with a customer CMS session — see [Patient portal](/developer-tools/rx/patient-portal) | | Activation, product mapping, ops | Server-side — [Node SDK](/developer-tools/rx/node-sdk) | | A hosted storefront on Tagada infra | [Plugin SDK](/developer-tools/rx/plugin-sdk) | # How it works Source: https://docs.tagada.io/developer-tools/rx/how-it-works Architecture, PHI handling, clinical webhooks, and the ship-day rebill engine — the Tagada Rx mental model. # How Tagada Rx works One page, four concepts: the **clinical network adapter**, the **PHI transit rule**, the **webhook pipeline**, and the **ship-day rebill engine**. Understand these and everything else in this section is just API calls. *** ## 1. The clinical network adapter Tagada does not run doctors. It integrates **clinical networks** — companies that operate licensed provider groups and pharmacy routing. Every network is wrapped behind one adapter interface, so your integration code never changes when the network does. ``` Your storefront ──► Tagada Rx API ──► Clinical network adapter ──► Network (MDI, …) │ └── rx_cases / rx_case_events (non-PHI only) ``` | What the adapter does | Example | | - | - | | Create patient + case from an intake | `rx.submitCase()` → network case `837858f1-…` | | Normalize webhooks into canonical events | `case_approved` → `case.approved` | | Relay patient ↔ care-team messages | portal thread | | Attach identity documents | driver-license upload | | Request refills | ship-day rebill cycle | The active network is configured per store (`clinicalNetworkSlug`, default `mdi`). You can list what's available to your account with `GET /api/v1/rx/networks`. *** ## 2. PHI: transit, never storage The single most important design rule: > [!WARNING] > > **Tagada never persists PHI.** Patient identity (name, DOB, address) and intake answers pass through the API to the clinical network in a single request and are not written to any Tagada table, queue, or log. What Tagada stores is routing data only: `rxcase_xxx`, the network's case id and patient id, statuses, timestamps, and non-PHI event metadata. Practical consequences: * **Case submission is synchronous** — there is no "queue the intake and retry later", because PHI must not sit in a queue. If the network is down, the storefront shows a retry UI. * **Message bodies live at the network.** The patient portal relays threads directly from the clinical network; Tagada records only that a `message.created` event happened. * **Emails are content-free.** "You have a new message from your care team" + a portal deep-link. Never the message text. *** ## 3. The webhook pipeline The clinical network notifies Tagada of everything that happens after submission: ``` Network ──POST──► /api/public/webhooks/rx/{networkSlug} (e.g. /rx/mdi) │ 1. resolve network + integration row │ 2. verify HMAC-SHA256 signature │ 3. normalize to canonical events ▼ Inngest (async, retried, idempotent) │ ├─ case.in_review / approved / declined … → status transition ├─ shipment.shipped → tracking + schedule next rebill ├─ shipment.delivered → resting state └─ message.created → portal thread event + patient email ``` Key properties: * **Signature-verified** — HMAC-SHA256 over the raw body, checked against the integration's `webhookSecret` before anything is processed. * **Fast ACK** — the receiver verifies, normalizes, enqueues, and returns `200`. All database work happens asynchronously with retries. * **Idempotent** — every event carries a synthesized `externalEventId`; duplicates are dropped at both the queue and the append-only event log. * **Patient-scoped fallback** — message webhooks may arrive without a case id; Tagada resolves the case through the stored network patient id. Your storefront never consumes these webhooks directly — it polls the public case-lookup endpoint or reads the portal API, both of which reflect the processed state. *** ## 4. The ship-day rebill engine Classic subscription engines charge every N days from signup — which drifts from what the pharmacy actually does. Tagada Rx anchors billing to **fulfillment**: **1. Pharmacy ships** The `shipment.shipped` webhook lands. Tagada records the tracking number and stamps `lastShipmentShippedAt`. **2. Next charge is scheduled** `scheduledNextChargeAt = ship day + cycle` (default **30 days**, configurable per offering). **3. Hourly scan** A cron scans cases whose `scheduledNextChargeAt` is due **and** whose status is `shipped` or `delivered` — i.e. active subscribers only. **4. Refill fires** The rebill charges the stored payment instrument and requests the refill from the network. On the next shipment, the loop repeats. > [!NOTE] > > Declined, cancelled, and errored cases never rebill. If a clinician declines mid-subscription, the commission accrued in affiliate mode is automatically reversed (see [Operating modes](/developer-tools/rx/operating-modes)). *** ## Product mapping: what makes a product "Rx" There is no flag on the product itself. A product requires a prescription when it has an **active offering mapping**: ``` Tagada product (product_xxx) ──► rx_product_offerings ──► network offering / SKU ``` Each mapping carries the clinical requirements the storefront needs to render the right flow: | Field | Meaning | | - | - | | `externalOfferingId` | The network's SKU for this treatment | | `requiresLabs` | Lab work needed before prescribing | | `requiresIdVerification` | Photo ID must be uploaded (portal handles it) | | `isDeaControlled` | Controlled substance — **blocked in affiliate mode** | Storefronts ask at product load: `GET /api/public/v1/rx/required-for-product?productId=…` → `{ required, requiresLabs, requiresIdVerification, … }`, and only render the intake when `required` is true. *** ## Next > [card] [Operating modes](/developer-tools/rx/operating-modes) > > MoR (affiliate) vs Direct Merchant. > [card] [End-to-end tutorial](/developer-tools/rx/tutorial) > > Build the whole flow in an afternoon. # Tagada Rx — Overview Source: https://docs.tagada.io/developer-tools/rx/introduction The telehealth layer of the Tagada OS: intake, clinician review, e-prescribing, pharmacy fulfillment, and ship-day rebilling — orchestrated on top of your Tagada store. # Tagada Rx > [!NOTE] > > **Who this is for** — Brands selling prescription-based treatments online (weight management, hair loss, skin care, hormones…). Tagada Rx turns a regular Tagada store into an **asynchronous telemedicine pharmacy**: the patient answers a medical intake, pays, a licensed clinician reviews the case, a partner pharmacy ships the treatment, and the subscription rebills on the day the pharmacy actually ships. > > Tagada Rx is an **opt-in add-on** — activated per store. On TagadaRx the sold price is **6.9% of GMV** (processing included), with **\$0 setup**. Clinician and pharmacy costs pass through at cost. See [Activation](/developer-tools/rx/crm-activation). *** ## What is Tagada Rx? Everything you already know from Tagada — products, checkout, payments, subscriptions, CRM — plus a **clinical layer**: > [card] Clinical network > > A pre-integrated network of US-licensed clinicians (all 50 states). Tagada submits patient intakes as **cases**; clinicians review asynchronously, approve or decline, and e-prescribe. > [card] Pharmacy fulfillment > > Approved prescriptions are routed to a partner pharmacy. Shipment and delivery events flow back into your Tagada order timeline automatically. > [card] Ship-day rebilling > > Recurring treatments rebill **the day the pharmacy ships** — not on an arbitrary calendar date. No "charged but never shipped" revenue. > [card] Patient portal > > A ready-made patient area: case timeline, secure messaging with the care team, and photo-ID upload for identity verification. > [!NOTE] > > **PHI never touches Tagada storage.** Patient identity and intake answers transit through the API straight to the clinical network. Tagada persists only non-PHI routing data: case ids, statuses, timestamps, and event metadata. *** ## How a sale works, end to end ``` Patient Tagada Clinical network / Pharmacy │ │ │ │ 1. Quiz + checkout │ │ ├──────────────────────────►│ card authorized (hold) │ │ │ │ │ 2. thank-you intake + │ 3. create patient + case │ │ rx.submitCase() │ │ ├──────────────────────────►├─────────────────────────────►│ │ │ │ 4. clinician reviews │ │◄─────────────────────────────┤ (webhooks) │ "Approved!" email │ approve → capture hold │ │◄──────────────────────────┤ decline → void hold │ │ │ │ 5. pharmacy ships │ │◄─────────────────────────────┤ (webhook) │ tracking email │ shipment.shipped │ │◄──────────────────────────┤ → schedule rebill at │ │ │ ship day + cycle │ │ │ │ │ 6. next cycle: rebill fires on the actual ship day │ ``` 1. **Checkout first, clinical second.** The patient completes a marketing quiz (no PHI) and authorizes a card hold. The hold is *not* clinical approval — the storefront copy must make that clear. 2. **Case submission.** On the thank-you page the storefront collects the network questionnaire and calls `rx.submitCase()` with the patient identity and intake answers. Tagada forwards everything to the clinical network and records a case (`rxcase_xxx`). 3. **Clinician review.** A licensed provider in the patient's state reviews asynchronously. Approval, decline, prescription, shipment, and delivery all arrive as **webhooks** which Tagada normalizes into case events. 4. **Capture or void — never a refund.** Approve captures the hold. Decline voids it. Money never leaves the card if the clinician does not prescribe. 5. **Recurring refills.** On every shipment, Tagada schedules the next charge at `ship day + cycle` (30 days by default). An hourly job scans due cases and fires the rebill. *** ## The case lifecycle Every clinical case (`rxcase_xxx`) moves through a strict state machine: ``` requested → submitted → in_review → approved → shipped → delivered │ │ │ └── declined ┘ │ └── cancelled ──────────┘ (error: from any non-terminal state) ``` | Status | Meaning | | - | - | | `requested` | Case created locally, not yet accepted by the network | | `submitted` | Intake accepted by the clinical network | | `in_review` | A clinician has the case | | `approved` | Prescription issued | | `shipped` | Pharmacy shipped (tracking attached, rebill scheduled) | | `delivered` | Carrier delivered — resting state of an active subscriber | | `declined` / `cancelled` / `error` | Terminal states | Each transition is recorded as an append-only **case event** (`case.approved`, `shipment.shipped`, `message.created`, …) that you can read from the API, the CRM, or the patient portal timeline. *** ## The three integration surfaces | Surface | Auth | Use it for | | - | - | - | | **Storefront API** — `/api/public/v1/rx/*` | No API key — per-resource proof (`orderId` + `checkoutToken`) | Submitting cases and polling status from the browser | | **Merchant API** — `/api/v1/rx/*` | Tagada API key (Node SDK: `tagada.rx.*`) | Activation, config, product mapping, listing cases, ops | | **Patient portal API** — `/api/v1/rx/portal/*` | Customer CMS session (email OTP) | Patient case list, messaging, photo-ID upload | You never talk to the clinical network directly — Tagada owns that integration, its credentials, and its webhooks. *** ## Choose your track > [card] [How it works (deep dive)](/developer-tools/rx/how-it-works) > > Architecture, PHI handling, webhooks, rebilling — the mental model in one page. > [card] [Operating modes](/developer-tools/rx/operating-modes) > > Merchant of Record (affiliate) vs Direct Merchant — who is the seller, who pays whom. > [card] [Activate in the CRM](/developer-tools/rx/crm-activation) > > Request activation, pay the setup fee, map your products. > [card] [End-to-end tutorial](/developer-tools/rx/tutorial) > > From empty store to first prescription — the complete flow, step by step. > [card] [Building blocks](/developer-tools/rx/building-blocks) > > The decoupled architecture: every storefront is a facade over the same Rx bricks. > [card] [Storefront templates](/developer-tools/rx/storefront-templates) > > Three funnel archetypes, one skeleton — with live demos. # With the Node SDK Source: https://docs.tagada.io/developer-tools/rx/node-sdk Server-side Rx operations: activation, clinical config, product mapping, case listing, and refills with tagada.rx. # Tagada Rx with the Node SDK The [Node SDK](/developer-tools/node-sdk/quick-start) exposes the whole **merchant-side** Rx surface under `tagada.rx.*`. Use it from your backend, ops scripts, or partner provisioning flows — anywhere you hold a Tagada API key. ```bash theme={null} npm install @tagadapay/node-sdk ``` ```ts theme={null} import { Tagada } from '@tagadapay/node-sdk'; const tagada = new Tagada(process.env.TAGADA_API_KEY!); ``` > [!NOTE] > > The Node SDK maps 1:1 onto the REST endpoints under `/api/v1/rx/*`, so everything here is also available as plain HTTP with `Authorization: Bearer `. *** ## Setup & configuration ```ts theme={null} // 1. Activate the integration (creates the pending setup-fee state) await tagada.rx.requestActivation({ storeId: 'store_xxx', clinicalNetworkSlug: 'mdi', operatingMode: 'affiliate', // or 'direct' — see Operating modes }); // 2. After the setup fee is captured (billing does this in prod; // admins can force it in sandbox): await tagada.rx.confirmSetupFeePaid({ storeId: 'store_xxx' }); // 3. Wire the clinical-network credentials for your brand await tagada.rx.configureBrandClinical({ storeId: 'store_xxx', credentials: { clientId: '…', clientSecret: '…', webhookSecret: '…', externalEnvironmentId: '…', }, }); // 4. Map products to network offerings ("this product requires Rx") await tagada.rx.setProductOffering({ storeId: 'store_xxx', productId: 'product_xxx', externalOfferingId: '', requiresIdVerification: true, }); ``` Check where you stand at any point: ```ts theme={null} const status = await tagada.rx.integrationStatus('store_xxx'); // { state: 'not_requested' | 'pending_payment' | 'active', ... } const networks = await tagada.rx.listNetworks(); const brand = await tagada.rx.getBrandConfig('store_xxx'); // Steps, missing items and whether Rx payments are ready const activation = await tagada.rx.activationStatus('store_xxx'); // { state: 'active', payments: 'setting_up' | 'ready', // missing: ['payout_kyc', 'statement_descriptor', ...], steps: [...] } ``` ### Statement descriptor In affiliate mode Tagada is the merchant of record, so the cardholder line is `TGDCARE*`. The brand chooses `` (A-Z, 0-9 and spaces, 14 characters max; accents are folded, other characters dropped) and Tagada reviews it. Until it is approved, statements show a line built from the store name. ```ts theme={null} await tagada.rx.setStatementDescriptor({ storeId: 'store_xxx', descriptor: 'Prime Rx' }); const d = await tagada.rx.getStatementDescriptor('store_xxx'); // { descriptor: 'PRIME RX', status: 'pending', preview: 'TGDCARE*PRIME RX', ... } ``` A rejected descriptor comes back with `status: 'rejected'` and a `rejectionReason`; submit a new one. *** ## Working with cases ```ts theme={null} // List cases for a store (filterable, paginated) const { cases } = await tagada.rx.cases.list({ storeId: 'store_xxx' }); // One case + its full append-only event timeline const detail = await tagada.rx.cases.retrieve('rxcase_xxx'); detail.events.forEach((e) => { console.log(e.eventType, e.statusAfter, e.postedAt); // case.submitted submitted 2026-07-16T22:01:11Z // case.in_review in_review 2026-07-16T22:16:31Z // case.approved approved 2026-07-16T23:02:05Z // shipment.shipped shipped 2026-07-17T14:30:00Z }); ``` You can also submit cases server-side (e.g. from a custom backend that already collected the intake) — but remember the PHI rule: pass it through, never store it: ```ts theme={null} const result = await tagada.rx.cases.submit({ orderId: 'order_xxx', productId: 'product_xxx', patient: { /* US address in the 50 states or DC, US phone, 5 digit ZIP, adult */ }, // One answer per question of the network questionnaire the patient saw, // keyed by the question title (see questions-for-product). intakeAnswers: [ { questionId: 'Do you have any drug allergies or intolerances?', value: 'No - No known drug allergies' }, // … ], }); ``` The same rules apply as from the browser: a patient or intake that does not meet the clinical network rules fails with **422** and the list of fields to fix, and nothing reaches the clinician. Check first with `POST /api/public/v1/rx/intake/validate` (see [Headless SDK](/developer-tools/rx/headless-sdk)); the headless SDK helpers `isQuestionActive` and `toIntakeAnswers` also run on Node. *** ## Refills Refills normally run themselves (ship-day rebill engine, see [How it works](/developer-tools/rx/how-it-works#4-the-ship-day-rebill-engine)). Trigger one manually when support needs it: ```ts theme={null} await tagada.rx.cases.requestRefill({ caseId: 'rxcase_xxx' }); ``` Only cases in `shipped` or `delivered` are refill-eligible. *** ## Affiliate terms (MoR mode) ```ts theme={null} // Read the active commission terms (rides along the brand config) const brand = await tagada.rx.getBrandConfig('store_xxx'); // Setting terms is account-manager-restricted: await tagada.rx.setAffiliateTerms({ storeId: 'store_xxx', basis: 'order_subtotal_bps', // or 'order_net_bps' | 'flat_per_case_minor' value: 1500, // 15% }); ``` Accruals post automatically at case submission and reverse automatically on clinician decline — there is nothing to call. *** ## Install the storefront Funnel v2 `tagada.rx.*` is the clinical surface. The **canvas** operators see in the CRM is a regular Funnel v2. After you activate Rx (or when you seed a headless store), create the same six-step graph the hosted templates get on publish: ```ts theme={null} await tagada.funnels.create({ storeId, isDefault: true, config: { id: 'rx-storefront', name: `${brandName} storefront`, /* nodes + edges */ }, }); ``` Copy the full graph from [With the Headless SDK](/developer-tools/rx/headless-sdk#install-the-same-funnel-v2-crm-canvas) or run the [rx-storefront example](https://github.com/TagadaPay/examples/tree/main/rx-storefront) (`pnpm seed` calls `funnels.create` and writes `funnel.bundle.json` for **Funnels → Import bundle**). *** ## Method reference | Method | What it does | | - | - | | `tagada.rx.requestActivation(input)` | Start activation (creates pending setup fee) | | `tagada.rx.confirmSetupFeePaid(input)` | Flip to active after the fee is captured | | `tagada.rx.configureBrandClinical(input)` | Wire clinical-network credentials | | `tagada.rx.integrationStatus(storeId)` | `not_requested` / `pending_payment` / `active` | | `tagada.rx.activationStatus(storeId)` | Steps, missing items, `payments: 'setting_up' \| 'ready'` (3.24.0+) | | `tagada.rx.getStatementDescriptor(storeId)` | Brand statement descriptor + review state (3.24.0+) | | `tagada.rx.setStatementDescriptor(input)` | Submit the brand descriptor for Tagada review (3.24.0+) | | `tagada.rx.listNetworks()` | Clinical networks available to the account | | `tagada.rx.getBrandConfig(storeId)` | Brand clinical config + terms | | `tagada.rx.setAffiliateTerms(input)` | Version new commission terms (AM only) | | `tagada.rx.setProductOffering(input)` | Map product ↔ network offering | | `tagada.rx.cases.list(params)` | List cases | | `tagada.rx.cases.retrieve(caseId)` | Case + event timeline | | `tagada.rx.cases.submit(input)` | Submit a case (PHI pass-through) | | `tagada.rx.cases.requestRefill(input)` | Manual refill trigger | # Operating modes Source: https://docs.tagada.io/developer-tools/rx/operating-modes Merchant of Record (affiliate) vs Direct Merchant — who sells, who processes, who owns compliance, and how commissions flow. # Operating modes Tagada Rx runs in one of two modes, chosen **per store at activation time** (`operatingMode`). They answer one question differently: **who is the merchant on the patient's card statement?** > [card] Merchant of Record — `affiliate` > > **Tagada carries the regulated relationship.** Your brand runs on TagadaRx infrastructure (LegitScript, clinical network, pharmacy). You keep 100% of your e-commerce margin — Tagada charges **6.9% of GMV** (processing included). Clinician and pharmacy costs pass through at cost. > [card] Direct Merchant — `direct` > > **You are the merchant.** Same stack, your own LegitScript and rails. Coming soon at **4.9% of GMV** (processing included) plus a \$4,980 setup. Clinician and pharmacy costs pass through at cost. *** ## Side by side | | Merchant of Record (`affiliate`) | Direct Merchant (`direct`) | | - | - | - | | Seller of record | Tagada | Your company | | Payment processing | Tagada's Rx processing stack | Your MIDs on TagadaPay | | Card statement | Tagada marketplace descriptor | Your descriptor | | Storefront hosting | Subdomain on the marketplace domain (e.g. `yourbrand.tgdcare.com`) or your own | Your own domain | | LegitScript / compliance | Carried by Tagada | Your responsibility (we assist) | | Your revenue | Full order revenue minus 6.9% of GMV | Full order revenue minus 4.9% of GMV | | Chargebacks & refunds | Tagada's book | Your book | | DEA-controlled products | **Not allowed** | Allowed where compliant | | Time to launch | Days (no merchant onboarding) | Depends on your KYB / MID setup | > [!TIP] > > **Rule of thumb:** start in **affiliate** mode to validate a vertical with zero payment/compliance setup, then graduate to **direct** mode once volume justifies owning the merchant relationship. The storefront code is identical in both modes — switching is a backend concern. *** ## How affiliate commissions work (legacy) > [!NOTE] > > New stores have **no commission terms**: you keep the residual after Tagada's 6.9% take (processing included) and medical pass-through at cost. The affiliate ledger below only applies to legacy marketplace agreements that pre-date this pricing. In legacy marketplace agreements, economics are defined by **affiliate terms** — a versioned contract stored on the store and managed by your Tagada account manager: | Basis | Meaning | Example | | - | - | - | | `order_subtotal_bps` | Basis points of the order subtotal | 1500 bps = 15% of subtotal | | `order_net_bps` | Basis points of the net (after discounts) | 1200 bps = 12% of net | | `flat_per_case_minor` | Flat amount per case, in minor units | `2500` = \$25.00 per case | The lifecycle is automatic: **1. Accrual at submission** When a case is successfully submitted to the clinical network, the commission is computed and posted to your affiliate ledger (double-entry, idempotent per case). The amount is returned in the `rx.submitCase()` response as `accrualAmountMinor`. **2. Reversal on decline** If the clinician declines the case, the accrual is automatically reversed — you're never paid for care that didn't happen. **3. Payout** Accrued commissions are settled to you on the agreed payout schedule. You can read your current terms with `GET /api/v1/rx/brand` (they ride along the brand config) and see the per-case accrual on every case detail. Terms are **write-restricted to account managers** — contact yours to negotiate changes. > [!WARNING] > > **Compliance guardrail:** in affiliate mode, products flagged `isDeaControlled` are rejected at case submission. If your catalog needs controlled substances, you must run in `direct` mode. *** ## How direct mode works Direct mode is regular TagadaPay economics plus the Rx orchestration layer: * Orders settle to **your** processing accounts, with the full multi-MID routing, cascade, and rebill engine you already know. * The clinical network and pharmacy fees pass through at network rates. * You own the storefront domain, the brand, the customer relationship, and the regulatory posture (LegitScript certification, state rules). Tagada assists with the LegitScript application as part of onboarding. There is no commission ledger in direct mode — `rx.submitCase()` returns `accrualAmountMinor: 0`. *** ## Choosing at activation The mode is passed when you request activation and cannot be changed silently afterwards (it defines the processing setup): ```ts theme={null} await tagada.rx.requestActivation({ storeId: 'store_xxx', clinicalNetworkSlug: 'mdi', operatingMode: 'affiliate', // or 'direct' }); ``` In the CRM the same choice appears as **"Marketplace — Tagada is merchant of record"** vs **"Direct — you are the merchant"** on the activation card. See [Activate in the CRM](/developer-tools/rx/crm-activation). # Patient portal & messaging Source: https://docs.tagada.io/developer-tools/rx/patient-portal OTP login, case timeline, secure patient↔care-team messaging, and photo-ID upload — the patient-facing half of Tagada Rx. # Patient portal & messaging After purchase, patients need three things: **see where their treatment stands**, **talk to their care team**, and (for some offerings) **verify their identity**. Tagada Rx ships all three as portal endpoints your storefront can skin however it likes — the Oakwell template's `/portal` page is a full reference implementation. > [!NOTE] > > **Auth model:** portal routes are scoped to the **customer**, not the merchant. The patient logs in with an **email OTP** which creates a CMS session; every portal call carries that session token (`x-cms-token`). With the Plugin SDK this is automatic once the customer has logged in via `useLogin` — no extra wiring. *** ## The endpoints All under `/api/v1/rx/portal/*`, CMS-session authenticated: | Endpoint | What it returns | | - | - | | `GET /rx/portal/cases` | The customer's cases (status, product, amounts, `canMessage`) | | `GET /rx/portal/cases/{caseId}` | One case + its lifecycle timeline (`events`) | | `GET /rx/portal/cases/{caseId}/messages` | The patient ↔ care-team thread, relayed live from the clinical network | | `POST /rx/portal/cases/{caseId}/messages` | Send a patient message (text + optional attachments) | | `POST /rx/portal/cases/{caseId}/identity` | Upload a photo ID for identity verification | Access control is strict: a case is only visible if it belongs to the authenticated customer, and messaging requires the case to have a linked network patient (`canMessage: true`). *** ## Messaging The thread is **relayed** from the clinical network — Tagada stores no message bodies (PHI transit rule). Messages carry an author so you can style the bubbles: ```json theme={null} { "messages": [ { "externalMessageId": "msg_…", "channel": "patient", "author": "clinician", "authorName": "Dr. Smith", "text": "Hi Jane — your dosage looks right. Any side effects?", "files": [], "createdAt": "2026-07-16T22:30:00Z" } ] } ``` Sending, with optional attachments (images, documents, audio, video — base64-encoded): ```json theme={null} POST /api/v1/rx/portal/cases/rxcase_xxx/messages { "text": "Here's the photo you asked for.", "attachments": [ { "filename": "arm.jpg", "mimeType": "image/jpeg", "contentBase64": "…" } ] } ``` ### Notifications When the **care team** writes (clinician or support — patient-authored messages are filtered out), Tagada emails the patient a content-free notification — *"You have a new message from your care team"* — deep-linking to your portal page. The email never contains the message text. > [!NOTE] > > This is why your storefront should have a stable portal URL: the notification links there. The Oakwell template registers `/portal` and the thank-you page links to it. *** ## Identity verification Offerings mapped with `requiresIdVerification: true` need a government photo ID before the clinician can prescribe. One call handles upload + attachment to the network patient: ```json theme={null} POST /api/v1/rx/portal/cases/rxcase_xxx/identity { "filename": "license.jpg", "mimeType": "image/jpeg", "contentBase64": "…" } ``` Show the upload block whenever the case's offering requires it and the case is still pre-approval — the Oakwell portal renders it inline in the case detail view. *** ## Plugin SDK wiring (Oakwell pattern) ```tsx theme={null} import { useTagada, useLogin } from '@tagadapay/plugin-sdk/react'; import { createPortalClient, fileToAttachment } from '@/lib/portal-client'; function Portal() { const { apiService } = useTagada(); const { isAuthenticated, sendOtp, verifyOtp } = useLogin(); const portal = useMemo(() => createPortalClient(apiService), [apiService]); // 1. OTP gate if (!isAuthenticated) return ; // 2. Then everything just works: // portal.listCases() // portal.getCase(caseId) → { case, events } timeline // portal.listMessages(caseId) // portal.sendMessage(caseId, { text, attachments }) // portal.uploadIdentity(caseId, await fileToAttachment(file)) } ``` From a **headless** site, call the same endpoints with the CMS session token you obtain from the customer OTP login flow (`tagada.customer` module), passed as the `x-cms-token` header. *** ## UX checklist for a good portal * **Timeline, not jargon** — render `case.in_review` as "A clinician is reviewing your information", with dates. * **Message composer with attachments** — patients often need to send photos; accept camera capture on mobile. * **ID upload prompt** — surface it prominently while the case waits on identity verification; it's the #1 stall cause. * **Content-free everywhere** — never mirror message text into your own emails, analytics, or logs. # Patient support inbox Source: https://docs.tagada.io/developer-tools/rx/patient-support How affiliate storefronts advertise a brand mailbox, how mail is routed through Resend, and who answers. # Patient support inbox In affiliate mode Tagada answers patient email for every brand. The storefront advertises a brand address; Resend receives it; the TGD Care desk (or a partner desk) replies as the brand. Identity (what the patient sees) and handling (who answers) are independent. Changing one never changes the other. ## Addresses | Kind | Example | DNS | | - | - | - | | Platform subdomain | `care@primerx.tgdcare.com` | Tagada owns `tgdcare.com`. Publish provisions the Resend domain and pushes DKIM / SPF / MX to Vercel DNS. | | Merchant custom domain | `care@help.primelabpeptides.com` | Merchant adds the records Resend returns. If the apex already has MX, we refuse it and suggest a dedicated subdomain so we never take over their inbox. | Until receiving is verified, storefronts fall back to `care@tgdcare.com` so patients never write into the void. Storefront subdomains resolve through a wildcard `ALIAS *` in the `tgdcare.com` zone; because a wildcard stops answering for any name that gets an explicit record, `ensureDnsRecords` first pins `` with an explicit `ALIAS` copying the wildcard target before adding the receiving MX (otherwise `.tgdcare.com` silently stops resolving). That apex mailbox belongs to the TGD Care root store and is provisioned once with `supportMailbox.provisionApexMailbox` (same mechanics as a slug subdomain: Resend domain on the apex, MX/DKIM/SPF pushed to Vercel DNS). It must stay verified, otherwise the fallback itself bounces. Publishing an Rx storefront provisions the platform mailbox automatically. The merchant can later swap the identity to their own domain from the storefront wizard — Tagada still handles the inbox. ## Who answers | `handledBy` | Desk | Surface | | - | - | - | | `platform` (default) | TGD Care | CRM `/rx` | | `partner` | Partner reselling the Rx module | CRM `/rx/:partner` | A superadmin can move a mailbox from the platform desk to a partner desk without touching the address. The desk has its own CRM namespace (`/rx`, entry **TagadaRx** in the account menu) rather than a tab of the admin backoffice: it is a support surface worked by `rx_ops` / `rx_admin`, not an admin one. The old `/admin/rx` and `/partner-admin/:partner/rx` URLs redirect. ### Roles | Role (Clerk `tgdRoles`) | Scope (`whitelabelOwnership`) | Sees | | - | - | - | | `superadmin` / `founder` | — | Platform desk `/rx` and every partner desk | | `rx_admin` | `null` | Same as superadmin for Rx, plus every store's Rx configuration | | `rx_ops` | `null` | Platform desk + any partner desk — conversations only, no configuration | | `rx_admin` | partner slug | `/rx/` and the Rx configuration of that partner's stores | | `rx_ops` | partner slug | `/rx/` — conversations only | `partneradmin` alone does not open the desk: a white-label partner (Vera, BNP, Kashu…) gets its own Rx desk when Tagada grants `rx_admin` to the partner owner, who can then hand `rx_admin` / `rx_ops` to their staff from the partner IAM tab. Moving a mailbox between desks and provisioning platform mailboxes remain platform-only. ## Inbound path 1. Patient writes to the brand address. 2. Resend POSTs `email.received` to `/api/public/webhooks/resend/inbound` (Svix-signed). 3. Inngest `rx/support.email.received` fetches the body + attachments and stores the thread. 4. Threading: `In-Reply-To` / `References` → `[TGD-XXXXXX]` in the subject → last open conversation of the same contact on that mailbox (7 days). 5. Auto-replies, bounces and list mail are dropped. ## Outbound path Agents reply from the desk. Resend sends from the verified brand address (`PrimeRx Care `). The subject carries `[TGD-XXXXXX]` so the next patient reply threads back. The agent never appears. ## Env | Variable | Role | | - | - | | `RESEND_API_KEY` | Send + Receiving API + domain create | | `RESEND_INBOUND_WEBHOOK_SECRET` | Svix secret of the inbound webhook (falls back to `RESEND_WEBHOOK_SECRET`) | | `AUTH_BEARER_TOKEN` / `TEAM_ID_VERCEL` | Push DNS records on `tgdcare.com` | | `TAGADA_RX_STOREFRONT_DOMAIN` | Apex (default `tgdcare.com`) | Create a Resend webhook on `email.received` pointing at `https://api.tagada.io/api/public/webhooks/resend/inbound`. Enable **sending + receiving** on each brand domain. Plan quota: Scale is required once you have more than 10 verified domains (one per affiliate subdomain). # Platform partners Source: https://docs.tagada.io/developer-tools/rx/platform-partners Running Tagada Rx for a fleet of merchants: white-label CRM, per-store activation, headless integration on your own funnel infrastructure, and partner economics. # Tagada Rx for platform partners You run a platform — a funnel builder, an agency, a telehealth enabler, a payment orchestrator — and **your merchants** (not you) sell the treatments. Tagada Rx is built so a partner can operate the whole clinical stack for a fleet of merchant stores without Tagada ever appearing patient-side. > [!NOTE] > > **The decoupling promise applies fleet-wide.** Every merchant store is a > standard Tagada store with the Rx add-on activated. Your merchants can use > Tagada-hosted [storefront templates](/developer-tools/rx/storefront-templates), > or you can keep them on **your own funnel infrastructure** and drive > everything through the [Headless SDK](/developer-tools/rx/headless-sdk) > (browser) + [Node SDK](/developer-tools/rx/node-sdk) (your backend). Same > [building blocks](/developer-tools/rx/building-blocks) either way. *** ## The two partner shapes > [card] Payment layer only > > Your merchants already have clinicians and pharmacies plugged in. They > apply with their LegitScript certificate; you take a markup on > processing (think Stripe Connect for regulated verticals). Integrate > headless with the Node SDK — no Tagada CRM required. > [card] Full stack with TagadaRx > > Your merchants need clinicians and pharmacies too. You operate the > **white-label CRM**; each merchant store activates the Rx integration > (clinical network, intake, cases, portal, ship-day rebilling). Your > margin flows through the CRM layer. The rest of this page covers the full-stack shape. *** ## Fleet provisioning, per merchant store Rx is activated **per store**, so a fleet is a loop over your merchants. From your backend, with your partner-scoped API key: ```ts theme={null} import { Tagada } from '@tagadapay/node-sdk'; const tagada = new Tagada(process.env.TAGADA_API_KEY!); // For each merchant store you provision: await tagada.rx.requestActivation({ storeId: merchant.storeId, clinicalNetworkSlug: 'mdi', operatingMode: 'affiliate', // or 'direct' — see Operating modes }); // After the setup fee is settled (billing confirms it in prod): await tagada.rx.confirmSetupFeePaid({ storeId: merchant.storeId }); // Map each Rx product to its clinical offering: await tagada.rx.setProductOffering({ storeId: merchant.storeId, productId: product.id, externalOfferingId: offering.uuid, requiresIdVerification: true, }); // Audit the fleet at any time: const status = await tagada.rx.integrationStatus(merchant.storeId); // 'not_requested' | 'pending_payment' | 'active' ``` The [operating mode](/developer-tools/rx/operating-modes) is chosen per store: merchants validating a vertical start in `affiliate` (Tagada is merchant of record, commission per case), and graduate to `direct` (their own MIDs, full revenue) when volume justifies it — with zero storefront changes. *** ## Storefronts: hosted templates or your infrastructure **Option 1 — Tagada-hosted (fastest).** Each merchant brand is one plugin instance of a [storefront template](/developer-tools/rx/storefront-templates) mounted on its own domain — same code, per-brand config (branding, verticals, products, payment flow). Good when your merchants don't have their own frontend stack. **Option 2 — Your funnel infrastructure (headless).** Your funnel builder renders the pages; the Rx bricks are API calls: ```ts theme={null} import { createHeadlessClient } from '@tagadapay/headless-sdk'; const tagada = createHeadlessClient({ storeId: merchant.storeId }); // At product load — should this SKU be gated behind an intake? const check = await tagada.rx.isRequiredForProduct(productId); // Post-payment — network-authored questionnaire, then case submission: const { questions } = await tagada.rx.getQuestionsForProduct(productId); const result = await tagada.rx.submitCase({ orderId, checkoutToken, productId, patient, intakeAnswers, }); // Thank-you page — authoritative status: const { cases } = await tagada.rx.getCasesForOrder({ orderId, checkoutToken }); ``` No API key ships to the browser: case routes prove ownership with the `(orderId, checkoutToken)` pair. Your platform backend keeps the API-key surface (`tagada.rx.*`) for provisioning and ops. > [!WARNING] > > **PHI rule, fleet edition:** patient identity and intake answers are > pass-through. Neither you nor your merchants may store them — they go from > the patient's browser through Tagada to the clinical network in one request. > Building intake storage into your platform would make you a PHI processor. *** ## White-label rules Patients must never see the platform plumbing: * **Branding priority:** the merchant's brand first; the marketplace brand (e.g. TGD Care) when attribution is unavoidable; the platform name never. * Storefront domains, transactional emails, questionnaires, and the patient portal all carry the merchant brand (hosted templates handle this via per-instance config). * The white-label CRM is your operator surface: your team and your merchants manage cases, orders, and patients there under your brand. *** ## Partner economics | Layer | Affiliate mode (MoR) | Direct mode | | - | - | - | | Merchant revenue | Commission per submitted case (versioned [affiliate terms](/developer-tools/rx/operating-modes#how-affiliate-commissions-work); auto-accrual, auto-reversal on decline) | Full order revenue minus platform fees | | Partner margin | Negotiated on top of the case commission / CRM layer | Markup on processing and/or CRM layer | | Who is merchant of record | Tagada | The merchant | Accruals post automatically at case submission (`accrualAmountMinor` in the `submitCase` response) and reverse automatically on clinician decline — there is no billing call to make per case. *** ## Fleet monitoring Everything your ops dashboard needs is on the Node SDK: ```ts theme={null} // Cases across a store, filterable and paginated const { cases } = await tagada.rx.cases.list({ storeId: merchant.storeId }); // One case + full append-only event timeline (for support tooling) const detail = await tagada.rx.cases.retrieve('rxcase_xxx'); // Manual refill for support edge cases (shipped/delivered only) await tagada.rx.cases.requestRefill({ caseId: 'rxcase_xxx' }); ``` Case webhooks land in each store's event stream, so your platform can mirror statuses into your own merchant dashboard without polling. # With the Plugin SDK Source: https://docs.tagada.io/developer-tools/rx/plugin-sdk Build a Tagada-hosted telehealth storefront: quiz, checkout, case submission, and patient portal — deployed on Tagada infrastructure. # Tagada Rx with the Plugin SDK The [Plugin SDK](/developer-tools/sdk/introduction) is the fastest way to ship an Rx storefront: your React app is deployed **on Tagada infrastructure** (custom domain, instant swap, A/B testing) and gets checkout, payments, and session plumbing for free. The reference implementation is the **TGD Care** template — live at [tgdcare.com](https://tgdcare.com). Two mono-vertical archetypes are also available: **Cobalt** (plan-first, [cobalt.tgdcare.com](https://cobalt.tgdcare.com)) and **Arbor** (quiz-first, [arbor.tgdcare.com](https://arbor.tgdcare.com)) — see [Storefront templates](/developer-tools/rx/storefront-templates) for the full catalog and how each maps onto the shared funnel skeleton. `oakwell.tgdcare.com` is a parked reskin until it is remounted. > [!NOTE] > > **Why Plugin SDK for Rx?** Multi-instance deploys (one plugin, many affiliate subdomains), integrated funnel engine, and the `apiService` that already knows the environment's API base URL and the customer's CMS session — which the patient portal needs. If you're integrating Rx into an existing external site instead, use the [Headless SDK](/developer-tools/rx/headless-sdk). *** ## The pattern The plugin SDK doesn't ship an `rx` namespace — you wrap its `apiService` with two tiny clients (copy them from the Oakwell template): ``` src/lib/rx-client.ts ← public storefront calls (/api/public/v1/rx/*) src/lib/portal-client.ts ← patient portal calls (/api/v1/rx/portal/*) ``` ```tsx theme={null} import { useTagada } from '@tagadapay/plugin-sdk/react'; import { createRxClient } from '@/lib/rx-client'; import { createPortalClient } from '@/lib/portal-client'; function useRx() { const { apiService } = useTagada(); return useMemo(() => createRxClient(apiService), [apiService]); } ``` * `createRxClient` calls the **public** endpoints with `skipAuth: true` — they authorize per-resource via `(orderId, checkoutToken)`. * `createPortalClient` calls the **portal** endpoints with normal auth — the SDK automatically attaches the customer's `x-cms-token` once they've logged in via the OTP flow (`useLogin`). *** ## 1. Gate the product behind the quiz ```tsx theme={null} const rx = useRx(); const { required, requiresIdVerification } = await rx.isRequiredForProduct(productId); if (required) { // route to the intake quiz before checkout } ``` ## 2. Authorize at checkout, submit the case on thank-you Payment is standard Plugin SDK (`useCheckout`, `usePayment`) with **`mode: 'auth'`**. That places a hold — it does not capture. On success, park identity in `sessionStorage` and send the patient to `/thank-you` to complete the network questionnaire, then `submitCase`. Approve later captures the hold; decline voids it. ```tsx theme={null} const { checkoutSession } = useCheckout(); await processCardPayment(checkoutSession.id, card, { paymentFlowId, // from your plugin config mode: 'auth', onPaymentSuccess: async ({ order }) => { saveRxPendingIntake({ orderId: order.id, checkoutToken: checkoutSession.checkoutToken, productId, patient, quizAnswers, }); navigate(`/thank-you?orderId=${order.id}&checkoutToken=${checkoutSession.checkoutToken}`); }, }); ``` > [!NOTE] > > **Multiselect answers:** join them into one comma-separated string before submitting (`{ questionId: 'goals', value: 'lose_weight,improve_sleep' }`). The networks only accept string/number/boolean values. ## 3. Live status on the thank-you page ```tsx theme={null} const { cases } = await rx.getCasesForOrder({ orderId, checkoutToken }); // poll every ~10s: requested → submitted → in_review → approved → shipped ``` ## 4. The patient portal Oakwell ships a complete portal page (`/portal`) you can lift as-is: ```tsx theme={null} import { useLogin } from '@tagadapay/plugin-sdk/react'; // 1. OTP login — creates the CMS session the portal API needs const { sendOtp, verifyOtp } = useLogin(); // 2. Then the portal client just works const portal = createPortalClient(apiService); const { cases } = await portal.listCases(); const { messages } = await portal.listMessages(caseId); await portal.sendMessage(caseId, { text, attachments }); await portal.uploadIdentity(caseId, fileToAttachment(file)); ``` Features you get by copying the template page: treatments list, case timeline, secure message thread with file attachments, and photo-ID upload for `requiresIdVerification` offerings. See [Patient portal](/developer-tools/rx/patient-portal) for the API contract. *** ## Starting from the Oakwell template The fastest path is to fork the template rather than build from scratch: ``` templates/v2/telehealth-oakwell/ ├── config/default.config.json ← products, paymentFlowId, branding ├── src/pages/quiz.tsx ← branching intake ├── src/components/checkout/ ← payment + case submission ├── src/pages/thank-you.tsx ← status polling + portal link ├── src/pages/portal.tsx ← full patient portal └── src/lib/{rx-client,portal-client}.ts ``` Key config knobs in `default.config.json`: ```json theme={null} { "checkout": { "productId": "product_xxx", "variantId": "variant_xxx", "paymentFlowId": "flow_xxx" } } ``` Deploy with the standard plugin pipeline (`plugins/v2` build → deploy → swap onto your domain). In **affiliate mode**, each affiliate brand is one plugin instance on its own marketplace subdomain — same code, different config. # Storefront templates Source: https://docs.tagada.io/developer-tools/rx/storefront-templates The Tagada Rx template catalog: three funnel archetypes, one shared skeleton, live demos — and the matrix showing how each template maps onto the same Rx building blocks. # Storefront templates Tagada ships ready-made Rx storefront templates (Plugin SDK apps). They look and sell very differently, but they are **facades over the same funnel skeleton and the same [Rx building blocks](/developer-tools/rx/building-blocks)**: change the facade, keep the orchestration, the tracking, and the clinical flow. ```mermaid theme={null} flowchart LR subgraph SKELETON["Shared funnel skeleton (invariant)"] direction LR S1[Landing] --> S2[Marketing quiz] --> S3[Catalog / Offer] --> S4[Checkout] --> S5[Thank-you +
medical intake] --> S6[Patient portal] end T1[/"Multi-vertical
(TGD Care)"/] -.facade.-> SKELETON T2[/"Mono-vertical, plan-first
(Cobalt)"/] -.facade.-> SKELETON T3[/"Mono-vertical, quiz-first
(Arbor)"/] -.facade.-> SKELETON ``` Templates differ **only** in the order and weight of the first three boxes (Landing / Quiz / Catalog) and in art direction. Checkout → Thank-you/intake → Portal are identical everywhere — that's the LegitScript-validated, FTC-sensitive core, and it never moves. *** ## The catalog | | Multi-vertical | Cobalt | Arbor | | - | - | - | - | | Template | `telehealth-tgdcare` (+ reskins `oakwell`, `kura`, `sanara`) | `telehealth-cobalt` | `telehealth-arbor` | | Live demo | [tgdcare.com](https://tgdcare.com) (catalog-first) | [cobalt.tgdcare.com](https://cobalt.tgdcare.com) | [arbor.tgdcare.com](https://arbor.tgdcare.com) | | Archetype | Catalog-first "clinic storefront" | Plan-first "impulse" | Quiz-first "specialist" | | Verticals | hair · weight · skin · sexual | sexual (ED) only | hair only | | Landing sells | The clinic (choose your treatment area) | The product (plan picker above the fold) | The diagnosis ("Start my assessment") | | Quiz role | Qualify within the chosen vertical | Preselect a plan (5–7 preference questions) | Diagnose and recommend (8–12 visual screens) | | Catalog | Central: verticals, then products | Reduced to an inline plan picker | Invisible: single-product recommendation page | | Best for | Umbrella brands, several verticals | Single vertical with simple SKUs | High-personalization verticals (hair, skin, weight) | | Status | **LegitScript-validated — structure frozen** | Demo live | Demo live | > [!NOTE] > > `oakwell`, `kura`, and `sanara` are anonymized reskins of the multi-vertical > template — same structure, different branding — used for demos and as forks > for new affiliate brands. `oakwell.tgdcare.com` is parked ("Coming soon") > until remounted; use [tgdcare.com](https://tgdcare.com) as the live catalog > demo. Cobalt and Arbor were built from a competitive audit of the DTC > telehealth market (structures and vocabulary, never brands or assets). *** ## Three orchestration patterns, same boxes ```mermaid theme={null} flowchart TB subgraph A["Quiz-first (Arbor)"] direction LR A1[Quiz] --> A2["Recommendation
(1 product)"] --> A3[Checkout] end subgraph B["Catalog-first (TGD Care)"] direction LR B1[Vertical
catalog] --> B2[Vertical
quiz] --> B3[Vertical
products] --> B4[Checkout] end subgraph C["Plan-first (Cobalt)"] direction LR C1["Plan picker
on the landing"] --> C2["Preference
mini-quiz"] --> C3["Checkout
(checkoutOffers)"] end ``` | | Quiz-first | Catalog-first | Plan-first | | - | - | - | - | | The quiz | writes the recommendation (product/variant) into the session | qualifies inside the chosen vertical | tags preferences, preselects an offer | | The catalog | invisible — single recommendation | central — verticals then products | an inline plan picker | | Funnel config | quiz output feeds `resources.product` | one step group per vertical | `checkoutOffers` (custom) + `defaultOfferId` | | Entry variant | ads can land directly on quiz question 1 (`entryStepId`) | landing is the entry | ads can deep-link a plan straight to checkout | *** ## How a template maps onto the bricks This is the load-bearing table: **each funnel step of every template calls the same brick the same way.** A headless rebuild of any template is exactly these calls, self-orchestrated. | Funnel step (box) | What the template does | Brick / SDK call | | - | - | - | | **Landing** (`/`) | Sell the promise; fire PageView pixels; start the funnel session | Funnel engine (`RuntimeStepConfig.pixels`) | | **Marketing quiz** (`/quiz/:id`) | Config-driven quiz (`config.quizzes`), zero medical questions; answers map to products via `config.productMappings` (defaults + conditions), kept locally with the cart | Template quiz engine → cart. Answers forwarded later as `intakeAnswers` | | **Catalog / Offer** | Plan picker (Cobalt), recommendation page (Arbor), or vertical catalog (TGD Care) | `checkoutOffers` / `resources.product` on the step config | | **Checkout** (`/checkout`) | Create session from cart, take payment, order bumps | Plugin SDK `useCheckout` + `usePayment`; `useFunnel().next` to advance | | **Thank-you + medical intake** (`/thank-you`) | Fetch the network-authored questionnaire, collect patient + answers, submit the case, poll status | `rx.getQuestionsForProduct` → `rx.submitCase` → `rx.getCasesForOrder` (poll with backoff until a terminal status) | | **Post-purchase offer** (`/offer`) | Optional upsell between payment and thank-you | Funnel `upsellOffers`; `useFunnel()` transition | | **Patient portal** (`/portal`) | OTP login, case timeline, secure messaging, photo-ID upload | Portal client over `/api/v1/rx/portal/*` (CMS session) | Publishing a template installs this **same Funnel v2** on the merchant instance. Every telehealth template (catalog + reskins) must serve these paths — that is the compatibility contract with `ensureRxStorefrontFunnel`: | Funnel box | Path | Remappable | | - | - | - | | Landing | `/` | yes | | Marketing quiz | `/quiz` | no (template-internal, `matchSubPaths`) | | Checkout | `/checkout` | yes | | Offer | `/offer` | yes | | Thank-you + medical intake | `/thank-you` | yes | | Patient portal | `/portal` | no (template-internal, `matchSubPaths`) | The plugin matcher is `.*` (catch-all), so the six boxes are the same site, not six mounts. The remappable pages carry feature contracts (checkout session from `checkoutToken`, order from context) so the funnel engine can rewire them per variant without touching template code. > [!NOTE] > > **Decoupling in practice:** the medical intake never moves. Whatever the > sales path — quiz-first, catalog-first, plan-first, or a headless funnel on > your own infrastructure — the `product → medical questionnaire` pair is > resolved *after payment* on the thank-you step. That's why the top of the > funnel is completely free to vary. *** ## Compliance rules baked into every template 1. **The marketing quiz contains no medical questions** — no PHI before the card hold. The medical intake is network-authored and post-hold. 2. **Prescription disclaimer wherever money changes hands**: authorizing or subscribing does not guarantee a prescription; the hold is voided if the clinician doesn't prescribe. 3. **Honest pricing**: displayed monthly price = billed price; billing cadence explicit at checkout. 4. **Safety information** reachable from every product surface. 5. **Self-service cancellation** in the patient portal. 6. **No platform branding patient-side** — the affiliate brand (or the marketplace brand) is the only name a patient ever sees. *** ## Launching from the CRM Merchants don't deploy templates by hand: the CRM storefront wizard (**Tagada Rx → Storefront**) lists this catalog. The merchant picks a template, uploads a logo, sets brand name/colors and a subdomain, and publishing **auto-deploys the chosen template and installs a Funnel v2** on `brand.tgdcare.com` — catalog remap, payment flow, domain mount, and the six-step canvas (landing → marketing quiz → checkout → offer → thank-you → portal) so each page is visible in the CRM funnel builder. Republishing with a different template swaps the facade in place: same subdomain, same funnel, same cases. The plugin stays mounted as a catch-all; the Funnel v2 graph is the operator view, not a second site. The wizard also offers a **build-your-own path** for merchants who prefer the [Headless SDK](/developer-tools/rx/headless-sdk) — with the constraint that the build is still hosted on the Tagada subdomain (LegitScript). *** ## Forking a template Templates live in the monorepo under `templates/v2/telehealth-*`. To create a new brand: fork the closest archetype, patch `config/default.config.json` (branding, verticals, products, `paymentFlowId`), adjust the theme CSS variables, and deploy with the standard plugin pipeline (deploy → instantiate → mount on the brand's domain). In affiliate mode, each brand is one plugin instance on its own subdomain — same code, different config. See [With the Plugin SDK](/developer-tools/rx/plugin-sdk) for the integration contract inside a template. # End-to-end tutorial Source: https://docs.tagada.io/developer-tools/rx/tutorial From an activated store to a first prescription and its first refill — the complete Tagada Rx flow in seven steps. # Tutorial: your first prescription This walkthrough covers the **complete** flow — activation is assumed done ([do that first](/developer-tools/rx/crm-activation)). We use the raw HTTP endpoints so the flow is crystal clear; the [Plugin SDK](/developer-tools/rx/plugin-sdk) and [Headless SDK](/developer-tools/rx/headless-sdk) pages show the same steps as one-liners. **Cast of characters:** | Actor | Credential | | - | - | | Storefront (browser) | none — public endpoints + `checkoutToken` proof | | Your backend / CRM | Tagada API key | | Patient (portal) | email OTP → CMS session token | *** **1. 1 — Check if the product is an Rx product** At product-page load, ask whether the clinical flow is needed: ```bash theme={null} curl "https://api.tagada.io/api/public/v1/rx/required-for-product?productId=product_xxx" ``` ```json theme={null} { "required": true, "clinicalNetworkId": "clinnet_xxx", "externalOfferingId": "3f6a…", "requiresLabs": false, "requiresIdVerification": true, "isDeaControlled": false } ``` If `required` is `false`, sell it like any normal product and skip the rest of this page. **2. 2 — Marketing quiz, then check out** Run a **marketing** quiz before payment (vertical, goals, preferences). No medical questions, no PHI. Then run a standard Tagada checkout with **`mode: 'auth'`** (card hold, not a capture). When the hold succeeds you have **`orderId`** and **`checkoutToken`**. > [!WARNING] > > Make the copy explicit: *a card hold is not medical approval*. A licensed clinician still reviews the case. Approve captures the hold; decline voids it. Nothing is refunded because nothing was captured. **3. 3 — Medical intake on the thank-you page, then submit the case** **After** the hold, fetch the network-authored questionnaire and collect the intake on `/thank-you`. Then submit. The `(orderId, checkoutToken)` pair proves ownership — no API key in the browser. Keep `patient` / `intakeAnswers` in memory only until `submitCase` succeeds. ```bash theme={null} curl -X POST "https://api.tagada.io/api/public/v1/rx/cases/submit" \ -H "Content-Type: application/json" \ -d '{ "orderId": "order_xxx", "checkoutToken": "chkt_…", "productId": "product_xxx", "patient": { "firstName": "Jane", "lastName": "Doe", "email": "jane@example.com", "phone": "+15125550100", "dateOfBirth": "1990-04-12", "sexAtBirth": "female", "address": { "line1": "1 Main St", "city": "Austin", "state": "TX", "zip": "78701", "country": "US" } }, "intakeAnswers": [ { "questionId": "Do you have any drug allergies or intolerances?", "value": "No - No known drug allergies" }, { "questionId": "Are you taking any medications?", "value": "No - Not taking any medications" } ] }' ``` ```json theme={null} { "rxCaseId": "rxcase_xxx", "externalCaseId": "837858f1-…", "status": "submitted", "accrualAmountMinor": 2500, "accrualCurrency": "USD" } ``` > [!NOTE] > > **Intake answers**: one per question of the network questionnaire the patient saw (`questions-for-product`), keyed by the question title, `string`, `number`, `boolean`, or an array for multi-select. Select answers must be one of the options offered. Questions with `visible: false` are never asked; questions with `rules` are asked only when a rule matches (headless SDK: `isQuestionActive`, `toIntakeAnswers`). > [!WARNING] > > The server enforces the clinical network rules on every submit: US address in the 50 states or DC, US phone, 5 digit ZIP, adult patient, every required question answered. Otherwise the call fails with **422** and the list of fields to fix; nothing is sent to the clinician and you can resubmit the same order. Check the patient **before** taking the payment with `POST /api/public/v1/rx/intake/validate`, so a card is never held for a patient who cannot be treated. **4. 4 — Show live status on the thank-you page** Poll the public lookup with the same ownership proof: ```bash theme={null} curl -X POST "https://api.tagada.io/api/public/v1/rx/cases/lookup" \ -H "Content-Type: application/json" \ -d '{ "orderId": "order_xxx", "checkoutToken": "chkt_…" }' ``` ```json theme={null} { "cases": [ { "id": "rxcase_xxx", "status": "in_review", … } ] } ``` Render it as: *"A licensed clinician is reviewing your information."* → *"Approved — your treatment ships soon."* **5. 5 — Let the webhooks do their thing** From here, everything is event-driven. The clinical network calls Tagada's webhook receiver and the case advances on its own: * `case.in_review` → clinician picked it up * `case.approved` → prescription issued * `shipment.shipped` → tracking attached, **next rebill scheduled at ship day + 30** * `shipment.delivered` → done for this cycle Watch it live in **CRM → your store → Tagada Rx → Cases**, or via the merchant API: ```ts theme={null} const { case: c, events } = await tagada.rx.cases.retrieve('rxcase_xxx'); // events = full append-only timeline ``` **6. 6 — The patient uses the portal** Point patients to your storefront's portal page (the Oakwell template ships one at `/portal`). They log in with an **email OTP**, see their treatments and timelines, **message the care team**, and upload a **photo ID** when the offering requires identity verification. Details: [Patient portal](/developer-tools/rx/patient-portal). When a clinician replies, Tagada emails the patient a content-free notification ("You have a new message") linking back to the portal. **7. 7 — Refills happen by themselves** On every shipment, Tagada schedules the next charge for **the ship day + cycle** (default 30 days). An hourly scan rebills due cases that are still `shipped`/`delivered`. You do nothing; declined or cancelled cases never rebill. *** ## What can go wrong (and what to do) | Situation | What happens | Your move | | - | - | - | | Clinician declines | `case.declined` event; affiliate accrual reversed | Refund the order, email the patient | | Patient or intake breaks the network rules | `rx.submitCase` fails with 422 and the fields to fix (nothing sent) | Show the issues, let the patient fix them, resubmit | | Network is down at submit | `rx.submitCase` fails (PHI is never queued) | Show a retry UI; the order stays paid | | Patient never uploads ID | Case stalls in review | Portal nags; you can nudge via messaging | | Duplicate webhook | Dropped by idempotency | Nothing | *** ## Next > [card] [Plugin SDK](/developer-tools/rx/plugin-sdk) > > The same flow inside a Tagada-hosted storefront. > [card] [Headless SDK](/developer-tools/rx/headless-sdk) > > The same flow from your own site. > [card] [Node SDK](/developer-tools/rx/node-sdk) > > Server-side ops: activation, cases, refills. # SaaS Billing with TagadaPay Source: https://docs.tagada.io/developer-tools/saas-billing/introduction Bill subscriptions from your own app — processor-agnostic, powered by payment flows # SaaS Billing with TagadaPay **Time**: \~20 minutes | **Difficulty**: Intermediate Bill subscriptions from **your own SaaS app** — not a storefront, not a funnel. You keep your UI; TagadaPay handles vaulting, routing, and recurring charges across **any processor or TPA**. > [!NOTE] > > **This guide is for SaaS builders** migrating from Stripe Billing or building subscription billing from scratch. For e-commerce storefronts, see [Build a Store with AI](/developer-tools/headless-sdk/build-store-with-ai). *** ## Why TagadaPay for SaaS (vs Stripe) | Stripe | TagadaPay | | - | - | | Locked to Stripe as processor | **Processor-agnostic** — TagadaPay (managed), Stripe, Checkout.com, NMI | | One `PaymentMethod` per Stripe account | **One vault** — card tokenized once, routed to any processor | | Switching processor = re-collect cards | **Payment flows** — switch TPAs/processors without touching customer cards | | `stripe.subscriptions.create` | `tagada.subscriptions.create` — same mental model | The killer feature: **payment flows**. Connect as many TPAs and processors as you want. If one TPA is banned, add a fallback in the flow — cards stay vaulted, rebills keep working. ``` Your SaaS checkout ↓ Card tokenized (core-js) — once ↓ ┌──── Payment Flow ────┐ │ sandbox (dev) │ │ → tagadapay-router │ ← live TPA (tpa_xxx) │ → Stripe (optional) │ │ → Checkout.com │ └──────────────────────┘ ↓ Subscription rebills — automatic, same vault ``` *** ## Architecture: frontend vs backend > [tab] Frontend (browser) > > **Package:** `@tagadapay/core-js` > > * Tokenize the card → `tagadaToken` > * Handle 3DS if the charge asks for it (`requireAction: 'redirect'` → send the customer to the processor's hosted page; standalone 3DS sessions are only for gateway-style processors like NMI — see [Quick Start](/developer-tools/saas-billing/quick-start#handle-3ds-usually-nothing-to-do)) > * **Never** put your CRM API key in the browser > > ```ts theme={null} > import { useCardTokenization } from '@tagadapay/core-js/react'; > > const { tokenizeCard } = useCardTokenization({ environment: 'production' }); > const { tagadaToken } = await tokenizeCard({ > cardNumber: '4242424242424242', > expiryDate: '12/30', > cvc: '123', > cardholderName: 'Alex Founder', > }); > > // Send tagadaToken to YOUR backend — not to TagadaPay directly > await fetch('/api/payment-instruments', { > method: 'POST', > body: JSON.stringify({ tagadaToken, storeId, customerData }), > }); > ``` > [tab] Backend (server) > > **Package:** `@tagadapay/node-sdk` > > * Create customer > * Vault card (`createFromToken`) > * Charge through payment flow (`payments.process`) > * Create subscription (`subscriptions.create`) > * Verify webhooks (`webhooks.constructEvent`) > > ```ts theme={null} > import Tagada from '@tagadapay/node-sdk'; > const tagada = new Tagada(process.env.TAGADA_API_KEY!); > > // Vault > const { paymentInstrument } = await tagada.paymentInstruments.createFromToken({ > tagadaToken, storeId, customerData, > }); > > // Charge (routes through your payment flow automatically) > const { payment } = await tagada.payments.process({ > amount: 1900, currency: 'EUR', storeId, > paymentInstrumentId: paymentInstrument.id, > customerId, initiatedBy: 'customer', > paymentFlowId: process.env.TAGADA_PAYMENT_FLOW_ID, > }); > > // Subscribe > const { subscription } = await tagada.subscriptions.create({ > customerId, priceId, storeId, currency: 'EUR', > defaultPaymentInstrumentId: paymentInstrument.id, > paymentId: payment.id, > }); > ``` *** ## Working example Everything in this guide was tested against production. Clone and run: ```bash theme={null} git clone https://github.com/TagadaPay/examples.git cd examples/mini-saas-billing # or examples/mini-saas-billing in the monorepo cp env.example .env # add TAGADA_API_KEY + TAGADA_STORE_ID npm install npm run seed # product + cascade payment flow npm run verify # automated end-to-end test npm run dev # frontend :5173 + backend :3001 ``` Open [http://localhost:5173](http://localhost:5173), click **Subscribe**, and watch the flow log. *** ## Next steps > [card] [Quick Start](/developer-tools/saas-billing/quick-start) > > Step-by-step: product → checkout → subscription in 15 minutes > [card] [Payment Flows](/developer-tools/saas-billing/payment-flows) > > Multi-TPA routing, cascade, failover — the Stripe killer > [card] [Migrate from Stripe](/developer-tools/saas-billing/migrate-from-stripe) > > Object mapping and cutover playbook > [card] [Subscriptions API](/developer-tools/node-sdk/subscriptions) > > Rebilling, trials, cancel, processor migration # Migrate from Stripe Billing Source: https://docs.tagada.io/developer-tools/saas-billing/migrate-from-stripe Map Stripe objects to TagadaPay and cut over without re-collecting cards # Migrate from Stripe Billing **Time**: \~15 minutes to read | **Difficulty**: Intermediate TagadaPay is not a drop-in Stripe replacement, but the object model maps cleanly. The biggest win: **payment flows let you route across multiple processors** — something Stripe cannot do without re-architecting. *** ## Object mapping | Stripe | TagadaPay | Notes | | - | - | - | | `Customer` (`cus_`) | `Customer` (`cus_`) | `tagada.customers.create` | | `PaymentMethod` (`pm_`) | `PaymentInstrument` (`inst_`) | Created via `createFromToken` — not attached directly | | `SetupIntent` | `core-js tokenize` + `createFromToken` | No separate SetupIntent object | | `PaymentIntent` (`pi_`) | `Payment` (`pay_`) | `tagada.payments.process` | | `Price` (`price_`) | `Price` (`price_`) | Lives inside a product variant | | `Product` (`prod_`) | `Product` (`product_`) | `tagada.products.create` with recurring variant | | `Subscription` (`sub_`) | `Subscription` (`sub_`) | `tagada.subscriptions.create` | | `Invoice` | — | Build from `orders` + `payments` + webhooks | | `BillingPortal` | — | Build your own with headless SDK | | `stripe.webhooks.constructEvent` | `tagada.webhooks.constructEvent` | Same ergonomics, `sha256=` HMAC | *** ## Code mapping ### Create a customer ```ts theme={null} // Stripe const customer = await stripe.customers.create({ email: 'user@saas.com' }); // TagadaPay const customer = await tagada.customers.create({ storeId: 'store_xxx', email: 'user@saas.com', firstName: 'Alex', lastName: 'Founder', }); ``` ### Save a card ```ts theme={null} // Stripe (browser) const { paymentMethod } = await stripe.createPaymentMethod({ type: 'card', card: element }); await stripe.paymentMethods.attach(paymentMethod.id, { customer: customer.id }); // TagadaPay (browser → server) // FRONTEND: const { tagadaToken } = await tokenizeCard({ cardNumber, expiryDate, cvc }); // BACKEND: const { paymentInstrument } = await tagada.paymentInstruments.createFromToken({ tagadaToken, storeId, customerData: { email, firstName, lastName }, }); ``` ### Charge + subscribe ```ts theme={null} // Stripe const paymentIntent = await stripe.paymentIntents.create({ amount: 1900, currency: 'eur', customer: customer.id, payment_method: paymentMethod.id, confirm: true, }); const subscription = await stripe.subscriptions.create({ customer: customer.id, items: [{ price: 'price_xxx' }], }); // TagadaPay const { payment } = await tagada.payments.process({ amount: 1900, currency: 'EUR', storeId, paymentInstrumentId: paymentInstrument.id, customerId: customer.id, initiatedBy: 'customer', paymentFlowId: 'flow_xxx', }); const { subscription } = await tagada.subscriptions.create({ customerId: customer.id, priceId: 'price_xxx', storeId, currency: 'EUR', defaultPaymentInstrumentId: paymentInstrument.id, paymentId: payment.id, }); ``` ### Webhooks ```ts theme={null} // Stripe const event = stripe.webhooks.constructEvent(rawBody, sig, secret); // TagadaPay const event = tagada.webhooks.constructEvent(rawBody, req.headers['x-tagadapay-signature'], secret); ``` *** ## Migration phases ### Phase 1 — New subscriptions on TagadaPay * Keep existing Stripe subs running * Route new signups through TagadaPay (SaaS quick start) * Use a **cascade payment flow**: sandbox for dev → live TPA for production * Map Stripe webhook handlers to TagadaPay events: | Stripe event | TagadaPay event | | - | - | | `invoice.paid` | `subscription/rebillSucceeded` | | `invoice.payment_failed` | `subscription/rebillDeclined` | | `customer.subscription.deleted` | `subscription/canceled` | | `payment_intent.succeeded` | `payment/succeeded` | ### Phase 2 — Processor flexibility (TagadaPay advantage) This is what Stripe cannot offer: ``` Stripe: locked to Stripe TagadaPay: sandbox → TPA → Stripe → Checkout.com (one vault) ``` Add processors to your payment flow as you grow. If one TPA is banned, switch the flow — cards stay vaulted. ### Phase 3 — Migrate existing subscriptions TagadaPay supports processor migration without re-vaulting: ```ts theme={null} await tagada.subscriptions.changeProcessor({ subscriptionIds: ['sub_xxx'], processorId: 'processor_new', }); ``` For bulk card migration from Stripe, contact support — the vault model supports importing tokenized instruments in some configurations. *** ## What Stripe has that TagadaPay doesn't (yet) | Feature | Workaround | | - | - | | Invoices / PDF | Build from payments + orders; email via your app | | Usage/metered billing | Custom metering in your app + `payments.process` | | Customer billing portal | Build with headless SDK customer hooks | | Subscription plan changes | Manual cancel + re-create (upgrade API coming) | *** ## Get started > [card] [SaaS Quick Start](/developer-tools/saas-billing/quick-start) > > Working example tested in production > [card] [Payment Flows](/developer-tools/saas-billing/payment-flows) > > Multi-TPA routing — the reason to switch # Payment Flows for SaaS Source: https://docs.tagada.io/developer-tools/saas-billing/payment-flows Route charges across multiple TPAs and processors — one vault, automatic failover # Payment Flows for SaaS **Time**: \~10 minutes | **Difficulty**: Intermediate Payment flows are TagadaPay's routing engine. For SaaS, they solve the problem Stripe cannot: **run multiple processors/TPAs behind one vaulted card**, with automatic cascade and failover. > [!NOTE] > > **Tested in production** with TPA `tpa_fb15b76112a8` (live TagadaPay-managed) and sandbox processor cascade. See [`mini-saas-billing`](https://github.com/TagadaPay/examples/tree/main/mini-saas-billing). *** ## The problem with Stripe ``` Customer card → Stripe only ↓ decline → lost sale ↓ Stripe bans account → all cards gone ``` ## The TagadaPay model ``` Customer card → vaulted once (payment instrument) ↓ ┌── Payment Flow ──┐ │ sandbox (dev) │ ← test cards │ → TPA (live) │ ← your TagadaPay account │ → Stripe │ ← optional direct processor │ → Checkout.com │ ← optional └──────────────────┘ ↓ Rebill every month — same vault, any processor ``` **If a TPA is banned:** update the payment flow to route through a different TPA or processor. Customers never re-enter their card. *** ## Create a cascade flow (backend) This is the flow created by `npm run seed` in the SaaS demo — tested and working: ```ts theme={null} import Tagada from '@tagadapay/node-sdk'; const tagada = new Tagada(process.env.TAGADA_API_KEY!); const { processors } = await tagada.processors.list(); const sandbox = processors.find((p) => p.type === 'sandbox'); const router = processors.find((p) => p.type === 'tagadapay-router'); const flow = await tagada.paymentFlows.create({ data: { name: 'SaaS Billing Flow', strategy: 'cascade', fallbackMode: true, maxFallbackRetries: 2, threeDsEnabled: true, stickyProcessorEnabled: true, pickProcessorStrategy: 'weighted', processorConfigs: [ { processorId: sandbox!.id, weight: 100, disabled: false, nonStickable: false }, ], fallbackProcessorConfigs: [ { processorId: router!.id, orderIndex: 0 }, ], }, }); console.log(flow.id); // flow_35f3975175fe — verified in production ``` | Setting | What it does for SaaS | | - | - | | `strategy: 'cascade'` | Try primary processor; on decline, fall through to next | | `stickyProcessorEnabled: true` | Returning customers reuse their last successful processor | | `threeDsEnabled: true` | SCA for EU rebills | | `fallbackProcessorConfigs` | Ordered list of backup processors/TPAs | > [!NOTE] > > **About `threeDsEnabled`:** this toggles *whether* 3DS is requested — *how* it runs is decided by the processor the flow routes to. With hosted-3DS PSPs (Stripe, Checkout.com, TagadaPay TPAs) the charge simply returns `requireAction: 'redirect'` and the processor hosts the challenge; you never create a 3DS session yourself. Standalone 3DS sessions (`threeds.createSession`) exist only for gateway-style processors like NMI and are rarely needed — see [Quick Start](/developer-tools/saas-billing/quick-start#handle-3ds-usually-nothing-to-do). *** ## Charge through a flow Pass `paymentFlowId` on every charge — first payment and rebills: ```ts theme={null} const { payment } = await tagada.payments.process({ amount: 1900, currency: 'EUR', storeId: 'store_xxx', paymentInstrumentId: 'inst_xxx', customerId: 'cus_xxx', initiatedBy: 'customer', paymentFlowId: 'flow_35f3975175fe', }); console.log(payment.status); // 'succeeded' console.log(payment.processorId); // which processor won the route ``` Verified output from production test: ``` Payment: pay_666f3a317d1b succeeded processor: processor_4ae47011dc96 ``` *** ## Add more processors to increase approval rate Connect Stripe, Checkout.com, or Airwallex in the dashboard, then add them to the flow: ```ts theme={null} await tagada.paymentFlows.update({ flowId: 'flow_35f3975175fe', data: { strategy: 'cascade', fallbackMode: true, maxFallbackRetries: 3, processorConfigs: [ { processorId: 'processor_sandbox', weight: 50, disabled: false, nonStickable: false }, { processorId: 'processor_stripe', weight: 50, disabled: false, nonStickable: false }, ], fallbackProcessorConfigs: [ { processorId: 'processor_tagadapay_router', orderIndex: 0 }, { processorId: 'processor_checkout_com', orderIndex: 1 }, ], }, }); ``` No frontend changes. No re-vaulting. The same `paymentInstrumentId` works across all processors. *** ## Switch TPA without re-collecting cards When your live TPA (`tpa_xxx`) has issues: 1. Provision a new TPA (or connect a direct Stripe/Checkout.com processor) 2. Add it to the payment flow's `fallbackProcessorConfigs` 3. Optionally disable the old processor 4. Existing subscriptions rebill through the new route automatically For subscription-level processor migration, use: ```ts theme={null} await tagada.subscriptions.changeProcessor({ subscriptionIds: ['sub_xyz'], processorId: 'processor_new', }); ``` See [Subscriptions & Rebilling](/developer-tools/node-sdk/subscriptions#change-processor-migrate-without-re-vaulting). *** ## Inspect your flow at runtime ```ts theme={null} const flow = await tagada.paymentFlows.retrieveWithProcessors('flow_35f3975175fe'); console.log(flow.name); // 'SaaS Billing Flow' console.log(flow.strategy); // 'cascade' console.log(flow.processorConfigs); // primary processors console.log(flow.fallbackProcessorConfigs); // fallback chain ``` The SaaS demo exposes this at `GET /api/payment-flow` so your frontend can display the active routing config. *** ## Strategies reference | Strategy | Best for SaaS | | - | - | | `simple` | Single processor — dev/testing | | `cascade` | **Recommended** — try primary, fall through on decline | | Weighted + sticky | Split traffic across processors, stick returning customers | Full multi-PSP guide: [Multi-PSP Routing & Vault](/developer-tools/node-sdk/multi-stripe-routing). # SaaS Billing Quick Start Source: https://docs.tagada.io/developer-tools/saas-billing/quick-start Subscribe a customer in 15 minutes — core-js frontend + node-sdk backend # SaaS Billing Quick Start **Time**: \~15 minutes | **Difficulty**: Intermediate This walkthrough matches the tested [`mini-saas-billing`](https://github.com/TagadaPay/examples/tree/main/mini-saas-billing) example. Every code block below runs in production. *** ## Prerequisites * Node.js 18+ * A Tagada CRM API key (`sk_crm_live_…`) — [Get an API key](/developer-tools/node-sdk/get-api-key) * A store (`store_xxx`) *** ## Step 1 — Seed your SaaS plan (backend) Create a recurring product and a **cascade payment flow** (sandbox for dev → live TPA for production): ```bash theme={null} cd mini-saas-billing cp env.example .env # TAGADA_API_KEY=sk_crm_live_... # TAGADA_STORE_ID=store_... npm install npm run seed ``` The seed script creates: | Resource | Example ID | Purpose | | - | - | - | | Payment flow | `flow_35f3975175fe` | Cascade: sandbox → `tagadapay-router` (TPA) | | Product | `product_…` | SaaS Pro Plan | | Price | `price_…` | €19.00/month recurring | Verify everything works: ```bash theme={null} npm run verify # ✅ Payment succeeded # ✅ Subscription active # ✅ Rebill OK ``` *** ## Step 2 — Backend API (node-sdk) Your server holds the API key and exposes routes the frontend calls. ```ts title="server/index.ts" theme={null} import Tagada from '@tagadapay/node-sdk'; const tagada = new Tagada(process.env.TAGADA_API_KEY!); // Vault card from browser tagadaToken app.post('/api/payment-instruments', async (req, res) => { const { tagadaToken, storeId, customerData } = req.body; const result = await tagada.paymentInstruments.createFromToken({ tagadaToken, storeId, customerData, }); res.json(result); }); // Charge through payment flow app.post('/api/payments', async (req, res) => { const { amount, currency, storeId, paymentInstrumentId, customerId } = req.body; const result = await tagada.payments.process({ amount, currency, storeId, paymentInstrumentId, customerId, initiatedBy: 'customer', paymentFlowId: process.env.TAGADA_PAYMENT_FLOW_ID, }); res.json(result); }); // Create subscription after first charge app.post('/api/subscriptions', async (req, res) => { const { customerId, priceId, storeId, currency, defaultPaymentInstrumentId, paymentId } = req.body; const result = await tagada.subscriptions.create({ customerId, priceId, storeId, currency, defaultPaymentInstrumentId, paymentId, }); res.json(result); }); ``` > [!WARNING] > > **Never expose `TAGADA_API_KEY` to the browser.** The frontend only sends `tagadaToken` to your backend. *** ## Step 3 — Frontend checkout (core-js) The browser tokenizes the card and calls your API routes. ```tsx title="web/src/App.tsx" theme={null} import { useCardTokenization } from '@tagadapay/core-js/react'; const { tokenizeCard } = useCardTokenization({ environment: 'production' }); async function subscribe() { // 1. FRONTEND — tokenize (PCI-safe) const { tagadaToken } = await tokenizeCard({ cardNumber: '4242424242424242', expiryDate: '12/30', cvc: '123', cardholderName: 'Alex Founder', }); // 2. BACKEND — create customer const { customer } = await fetch('/api/customers', { method: 'POST', body: JSON.stringify({ storeId, email, firstName, lastName }), }).then((r) => r.json()); // 3. BACKEND — vault card const { paymentInstrument } = await fetch('/api/payment-instruments', { method: 'POST', body: JSON.stringify({ tagadaToken, storeId, customerData: { email, firstName, lastName } }), }).then((r) => r.json()); // 4. BACKEND — charge via payment flow const { payment } = await fetch('/api/payments', { method: 'POST', body: JSON.stringify({ amount: 1900, currency: 'EUR', storeId, paymentInstrumentId: paymentInstrument.id, customerId: customer.id, }), }).then((r) => r.json()); // 5. BACKEND — create subscription const { subscription } = await fetch('/api/subscriptions', { method: 'POST', body: JSON.stringify({ customerId: customer.id, priceId, storeId, currency: 'EUR', defaultPaymentInstrumentId: paymentInstrument.id, paymentId: payment.id, }), }).then((r) => r.json()); console.log('Subscribed:', subscription.id, subscription.status); } ``` *** ## Step 4 — Run the demo ```bash theme={null} npm run dev ``` Open [http://localhost:5173](http://localhost:5173). The right panel shows your **payment flow** — primary processor and fallbacks. *** ## Test card ``` 4242 4242 4242 4242 · 12/30 · 123 ``` Works with the **sandbox** processor in the cascade flow. For live TPA charges, use a real card. *** ## Handle 3DS (usually nothing to do) There are **two very different 3DS modes**, and most SaaS integrations only ever meet the first one: ### Option 1 — Platform / PSP-hosted 3DS (the default) Modern PSPs (Stripe, Checkout.com, TagadaPay TPAs…) host the 3DS challenge themselves. You **never** call `threeds.createSession`. Just pass a `returnUrl` when charging; if the issuer requires SCA, the payment comes back with `requireAction: 'redirect'` and a `redirectUrl` pointing at the processor's own hosted 3DS page: ```ts theme={null} const { payment } = await tagada.payments.process({ amount: 1900, currency: 'EUR', storeId, paymentInstrumentId, customerId, initiatedBy: 'customer', paymentFlowId: process.env.TAGADA_PAYMENT_FLOW_ID, // REQUIRED for any flow that can challenge (EU cards on hosted-3DS PSPs): returnUrl: 'https://your-saas.com/billing/return', }); if (payment.requireAction === 'redirect') { // Send the customer to the processor's hosted 3DS page. // After authentication they come back to your returnUrl — // resume with payments.continue(): const { payment: resumed } = await tagada.payments.continue(payment.id); } ``` Whether 3DS triggers is controlled by `threeDsEnabled: true` on your payment flow (or forced by the issuer). **How** it runs is the processor's business — you only handle `requireAction`. ### Option 2 — Standalone 3DS (the exception, rarely needed) Some gateway-style processors (e.g. **NMI**) don't host 3DS but accept pre-authenticated values (CAVV, ECI…) on the charge. Only for those, Tagada runs the 3DS flow itself via `threeds.createSession` + `threedsSessionId`. If your flow routes to Stripe, Checkout.com, or a TagadaPay TPA, **skip this entirely**. Full explanation: [Partners → Payments, Step 3](/developer-tools/partners/payments). > [!TIP] > > **When in doubt:** don't pre-create anything. Charge with a `returnUrl`, then handle whatever `requireAction` the response carries. *** ## What happens on rebill? TagadaPay automatically rebills the subscription each cycle. The charge routes through the same payment flow — cascade, weighted, fallback — with **no extra code**. Manual rebill (support tool, retry script): ```ts theme={null} await tagada.subscriptions.rebill('sub_xyz789'); ``` Webhook events: `subscription/rebillSucceeded`, `subscription/rebillDeclined`, `subscription/pastDue`. *** ## Stripe mapping | Stripe | TagadaPay | | - | - | | `stripe.customers.create` | `tagada.customers.create` | | `stripe.paymentMethods.create` + attach | `core-js tokenize` → `paymentInstruments.createFromToken` | | `stripe.paymentIntents.create` | `tagada.payments.process` | | `stripe.subscriptions.create` | `tagada.subscriptions.create` | | `stripe.webhooks.constructEvent` | `tagada.webhooks.constructEvent` | Full migration guide: [Migrate from Stripe](/developer-tools/saas-billing/migrate-from-stripe). # SDK versions Source: https://docs.tagada.io/developer-tools/sdk-versions Each TagadaPay SDK, its current version, the API it talks to, its status and the minimum version to use. Every SDK follows semantic versioning and is published on npm under `@tagadapay`. This page says which payments API each one talks to: [V2](/payments-api/v2-or-v3) (the Commerce API, `https://api.tagada.io/api/public/v1`) or [V3](/payments-api/overview) (the Payments API, `https://api.tagada.io/v1`). ## Current versions | Package | Current | Runs in | Payments API | Status | | - | - | - | - | - | | [`@tagadapay/node-sdk`](https://www.npmjs.com/package/@tagadapay/node-sdk) | `3.27.1` | Your server (Node.js 18+) | V2 | Stable | | [`@tagadapay/headless-sdk`](https://www.npmjs.com/package/@tagadapay/headless-sdk) | `1.21.0` | Browser, your own checkout | V2, and V3 stores with the same calls | Stable | | [`@tagadapay/core-js`](https://www.npmjs.com/package/@tagadapay/core-js) | `3.7.0` | Browser | V2 (root), V3 (`/payments-v3`) | Stable; `/payments-v3` is Preview | | [`@tagadapay/plugin-sdk`](https://www.npmjs.com/package/@tagadapay/plugin-sdk) | `4.4.1` | Browser, inside TagadaPay plugins | V2 | Legacy | | Status | Meaning | | - | - | | Stable | Supported. New features land here. Breaking changes only in a new major version. | | Preview | Usable, follows the [Payments API preview](/payments-api/overview#release-phases). | | Legacy | Fixes only, no new features. Keeps working. Plan a move to its replacement. | ## Package by package ### `@tagadapay/node-sdk` The server SDK for the Commerce API: stores, orders, customers, subscriptions, and V2 payments (`tagada.payments.process()`, `refund()`, `void()`). Default base URL `https://api.tagada.io/api/public/v1`. * **Payments API (V3):** no methods yet. A `tagada.payments` namespace for V3 is **coming soon**. Until then, call `https://api.tagada.io/v1` over HTTP. * On a store switched to V3, `payments.process()` keeps working. See [compatibility](/payments-api/migrate-from-v2#compatibility-v2-calls-keep-working). ### `@tagadapay/headless-sdk` Builds a custom checkout on your domain when TagadaPay manages the cart. Pays a checkout session with `payment.processPayment()` (`checkout/pay-v2`) and handles 3DS and redirects itself. * **Payments API (V3):** since `1.21.0`, a store switched to V3 pays with the same calls: cards, Apple Pay and Google Pay go through the server, and local methods and redirects run the V3 `next_action` loop inside the SDK (npm build, with `@tagadapay/core-js` `^3.7.0`). The CDN build does not run that loop yet. Nothing changes in your calls. * Replaces `@tagadapay/plugin-sdk` over time. ### `@tagadapay/core-js` Low-level browser building blocks. * **Root export (V2):** card and wallet tokenization (`tagadaToken`), 3DS helpers, Radar. Pair it with `node-sdk` `payments.process()`. * **`@tagadapay/core-js/payments-v3` (V3, Preview), since 3.7.0:** the browser client of the Payments API: `loadPayments`, card fields, wallets, `confirmPayment` and the `next_action` loop. See [Browser client](/payments-api/browser-client). ### `@tagadapay/plugin-sdk` React SDK for plugins that run inside TagadaPay's plugin and funnel runtime. * **Legacy, frozen:** fixes only. It will not get Payments API features. * On a store switched to V3, it keeps working through the compatibility layer. * For new custom checkouts, use `@tagadapay/headless-sdk`. ## Minimum versions | Package | Minimum | Why | | - | - | - | | `@tagadapay/core-js` | `3.7.0` | First version with `/payments-v3`. | | `@tagadapay/node-sdk` | `3.27.1` | First version that sends `X-Tagada-SDK`. | | `@tagadapay/headless-sdk` | `1.21.0` | Pays V3 stores with the same calls; `1.20.1` was the first to send `X-Tagada-SDK`. | | `@tagadapay/plugin-sdk` | `4.4.1` | First version that sends `X-Tagada-SDK`. | Older versions keep working. Upgrade so support can tell which SDK and version sent a request. ## The X-Tagada-SDK header Every SDK names itself on its requests: ```http theme={null} X-Tagada-SDK: node-sdk/3.27.1 ``` | Package | Header value | | - | - | | `@tagadapay/node-sdk` | `node-sdk/` | | `@tagadapay/headless-sdk` | `headless-sdk/` | | `@tagadapay/plugin-sdk` | `plugin-sdk/` | | `@tagadapay/core-js` (3DS calls of the root export) | `core-js/` | | `@tagadapay/core-js/payments-v3` | `payments-js/0` | The header is informational. Do not set it yourself in direct HTTP calls. ## SDKs and API versions V2 has no dated versions: any supported SDK version talks to it. The Payments API is dated: `@tagadapay/core-js/payments-v3` sends the `Payments-Version` it was built against (`2026-11-01` in 3.7.0), so upgrading the package is how you move to a newer API version. See [Versioning](/payments-api/versioning). # SDK API Reference (React) Source: https://docs.tagada.io/developer-tools/sdk/api Complete API documentation for TagadaPay Plugin SDK v2 # SDK API Reference for React > [card] Latest Version > > **v2.7.14** - Complete TypeScript documentation > [card] Framework > > **React SDK** - Hooks-based API for React 18+ Complete API documentation for all hooks, components, and utilities in the TagadaPay Plugin SDK v2. > [!NOTE] > > **React is Required**: This API reference covers the React-based TagadaPay Plugin SDK v2 > (`@tagadapay/plugin-sdk/v2`). All hooks and components require React 18+. For V1 docs, see the legacy > documentation. ## Quick Navigation > [card] [Query Hooks](#query-hooks) > > TanStack Query hooks for data fetching > [card] [Mutation Hooks](#mutation-hooks) > > Hooks for data updates > [card] [Utility Hooks](#utility-hooks) > > Helper hooks for common tasks > [card] [Payment Hooks](#payment-hooks) > > Payment processing and 3DS > [card] [Location Hooks](#location-hooks) > > Address and geolocation > [card] [Components](#components) > > Reusable React components ## Installation & Setup ```bash theme={null} npm install @tagadapay/plugin-sdk ``` ### Provider Setup Wrap your app with `TagadaProvider`: ```tsx theme={null} import { TagadaProvider } from '@tagadapay/plugin-sdk/v2'; export default function App() { return ( ); } ``` ## Query Hooks ### useCheckout() Fetch and manage checkout data with automatic caching. ```tsx theme={null} import { useCheckout } from '@tagadapay/plugin-sdk/v2'; function CheckoutPage() { const { data: checkout, isLoading, error, refetch } = useCheckout(); if (isLoading) return
Loading checkout...
; if (error) return
Error loading checkout
; return (

Checkout

Total: {checkout.total} {checkout.currency}

); } ``` **Returns:** * `data`: Checkout object with all checkout data * `isLoading`: Boolean loading state * `error`: Error object if request failed * `refetch()`: Function to manually refetch data * `isFetching`: Boolean indicating background refetch **Checkout Data Structure:** ```typescript theme={null} interface CheckoutData { checkoutSession: { id: string; token: string; status: string; }; items: CartItem[]; total: number; currency: string; customer?: CustomerInfo; shipping?: ShippingInfo; payment?: PaymentInfo; } ``` ### useProducts() Fetch product catalog with automatic caching. ```tsx theme={null} import { useProducts } from '@tagadapay/plugin-sdk/v2'; function ProductCatalog() { const { data: products, isLoading } = useProducts(); return (
{products?.map((product) => ( ))}
); } ``` **Returns:** * `data`: Array of product objects * `isLoading`: Loading state * `error`: Error state * `refetch()`: Manual refetch function ### useOffer() ⚠️ Deprecated (Deprecated — use usePreviewOffer instead) > [!WARNING] > > **Deprecated.** Use [`usePreviewOffer()`](#usepreviewoffer) instead. > `useOffer` (aliased from `useOfferQuery`) still works but is no longer the > recommended hook for upsell pages. `usePreviewOffer` skips the upfront > checkout-session round-trip, recomputes pricing client-side, and applies the > CRM-configured MIT/CIT payment initiator automatically. `useOffer` will be > removed in a future major version. Single-offer hook that initializes a checkout session up front, exposes a `payOffer()` mutation, and returns offer + line-item state. Kept exported as `useOffer` (aliasing `useOfferQuery`) for backwards compatibility. ```tsx theme={null} import { useOffer } from '@tagadapay/plugin-sdk/v2'; function LegacyUpsell({ offerId, mainOrderId }: { offerId: string; mainOrderId: string }) { const { offer, summary, payOffer, isPaying } = useOffer({ offerId, mainOrderId }); return (

{offer?.name}

{summary?.totalAdjustedAmount} {summary?.currency}

); } ``` New code should use [`usePreviewOffer()`](#usepreviewoffer) instead — same single-offer shape, lighter footprint, automatic MIT/CIT pickup. ### usePreviewOffer() Lightweight offer preview hook for post-checkout upsell pages. Fetches an offer with a precomputed summary, lets the customer pick variants and quantities, and recomputes totals client-side without round-tripping to the backend on every change. Pay once the customer accepts. ```tsx theme={null} import { usePreviewOffer } from '@tagadapay/plugin-sdk/v2'; function UpsellOffer({ offerId, mainOrderId }: { offerId: string; mainOrderId: string }) { const { offer, isLoading, summary, selections, selectVariant, updateQuantity, pay, isPaying, } = usePreviewOffer({ offerId }); if (isLoading) return
Loading…
; const handleAccept = async () => { const { checkoutUrl } = await pay(mainOrderId); if (checkoutUrl) window.location.href = checkoutUrl; }; return (

{offer?.name}

Total: {summary?.totalAdjustedAmount} {summary?.currency}

); } ``` **Options** | Name | Type | Description | | - | - | - | | `offerId` | `string` | The offer to preview. Required. | | `currency` | `string` | Optional override. Defaults to the `?currency=` URL param or the funnel context currency. | | `initialSelections` | `Record` | Pre-populate variant/quantity selections keyed by line-item id. | **Returns** | Name | Description | | - | - | | `offer` | The raw offer object (or `null` while loading). | | `summary` | Computed pricing summary — items, totals, available variants per line. | | `selections` | Current per-line variant + quantity. | | `selectVariant(lineItemId, variantId)` / `selectVariantByProduct(productId, variantId)` | Change variant. | | `updateQuantity(lineItemId, quantity)` / `updateQuantityByProduct(productId, quantity)` | Change quantity. | | `getAvailableVariants(productId)` | List variants for a product including unit prices. | | `pay(mainOrderId?, options?)` | Charge the customer's stored card and return `{ checkoutUrl }`. | | `toCheckout(mainOrderId?)` | Create a checkout session without paying. | | `isLoading` / `isFetching` / `isPaying` / `error` | Loading + error state. | **MIT vs CIT auto-pickup** `pay()` looks up `stepConfig.paymentInitiator` from the runtime `window.__TGD_STEP_CONFIG__` injection and applies it automatically: * `paymentInitiator: 'merchant'` (default) → **MIT**, sent to Stripe as `off_session: true`. No 3DS challenge, higher conversion. * `paymentInitiator: 'customer'` → **CIT**, sent as `setup_future_usage: 'off_session'`. May trigger 3DS — useful when MITs are being declined by the issuer. Merchants flip the toggle from the CRM step config; no plugin code change is required. To override per call, pass `{ initiatedBy }`: ```tsx theme={null} await pay(mainOrderId, { initiatedBy: 'customer' }); ``` `OffersResource.payOffer()` and `OffersResource.payWithCheckoutSession()` use the same auto-pickup. All three paths share `getAssignedPaymentInitiator()` under the hood. ### usePromotions() Fetch active promotions and campaigns. ```tsx theme={null} import { usePromotions } from '@tagadapay/plugin-sdk/v2'; function PromotionsBanner() { const { data: promotions, isLoading } = usePromotions(); return (
{promotions?.map((promo) => ( ))}
); } ``` ### useDiscounts() Manage discount codes and validation. ```tsx theme={null} import { useDiscounts } from '@tagadapay/plugin-sdk/v2'; function DiscountInput() { const { data: discounts, mutate: applyDiscount } = useDiscounts(); const handleApply = (code: string) => { applyDiscount({ code }); }; return (
handleApply(e.target.value)} /> {discounts?.applied &&

✅ Discount applied: {discounts.applied.code}

}
); } ``` ### useOrder() Fetch order details. ```tsx theme={null} import { useOrder } from '@tagadapay/plugin-sdk/v2'; function OrderDetails({ orderId }: { orderId: string }) { const { data: order, isLoading } = useOrder({ orderId }); if (isLoading) return
Loading order...
; return (

Order #{order.id}

Status: {order.status}

Total: {order.total} {order.currency}

); } ``` ### useOrderBump() Manage upsell offers (order bumps). ```tsx theme={null} import { useOrderBump } from '@tagadapay/plugin-sdk/v2'; function OrderBumpSection() { const { data: orderBumps } = useOrderBump(); return (
{orderBumps?.map((bump) => ( ))}
); } ``` ### useStoreConfig() Access store configuration and settings. ```tsx theme={null} import { useStoreConfig } from '@tagadapay/plugin-sdk/v2'; function StoreHeader() { const { data: config } = useStoreConfig(); return (

{config?.storeName}

{config?.storeDescription}

); } ``` ### useShippingRates() Fetch available shipping options. ```tsx theme={null} import { useShippingRates } from '@tagadapay/plugin-sdk/v2'; function ShippingSelector() { const { data: rates, isLoading } = useShippingRates(); return (
{rates?.map((rate) => ( ))}
); } ``` ### usePostPurchases() Fetch post-purchase offers. ```tsx theme={null} import { usePostPurchases } from '@tagadapay/plugin-sdk/v2'; function PostPurchaseOffers() { const { data: offers } = usePostPurchases(); return (
{offers?.map((offer) => ( ))}
); } ``` ### useVipOffers() Fetch VIP exclusive offers. ```tsx theme={null} import { useVipOffers } from '@tagadapay/plugin-sdk/v2'; function VipSection() { const { data: vipOffers } = useVipOffers(); return (

VIP Exclusive Offers

{vipOffers?.map((offer) => ( ))}
); } ``` ### useClubOffers() Manage subscription/club offers. ```tsx theme={null} import { useClubOffers } from '@tagadapay/plugin-sdk/v2'; function ClubOffers() { const { data: clubOffers } = useClubOffers(); return (
{clubOffers?.map((offer) => ( ))}
); } ``` ### useCustomerOrders() Fetch customer order history. ```tsx theme={null} import { useCustomerOrders } from '@tagadapay/plugin-sdk/v2'; function OrderHistory() { const { data: orders, isLoading } = useCustomerOrders(); if (isLoading) return
Loading orders...
; return (

Order History

{orders?.map((order) => ( ))}
); } ``` ### useCustomerSubscriptions() Manage customer subscriptions. ```tsx theme={null} import { useCustomerSubscriptions } from '@tagadapay/plugin-sdk/v2'; function Subscriptions() { const { data: subscriptions } = useCustomerSubscriptions(); return (
{subscriptions?.map((sub) => ( ))}
); } ``` ## Mutation Hooks ### useCheckout() Manage checkout sessions with create, update, and payment capabilities. ```tsx theme={null} import { useCheckout } from '@tagadapay/plugin-sdk/v2'; function CheckoutPage() { const { checkout, init, updateLineItems, updateCustomerAndSessionInfo, error } = useCheckout({ checkoutToken: '', // Empty if creating new checkout }); // Initialize new checkout with items const handleCreateCheckout = async () => { await init({ storeId: 'your-store-id', lineItems: [ { variantId: 'variant_abc123', quantity: 1, }, ], }); }; return ; } ``` **Parameters:** * `checkoutToken`: String - Existing checkout token, or empty string to create new **Returns:** * `checkout`: Checkout session object * `init()`: Function to create a new checkout session with line items * `updateLineItems()`: Function to update cart items * `updateCustomerAndSessionInfo()`: Function to update customer/shipping info * `error`: Error object if any operation fails > [!TIP] > > **Creating a checkout from scratch?** See the complete [Initialize Checkout guide](/developer-tools/sdk/init-checkout-example) for detailed examples including BOGO funnels, bundle selectors, and static resources. *** ### usePayment() Process payments with automatic state management. ```tsx theme={null} import { usePayment } from '@tagadapay/plugin-sdk/v2'; function PaymentForm() { const { mutate: processPayment, isPending, error } = usePayment(); const handleSubmit = async (paymentData) => { await processPayment({ method: 'card', cardNumber: '4242424242424242', // ... other payment data }); }; return (
{/* Payment form fields */} {error &&

Error: {error.message}

}
); } ``` ### usePaymentPolling() Poll payment status for async payments. ```tsx theme={null} import { usePaymentPolling } from '@tagadapay/plugin-sdk/v2'; function PaymentStatus({ paymentId }: { paymentId: string }) { const { data: status, isPolling } = usePaymentPolling({ paymentId }); return (
{isPolling &&

Checking payment status...

}

Status: {status?.status}

); } ``` ## Utility Hooks ### useAuth() Manage authentication and user sessions. ```tsx theme={null} import { useAuth } from '@tagadapay/plugin-sdk/v2'; function AuthButton() { const { user, isAuthenticated, login, logout } = useAuth(); if (isAuthenticated) { return (

Welcome, {user?.name}

); } return ; } ``` **Returns:** * `user`: Current user object * `isAuthenticated`: Boolean auth state * `login()`: Login function * `logout()`: Logout function * `isLoading`: Auth check in progress ### useCustomer() Access customer profile data. ```tsx theme={null} import { useCustomer } from '@tagadapay/plugin-sdk/v2'; function CustomerProfile() { const { data: customer, updateProfile } = useCustomer(); return (

{customer?.firstName} {customer?.lastName}

{customer?.email}

); } ``` ### useCustomerInfos() Manage customer information and validation. ```tsx theme={null} import { useCustomerInfos } from '@tagadapay/plugin-sdk/v2'; function CustomerInfoForm() { const { data, update, validate } = useCustomerInfos(); const handleSubmit = async (formData) => { const isValid = await validate(formData); if (isValid) { await update(formData); } }; return
{/* form fields */}
; } ``` ### useCredits() Manage store credit and balance. ```tsx theme={null} import { useCredits } from '@tagadapay/plugin-sdk/v2'; function CreditBalance() { const { data: credits, apply, remove } = useCredits(); return (

Available Credits: ${credits?.balance}

{credits?.applied && }
); } ``` ### useFunnel() Navigate and track funnel steps. ```tsx theme={null} import { useFunnel } from '@tagadapay/plugin-sdk/v2'; function FunnelNavigation() { const { currentStep, nextStep, previousStep, goToStep } = useFunnel(); return (

Current Step: {currentStep}

); } ``` ### useCheckoutToken() Manage checkout session tokens. ```tsx theme={null} import { useCheckoutToken } from '@tagadapay/plugin-sdk/v2'; function CheckoutSession() { const { checkoutToken, isValid, refresh } = useCheckoutToken(); if (!isValid) { return (
Session expired.
); } return
Token: {checkoutToken}
; } ``` ### useCurrency() Format money and handle currency conversions. ```tsx theme={null} import { useCurrency } from '@tagadapay/plugin-sdk/v2'; function PriceDisplay({ amount, currency }) { const { formatMoney, convertCurrency } = useCurrency(); return (

Price: {formatMoney(amount, currency)}

In USD: {formatMoney(convertCurrency(amount, currency, 'USD'), 'USD')}

); } ``` **formatMoney Options:** ```typescript theme={null} formatMoney(amount: number, currency: string, options?: { showSymbol?: boolean; // Show currency symbol (default: true) showCode?: boolean; // Show currency code (default: false) decimals?: number; // Decimal places (default: 2) locale?: string; // Locale for formatting (default: 'en-US') }) ``` ### useGeoLocation() Detect user's geographic location. ```tsx theme={null} import { useGeoLocation } from '@tagadapay/plugin-sdk/v2'; function LocationBasedContent() { const { country, region, city, loading } = useGeoLocation(); if (loading) return
Detecting location...
; return (

Shipping to: {city}, {region}, {country}

); } ``` ### usePluginConfig() Access plugin-specific configuration. ```tsx theme={null} import { usePluginConfig } from '@tagadapay/plugin-sdk/v2'; function ThemedButton() { const config = usePluginConfig(); return ( ); } ``` ### useTranslation() Internationalization and localization. ```tsx theme={null} import { useTranslation } from '@tagadapay/plugin-sdk/v2'; function TranslatedContent() { const { formatMessage, locale, changeLocale } = useTranslation(); return (

{formatMessage({ id: 'checkout.title' })}

Current locale: {locale}

); } ``` ### useApiClient() Direct access to API client for custom requests. ```tsx theme={null} import { useApiClient } from '@tagadapay/plugin-sdk/v2'; function CustomApiCall() { const apiClient = useApiClient(); const fetchCustomData = async () => { const response = await apiClient.get('/custom-endpoint'); return response.data; }; return ; } ``` ### useApiQuery() Create custom API queries with TanStack Query. ```tsx theme={null} import { useApiQuery } from '@tagadapay/plugin-sdk/v2'; function CustomQuery() { const { data, isLoading } = useApiQuery({ queryKey: ['custom-data'], queryFn: async () => { // Custom API call return await fetch('/api/custom').then((r) => r.json()); }, }); return
{data?.result}
; } ``` ## Payment Hooks ### useThreeds() Handle 3D Secure authentication. ```tsx theme={null} import { useThreeds } from '@tagadapay/plugin-sdk/v2'; function PaymentWithThreeDS() { const { handleThreeDS, isProcessing } = useThreeds(); const processPayment = async (paymentData) => { const result = await handleThreeDS(paymentData); if (result.authenticated) { // Proceed with payment } }; return ( ); } ``` ### useThreedsModal() Manage 3DS modal display. ```tsx theme={null} import { useThreedsModal } from '@tagadapay/plugin-sdk/v2'; function ThreeDSModalManager() { const { isOpen, open, close, authUrl } = useThreedsModal(); return ( <> {isOpen && (