# Combined LLM Context from https://developers.firmly.ai > This file aggregates the Markdown content linked from https://developers.firmly.ai/llms.txt for easier consumption by LLMs. --- # API Reference > **Tip** > **Try it live:** the [interactive API Explorer](/api-explorer/) renders the OpenAPI spec with a built-in request client — browse endpoints, inspect schemas, and build requests in curl, JavaScript, Python, and more. The Explorer covers the **verified core purchase flow** (Standard, `/api/v1`) and the **Agentic Pay** endpoints; the complete endpoint set, including the Advanced (`/api/v2`) flow, is documented on the pages below. ## Base URLs | Surface | Sandbox | Production | |---|---|---| | General API (auth, discovery, catalog, cart, checkout, orders, sessions) | `https://api.firmly.work` | Provided by Firmly at go-live | | Payment (public key, place-order, wallets) | `https://cc.firmly.work` | Provided by Firmly at go-live | These are the **sandbox** hosts. Production runs on **different hosts** from the sandbox. Firmly provides your production base URLs at go-live — plan for a configuration change, not just a new App ID. Going live changes your App ID, your merchants, and your base URLs. > **Note** > Each merchant is served by an **adapter** — Firmly's connector for that merchant's commerce platform. An adapter implements only the operations its platform supports, so some endpoints can return `OperationNotSupported` / `NotImplemented` for a given merchant. See the [glossary](/resources/glossary#adapter). ## Request Format - **Content-Type**: `application/json` for all POST/PUT requests - **Accept**: `application/json` - **Domain Parameter**: Most endpoints require a merchant domain (e.g., `staging.luma.gift`) ## Response Format All responses return JSON with consistent structure: ### Success Response ```json { "cart_id": "1d6af01a-08ec-59f7-8dc6-abd6f6eeed25", "line_items": [ { "line_item_id": "4958451e-0ad5-a545-c865-7b12623e917f", "sku": "MH07-XS-Gray", "quantity": 1, "price": { "currency": "USD", "value": 22.0, "number": 2200, "symbol": "$" }, "line_price": { "currency": "USD", "value": 22.0, "number": 2200, "symbol": "$" }, "msrp": { "currency": "USD", "value": 26.4, "number": 2640, "symbol": "$" }, "image": { "url": "https://staging.luma.gift/mh07-xs-gray.jpg", "alt": "MH07-XS-Gray", "type": "default" } } ], "total": { "currency": "USD", "value": 99.99, "number": 9999, "symbol": "$" } } ``` Every currency-valued field (`price`, `line_price`, `sub_total`, `shipping_total`, `tax_total`, `total`, `msrp`, addon prices, etc.) is returned as an object with `currency` (ISO 4217 code), `value` (decimal), `number` (smallest currency unit — cents for USD), and `symbol`. ### Error Response ```json { "code": 400, "error": "ErrorCode", "description": "Human-readable error message" } ``` ## HTTP Status Codes | Status | Description | |--------|-------------| | 200 | Success | | 400 | Bad Request — Invalid parameters | | 401 | Unauthorized — Invalid or missing token | | 404 | Not Found — Resource doesn't exist | | 409 | Conflict — Business logic error | | 410 | Gone — `ProductDiscontinued`; the resource existed but has been discontinued | | 412 | Precondition Failed — Operation not supported by this merchant, or required consents missing | | 422 | Unprocessable Entity — Validation failed | | 429 | Too Many Requests — `RateLimited`; retry after the `Retry-After` window | | 500 | Internal Server Error | | 501 | Not Implemented — `NotImplemented`; the merchant's adapter does not implement this operation | | 503 | Service Unavailable — `StoreUnavailable`; the merchant store or a downstream dependency is temporarily unavailable | See [Errors & Conventions](/api-reference/errors-and-conventions) for the full error catalog and retry patterns. ## Available APIs - [Authentication](/api-reference/authentication/browser-session) — Token generation and session management - [Discovery](/api-reference/discovery/) — Search products across connected merchants - [Affiliate](/api-reference/affiliate/) — Preserve affiliate attribution through the shopping session - [Catalog](/api-reference/catalog/) — Browse products and retrieve variant information - [Session](/api-reference/session/) — Manage device sessions and preferences - [Cart Management](/api-reference/cart-management/) — Core cart operations - [Promotions](/api-reference/promotions/) — Apply and manage promotional codes - [Shipment Configuration](/api-reference/shipment-configuration/) — Configure fulfillment and shipping methods - [Addon Management](/api-reference/addon-management/) — Manage warranties and protection plans - [Checkout](/api-reference/checkout/) — Complete the purchase flow - [Payment](/api-reference/payment/get-public-key) — Secure payment processing, express checkout, and wallets - [Agentic Pay](/api-reference/agentic-pay/) — Network Token Router for autonomous agent purchases - [Headless SDK](/api-reference/headless-sdk/) — Client SDK for headless checkout builds ## Common Headers ### Required Headers | Header | Description | Example | |--------|-------------|---------| | `x-firmly-authorization` | Access token from authentication. Required on all endpoints **except** the authentication bootstrap — [Browser Session](/api-reference/authentication/browser-session) uses `x-firmly-app-id` instead. See each endpoint's Authentication section for the header it accepts. | `eyJhbGc...` | ### Optional Headers | Header | Description | Example | |--------|-------------|---------| | `x-firmly-request-id` | Unique request identifier for tracking | `req_123abc` | ## Rate Limits See [Rate Limits](/api-reference/rate-limits) for how limits are communicated, the `429` retry pattern, and how to design for them. Specific thresholds are shared during commercial onboarding. ## Support - **Support**: [firmlydocs@firmly.ai](mailto:firmlydocs@firmly.ai) ## Need Implementation Help? - [Implementation Guides](/cookbook/full-cart-api-guide) — Step-by-step guides for building with Firmly APIs - [Pagination](/api-reference/pagination/index.md) - [Standard flow](/api-reference/standard-flow/index.md) --- # Add Addons `POST https://api.firmly.work/api/v2/domains/{domain}/cart/addons` `POST /api/v2/domains/{domain}/cart/addons` Applies the addon selections represented in the request body as the cart's **desired final state**. The endpoint replaces the cart's selections with the supplied list — entries you omit are deselected, entries you include are selected (or updated). Pass `selections: []` to clear all addons. > **Note** > This is a **replace** operation, not an append. Entries you omit are deselected; the request body is treated as the complete desired selection list. ## Authentication - `x-firmly-authorization` (string, required) — Device access token from [Browser Session](/api-reference/authentication/browser-session) > **Note** > This endpoint also accepts **server-to-server (S2S) authentication** for backend integrations acting on behalf of a device: send `Authorization: Bearer ` (or the equivalent `x-firmly-authorization: `) together with `x-firmly-device-id`. See [Server-to-Server Authentication](/api-reference/authentication/server-to-server). ## Path Parameters - `domain` (string, required) — The merchant's domain (e.g. `staging.luma.gift`). ## Request Body - `selections` (object[], required) — Desired final list of selected addons. **Selection entry** - `addon_id` (string, required) — The `addon_id` from one of `cart.addons.offers`. - `selected_line_item_ids` (string[]) — For `PER_ITEM` / `FREE_GROUPING` offers, the line items this addon applies to. Pass an empty array to disable the addon for all items while keeping it referenced. - `selected_child_ids` (string[]) — For offers with `child_offers`, the `addon_id`s of the chosen child entries. ## Response Returns the full cart (same schema as [Get Cart](/api-reference/cart-management/get-cart)). The relevant areas after a successful call: - `cart.addons.selections` — the new list. - `cart.addons.offers` — possibly re-evaluated (e.g. mutually-exclusive offers in the same `exclusive_group_id`). - `cart.addon_total`, `cart.total` — recalculated. ## Examples **Single CART-scope addon** ```bash curl -X POST https://api.firmly.work/api/v2/domains/staging.luma.gift/cart/addons \ -H "x-firmly-authorization: YOUR_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "selections": [ { "addon_id": "shipping_protection" } ] }' ``` **Item-scoped addon on multiple items** ```bash curl -X POST https://api.firmly.work/api/v2/domains/staging.luma.gift/cart/addons \ -H "x-firmly-authorization: YOUR_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "selections": [ { "addon_id": "extended_warranty", "selected_line_item_ids": ["761ff52b-8e6d-d373-fdf2-91a1a70df20c", "38d3f385-ea8d-8bb2-dcfc-759ac85af6ef"] } ] }' ``` **Tiered addon (parent + child)** ```bash curl -X POST https://api.firmly.work/api/v2/domains/staging.luma.gift/cart/addons \ -H "x-firmly-authorization: YOUR_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "selections": [ { "addon_id": "extended_warranty", "selected_line_item_ids": ["761ff52b-8e6d-d373-fdf2-91a1a70df20c"], "selected_child_ids": ["33fd7d89-635d-5466-1a50-01519c4488a3"] } ] }' ``` **Clear all addons** ```bash curl -X POST https://api.firmly.work/api/v2/domains/staging.luma.gift/cart/addons \ -H "x-firmly-authorization: YOUR_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "selections": [] }' ``` ## Response Example ```json { "cart_id": "eac41edf-215f-cdf5-9bab-1253e3fc6390", "platform_id": "example_commerce", "shop_id": "staging.luma.gift", "cart_status": "active", "line_items": [ { "line_item_id": "761ff52b-8e6d-d373-fdf2-91a1a70df20c", "sku": "MH07-XS-Gray", "quantity": 1, "price": { "currency": "USD", "value": 54.0, "number": 5400, "symbol": "$" }, "line_price": { "currency": "USD", "value": 54.0, "number": 5400, "symbol": "$" }, "msrp": { "currency": "USD", "value": 64.8, "number": 6480, "symbol": "$" }, "image": { "url": "https://staging.luma.gift/mh07-xs-gray.jpg", "alt": "MH07-XS-Gray", "type": "default" } }, { "line_item_id": "38d3f385-ea8d-8bb2-dcfc-759ac85af6ef", "sku": "WS12-XS-Orange", "quantity": 1, "price": { "currency": "USD", "value": 22.0, "number": 2200, "symbol": "$" }, "line_price": { "currency": "USD", "value": 22.0, "number": 2200, "symbol": "$" }, "msrp": { "currency": "USD", "value": 26.4, "number": 2640, "symbol": "$" }, "image": { "url": "https://staging.luma.gift/ws12-xs-orange.jpg", "alt": "WS12-XS-Orange", "type": "default" } } ], "addons": { "offers": [ { "addon_id": "shipping_protection", "display": { "name": "Shipping Protection" }, "scope": "CART", "coverage_mode": "PREDEFINED_GROUP", "price": { "currency": "USD", "value": 12.99, "number": 1299, "symbol": "$" } }, { "addon_id": "extended_warranty", "display": { "name": "Extended Warranty - 3 Year" }, "scope": "ITEM", "coverage_mode": "PER_ITEM", "eligible_line_item_ids": [ "761ff52b-8e6d-d373-fdf2-91a1a70df20c", "38d3f385-ea8d-8bb2-dcfc-759ac85af6ef" ], "price": { "currency": "USD", "value": 5.4, "number": 540, "symbol": "$" } } ], "selections": [ { "addon_id": "shipping_protection", "price": { "currency": "USD", "value": 12.99, "number": 1299, "symbol": "$" } } ] }, "sub_total": { "currency": "USD", "value": 76.0, "number": 7600, "symbol": "$" }, "fees": [ { "description": "Recycle fee", "currency": "USD", "value": 2.00, "number": 200, "symbol": "$" } ], "fee_total": { "currency": "USD", "value": 2.00, "number": 200, "symbol": "$" }, "addon_total": { "currency": "USD", "value": 12.99, "number": 1299, "symbol": "$" }, "total": { "currency": "USD", "value": 90.99, "number": 9099, "symbol": "$" }, "schema_version": "2.0" } ``` ## Error Responses Errors return a JSON body with `code`, `error`, and `description`. Program against the `error` value — descriptions are human-readable and may change. **400 — MissingAuthHeader** The `x-firmly-authorization` header is missing or empty. ```json { "code": 400, "error": "MissingAuthHeader", "description": "x-firmly-authorization header is missing or invalid." } ``` **400 — InvalidToken** The authorization token is not a valid JWT structure. ```json { "code": 400, "error": "InvalidToken", "description": "Jwt token is invalid." } ``` **400 — InvalidAPIToken** The API token (server-to-server secret) is invalid or has been revoked. ```json { "code": 400, "error": "InvalidAPIToken", "description": "API token is invalid." } ``` **400 — BadRequest** Server-to-server auth was attempted but required headers are missing or malformed. ```json { "code": 400, "error": "BadRequest", "description": "Bad request." } ``` **401 — Unauthorized** The authorization token was rejected. ```json { "code": 401, "error": "Unauthorized", "description": "Unauthorized." } ``` **401 — InvalidJWTToken** The device JWT signature does not verify, or required claims are missing. ```json { "code": 401, "error": "InvalidJWTToken", "description": "Jwt token is invalid." } ``` **404 — PartnerNotFound** The `appid` claim on the device JWT does not map to a known partner / tenant. ```json { "code": 404, "error": "PartnerNotFound", "description": "Partner not found." } ``` **404 — DomainNotFound** The `{domain}` path parameter does not match any merchant configured with Firmly, or the merchant has been disabled. ```json { "code": 404, "error": "DomainNotFound", "description": "This domain was not found in firmly servers." } ``` **404 — CartNotFound** No cart exists for this device on this domain. ```json { "code": 404, "error": "CartNotFound", "description": "Cart was not found." } ``` **412 — OperationNotSupported** The merchant's platform does not support addon operations. ```json { "code": 412, "error": "OperationNotSupported", "description": "This operation is not supported for this store." } ``` **400 — InvalidInputBody** Request body fails schema validation. Each `selections[]` entry needs at minimum an `addon_id` string; `selected_line_item_ids` and `selected_child_ids` must be string arrays when present. ```json { "code": 400, "error": "InvalidInputBody", "description": "The body is not processable" } ``` **422 — InvalidInputBody** The body is well-formed, but the merchant rejected a value in it — typically an `addon_id` that does not exist on this cart, or a selection shape the merchant does not offer. Same error name as the 400 above, raised one layer deeper, so branch on `code` and not on `error` alone. `description` names the rejected value. ```json { "code": 422, "error": "InvalidInputBody", "description": "No platform_addon_id found for addon_id: 8f3a2b1c-1d2e-4a5b-9c8d-1a2b3c4d5e6f" } ``` **422 — UnprocessableEntity** The selections violate a constraint exposed by the merchant — e.g. an `addon_id` that isn't in `cart.addons.offers`, a `selected_line_item_id` not in `eligible_line_item_ids`, a missing addon listed in another offer's `requires_addon_ids`, or two simultaneously-selected offers sharing the same `exclusive_group_id`. ```json { "code": 422, "error": "UnprocessableEntity", "description": "The given payload has unprocessable, invalid or non-existent data. Please check the data and try again." } ``` **503 — StoreUnavailable** The merchant's API returned an unexpected response and the request could not be fulfilled. Retry with backoff. ```json { "code": 503, "error": "StoreUnavailable", "description": "Store is unavailable." } ``` --- # Add Line Item `POST https://api.firmly.work/api/v2/domains/{domain}/cart/line-items` ## Overview The Add Line Item endpoint adds a new product to the shopping cart with these features: - **Automatic Shipment Assignment**: Once a shipping address is set, items are automatically grouped into shipments based on their fulfillment requirements — see [Shipping & Fulfillment](/api-reference/shipment-configuration/shipping-and-fulfillment#automatic-shipment-assignment) - **Catalog Integration**: Uses `add_to_cart_ref` object directly from catalog API responses - **Variant Support**: Handles configurable products with variant handles - **Cart Creation**: Automatically creates a new cart if one doesn't exist - **Optional Cart Clearing**: Can clear existing cart before adding new item ## Authentication - `x-firmly-authorization` (string, required) — Device access token from [Browser Session](/api-reference/authentication/browser-session) > **Note** > This endpoint also accepts **server-to-server (S2S) authentication** for backend integrations acting on behalf of a device: send `Authorization: Bearer ` (or the equivalent `x-firmly-authorization: `) together with `x-firmly-device-id`. See [Server-to-Server Authentication](/api-reference/authentication/server-to-server). ## Path Parameters - `domain` (string, required) — Domain of the merchant website (e.g., `staging.luma.gift`) ## Query Parameters - `flush_cart` (string `"true"` | `"false"`, default `"false"`) — When `"true"`, clears the cart before adding the new item. **This is a string, not a boolean** — only the exact lowercase strings `"true"`/`"false"` are accepted; any other value (`1`, `0`, `True`, empty string) returns **`400 InvalidInputQuery`** rather than being treated as falsy. > **Warning** > This endpoint's query-string validation is **strict — it rejects unrecognized parameters**. Sending any query key other than `flush_cart` (e.g. a stray `utm_*` tracking param) returns **`400 InvalidInputQuery`**. Don't append arbitrary query parameters to this URL. ## Request Body - `add_to_cart_ref` (object, required) — Product reference from catalog API containing variant information **Properties:** - `variant_id` (string, required): Product variant identifier - `product_id` (string, optional): Parent product identifier - `variant_handles` (array, optional): Array of variant configuration handles (e.g., `["color:blue", "size:large"]`) - `quantity` (integer, required) — Quantity to add (minimum 1). Numeric strings (e.g. `"2"`) are also accepted and coerced to a number. ## Response Returns the complete shopping cart including the newly added item. See [Get Cart](/api-reference/cart-management/get-cart) for full response schema. ### Key Response Features: - `shipments` (array) — Empty until a shipping address is set. Shipment grouping is populated by [Set Shipping Info](/api-reference/checkout/set-shipping-info). - `addons.offers` (array) — Available addon services for the updated cart. Offer fields such as `coverage_mode`, `eligible_line_item_ids`, and `child_offers` are documented in [Addon Management](/api-reference/addon-management/). - `schema_version` (string) — Indicates the cart schema version ## Code Examples **cURL** ```bash curl --request POST \ --url https://api.firmly.work/api/v2/domains/staging.luma.gift/cart/line-items \ --header 'Content-Type: application/json' \ --header 'x-firmly-authorization: YOUR_TOKEN' \ --data '{ "add_to_cart_ref": { "variant_id": "WS12-XS-Orange" }, "quantity": 1 }' ``` **JavaScript** ```javascript const response = await fetch('https://api.firmly.work/api/v2/domains/staging.luma.gift/cart/line-items', { method: 'POST', headers: { 'Content-Type': 'application/json', 'x-firmly-authorization': 'YOUR_TOKEN' }, body: JSON.stringify({ add_to_cart_ref: { variant_id: 'WS12-XS-Orange' }, quantity: 1 }) }); const cart = await response.json(); console.log(cart); ``` **Python** ```python import requests response = requests.post( 'https://api.firmly.work/api/v2/domains/staging.luma.gift/cart/line-items', headers={ 'Content-Type': 'application/json', 'x-firmly-authorization': 'YOUR_TOKEN' }, json={ 'add_to_cart_ref': { 'variant_id': 'WS12-XS-Orange' }, 'quantity': 1 } ) cart = response.json() print(cart) ``` **PHP** ```php [ 'variant_id' => 'WS12-XS-Orange' ], 'quantity' => 1 ]; curl_setopt_array($curl, [ CURLOPT_URL => "https://api.firmly.work/api/v2/domains/staging.luma.gift/cart/line-items", CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => true, CURLOPT_HTTPHEADER => [ "Content-Type: application/json", "x-firmly-authorization: YOUR_TOKEN" ], CURLOPT_POSTFIELDS => json_encode($data) ]); $response = curl_exec($curl); curl_close($curl); $cart = json_decode($response, true); print_r($cart); ?> ``` ## Advanced Examples ### With Variant Handles For configurable products with multiple options: ```json { "add_to_cart_ref": { "variant_id": "MH07-XS-Gray", "variant_handles": ["color:gray", "size:xs"] }, "quantity": 1 } ``` ### Clear Cart First To replace cart contents with a new item: ```bash curl --request POST \ --url 'https://api.firmly.work/api/v2/domains/staging.luma.gift/cart/line-items?flush_cart=true' \ --header 'Content-Type: application/json' \ --header 'x-firmly-authorization: YOUR_TOKEN' \ --data '{ "add_to_cart_ref": { "variant_id": "WT09-XS-White" }, "quantity": 2 }' ``` ## Catalog Integration The `add_to_cart_ref` object should be passed directly from catalog API responses: **Catalog API Response** ```json { "products": [ { "product_id": "WS12", "variants": [ { "add_to_cart_ref": { "variant_id": "WS12-XS-Orange", "variant_handles": ["color:orange", "size:xs"] } } ] } ] } ``` **Add to Cart Request** ```json { "add_to_cart_ref": { "variant_id": "WS12-XS-Orange", "variant_handles": ["color:orange", "size:xs"] }, "quantity": 1 } ``` ## Response Example ```json { "line_items": [ { "line_item_id": "9b13b973-8d55-5d00-b22a-1b1b788d80f9", "platform_line_item_id": "0", "sku": "WS12-XS-Orange", "variant_description": "Color: Orange, Size: XS", "description": "Radiant Tee", "base_sku": "WS12", "quantity": 1, "price": { "currency": "USD", "value": 22.00, "number": 2200, "symbol": "$" }, "line_price": { "currency": "USD", "value": 22.00, "number": 2200, "symbol": "$" }, "msrp": { "currency": "USD", "value": 22.00, "number": 2200, "symbol": "$" }, "image": { "url": "https://cdn.staging.luma.gift/product/radiant-tee-orange.jpg", "alt": "Radiant Tee in Orange", "type": "default" }, "requires_shipping": true } ], "shipments": [], "sub_total": { "currency": "USD", "value": 22.00, "number": 2200, "symbol": "$" }, "shipping_total": { "currency": "USD", "value": 0, "number": 0, "symbol": "$" }, "tax_total": { "currency": "USD", "value": 0, "number": 0, "symbol": "$" }, "fees": [ { "description": "Recycle fee", "currency": "USD", "value": 2.00, "number": 200, "symbol": "$" } ], "fee_total": { "currency": "USD", "value": 2.00, "number": 200, "symbol": "$" }, "total": { "currency": "USD", "value": 24.00, "number": 2400, "symbol": "$" }, "addons": { "offers": [ { "addon_id": "protection-new-item-12345", "display": { "name": "Product Protection Plan" }, "price": { "currency": "USD", "value": 0, "number": 0, "symbol": "$" }, "scope": "ITEM", "coverage_mode": "PER_ITEM", "eligible_line_item_ids": [ "9b13b973-8d55-5d00-b22a-1b1b788d80f9" ], "child_offers": [ { "addon_id": "A0-FURN-2y", "display": { "name": "2 Year Protection" }, "scope": "INHERIT", "coverage_mode": "PER_ITEM", "eligible_line_item_ids": [ "9b13b973-8d55-5d00-b22a-1b1b788d80f9" ], "price": { "currency": "USD", "value": 149.99, "number": 14999, "symbol": "$" } }, { "addon_id": "A0-FURN-3y", "display": { "name": "3 Year Protection" }, "scope": "INHERIT", "coverage_mode": "PER_ITEM", "eligible_line_item_ids": [ "9b13b973-8d55-5d00-b22a-1b1b788d80f9" ], "price": { "currency": "USD", "value": 199.99, "number": 19999, "symbol": "$" } } ] } ], "selections": [] }, "addon_total": { "currency": "USD", "value": 0, "number": 0, "symbol": "$" }, "schema_version": "2.0" } ``` --- ## Related Endpoints - [Get Cart](/api-reference/cart-management/get-cart) — View current cart state - [Update Line Item](/api-reference/cart-management/update-line-item) — Modify cart items - [Clear Cart](/api-reference/cart-management/clear-cart) — Empty the cart ## Error Responses Errors return a JSON body with `code`, `error`, and `description`. Program against the `error` value — descriptions are human-readable and may change. **400 — MissingAuthHeader** The `x-firmly-authorization` header is missing or empty. ```json { "code": 400, "error": "MissingAuthHeader", "description": "x-firmly-authorization header is missing or invalid." } ``` **400 — InvalidToken** The authorization token is not a valid JWT structure. ```json { "code": 400, "error": "InvalidToken", "description": "Jwt token is invalid." } ``` **400 — InvalidAPIToken** The API token (server-to-server secret) is invalid or has been revoked. ```json { "code": 400, "error": "InvalidAPIToken", "description": "API token is invalid." } ``` **400 — BadRequest** Server-to-server auth was attempted but the required headers (`x-firmly-authorization` plus `x-firmly-device-id`) are missing or malformed. ```json { "code": 400, "error": "BadRequest", "description": "Bad request." } ``` **401 — Unauthorized** The authorization token was rejected. ```json { "code": 401, "error": "Unauthorized", "description": "Unauthorized." } ``` **401 — InvalidJWTToken** The device JWT signature does not verify, or required claims are missing. ```json { "code": 401, "error": "InvalidJWTToken", "description": "Jwt token is invalid." } ``` **404 — PartnerNotFound** The `appid` claim on the device JWT does not map to a known partner / tenant — typically a token from a different environment. ```json { "code": 404, "error": "PartnerNotFound", "description": "Partner not found." } ``` **404 — DomainNotFound** The `{domain}` path parameter does not match any merchant configured with Firmly, or the merchant has been disabled. Verify the domain string (case-sensitive, no protocol or trailing slash). ```json { "code": 404, "error": "DomainNotFound", "description": "This domain was not found in firmly servers." } ``` **404 — ProductNotFound** The `variant_id` supplied in `add_to_cart_ref` does not exist in the merchant catalog. Refresh from the Catalog API and retry with a current ID. ```json { "code": 404, "error": "ProductNotFound", "description": "Product not found." } ``` **409 — NotEnoughStockError** The requested `quantity` exceeds available inventory for the variant. Reduce quantity or wait for restock. ```json { "code": 409, "error": "NotEnoughStockError", "description": "Not enough stock." } ``` **409 — CannotCreateCart** The merchant system rejected creation of a new cart. Often transient — retry; if it persists, check merchant system health. ```json { "code": 409, "error": "CannotCreateCart", "description": "Cannot create cart." } ``` **412 — ProductNotSupported** The product type is not supported by this merchant's adapter (e.g. some adapters reject gift cards, digital-only SKUs, or subscription items). ```json { "code": 412, "error": "ProductNotSupported", "description": "Product is not supported." } ``` **412 — PostalCodeRequired** The merchant requires a postal code before items can be added. Call [Set Postal Code](/api-reference/session/set-postal-code), then retry. ```json { "code": 412, "error": "PostalCodeRequired", "description": "Postal code is required." } ``` **412 — OperationNotSupported** The merchant's platform does not support this operation. Some platform adapters do not implement every cart operation; check with [Firmly](/contact) whether this endpoint is available for the merchant. ```json { "code": 412, "error": "OperationNotSupported", "description": "This operation is not supported for this store." } ``` **412 — NoLineItemError** The merchant accepted the request but did not return a line item — typically indicates a product was silently rejected by merchant validation. Verify the variant is purchasable and try again. ```json { "code": 412, "error": "NoLineItemError", "description": "No line item." } ``` **400 — InvalidInputBody** Request body is missing required fields or fails schema validation. Ensure `add_to_cart_ref.variant_id` and `quantity` are present and `quantity >= 1`. ```json { "code": 400, "error": "InvalidInputBody", "description": "The body is not processable" } ``` --- # Add Promo Codes `POST https://api.firmly.work/api/v2/domains/{domain}/cart/promo-codes` Applies one or more promotional codes to the cart. The merchant validates each code and applies any eligible discount. The response is the updated cart with applied codes in `coupons` and recalculated totals. ## Authentication - `x-firmly-authorization` (string, required) — Device access token from [Browser Session](/api-reference/authentication/browser-session) > **Note** > This endpoint also accepts **server-to-server (S2S) authentication** for backend integrations acting on behalf of a device. Instead of the `x-firmly-authorization` device token, send `Authorization: Bearer ` (your Firmly API token) together with `x-firmly-device-id` identifying the target device. ## Path Parameters - `domain` (string, required) — The merchant's domain (e.g. `staging.luma.gift`). ## Request Body - `promo_codes` (string[], required) — Array of promotional codes to apply. Length 1–10. Each entry is a non-empty trimmed string. ## Response Returns the full cart (same schema as [Get Cart](/api-reference/cart-management/get-cart)). Promotion-relevant fields after a successful apply: - `coupons` — array of currently applied codes (strings). - `cart_discount` — total discount applied to the cart (Amount). - `cart_discount_breakdown` — per-promotion breakdown (when the merchant exposes it). - `line_items[].discount` / `line_items[].line_discount` — per-line amounts (when the merchant exposes them). - `sub_total`, `tax_total`, `total` — recalculated. > **Note** > When a promotion applies, a line item's `line_price` is returned **net of the line's discount**. In the example below the tee is `price` $22.00 × 2 = $44.00 gross; after the code's $20.00 line discount, `line_price` is $24.00. `sub_total` remains the gross total across line items; `cart_discount` is subtracted separately when computing `total`. ## Examples **Single Code** ```bash curl -X POST https://api.firmly.work/api/v2/domains/staging.luma.gift/cart/promo-codes \ -H "x-firmly-authorization: YOUR_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "promo_codes": ["SAVE20"] }' ``` **Multiple Codes** ```bash curl -X POST https://api.firmly.work/api/v2/domains/staging.luma.gift/cart/promo-codes \ -H "x-firmly-authorization: YOUR_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "promo_codes": ["SAVE20", "FREESHIP", "LOYALTY10"] }' ``` **JavaScript** ```javascript const response = await fetch('https://api.firmly.work/api/v2/domains/staging.luma.gift/cart/promo-codes', { method: 'POST', headers: { 'x-firmly-authorization': 'YOUR_TOKEN', 'Content-Type': 'application/json' }, body: JSON.stringify({ promo_codes: ['SAVE20'] }) }); const cart = await response.json(); ``` **Python** ```python import requests response = requests.post( 'https://api.firmly.work/api/v2/domains/staging.luma.gift/cart/promo-codes', headers={ 'x-firmly-authorization': 'YOUR_TOKEN', 'Content-Type': 'application/json' }, json={'promo_codes': ['SAVE20']} ) cart = response.json() ``` ## Response Example ```json { "cart_id": "a5600193-2c13-3356-d063-711da63b7cd7", "platform_id": "example_commerce", "shop_id": "staging.luma.gift", "cart_status": "active", "line_items": [ { "line_item_id": "bd3710bc-97ef-408d-7382-43b7e5de712f", "sku": "WS12-XS-Orange", "description": "Radiant Tee", "quantity": 2, "price": { "currency": "USD", "value": 22.00, "number": 2200, "symbol": "$" }, "line_price": { "currency": "USD", "value": 44.00, "number": 4400, "symbol": "$" }, "msrp": { "currency": "USD", "value": 28.00, "number": 2800, "symbol": "$" }, "discount": { "currency": "USD", "value": 10.00, "number": 1000, "symbol": "$" }, "line_discount": { "currency": "USD", "value": 20.00, "number": 2000, "symbol": "$" }, "image": { "url": "https://staging.luma.gift/radiant-tee.jpg", "alt": "Radiant Tee", "type": "default" }, "requires_shipping": true } ], "coupons": ["SAVE20"], "sub_total": { "currency": "USD", "value": 44.00, "number": 4400, "symbol": "$" }, "cart_discount": { "currency": "USD", "value": 20.00, "number": 2000, "symbol": "$" }, "shipping_total": { "currency": "USD", "value": 9.99, "number": 999, "symbol": "$" }, "tax_total": { "currency": "USD", "value": 2.40, "number": 240, "symbol": "$" }, "fees": [{ "description": "Recycle fee", "currency": "USD", "value": 2.00, "number": 200, "symbol": "$" }], "fee_total": { "currency": "USD", "value": 2.00, "number": 200, "symbol": "$" }, "total": { "currency": "USD", "value": 38.39, "number": 3839, "symbol": "$" }, "schema_version": "2.0" } ``` ## Error Responses Errors return a JSON body with `code`, `error`, and `description`. Program against the `error` value — descriptions are human-readable and may change. **400 — MissingAuthHeader** The `x-firmly-authorization` header is missing or empty. ```json { "code": 400, "error": "MissingAuthHeader", "description": "x-firmly-authorization header is missing or invalid." } ``` **400 — InvalidToken** The authorization token is not a valid JWT structure. ```json { "code": 400, "error": "InvalidToken", "description": "Jwt token is invalid." } ``` **400 — InvalidAPIToken** The API token (server-to-server secret) is invalid or has been revoked. ```json { "code": 400, "error": "InvalidAPIToken", "description": "API token is invalid." } ``` **400 — BadRequest** Server-to-server auth was attempted but required headers are missing or malformed. ```json { "code": 400, "error": "BadRequest", "description": "Bad request." } ``` **401 — Unauthorized** The authorization token was rejected. ```json { "code": 401, "error": "Unauthorized", "description": "Unauthorized." } ``` **401 — InvalidJWTToken** The device JWT signature does not verify, or required claims are missing. ```json { "code": 401, "error": "InvalidJWTToken", "description": "Jwt token is invalid." } ``` **404 — PartnerNotFound** The `appid` claim on the device JWT does not map to a known partner / tenant. ```json { "code": 404, "error": "PartnerNotFound", "description": "Partner not found." } ``` **404 — DomainNotFound** The `{domain}` path parameter does not match any merchant configured with Firmly, or the merchant has been disabled. ```json { "code": 404, "error": "DomainNotFound", "description": "This domain was not found in firmly servers." } ``` **404 — CartNotFound** No cart exists for this device on this domain. Add an item first via [Add Line Item](/api-reference/cart-management/add-line-item). ```json { "code": 404, "error": "CartNotFound", "description": "Cart was not found." } ``` **409 — InvalidPromoCode** One or more codes are invalid, expired, or not recognized by the merchant. ```json { "code": 409, "error": "InvalidPromoCode", "description": "Invalid promo code." } ``` **409 — PromoNotAvailable** The code exists but is not available for the current cart (e.g. minimum-purchase not met, product-restricted, customer-segment-restricted). ```json { "code": 409, "error": "PromoNotAvailable", "description": "Promo is not available." } ``` **409 — MultipleDiscountCodesNotSupported** The merchant does not allow more than one discount code to be applied at once, but the request (or the resulting cart) would carry multiple codes. Apply a single code instead. ```json { "code": 409, "error": "MultipleDiscountCodesNotSupported", "description": "Multiple discount codes are not supported." } ``` **412 — OperationNotSupported** The merchant's platform does not support applying promo codes via API. ```json { "code": 412, "error": "OperationNotSupported", "description": "This operation is not supported for this store." } ``` **400 — InvalidInputBody** Request body fails schema validation. `promo_codes` must be an array of 1–10 non-empty trimmed strings. ```json { "code": 400, "error": "InvalidInputBody", "description": "The body is not processable" } ``` --- # Addon Management The Addon Management API selects or removes merchant-defined add-on (addon) services on a cart (warranties, protection plans, gift wrap, installation services, etc.). The set of available offers, their pricing, and any constraints come from the merchant — Firmly exposes them on `cart.addons.offers` and applies the buyer's choices to `cart.addons.selections`. ## Available Endpoints | Method | Path | Description | | ------ | ---- | ----------- | | POST | `/api/v2/domains/{domain}/cart/addons` | Set the desired addon selections (add / replace). | | POST | `/api/v2/domains/{domain}/cart/addons/_remove` | Remove a specific addon (whole, per-item, or per-child). | - [Add Addons](/api-reference/addon-management/add-addon) — Set the desired addon selections on the cart. - [Remove Addon](/api-reference/addon-management/remove-addon) — Remove a specific addon (whole, per-item, or per-child). ## Cart Addons Shape `cart.addons` is an object with two arrays: - `offers` — what the merchant is offering for this cart. - `selections` — what the buyer has currently selected. ### Offer fields | Field | Type | Description | | ------------------------ | ----------------------------------------------------- | ----------- | | `addon_id` | string | Stable id used to select / remove the offer. | | `platform_addon_id` | string (optional) | Merchant-side identifier. | | `display` | `{ name, description?, long_description?, image_url?, links? }` | Render-ready content. | | `scope` | `ITEM` \| `GROUP` \| `CART` \| `INHERIT` | Where the addon applies. | | `coverage_mode` | `PER_ITEM` \| `PREDEFINED_GROUP` \| `FREE_GROUPING` | How a selection maps onto line items. | | `price` | Amount | Headline price. Always present; `hide_price: true` only suppresses display — the value is still returned. | | `hide_price` | boolean (optional) | Suppress price in the UI. | | `eligible_line_item_ids` | string[] (optional) | Line items the offer can attach to. | | `line_item_pricing` | object keyed by `line_item_id` (optional) | Per-item override of `price` / `hide_price`. | | `constraints` | `{ exclusive_group_id?, requires_addon_ids? }` (optional) | Selection rules. | | `child_offers` | array of nested offers (optional) | For tiered or hierarchical addons. | ### Selection fields | Field | Type | Description | | ------------------------ | ------------------------------------- | ----------- | | `addon_id` | string | The offer's `addon_id`. | | `selected_line_item_ids` | string[] (optional) | Items the selection applies to (for `PER_ITEM` and `FREE_GROUPING` modes). | | `selected_child_ids` | string[] (optional) | Chosen child offer ids when the offer has `child_offers`. | | `hide_price` | boolean (optional) | Mirror of the offer flag. | | `price` | Amount (optional) | Calculated server-side. | | `line_item_pricing` | object keyed by `line_item_id` (optional) | Per-item calculated price. | | `metadata` | object (optional) | Arbitrary merchant-specific metadata returned with the selection. | ## Constraint Semantics The `constraints` block on an offer has only two fields, both optional: - `exclusive_group_id` — when multiple offers share the same `exclusive_group_id`, selecting one of them deselects the others (e.g. mutually exclusive warranty tiers). - `requires_addon_ids` — selecting this offer requires the listed `addon_id`s to also be selected (e.g. an extended warranty that requires the base warranty). ## Pricing Notes - `price` on a `CART`-scope offer is the headline cart-wide price. - `price` on an `ITEM` / `GROUP`-scope offer is the per-attached-entity price; per-item overrides appear in `line_item_pricing` keyed by `line_item_id`. - `cart.addon_total` carries the sum of selected-addon prices and feeds into `cart.total`. ## Example: `cart.addons` Snippet ```json { "offers": [ { "addon_id": "shipping_protection", "display": { "name": "Shipping Protection", "description": "Protect your entire order" }, "scope": "CART", "coverage_mode": "PREDEFINED_GROUP", "price": { "currency": "USD", "value": 4.99, "number": 499, "symbol": "$" } }, { "addon_id": "extended_warranty", "display": { "name": "3-Year Extended Warranty" }, "scope": "ITEM", "coverage_mode": "PER_ITEM", "eligible_line_item_ids": ["761ff52b-8e6d-d373-fdf2-91a1a70df20c", "38d3f385-ea8d-8bb2-dcfc-759ac85af6ef"], "price": { "currency": "USD", "value": 89.99, "number": 8999, "symbol": "$" }, "line_item_pricing": { "761ff52b-8e6d-d373-fdf2-91a1a70df20c": { "price": { "currency": "USD", "value": 89.99, "number": 8999, "symbol": "$" } }, "38d3f385-ea8d-8bb2-dcfc-759ac85af6ef": { "price": { "currency": "USD", "value": 29.99, "number": 2999, "symbol": "$" } } }, "child_offers": [ { "addon_id": "EW-2YR", "display": { "name": "2 Year" }, "scope": "INHERIT", "coverage_mode": "PER_ITEM", "price": { "currency": "USD", "value": 49.99, "number": 4999, "symbol": "$" } }, { "addon_id": "33fd7d89-635d-5466-1a50-01519c4488a3", "display": { "name": "3 Year" }, "scope": "INHERIT", "coverage_mode": "PER_ITEM", "price": { "currency": "USD", "value": 89.99, "number": 8999, "symbol": "$" } } ] } ], "selections": [] } ``` --- # Affiliate The Affiliate API supports two ways to associate a shopper's purchase with affiliate tracking: a partner-supplied affiliate link (BYO) or Firmly-managed tracking created during the shopping session. If the shopper later completes an eligible order, Firmly can report the conversion to the configured affiliate network. > **Warning** > **This section is for partner integrations enabled by Firmly.** Firmly's drop-in handles affiliate attribution automatically. Standard merchant and drop-in integrations should not call Start Journey directly. ## In plain terms Publishers such as media sites, blogs, and creators may earn commission when a shopper purchases through an eligible link. Affiliate attribution connects the original link interaction to a later order. Firmly keeps that attribution in the authenticated shopping session and uses it when an eligible order is completed. ## Attribution models Firmly configures one of these models during partner onboarding. **Start Journey is used only for BYO attribution**. Firmly-managed attribution is used when the partner does not have its own affiliate-network relationship. | Mode | How tracking starts | Affiliate-network account | Conversion reporting | |---|---|---|---| | **BYO (Bring Your Own Link)** | Shopper clicks an affiliate link supplied by the partner; Firmly resolves and stores the click. | The partner's own account and network credentials | Firmly reports through the partner's network account. | | **Firmly-managed** | Used when the partner has no affiliate-network relationship; Firmly creates and stores tracking for the shopping session. | Firmly's existing affiliate relationships and accounts | Firmly reports through its own account and settles the partner's commission according to the agreement. | Both models can lead to conversion reporting when the partner, merchant, and affiliate-network rules allow it. Partners with an existing affiliate business typically choose BYO; partners new to affiliate marketing typically start with Firmly-managed. ## What Firmly provides - **Link resolution** — follows the affiliate link supplied by the partner, then identifies the merchant page and available attribution. - **Session continuity** — keeps attribution associated with the authenticated device session while the shopper moves through checkout. - **Conversion reporting** — submits eligible completed orders using the reporting method configured for the partner and merchant. - **Checkout independence** — if affiliate tracking fails, the shopper can still browse and complete checkout. The order may simply not be linked to an affiliate. ## Business boundaries > **Note** > A captured click or submitted conversion does not guarantee commission. Final attribution, commission approval, attribution windows, cancellations, returns, and payout are governed by the merchant's affiliate program and the affiliate network. - Attribution is scoped by merchant within the authenticated device session. Start Journey does not connect attribution across separate device sessions. - Direct use requires partner enablement and access to the merchant reached by the supplied URL. - The partner and merchant must be configured for affiliate reporting before a conversion can be submitted. - For the same merchant and device session, a later successfully resolved journey replaces the previously stored attribution. Call Start Journey once for each qualified landing; replaying the same request may register the click more than once. ## Where it fits 1. Establish a device session with [Browser Session](/api-reference/authentication/browser-session). 2. For **BYO only**, a partner integration enabled by Firmly sends the affiliate link itself, once and before cart building. Managed attribution does not call Start Journey. 3. Continue shopping without making browsing or checkout conditional on attribution success. 4. Complete the order. If the partner, merchant, and attribution are eligible, Firmly reports the conversion using the configured integration. ## Supported networks Firmly can resolve links from Impact, Awin, CJ, Rakuten, Pepperjam, and Partnerize. Links from supported content-monetization services may resolve through one of these networks. Network availability and conversion reporting depend on the partner's commercial setup and the merchant's affiliate-program configuration. Contact Firmly to confirm eligibility before implementing the endpoint directly. - [Start Journey](/api-reference/affiliate/start-journey/index.md) --- # Agentic Pay Agentic Pay is Firmly's **Network Token Router** — an API that enables card enrollment and network token payment authorization. Destinations integrate one abstract API; Firmly handles the network-specific mechanics behind the scenes. ## Supported Networks - **Visa** — Iframe handshake and FIDO2 verification - **Mastercard** — Iframe-based authentication and FIDO2 verification - **Discover** — No cardholder-verification step — enroll and intent complete in one call each The network is automatically detected from the card's BIN (Bank Identification Number — the leading digits of the card number) — destinations never specify which network to use. > **Tip** > **Try it live:** the [API Explorer](/api-explorer/) has an **Agentic Pay** group with every endpoint below. You need the Agentic Pay API token and network sandbox test cards described in [Agentic Pay in the sandbox](/for-destinations/sandbox-setup#agentic-pay-in-the-sandbox). OTP enrollment, Discover, `/intent`, and `/cards/delete` complete from the Explorer; steps that need the network iframe (FIDO, Mastercard authentication) are listed for reference and must run in the cardholder's browser. ## Authentication All Agentic Pay endpoints accept your API token either in the `x-firmly-authorization` header (raw token, no prefix) or as a standard `Authorization: Bearer ` header. This is an app-level token, not a browser session token. The [Headless SDK](/api-reference/headless-sdk/) sends the same token as `Authorization: Bearer` — its `apiToken` config value is that token. | Header | Type | Required | Description | |---|---|---|---| | `x-firmly-authorization` | string | Yes | API token for authentication | > **Warning** > Agentic Pay endpoints are designed for server-to-server use only. Never expose your API token in client-side code. ## Flow Token Every Agentic Pay response includes a `flow_token` — a JWE-encrypted (JSON Web Encryption) state token that carries the enrollment or payment context forward. Each subsequent call requires the `flow_token` from the previous response. This eliminates the need for server-side session storage and ensures stateless, tamper-proof request chaining. ## Two Entry Points, One Payment Chain There are two ways to start a payment. **Choose one** based on whether the buyer is entering a new card or reusing a saved one — both paths return the same shape and then converge on the identical intent → order chain below. - **Path A — New Card (Enroll)** — POST `/enroll` with the cardholder's PAN (Primary Account Number — the full card number). Firmly enrolls the card and returns verification challenges (OTP — one-time password, and FIDO2 — the FIDO Alliance passkey/WebAuthn standard). Persist `virtual_card_id`, `card_art`, and `masked` for returning buyers. - **Path B — Saved Card (Select Card)** — POST `/select-card` with a stored `virtual_card_id` — no PAN re-entry. Returns the same shape as `/enroll`, so the rest of the flow is identical. Once you have a `flow_token` from either path, the remainder of the chain is shared: ### Payment Intent POST `/intent` with the transaction amount. A FIDO2 assertion proves cardholder presence. ### Order Completion Send the `flow_token` and `intent_id` to the wallet-complete-order endpoint. Firmly retrieves network token credentials and places the order. ## Available Endpoints | Method | Path | Description | | ------ | ---- | ----------- | | POST | `/enroll` | Enroll a card and receive verification methods | | POST | `/select-card` | Start a payment from a previously-enrolled card (no PAN) | | POST | `/enroll/trigger` | Trigger a verification challenge (OTP, iframe) for enrollment | | POST | `/enroll/verify` | Submit the verification response to complete enrollment | | POST | `/intent` | Create a payment intent for an enrolled card | | POST | `/intent/challenge` | Complete a payment-level FIDO challenge for the intent | | GET | `/card-art/:token` | Retrieve the card art image for an enrolled card | | GET | `/iframe-callback` | Iframe postMessage bridge for browser-based verification flows | | POST | `/cards/delete` | Revoke an enrolled card on the network | > **Note** > All endpoint paths in the table above are relative to `https://api.firmly.work/api/v1/wallets/agentic-pay`. Order placement is the exception: it uses [Wallet Complete Order](/api-reference/payment/wallet-complete-order), which lives on the payment/vault surface (`https://cc.firmly.work/api/v2/payment/domains/{domain}/wallet-complete-order`), **not** under this base. ## Endpoint Reference ### Enrollment - [Enroll Card](/api-reference/agentic-pay/enroll) — Submit card details to begin enrollment and receive available verification methods - [Select Card](/api-reference/agentic-pay/select-card) — Start a payment from a previously-enrolled card without re-entering card details - [Trigger Enrollment](/api-reference/agentic-pay/trigger-enrollment) — Trigger a specific verification challenge (OTP or iframe handshake) for the enrollment - [Verify Enrollment](/api-reference/agentic-pay/verify-enrollment) — Submit the OTP code or FIDO iframe result to complete card registration - [Delete Card](/api-reference/agentic-pay/delete-card) — Revoke an enrolled card on the network when the buyer removes it ### Payment - [Create Intent](/api-reference/agentic-pay/create-intent) — Create a payment intent with the transaction mandate — returns a FIDO challenge, or the `intent_id` directly when no challenge is needed - [Intent Challenge](/api-reference/agentic-pay/intent-challenge) — Submit the FIDO assertion result and receive the `intent_id` for order placement ### Browser Helpers - [Get Card Art](/api-reference/agentic-pay/card-art) — Retrieve the issuer card-art image for an enrolled card via an HMAC-signed URL - [Iframe Callback](/api-reference/agentic-pay/iframe-callback) — The postMessage bridge that returns network iframe results to the parent window > **Note** > Order placement uses [Wallet Complete Order](/api-reference/payment/wallet-complete-order), and the > [Headless SDK](/api-reference/headless-sdk/) wraps all of the above (including the auth iframes) behind a small browser API. ## Typical Flow ### Start Session **New card:** POST `/enroll` with card details (PAN, expiry, `consumer` info). Receive `flow_token`, `virtual_card_id`, `verification_methods`, `card_art`, and `masked`. Persist `virtual_card_id`, `card_art`, and `masked` for returning buyers. **Saved card:** POST `/select-card` with the stored `virtual_card_id` and `network` — no PAN needed. Returns the same shape as `/enroll` (`card_art` and `masked` are `null` — use persisted values). ### Verify Cardholder (New Card) POST `/enroll/trigger` with the chosen `method_id`, then POST `/enroll/verify` with the cardholder's response (OTP or FIDO2). May require multiple verify calls. Discover returns an empty `verification_methods` array from `/enroll` — the card is enrolled immediately and both calls are skipped. Saved cards skip enrollment verification, but a **Visa** saved card still returns an `embed_iframe_handshake` from `/select-card` whose `secure_token` must be captured and passed to `/intent`; Mastercard saved cards proceed straight to `/intent`. ### Create Payment Intent POST `/intent` with the `flow_token` and transaction mandate. Receive either a FIDO2 assertion `challenge`, or — for Discover, and for Mastercard when a fresh enrollment authentication can be reused — the `intent_id` directly. ### Complete Intent (when a challenge was returned) POST `/intent/challenge` with the FIDO2 result. Receive `intent_id`. Skip this step if `/intent` already returned `intent_id`. ### Place Order POST `/api/v2/payment/domains/{domain}/wallet-complete-order` with `flow_token`, `intent_id`, and `billing_info`. (This is the payment/vault surface at `cc.firmly.work`, outside the Agentic Pay base URL.) --- # Authentication Firmly supports two authentication models. Pick the one that matches where your code runs. - **Browser session** (most common) — client-side code (browser, mobile app, ad surface, embed) bootstraps a session by sending your App ID in the `x-firmly-app-id` header to `POST /api/v1/browser-session`. That call returns a short-lived JWT `access_token`. - **Server-to-server (S2S)** — backend services (banks, wallets, autonomous agents) authenticate with a Firmly-issued secret instead of a per-buyer JWT, paired with an `x-firmly-device-id` for cart isolation. On every authenticated call afterward, pass the credential in the `x-firmly-authorization` header — the browser-session JWT for the browser model, or the S2S secret for the server-to-server model. The base URL is `https://api.firmly.work` (payment calls use `https://cc.firmly.work` — see [Base URLs](/api-reference)). Those are the sandbox hosts — production uses different ones, provided at go-live. Your App ID and the merchant domain you call determine which merchants you can reach. - [Browser Session](/api-reference/authentication/browser-session) - [Server-to-Server Authentication](/api-reference/authentication/server-to-server) --- # Authorize Klarna Checkout `POST https://api.firmly.work/api/v1/domains/{domain}/express/klarna/authorize` ## Overview After the buyer authorizes payment in the Klarna widget (client-side), this endpoint confirms the authorization with Firmly. It stores the `authorization_token` in the session and returns the cart with the confirmed Klarna payment method. Availability and the host this endpoint runs on are covered in the [Klarna Express Checkout](/api-reference/payment/express-checkout/klarna/) overview. ## Authentication - `x-firmly-authorization` (string, required) — Device access token from [Browser Session](/api-reference/authentication/browser-session) ## Path Parameters - `domain` (string, required) — The merchant domain (e.g., "staging.luma.gift") ## Request Body - `attributes` (object, required) — Klarna authorization details **Attributes** - `authorization_token` (string, required) — The authorization token received from the Klarna Payments SDK after the buyer approves payment. Obtained from the `Klarna.Payments.authorize()` callback. ## Response Returns the cart with the confirmed Klarna payment method. - `cart_id` (string) — Unique identifier for the cart - `line_items` (array) — Array of items in the cart - `payment_method` (object) — Confirmed Klarna payment method **Payment Method** - `payment_type` (string) — Always `"Klarna"` for this gateway - `attributes` (object) — Klarna authorization details - `session_id` (string) — Klarna payment session identifier (from start checkout) - `authorization_token` (string) — The confirmed authorization token - `shipping_info` (object) — Delivery address details - `total` (object) — Grand total including all costs - `sub_total` (object) — Subtotal before shipping and tax - `shipping_total` (object) — Shipping cost - `tax` (object) — Tax amount ## Code Example **JavaScript** ```javascript // After Klarna.Payments.authorize() callback returns authorization_token const response = await fetch( 'https://api.firmly.work/api/v1/domains/staging.luma.gift/express/klarna/authorize', { method: 'POST', headers: { 'x-firmly-authorization': authToken, 'Content-Type': 'application/json' }, body: JSON.stringify({ attributes: { authorization_token: 'klarna_auth_token_from_widget' } }) } ); const cart = await response.json(); // Payment is now authorized, proceed to complete order ``` **Python** ```python import requests response = requests.post( 'https://api.firmly.work/api/v1/domains/staging.luma.gift/express/klarna/authorize', headers={ 'x-firmly-authorization': auth_token, 'Content-Type': 'application/json' }, json={ 'attributes': { 'authorization_token': 'klarna_auth_token_from_widget' } } ) cart = response.json() ``` **cURL** ```bash curl -X POST https://api.firmly.work/api/v1/domains/staging.luma.gift/express/klarna/authorize \ -H "x-firmly-authorization: YOUR_AUTH_TOKEN" \ -H "Content-Type: application/json" \ -d '{"attributes": {"authorization_token": "klarna_auth_token_from_widget"}}' ``` ## Response Example ```json { "cart_id": "9cf76530-1344-420f-9ca6-c7a96fb6db45", "line_items": [ { "line_item_id": "3e66bef5-43f5-4a80-8957-91c5c8233163", "sku": "MT12", "quantity": 1, "description": "Cassius Sparring Tank", "price": { "currency": "USD", "value": 18, "number": 1800, "symbol": "$" }, "line_price": { "currency": "USD", "value": 18, "number": 1800, "symbol": "$" }, "msrp": { "currency": "USD", "value": 21.6, "number": 2160, "symbol": "$" }, "image": { "url": "https://staging.luma.gift/cassius-sparring-tank.jpg", "alt": "Cassius Sparring Tank", "type": "default" } } ], "payment_method": { "payment_type": "Klarna", "attributes": { "session_id": "kp_abc123def456", "authorization_token": "klarna_auth_token_from_widget" } }, "shipping_info": { "first_name": "John", "last_name": "Smith", "email": "john@example.com", "phone": "2065551212", "address1": "123 Main St", "city": "Seattle", "state_or_province": "WA", "country": "US", "postal_code": "98101" }, "total": { "currency": "USD", "value": 32, "number": 3200, "symbol": "$" }, "sub_total": { "currency": "USD", "value": 18, "number": 1800, "symbol": "$" }, "shipping_total": { "currency": "USD", "value": 10, "number": 1000, "symbol": "$" }, "tax": { "currency": "USD", "value": 2, "number": 200, "symbol": "$" }, "fees": [ { "description": "Recycle fee", "currency": "USD", "value": 2, "number": 200, "symbol": "$" } ], "fee_total": { "currency": "USD", "value": 2, "number": 200, "symbol": "$" } } ``` --- ## Related Endpoints - [Start Klarna Checkout](/api-reference/payment/express-checkout/klarna/start) — Create Klarna session first - [Complete Klarna Order](/api-reference/payment/express-checkout/klarna/complete-order) — Finalize the order ## Error Responses Errors return a JSON body with `code`, `error`, and `description`. Program against the `error` value — descriptions are human-readable and may change. **400 — BadRequest** `attributes.authorization_token` is missing or empty. ```json { "code": 400, "error": "BadRequest", "description": "Missing Klarna authorization_token" } ``` **400 — ErrorSubmitExpressCheckout** Authorization with the merchant failed — Klarna rejected the token, or the merchant adapter could not submit the checkout. ```json { "code": 400, "error": "ErrorSubmitExpressCheckout", "description": "Could not submit checkout." } ``` **412 — PreconditionError** A required prior step has not been completed — typically the cart is not in a state ready for express-checkout authorization (e.g. no shipping address set). ```json { "code": 412, "error": "PreconditionError", "description": "A precondition was not completed." } ``` **400 — InvalidToken** The `x-firmly-authorization` header is missing, empty, or not a well-formed JWT. Device-auth can also surface as `MissingAuthHeader` or `PartnerNotFound`; see [Authentication errors](/api-reference/errors-and-conventions#authentication) for the full set. ```json { "code": 400, "error": "InvalidToken", "description": "Jwt token is invalid." } ``` **401 — InvalidJWTToken** The device JWT is well-formed but its signature does not verify, or required claims are missing. ```json { "code": 401, "error": "InvalidJWTToken", "description": "Jwt token is invalid." } ``` **404 — CartNotFound** No active cart exists for this device on this domain. ```json { "code": 404, "error": "CartNotFound", "description": "Cart was not found." } ``` **404 — DomainNotFound** The `{domain}` path parameter does not match any merchant configured with Firmly, or the merchant has been disabled. ```json { "code": 404, "error": "DomainNotFound", "description": "This domain was not found in firmly servers." } ``` **404 — GatewayNotFound** Klarna is not enabled as a payment gateway for this merchant. Check `payment_method_options` before offering it. ```json { "code": 404, "error": "GatewayNotFound", "description": "Payment gateway 'klarna' not found" } ``` **412 — OperationNotSupported** The merchant adapter does not implement Klarna express checkout. ```json { "code": 412, "error": "OperationNotSupported", "description": "This operation is not supported for this store." } ``` **503 — StoreUnavailable** The merchant's own API was unavailable or timed out. Retry with backoff. ```json { "code": 503, "error": "StoreUnavailable", "description": "Store temporarily unavailable. Please try again later." } ``` **429 — RateLimited** Too many requests from this device. Back off and retry after the `Retry-After` window — see [Rate Limits](/api-reference/rate-limits). ```json { "code": 429, "error": "RateLimited", "description": "Too many requests. Please try again later." } ``` --- # Authorize PayPal Express Checkout `POST https://api.firmly.work/api/v1/domains/{domain}/express/paypal/authorize` ## Overview Records the buyer's PayPal approval against the cart. After [Start](/api-reference/payment/express-checkout/paypal/start) returns an EC token, the buyer approves the payment in PayPal's own window and PayPal hands back a **payer ID**. Pass both here, and the merchant attaches the approved PayPal payment to its checkout. This call does not charge the buyer and does not place the order — [Complete Order](/api-reference/payment/express-checkout/paypal/complete-order) does both. This step is **optional**. [Complete Order](/api-reference/payment/express-checkout/paypal/complete-order) performs the authorization itself when none has been recorded, so you can go straight there from Start. Call this endpoint when you want the approval confirmed as its own step, before committing to the order. Availability and the host this endpoint runs on are covered in the [PayPal Express Checkout](/api-reference/payment/express-checkout/paypal/) overview. > **Warning** > **A `200` here does not mean the payment will succeed.** This step confirms that the merchant accepted the token and resolved the payer. Some merchants return `200` while still failing to mint a usable payment authorization from it — the rejection then surfaces at [Complete Order](/api-reference/payment/express-checkout/paypal/complete-order), not here. Do not treat this response as a guarantee of funds. ## Authentication - `x-firmly-authorization` (string, required) — Device access token from [Browser Session](/api-reference/authentication/browser-session) ## Path Parameters - `domain` (string, required) — The merchant domain (e.g., "staging.luma.gift") ## Prerequisites - [Start](/api-reference/payment/express-checkout/paypal/start) must have been called on this cart, and you must have the `paypal_token` it returned. - The buyer must have approved the payment in PayPal, and you must have the payer ID PayPal returned. ## Request Body - `attributes` (object, required) — PayPal approval values. The object itself is required; omitting it returns `400 InvalidInputBody`. **Attributes** - `paypal_token` (string, required) — The EC token from [Start](/api-reference/payment/express-checkout/paypal/start). Missing returns `400 BadRequest` — "Missing PayPal EC Token". - `payer_id` (string, required) — The payer ID PayPal returned when the buyer approved. Missing returns `400 BadRequest` — "Missing Payer ID". > **Note** > **Both fields are required by this API, but not every merchant uses both.** Some merchants resolve the payer themselves from the EC token and never receive the `payer_id` you send — Firmly still requires it, and still stores it on the cart. Always send both. ## Response Returns the cart with `payment_method.attributes` extended with the payer ID. - `cart_id` (string) — Unique identifier for the cart - `line_items` (array) — Array of items in the cart - `payment_method` (object) — PayPal details, now including the payer **Payment Method** - `payment_type` (string) — The gateway label; case varies by merchant - `attributes` (object) - `paypal_token` (string) — The EC token, unchanged - `payer_id` (string) — The payer ID you supplied, now stored on the cart - `url` (string) — The PayPal approval URL, where the merchant supplies one - `sandbox` (boolean) — Whether the merchant's PayPal account is in sandbox mode - `shop_properties` (object) — Merchant-level configuration, including `paypal.clientId` - `shipping_info` (object) — Delivery address details - `total` / `sub_total` / `tax` / `shipping_total` (object) — Cart totals > **Note** > **`shipping_method` may be absent from this response** even when it was present on the [Start](/api-reference/payment/express-checkout/paypal/start) response. Read the shipping method from the cart rather than from this payload. ## Code Example **JavaScript** ```javascript // paypalToken came from the Start response; // payerID came from the PayPal approval callback const response = await fetch( 'https://api.firmly.work/api/v1/domains/staging.luma.gift/express/paypal/authorize', { method: 'POST', headers: { 'x-firmly-authorization': authToken, 'Content-Type': 'application/json' }, body: JSON.stringify({ attributes: { paypal_token: paypalToken, payer_id: payerID } }) } ); const cart = await response.json(); // A 200 confirms the approval was recorded — not that the payment will clear ``` **Python** ```python import requests response = requests.post( 'https://api.firmly.work/api/v1/domains/staging.luma.gift/express/paypal/authorize', headers={ 'x-firmly-authorization': auth_token, 'Content-Type': 'application/json' }, json={ 'attributes': { 'paypal_token': paypal_token, 'payer_id': payer_id } } ) cart = response.json() ``` **cURL** ```bash curl -X POST https://api.firmly.work/api/v1/domains/staging.luma.gift/express/paypal/authorize \ -H "x-firmly-authorization: YOUR_AUTH_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "attributes": { "paypal_token": "EC-XXXXXXXXXXXXXXXXX", "payer_id": "XXXXXXXXXXXXX" } }' ``` ## Response Example ```json { "cart_id": "a8e61139-3045-470f-b211-90820e862335", "line_items": [ { "line_item_id": "d2d196b2-733c-457a-a7c9-001b68517807", "sku": "MT12", "base_sku": "MT12", "quantity": 1, "requires_shipping": true, "description": "Cassius Sparring Tank", "price": { "currency": "USD", "value": 18, "number": 1800, "symbol": "$" }, "line_price": { "currency": "USD", "value": 18, "number": 1800, "symbol": "$" }, "msrp": { "currency": "USD", "value": 21.6, "number": 2160, "symbol": "$" }, "image": { "url": "https://staging.luma.gift/cassius-sparring-tank.jpg", "alt": "Cassius Sparring Tank", "type": "default" } } ], "payment_method": { "payment_type": "paypal", "attributes": { "paypal_token": "EC-XXXXXXXXXXXXXXXXX", "payer_id": "XXXXXXXXXXXXX", "url": "https://www.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=EC-XXXXXXXXXXXXXXXXX", "sandbox": false } }, "payment_method_options": [ { "type": "CreditCard", "wallet": "user" }, { "type": "PayPal", "wallet": "paypal" } ], "shop_properties": { "paypal": { "clientId": "YOUR_MERCHANT_PAYPAL_CLIENT_ID", "sandbox": false, "intent": "order", "integration_version": "v2" }, "order_status_supported": true }, "shipping_info": { "first_name": "John", "last_name": "Smith", "email": "john@example.com", "phone": "2065551212", "address1": "123 Main St", "address2": "", "city": "Seattle", "state_or_province": "WA", "state_name": "Washington", "country": "US", "postal_code": "98101" }, "sub_total": { "currency": "USD", "value": 18, "number": 1800, "symbol": "$" }, "shipping_total": { "currency": "USD", "value": 10, "number": 1000, "symbol": "$" }, "tax": { "currency": "USD", "value": 2, "number": 200, "symbol": "$" }, "total": { "currency": "USD", "value": 30, "number": 3000, "symbol": "$" }, "cart_status": "active", "display_name": "Luma (Staging)", "shop_id": "staging.luma.gift" } ``` --- ## Related Endpoints - [Start](/api-reference/payment/express-checkout/paypal/start) — Open the PayPal session - [Complete Order](/api-reference/payment/express-checkout/paypal/complete-order) — Place the order ## Error Responses Errors return a JSON body with `code`, `error`, and `description`. Program against the `error` value — descriptions are human-readable and may change. **400 — InvalidInputBody** The `attributes` object is missing from the request body. ```json { "code": 400, "error": "InvalidInputBody", "description": "At path: attributes -- Expected an object, but received: undefined" } ``` **400 — BadRequest (missing EC token)** `attributes` was supplied but contains no `paypal_token`. ```json { "code": 400, "error": "BadRequest", "description": "Missing PayPal EC Token" } ``` **400 — BadRequest (missing payer ID)** `attributes.paypal_token` was supplied but `payer_id` was not. ```json { "code": 400, "error": "BadRequest", "description": "Missing Payer ID" } ``` **400 — ErrorSubmitExpressCheckout** The merchant rejected the authorization, or the adapter failed to submit it. ```json { "code": 400, "error": "ErrorSubmitExpressCheckout", "description": "Could not submit checkout." } ``` **409 — PaymentMethodNotAvailable** PayPal is no longer selectable on this cart — commonly because the cart changed after the EC token was created. ```json { "code": 409, "error": "PaymentMethodNotAvailable", "description": "The payment method is not available. Please, choose a diferent one or try again later." } ``` **412 — PreconditionError** A required step has not been completed on this cart. ```json { "code": 412, "error": "PreconditionError", "description": "A precondition was not completed." } ``` **400 — InvalidToken** The `x-firmly-authorization` header is missing, empty, or not a well-formed JWT. Device-auth can also surface as `MissingAuthHeader` or `PartnerNotFound`; see [Authentication errors](/api-reference/errors-and-conventions#authentication) for the full set. ```json { "code": 400, "error": "InvalidToken", "description": "Jwt token is invalid." } ``` **401 — InvalidJWTToken** The device JWT is well-formed but its signature does not verify, or required claims are missing. ```json { "code": 401, "error": "InvalidJWTToken", "description": "Jwt token is invalid." } ``` **404 — CartNotFound** No active cart exists for this device on this domain. ```json { "code": 404, "error": "CartNotFound", "description": "Cart was not found." } ``` **404 — DomainNotFound** The `{domain}` path parameter does not match any merchant configured with Firmly, or the merchant has been disabled. ```json { "code": 404, "error": "DomainNotFound", "description": "This domain was not found in firmly servers." } ``` **404 — GatewayNotFound** PayPal is not enabled as a payment gateway for this merchant. Check `payment_method_options` before offering it. ```json { "code": 404, "error": "GatewayNotFound", "description": "Payment gateway 'paypal' not found" } ``` **412 — OperationNotSupported** The merchant adapter does not implement PayPal express checkout. ```json { "code": 412, "error": "OperationNotSupported", "description": "This operation is not supported for this store." } ``` **503 — StoreUnavailable** The merchant's own API was unavailable or timed out. Retry with backoff. ```json { "code": 503, "error": "StoreUnavailable", "description": "Store temporarily unavailable. Please try again later." } ``` **429 — RateLimited** Too many requests from this device. Back off and retry after the `Retry-After` window — see [Rate Limits](/api-reference/rate-limits). ```json { "code": 429, "error": "RateLimited", "description": "Too many requests. Please try again later." } ``` --- # Browser Session `POST https://api.firmly.work/api/v1/browser-session` ## Overview ```text POST https://api.firmly.work/api/v1/browser-session ``` Browser Session is the authentication endpoint that serves as the starting point for all Cart API integrations. It exchanges your App ID for a JWT access token that authenticates subsequent API calls. Send the request **without a body** to start a new device session, or include an existing `access_token` (in the body or `fsession_v2` cookie) to renew an existing session while preserving the same `device_id`. ## Authentication - `x-firmly-app-id` (string, required) — Your App ID, provided by Firmly. This is the only credential this endpoint requires — it does **not** use the `x-firmly-authorization` header. ## Request Body The body is optional. Send it only to [renew an existing token](#token-renewal); omit it to start a new device session. - `access_token` (string) — An existing access token (active or expired) to renew. When provided, the response returns a new token bound to the **same `device_id`**. When omitted, a fresh device session is created. ## Response - `device_created` (boolean, required) — `true` when a brand-new device was created for this session; `false` when an existing token was renewed. - `access_token` (string, required) — The JWT to pass in the `x-firmly-authorization` header on all subsequent API calls. - `device_id` (string, required) — Unique identifier for this device session. - `expires_in` (number, required) — Seconds until the token expires. Defaults to **3600** (1 hour); a different lifetime may be configured for your App ID. - `expires` (number, required) — Unix timestamp (seconds) when the token expires. ## Code Examples **cURL** ```bash curl -X POST https://api.firmly.work/api/v1/browser-session \ -H "x-firmly-app-id: YOUR_APPLICATION_ID" ``` **JavaScript** ```javascript const response = await fetch('https://api.firmly.work/api/v1/browser-session', { method: 'POST', headers: { 'x-firmly-app-id': 'YOUR_APPLICATION_ID' } }); const { access_token, expires_in } = await response.json(); console.log(`Token expires in ${expires_in} seconds`); ``` **Python** ```python import requests response = requests.post( 'https://api.firmly.work/api/v1/browser-session', headers={'x-firmly-app-id': 'YOUR_APPLICATION_ID'} ) data = response.json() access_token = data['access_token'] expires_in = data['expires_in'] print(f"Token expires in {expires_in} seconds") ``` ## Response Example ```json { "device_created": true, "access_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJkZXZpY2VfaWQiOiI4MmIxMDUyMi01NDgzLTQ3MTktYjU5OS02ZDc4YjEyODI3ZjAiLCJhcHBfaWQiOiJhcHAtMTIzNDU2IiwiZXhwIjoxNjg4OTk4NTcyLCJpYXQiOjE2ODg5OTQ5NzJ9.signature", "expires_in": 3600, "expires": 1688998572, "device_id": "82b10522-5483-4719-b599-6d78b12827f0" } ``` ## Token Renewal To preserve the same `device_id` — and therefore the cart and session state attached to it — pass the previous `access_token` in the request body **or** in the `fsession_v2` cookie. The server verifies the token's signature but does not enforce an expiry window, so even long-expired tokens can be renewed as long as the signature is still valid. **Using Body Parameter** ```bash curl -X POST https://api.firmly.work/api/v1/browser-session \ -H "x-firmly-app-id: YOUR_APPLICATION_ID" \ -H "Content-Type: application/json" \ -d '{"access_token": "EXPIRED_TOKEN"}' ``` **Using Cookie** ```bash curl -X POST https://api.firmly.work/api/v1/browser-session \ -H "x-firmly-app-id: YOUR_APPLICATION_ID" \ -H "Cookie: fsession_v2=EXPIRED_TOKEN" ``` ## Using the Access Token After obtaining the access token, include it in the `x-firmly-authorization` header on all subsequent API requests: ```bash curl -X GET https://api.firmly.work/api/v2/domains/staging.luma.gift/cart \ -H "x-firmly-authorization: YOUR_ACCESS_TOKEN" ``` ## Implementation Example ```javascript JavaScript class FirmlyAuth { constructor(appId) { this.appId = appId; this.token = null; this.expiresAt = null; } async getToken() { // Return existing token if still valid if (this.token && Date.now() < this.expiresAt) { return this.token; } // Get new token const response = await fetch('https://api.firmly.work/api/v1/browser-session', { method: 'POST', headers: { 'x-firmly-app-id': this.appId } }); const data = await response.json(); this.token = data.access_token; this.expiresAt = data.expires * 1000; // Convert to milliseconds return this.token; } } ``` ## Next Steps After authentication, you can: - [Get Cart](/api-reference/cart-management/get-cart) — Retrieve the current cart - [Browse Products](/api-reference/catalog/get-all-products) — View available products - [Add to Cart](/api-reference/cart-management/add-line-item) — Add items to cart ## Error Responses Errors return a JSON body with `code`, `error`, and `description`. Program against the `error` value — descriptions are human-readable and may change. **400 — ErrorMissingAppId** The `x-firmly-app-id` header was not sent. ```json { "code": 400, "error": "ErrorMissingAppId", "description": "x-firmly-app-id header is missing or invalid." } ``` **400 — ErrorInvalidAppId** The App ID is not recognized or exceeds the maximum length (512 characters). ```json { "code": 400, "error": "ErrorInvalidAppId", "description": "App ID is invalid." } ``` **400 — InvalidToken** An `access_token` was supplied (in the body or `fsession_v2` cookie) but it is not a valid JWT structure (malformed). *Returned only during token-renewal calls.* ```json { "code": 400, "error": "InvalidToken", "description": "Jwt token is invalid." } ``` **401 — InvalidJWTToken** An `access_token` was supplied but its signature could not be verified, or required claims are missing. *Returned only during token-renewal calls.* ```json { "code": 401, "error": "InvalidJWTToken", "description": "The JWT token is invalid." } ``` --- # Cart Lifecycle Learn how carts progress through different states from creation to order completion. ## Cart States The cart status is dynamically determined based on the cart's current state and any blocking conditions: ```mermaid stateDiagram-v2 direction LR [*] --> active: cart created active --> submitted: order placed active --> item_not_shippable: shipping fails active --> checkout_blocked: validation fails item_not_shippable --> active: fix item or address checkout_blocked --> active: errors resolved submitted --> [*]: read-only ``` ### 1. Active State (`cart_status: "active"`) - Default state for carts with no blocking issues - Can contain items or be empty - All operations allowed: add/update/remove items, set shipping, etc. - Ready for checkout when all required fields are set ### 2. Submitted State (`cart_status: "submitted"`) - Cart has been successfully submitted as an order - Indicated by presence of `platform_order_number` - Cart is read-only — no modifications allowed - Represents a completed purchase ### 3. Item Not Shippable State (`cart_status: "item_not_shippable"`) - One or more items cannot be shipped to the selected address - Checkout is blocked until issue is resolved - Buyer must remove items or change shipping address ### 4. Checkout Blocked State (`cart_status: "checkout_blocked"`) - Cart has validation errors preventing checkout - Examples: out of stock items, expired promotions, shipping unavailable - Must resolve all errors before proceeding > **Note** > A `pending` value also exists in the `cart_status` enum but is **reserved** — no current cart operation produces it. Treat it as an unexpected state and do not branch checkout logic on it. ## Key Operations by State | cart_status | Available Operations | Restrictions | | ------------------ | ------------------------------------------------------------------------- | ---------------------------------------- | | active | All operations: add/update/remove items, set shipping, apply promos, etc. | None — full access | | submitted | Read-only access | No modifications allowed | | item_not_shippable | Can remove items, change shipping address | Cannot checkout until resolved | | checkout_blocked | Can fix blocking issues (remove items, update info) | Cannot checkout until all errors cleared | ## Cart Notices The cart response includes a `notices` array that provides information about cart issues. > **Note** > The `notices` array is only returned in V2 cart responses. V1 adapters do not populate it. ### Notice Codes - `ITEM_NOT_SHIPPABLE` — Item cannot be shipped to selected address - `ITEM_OUT_OF_STOCK` — Item is currently out of stock - `PROMO_EXPIRED` — Promotional code has expired - `PROMO_NOT_APPLICABLE` — Promotion doesn't apply to cart contents - `SHIPPING_NOT_AVAILABLE` — Selected shipping method is unavailable - `PRICE_INCREASED` — Item price has increased since added to cart - `PRICE_DECREASED` — Item price has decreased since added to cart ### Notice Structure ```json { "code": "ITEM_NOT_SHIPPABLE", "severity": "error", "item_id": "4958451e-0ad5-a545-c865-7b12623e917f", "details": { "description": "Cannot ship to selected location", "reason": "Shipping restrictions apply" } } ``` | Field | Required | Description | | ----------- | -------- | ------------------------------------------------------------------ | | `code` | Yes | Notice code (see [Notice Codes](#notice-codes) above) | | `severity` | Yes | One of `error`, `warning`, `info` | | `item_id` | No | Present when the notice applies to a specific line item | | `details` | No | Additional context — free-form `description` and `reason` strings | ### Notice Severities - `error` — Critical issues that may block checkout - `warning` — Important information that doesn't block checkout - `info` — Informational messages only ## Best Practices 1. **Check cart_status before checkout** - Don't allow checkout if status isn't `active` 2. **Display notices to users** - Show cart notices to help users understand issues (the `notices` array is returned only in V2 cart responses) 3. **Handle status changes** - Cart status can change between API calls based on merchant system state 4. **Resolve blocking issues** - Guide users to fix errors (remove unavailable items, change address, etc.) ## Next Steps - [Shipping & Fulfillment](/api-reference/shipment-configuration/shipping-and-fulfillment) - [API Reference](/api-reference/cart-management/) --- # Cart Management The Cart Management API provides core operations for creating and managing shopping carts. These endpoints handle adding items, updating quantities, and clearing cart contents. ## Overview Cart Management provides: - **Real-time Merchant Integration**: All operations are transmitted to merchant systems in real-time - **Session-based Cart Management**: Carts are managed through device-based authentication - **Multi-shipment Support**: Items are organized into shipments based on merchant configuration - **Merchant-sourced pricing**: Prices, tax, and shipping totals are calculated by the merchant's platform and returned in the cart ## Key Concepts ### Cart Structure Carts contain: - **Line Items** — Individual products with quantities, pricing, and metadata - **Shipments** — Items grouped based on merchant-defined fulfillment rules - **Pricing** — Calculated subtotal, shipping, tax, addon costs, and total - **Addons** — Available and selected value-added services ### Merchant Integration > **Note** > All cart operations are processed through the merchant's systems in real-time. Firmly acts as a unified interface to the merchant's cart functionality. ## Available Endpoints - [Get Cart](/api-reference/cart-management/get-cart) — Retrieve the current cart state with all items, shipments, and pricing - [Add Line Item](/api-reference/cart-management/add-line-item) — Add new products to the cart - [Update Line Item](/api-reference/cart-management/update-line-item) — Modify quantities or remove items from the cart - [Clear Cart](/api-reference/cart-management/clear-cart) — Remove all items from the cart - [Set Cart Attribution](/api-reference/cart-management/set-attribution) — Attach marketing attribution (UTM, referrer, referral code, landing page) to the cart ## Typical Cart Flow ### Initialize Cart Cart is automatically created on first item addition or can be retrieved if one exists ### Add Items Use Add Line Item endpoint to add products with a `variant_id` (inside `add_to_cart_ref`) and `quantity`. Price, description, and other product metadata are resolved server-side from the merchant catalog. ### Review Cart Get Cart returns complete state including shipments and pricing ### Modify as Needed Update quantities or remove items using Update Line Item ### Proceed to Checkout Once cart is finalized, move to shipment configuration and checkout ## Example: Building a Cart ### 1. Add First Item ```bash POST /api/v2/domains/staging.luma.gift/cart/line-items ``` **Request body:** ```json { "add_to_cart_ref": { "variant_id": "MH07-XS-Gray" }, "quantity": 1 } ``` ### 2. Add Another Item ```bash POST /api/v2/domains/staging.luma.gift/cart/line-items ``` **Request body:** ```json { "add_to_cart_ref": { "variant_id": "WS12-XS-Orange" }, "quantity": 2 } ``` ### 3. Review Cart State ```bash GET /api/v2/domains/staging.luma.gift/cart ``` **Response** — line items with price and description resolved from the merchant catalog. Shipments are populated only after a shipping address is set (see [Set Shipping Info](/api-reference/checkout/set-shipping-info)), so `shipments` is empty at this stage: ```json { "cart_id": "a5600193-2c13-3356-d063-711da63b7cd7", "line_items": [ { "line_item_id": "380c6749-dc4f-7c63-f049-847e3862f396", "sku": "MH07-XS-Gray", "quantity": 1, "price": { "currency": "USD", "value": 54.0, "number": 5400, "symbol": "$" }, "line_price": { "currency": "USD", "value": 54.0, "number": 5400, "symbol": "$" }, "msrp": { "currency": "USD", "value": 64.8, "number": 6480, "symbol": "$" }, "image": { "url": "https://staging.luma.gift/mh07-xs-gray.jpg", "alt": "MH07-XS-Gray", "type": "default" } }, { "line_item_id": "d3e502a4-1fc8-e244-532c-4f5ffbcfc4d8", "sku": "WS12-XS-Orange", "quantity": 2, "price": { "currency": "USD", "value": 22.0, "number": 2200, "symbol": "$" }, "line_price": { "currency": "USD", "value": 44.0, "number": 4400, "symbol": "$" }, "msrp": { "currency": "USD", "value": 26.4, "number": 2640, "symbol": "$" }, "image": { "url": "https://staging.luma.gift/ws12-xs-orange.jpg", "alt": "WS12-XS-Orange", "type": "default" } } ], "shipments": [], "sub_total": { "currency": "USD", "value": 98.0, "number": 9800, "symbol": "$" }, "fees": [ { "description": "Recycle fee", "currency": "USD", "value": 2.00, "number": 200, "symbol": "$" } ], "fee_total": { "currency": "USD", "value": 2.00, "number": 200, "symbol": "$" }, "total": { "currency": "USD", "value": 100.00, "number": 10000, "symbol": "$" } } ``` ## Validation - `variant_id` must exist in the merchant's catalog - `quantity` must be a positive integer (`>= 1`) - Stock, availability, and eligibility are validated against the merchant in real time ## Next Steps Once your cart is built: - [Configure Shipments](/api-reference/shipment-configuration/) — Set fulfillment types and shipping methods - [Apply Addons](/api-reference/addon-management/) — Offer value-added services to buyers ## Error Handling The `error` field in the response body identifies the failure. Common errors when managing carts: | `error` | HTTP | Description | Resolution | | -------------------- | ---- | ------------------------------------------------------------ | -------------------------------------------------------------- | | `DomainNotFound` | 404 | `{domain}` path parameter is not a Firmly-configured merchant (or merchant is disabled) | Verify the domain string is exact (case-sensitive, no protocol or trailing slash) | | `OperationNotSupported`| 412 | This operation is not implemented for the merchant's platform | Confirm with [Firmly](/contact) which endpoints are available for this merchant | | `InvalidInputBody` | 400 | Request body is missing required fields or is malformed | Ensure `add_to_cart_ref.variant_id` and `quantity` are present | | `ProductNotFound` | 404 | The `variant_id` does not exist in the merchant catalog | Verify the variant exists; fetch fresh IDs from Catalog APIs | | `ProductNotSupported` | 412 | Product type is not supported by this merchant's adapter | Some merchants reject specific product types (e.g. gift cards) | | `NotEnoughStockError` | 409 | Requested quantity exceeds available inventory | Reduce quantity or wait for restock | | `CannotCreateCart` | 409 | Merchant system rejected cart creation | Retry; if persistent, check merchant system health | | `CartNotFound` | 404 | Cart no longer exists (e.g. expired or cleared by merchant) | Start a new session — cart will be created on first add | | `PostalCodeRequired` | 412 | Merchant requires a postal code before items can be added | Call [Set Postal Code](/api-reference/session/set-postal-code) before retrying | | `NoLineItemError` | 412 | The merchant accepted the request but returned no line item — meaning depends on the endpoint (on Add Line Item, the product was silently rejected; on Set Shipping Info, the cart is empty after the merchant call) | Verify the item is purchasable, then refresh cart state | - [Cart Lifecycle](/api-reference/cart-management/cart-lifecycle/index.md) --- # Catalog The Firmly Catalog APIs allow you to browse merchant product catalogs and retrieve detailed product information. These APIs are essential for building product discovery experiences before adding items to the cart. ## Available Endpoints - [Get a Product](/api-reference/catalog/get-product) — Retrieve detailed information about a specific product - [Get All Products](/api-reference/catalog/get-all-products) — Browse all products from a merchant's catalog - [Get Product from URL](/api-reference/catalog/get-product-from-url) — Extract product information from a merchant's product page URL > **Note** > Need filters, facets, and cursor pagination across merchants? See [Discovery Search](/api-reference/discovery/search) — the richer alternative to keyword search. ## Key Concepts ### Product Structure Products in Firmly have a rich structure that includes: - **Base product information**: SKU, title, description, images - **Variants**: Different options like size, color with individual pricing - **Availability**: Stock status and regional availability - **Pricing**: Current price, MSRP, and currency information - **Cart references**: The `add_to_cart_ref` field connects products to cart operations ### Integration with Cart APIs Each variant carries an `add_to_cart_ref` object. Pass that **entire object** as `add_to_cart_ref` in the [Add Line Item](/api-reference/cart-management/add-line-item) request body — do not reconstruct it or send only `variant_id`, since it may also carry `product_id`, `variant_handles`, or `properties` the merchant needs. ```json { "variants": [{ "sku": "SHIRT-M-BLUE", "add_to_cart_ref": { "variant_id": "SHIRT-M-BLUE" }, "price": { "value": 29.99, "currency": "USD" } }] } ``` The corresponding [Add Line Item](/api-reference/cart-management/add-line-item) request passes that `add_to_cart_ref` through unchanged: ```json { "add_to_cart_ref": { "variant_id": "SHIRT-M-BLUE" }, "quantity": 1 } ``` ### Regional Customization The single-product endpoints — [Get a Product](/api-reference/catalog/get-product) and [Get Product from URL](/api-reference/catalog/get-product-from-url) — accept a `postal_code` query parameter for localized pricing, inventory, and availability. [Get All Products](/api-reference/catalog/get-all-products) instead takes a `countryCode` parameter (default `us`). ## Common Use Cases ### Product Browsing Flow 1. Use [Get All Products](/api-reference/catalog/get-all-products) to display a product grid 2. When user selects a product, use [Get a Product](/api-reference/catalog/get-product) for details 3. Display variant options and let user select size/color 4. Pass the selected variant's full `add_to_cart_ref` object to the [Add Line Item](/api-reference/cart-management/add-line-item) API ### URL-Based Product Discovery 1. User shares or navigates to a merchant product page 2. Use [Get Product from URL](/api-reference/catalog/get-product-from-url) to extract product data 3. Display product information in your interface 4. Add to cart by passing the chosen variant's full `add_to_cart_ref` object to [Add Line Item](/api-reference/cart-management/add-line-item) ## Authentication All catalog endpoints require authentication using the `x-firmly-authorization` header. See [Authentication](/api-reference/authentication/browser-session) for details. --- # Checkout The Checkout API covers the steps between cart-building and payment: setting the shipping address, reviewing and recording buyer consents, and — for a subset of merchants — staging billing info on the cart. ## Typical Flow ### Set Shipping Info Send one shipping address for the cart via [Set Shipping Info](/api-reference/checkout/set-shipping-info). The same address is used by every shipment; the response carries per-shipment cost and tax breakdowns. ### Handle Consents (when applicable) Call [Get Consents](/api-reference/checkout/get-consents) to retrieve any consents the merchant has configured for this cart. The endpoint returns an empty array for merchants without consents — skip the next step in that case. When the array is non-empty, present each item to the buyer (using `text` / `html` and the `ui_slot` placement hint) and submit the buyer's selections via [Set Consents](/api-reference/checkout/set-consents). Required consents (`required: true`) must be signed before payment — see [Set Consents](/api-reference/checkout/set-consents) for the enforcement rule. ### Place / Complete Order Pass `billing_info` directly in the body of [Place Order](/api-reference/payment/place-order-v2) or [Complete Order](/api-reference/payment/complete-order-v2). This is the standard path for nearly all merchants. > **Note** > Billing info and consents are optional and merchant-dependent. Most merchants do not configure consents (Get Consents returns an empty array) and accept `billing_info` directly in the place-order body without a separate Set Billing Info call. ## Available Endpoints - [Set Shipping Info](/api-reference/checkout/set-shipping-info) — Set the cart shipping address; response includes recalculated shipping and tax. - [Set Billing Info](/api-reference/checkout/set-billing-info) — Stage billing info on the cart. Optional — required only by specific merchants. - [Get Consents](/api-reference/checkout/get-consents) — Retrieve consents the merchant has configured for this cart. - [Set Consents](/api-reference/checkout/set-consents) — Grant or revoke consents by id. ## Shipping Address One shipping address applies to the whole cart. The address is validated for supported country and state/province, then used to recalculate shipping methods and tax. See [Set Shipping Info](/api-reference/checkout/set-shipping-info) for the full field list and response example. The shipping address may also be used for billing when `billing_info` is omitted from the place-order request. Whether the merchant accepts the shipping address as the billing address depends on the merchant: many do, but for merchants that require a distinct billing address, omitting `billing_info` causes place-order to reject the request (an `OperationNotSupported`-class or validation error). If you are unsure, pass `billing_info` explicitly. ## Consents Consent objects are returned as a top-level array from [Get Consents](/api-reference/checkout/get-consents). Each carries a stable `id`, a `type` (`MARKETING` / `TERMS_AND_CONDITIONS` / `PRIVACY_POLICY` / `OTHER`), placement hint (`ui_slot`), and three booleans that drive integration logic: | Field | Meaning | | ----------- | ---------------------------------------------------------------------------------------- | | `explicit` | When `true`, the buyer must take an action (e.g. tick a box). When `false`, granted implicitly. | | `required` | When `true`, must be signed before the order can be placed. A required consent that is also `explicit: true` must be actively accepted by the buyer via [Set Consents](/api-reference/checkout/set-consents); a required consent that is `explicit: false` is auto-signed (see [Get Consents](/api-reference/checkout/get-consents)). | | `revokable` | When `true`, the buyer can revoke after signing. | The accepted/revoked state is recorded by calling [Set Consents](/api-reference/checkout/set-consents) with `{ consents: [{ id, revoke? }, ...] }`. Required-explicit consents are enforced at place-order: an unsigned required-explicit consent rejects the order. ## Payment Card data and final order placement are handled by the [Payment](/api-reference/payment/get-public-key) endpoints. The Checkout endpoints never receive card numbers; card data is encrypted client-side and sent only to the Payment endpoints. ## Next Steps - [Payment Processing](/api-reference/payment/get-public-key) — Encrypt the buyer's card and place the order. --- # Clear Cart `DELETE https://api.firmly.work/api/v2/domains/{domain}/cart/line-items` ## Overview The Clear Cart endpoint removes all line items from the cart. The response is the fresh cart state as returned by the merchant after the operation completes. - **Line items are removed.** Shipments are rebuilt against the (now empty) line items, so the response typically returns `line_items: []` and `shipments: []`. - **Session continuity.** The Firmly session, `device_id`, and the underlying merchant cart identifier remain active — subsequent calls keep working without re-authenticating. - **Everything else is merchant-defined.** What happens to `shipping_info`, `coupons`, `billing_info`, selected fulfillment / shipping methods, applied promotions, and addon selections depends entirely on the merchant platform — some reset these along with line items, others retain them tied to the customer profile. See the Response section below for the field-by-field breakdown. ## Authentication - `x-firmly-authorization` (string, required) — Device access token from [Browser Session](/api-reference/authentication/browser-session) > **Note** > This endpoint also accepts **server-to-server (S2S) authentication** for backend integrations acting on behalf of a device: send `Authorization: Bearer ` (or the equivalent `x-firmly-authorization: `) together with `x-firmly-device-id`. See [Server-to-Server Authentication](/api-reference/authentication/server-to-server). ## Path Parameters - `domain` (string, required) — Domain of the merchant website (e.g., `staging.luma.gift`) ## Response Returns the cart state after line items are removed — same schema as [Get Cart](/api-reference/cart-management/get-cart). In the typical case `line_items` and `shipments` are empty and totals are zero, but the rest of the cart reflects whatever the merchant returns post-clear. ### Guaranteed by Firmly - `line_items` — emptied - `cart_id`, session, and device binding — unchanged ### Merchant-defined - `shipping_info`, `billing_info` — some merchants keep the customer's address; others reset it - `coupons` / promotion state — some merchants clear applied codes when the cart empties - `shipping_method` / `shipping_method_options` — fulfillment selection often resets to defaults - `addons.selections` — typically clears (offers and selections are tied to line items) - `payment_handle`, `payment_method_options` — usually reset ## Code Examples **cURL** ```bash curl --request DELETE \ --url https://api.firmly.work/api/v2/domains/staging.luma.gift/cart/line-items \ --header 'x-firmly-authorization: YOUR_TOKEN' ``` **JavaScript** ```javascript const response = await fetch('https://api.firmly.work/api/v2/domains/staging.luma.gift/cart/line-items', { method: 'DELETE', headers: { 'x-firmly-authorization': 'YOUR_TOKEN' } }); const emptyCart = await response.json(); console.log(emptyCart); ``` **Python** ```python import requests response = requests.delete( 'https://api.firmly.work/api/v2/domains/staging.luma.gift/cart/line-items', headers={ 'x-firmly-authorization': 'YOUR_TOKEN' } ) empty_cart = response.json() print(empty_cart) ``` **PHP** ```php "https://api.firmly.work/api/v2/domains/staging.luma.gift/cart/line-items", CURLOPT_RETURNTRANSFER => true, CURLOPT_CUSTOMREQUEST => "DELETE", CURLOPT_HTTPHEADER => [ "x-firmly-authorization: YOUR_TOKEN" ], ]); $response = curl_exec($curl); curl_close($curl); $emptyCart = json_decode($response, true); print_r($emptyCart); ?> ``` ## Response Example ```json { "cart_id": "a5600193-2c13-3356-d063-711da63b7cd7", "platform_id": "example_commerce", "shop_id": "staging.luma.gift", "display_name": "Luma Store", "cart_status": "active", "line_items": [], "shipments": [], "sub_total": { "currency": "USD", "value": 0, "number": 0, "symbol": "$" }, "shipping_total": { "currency": "USD", "value": 0, "number": 0, "symbol": "$" }, "tax_total": { "currency": "USD", "value": 0, "number": 0, "symbol": "$" }, "total": { "currency": "USD", "value": 0, "number": 0, "symbol": "$" }, "addons": { "offers": [], "selections": [] }, "addon_total": { "currency": "USD", "value": 0, "number": 0, "symbol": "$" }, "schema_version": "2.0" } ``` --- ## Related Endpoints - [Get Cart](/api-reference/cart-management/get-cart) — View current cart state - [Add Line Item](/api-reference/cart-management/add-line-item) — Add new items to cart - [Update Line Item](/api-reference/cart-management/update-line-item) — Modify cart items ## Error Responses Errors return a JSON body with `code`, `error`, and `description`. Program against the `error` value — descriptions are human-readable and may change. **400 — MissingAuthHeader** The `x-firmly-authorization` header is missing or empty. ```json { "code": 400, "error": "MissingAuthHeader", "description": "x-firmly-authorization header is missing or invalid." } ``` **400 — InvalidToken** The authorization token is not a valid JWT structure. ```json { "code": 400, "error": "InvalidToken", "description": "Jwt token is invalid." } ``` **400 — InvalidAPIToken** The API token (server-to-server secret) is invalid or has been revoked. ```json { "code": 400, "error": "InvalidAPIToken", "description": "API token is invalid." } ``` **400 — BadRequest** Server-to-server auth was attempted but the required headers (`x-firmly-authorization` plus `x-firmly-device-id`) are missing or malformed. ```json { "code": 400, "error": "BadRequest", "description": "Bad request." } ``` **401 — Unauthorized** The authorization token was rejected. ```json { "code": 401, "error": "Unauthorized", "description": "Unauthorized." } ``` **401 — InvalidJWTToken** The device JWT signature does not verify, or required claims are missing. ```json { "code": 401, "error": "InvalidJWTToken", "description": "Jwt token is invalid." } ``` **404 — PartnerNotFound** The `appid` claim on the device JWT does not map to a known partner / tenant — typically a token from a different environment. ```json { "code": 404, "error": "PartnerNotFound", "description": "Partner not found." } ``` **404 — DomainNotFound** The `{domain}` path parameter does not match any merchant configured with Firmly, or the merchant has been disabled. Verify the domain string (case-sensitive, no protocol or trailing slash). ```json { "code": 404, "error": "DomainNotFound", "description": "This domain was not found in firmly servers." } ``` **404 — CartNotFound** No cart exists for this device on this domain. There is nothing to clear. ```json { "code": 404, "error": "CartNotFound", "description": "Cart was not found." } ``` **404 — ProductNotFound** The fallback clear path (used when an adapter does not implement a native `clearCart`) iterates over line items and removes them one by one. This error surfaces if one of those removals cannot be mapped back to a merchant product — typically a stale cart whose contents diverged from the merchant view. ```json { "code": 404, "error": "ProductNotFound", "description": "Product not found." } ``` **412 — OperationNotSupported** The merchant's platform does not support this operation. Check with [Firmly](/contact) whether this endpoint is available for the merchant. ```json { "code": 412, "error": "OperationNotSupported", "description": "This operation is not supported for this store." } ``` --- # Clear Promo Codes `DELETE https://api.firmly.work/api/v2/domains/{domain}/cart/promo-codes` Removes promotional codes from the cart. The merchant determines what cleared state looks like (typically `coupons: []`, `cart_discount` reset, line-item discounts removed) and returns the updated cart. > **Note** > Some merchants do not allow API-driven promo-code removal. In that case the request returns `409 ClearPromoCodeNotAllowed`. ## Authentication - `x-firmly-authorization` (string, required) — Device access token from [Browser Session](/api-reference/authentication/browser-session) > **Note** > This endpoint also accepts **server-to-server (S2S) authentication** for backend integrations acting on behalf of a device: send `Authorization: Bearer ` (or the equivalent `x-firmly-authorization: `) together with `x-firmly-device-id`. See [Server-to-Server Authentication](/api-reference/authentication/server-to-server). ## Path Parameters - `domain` (string, required) — The merchant's domain (e.g. `staging.luma.gift`). ## Request Body No request body. ## Response Returns the full cart (same schema as [Get Cart](/api-reference/cart-management/get-cart)) with promotions cleared. ## Examples **cURL** ```bash curl -X DELETE https://api.firmly.work/api/v2/domains/staging.luma.gift/cart/promo-codes \ -H "x-firmly-authorization: YOUR_TOKEN" ``` **JavaScript** ```javascript const response = await fetch('https://api.firmly.work/api/v2/domains/staging.luma.gift/cart/promo-codes', { method: 'DELETE', headers: { 'x-firmly-authorization': 'YOUR_TOKEN' } }); const cart = await response.json(); ``` **Python** ```python import requests response = requests.delete( 'https://api.firmly.work/api/v2/domains/staging.luma.gift/cart/promo-codes', headers={'x-firmly-authorization': 'YOUR_TOKEN'} ) cart = response.json() ``` ## Response Example ```json { "cart_id": "a5600193-2c13-3356-d063-711da63b7cd7", "platform_id": "example_commerce", "shop_id": "staging.luma.gift", "cart_status": "active", "line_items": [ { "line_item_id": "c62279b9-3a72-0bbd-1377-be0033ad23dd", "sku": "WT08-XS-Purple", "description": "Antonia Racer Tank", "quantity": 2, "price": { "currency": "USD", "value": 49.99, "number": 4999, "symbol": "$" }, "line_price": { "currency": "USD", "value": 99.98, "number": 9998, "symbol": "$" }, "msrp": { "currency": "USD", "value": 59.99, "number": 5999, "symbol": "$" }, "image": { "url": "https://staging.luma.gift/antonia-racer-tank.jpg", "alt": "Antonia Racer Tank", "type": "default" } } ], "coupons": [], "sub_total": { "currency": "USD", "value": 99.98, "number": 9998, "symbol": "$" }, "cart_discount": { "currency": "USD", "value": 0, "number": 0, "symbol": "$" }, "shipping_total": { "currency": "USD", "value": 9.99, "number": 999, "symbol": "$" }, "tax_total": { "currency": "USD", "value": 8.80, "number": 880, "symbol": "$" }, "fees": [{ "description": "Recycle fee", "currency": "USD", "value": 2.00, "number": 200, "symbol": "$" }], "fee_total": { "currency": "USD", "value": 2.00, "number": 200, "symbol": "$" }, "total": { "currency": "USD", "value": 120.77, "number": 12077, "symbol": "$" }, "schema_version": "2.0" } ``` ## Error Responses Errors return a JSON body with `code`, `error`, and `description`. Program against the `error` value — descriptions are human-readable and may change. **400 — MissingAuthHeader** The `x-firmly-authorization` header is missing or empty. ```json { "code": 400, "error": "MissingAuthHeader", "description": "x-firmly-authorization header is missing or invalid." } ``` **400 — InvalidToken** The authorization token is not a valid JWT structure. ```json { "code": 400, "error": "InvalidToken", "description": "Jwt token is invalid." } ``` **400 — InvalidAPIToken** The API token (server-to-server secret) is invalid or has been revoked. ```json { "code": 400, "error": "InvalidAPIToken", "description": "API token is invalid." } ``` **400 — BadRequest** Server-to-server auth was attempted but required headers are missing or malformed. ```json { "code": 400, "error": "BadRequest", "description": "Bad request." } ``` **401 — Unauthorized** The authorization token was rejected. ```json { "code": 401, "error": "Unauthorized", "description": "Unauthorized." } ``` **401 — InvalidJWTToken** The device JWT signature does not verify, or required claims are missing. ```json { "code": 401, "error": "InvalidJWTToken", "description": "Jwt token is invalid." } ``` **404 — PartnerNotFound** The `appid` claim on the device JWT does not map to a known partner / tenant. ```json { "code": 404, "error": "PartnerNotFound", "description": "Partner not found." } ``` **404 — DomainNotFound** The `{domain}` path parameter does not match any merchant configured with Firmly, or the merchant has been disabled. ```json { "code": 404, "error": "DomainNotFound", "description": "This domain was not found in firmly servers." } ``` **404 — CartNotFound** No cart exists for this device on this domain. ```json { "code": 404, "error": "CartNotFound", "description": "Cart was not found." } ``` **409 — ClearPromoCodeNotAllowed** The merchant's configuration disables API-driven promo-code clearing for this store. ```json { "code": 409, "error": "ClearPromoCodeNotAllowed", "description": "Clear promo code is not allowed." } ``` **412 — OperationNotSupported** The merchant's platform does not support clearing promo codes via API. ```json { "code": 412, "error": "OperationNotSupported", "description": "This operation is not supported for this store." } ``` --- # Complete Google Pay Order `POST https://api.firmly.work/api/v1/domains/{domain}/express/google-pay/complete-order` ## Overview Completes the checkout process by placing an order with the merchant using Google Pay. This is a single-step flow — no prior start or authorize calls are required. The endpoint accepts the payment credentials from the Google Pay SDK and places the order directly with the merchant. Availability and the host this endpoint runs on are covered in the [Google Pay Express Checkout](/api-reference/payment/express-checkout/google-pay/) overview. > **Note** > Google Pay accepts three credential shapes, depending on the merchant's payment processor: **Aurus Pay** wallet-ceremony references, the **token flow**, or the **Braintree nonce flow**. The **token flow** — a single `google_pay_token` (plus optional `google_pay_card_network`) — covers most processors, including **Stripe** and **Adyen**. **Braintree** merchants use the **nonce flow** instead: `nonce`, `email`, and `google_pay_address`. Send exactly one shape. They are checked in order — Aurus Pay first, then the token flow, then the nonce flow — so `aurus_ott_ref` takes precedence over `google_pay_token`, which takes precedence over `nonce`. ## Authentication - `x-firmly-authorization` (string, required) — Device access token from [Browser Session](/api-reference/authentication/browser-session) ## Path Parameters - `domain` (string, required) — The merchant domain (e.g., "staging.luma.gift") ## Prerequisites Before calling this endpoint: - A cart must already exist for `{domain}` on this device session and hold at least one line item. - A shipping method must be selected on the cart. If none is selected, the request fails with `412 MissingShippingMethod`. ## Request Body - `attributes` (object, required) — Google Pay payment attributes. Supply **one** of the three credential shapes below. They are checked in order: **Aurus Pay** first, then the **token flow**, then the **Braintree nonce flow** — so if `aurus_ott_ref` is present the other shapes are ignored, and if `google_pay_token` is present the nonce fields are ignored. **Aurus Pay (wallet-ceremony references)** - `aurus_ott_ref` (string, required) — One-time-token reference from the Aurus wallet ceremony. Its presence selects this shape. - `aurus_prep` (string, required) — Aurus prep reference. Required whenever `aurus_ott_ref` is sent. - `aurus_enonce` (string, required) — Aurus encrypted nonce. Required whenever `aurus_ott_ref` is sent. All three must be sent together; sending `aurus_ott_ref` alone returns `400 BadRequest` — "Aurus Pay requires aurus_ott_ref, aurus_prep and aurus_enonce together." **Token flow (Stripe, Adyen, most processors)** - `google_pay_token` (string, required) — The Google Pay payment token. For **Stripe** this is the tokenized id (`pm_...` or `tok_...`) returned by the Stripe Payment Request API. For **Adyen** (and other raw-token processors) this is the raw Google Pay ECv2 token blob returned by the Google Pay SDK. - `google_pay_card_network` (string) — Optional. The card network reported by Google Pay for the selected card (e.g., `VISA`, `MASTERCARD`). Forwarded to the processor when supplied. - `google_pay_address` (object) — Optional. The Google Pay `paymentData.shippingAddress`. When supplied with the token flow it is mapped onto the cart's shipping info; pair it with `email`. Same field shape as the nonce flow below. - `email` (string) — Optional. Buyer email, used with `google_pay_address` when mapping shipping info. **Braintree (nonce flow)** - `nonce` (string, required) — The Braintree payment nonce (UUID format) returned by `googlePayInstance.parseResponse()`. - `email` (string, required) — Buyer email address from the Google Pay `paymentData.email`. - `google_pay_address` (object, required) — Shipping address from Google Pay `paymentData.shippingAddress`. - `name` (string, required) — Full name - `address1` (string, required) — Street address line 1 - `address2` (string) — Street address line 2 - `address3` (string) — Street address line 3 - `locality` (string, required) — City - `administrativeArea` (string, required) — State/province code (e.g., "CA") - `postalCode` (string, required) — Postal/ZIP code - `countryCode` (string, required) — Two-letter country code (e.g., "US") - `sortingCode` (string) — Sorting code (used in some countries) - `device_data` (object) — Optional. Braintree device-data payload for fraud/risk checks. ## Response Returns the order confirmation object. - `cart_id` (string) — Unique identifier for the cart - `platform_order_number` (string) — The order number from the merchant platform - `cart_status` (string) — Status of the cart (e.g., "submitted") - `submitted_at` (string) — ISO timestamp when the order was submitted - `display_name` (string) — Merchant's display name - `platform_id` (string) — Identifier of the merchant's underlying commerce platform, or `"custom"` for direct integrations. - `shop_id` (string) — Merchant domain - `urls` (object) — Relevant URLs for the order **URLs** - `thank_you_page` (string) — URL to the merchant's order confirmation page - `line_items` (array) — Array of items in the order **Line Item Details** - `line_item_id` (string) — Unique identifier for the line item - `sku` (string) — Product SKU - `quantity` (number) — Quantity ordered - `description` (string) — Product description - `price` (object) — Unit price - `line_price` (object) — Total price for this line item - `image` (object) — Product image information - `shipping_info` (object) — Delivery address details - `billing_info` (object) — Billing address details - `shipping_method` (object) — Selected shipping method with pricing - `payment_summary` (object) — Summary of the Google Pay payment **Payment Summary** - `payment_type` (string) — Always `"GooglePay"` for this gateway - `total` (object) — Grand total including all costs - `sub_total` (object) — Subtotal before shipping and tax - `shipping_total` (object) — Shipping cost - `tax` (object) — Tax amount - `cart_discount` (object) — Total discount applied ## Code Examples ### Token flow (Stripe / Adyen) **JavaScript (Stripe)** ```javascript // After user confirms in Google Pay popup paymentRequest.on('paymentmethod', async (ev) => { const googlePayToken = ev.paymentMethod.id; // pm_... / tok_... for Stripe ev.complete('success'); const response = await fetch( 'https://api.firmly.work/api/v1/domains/staging.luma.gift/express/google-pay/complete-order', { method: 'POST', headers: { 'x-firmly-authorization': authToken, 'Content-Type': 'application/json' }, body: JSON.stringify({ attributes: { google_pay_token: googlePayToken, google_pay_card_network: ev.paymentMethod.card?.brand?.toUpperCase() // optional } }) } ); const order = await response.json(); console.log('Order number:', order.platform_order_number); }); ``` **cURL (token flow)** ```bash curl -X POST https://api.firmly.work/api/v1/domains/staging.luma.gift/express/google-pay/complete-order \ -H "x-firmly-authorization: YOUR_AUTH_TOKEN" \ -H "Content-Type: application/json" \ -d '{"attributes": {"google_pay_token": "pm_1ABC123xyz", "google_pay_card_network": "VISA"}}' ``` ### Braintree Integration (nonce flow) **JavaScript (Braintree)** ```javascript // After user confirms in Google Pay popup const paymentData = await paymentsClient.loadPaymentData(paymentDataRequest); const result = await googlePayInstance.parseResponse(paymentData); const response = await fetch( 'https://api.firmly.work/api/v1/domains/staging.luma.gift/express/google-pay/complete-order', { method: 'POST', headers: { 'x-firmly-authorization': authToken, 'Content-Type': 'application/json' }, body: JSON.stringify({ attributes: { nonce: result.nonce, email: paymentData.email, google_pay_address: { name: paymentData.shippingAddress.name, address1: paymentData.shippingAddress.address1, address2: paymentData.shippingAddress.address2 || '', address3: paymentData.shippingAddress.address3 || '', locality: paymentData.shippingAddress.locality, administrativeArea: paymentData.shippingAddress.administrativeArea, postalCode: paymentData.shippingAddress.postalCode, countryCode: paymentData.shippingAddress.countryCode, sortingCode: paymentData.shippingAddress.sortingCode || '' } } }) } ); const order = await response.json(); console.log('Order number:', order.platform_order_number); ``` **cURL (Braintree)** ```bash curl -X POST https://api.firmly.work/api/v1/domains/staging.luma.gift/express/google-pay/complete-order \ -H "x-firmly-authorization: YOUR_AUTH_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "attributes": { "nonce": "9d4224d5-9c7e-1cf5-5d93-9805ed06c50a", "email": "customer@example.com", "google_pay_address": { "name": "John Smith", "address1": "1600 Amphitheatre Parkway", "address2": "", "address3": "", "locality": "Mountain View", "administrativeArea": "CA", "postalCode": "94043", "countryCode": "US", "sortingCode": "" } } }' ``` ## Response Example ```json { "cart_id": "9cf76530-1344-420f-9ca6-c7a96fb6db45", "platform_order_number": "23408043", "cart_status": "submitted", "submitted_at": "2026-03-17T10:30:00.000Z", "display_name": "Test Merchant (Staging)", "platform_id": "example_commerce", "shop_id": "staging.luma.gift", "urls": { "thank_you_page": "https://staging.luma.gift/checkout/post_payment_processing?order_id=23408043" }, "line_items": [ { "line_item_id": "3e66bef5-43f5-4a80-8957-91c5c8233163", "sku": "7225743", "quantity": 1, "description": "Radiant Tee — Blue", "price": { "currency": "USD", "value": 25, "number": 2500, "symbol": "$" }, "line_price": { "currency": "USD", "value": 25, "number": 2500, "symbol": "$" }, "image": { "url": "https://cdn.staging.luma.gift/products/radiant-tee-blue.jpg" }, "msrp": { "currency": "USD", "value": 30.0, "number": 3000, "symbol": "$" } } ], "shipping_info": { "first_name": "John", "last_name": "Smith", "email": "customer@example.com", "phone": "(650) 555-1234", "address1": "1600 Amphitheatre Parkway", "city": "Mountain View", "state_or_province": "CA", "country": "US", "postal_code": "94043" }, "shipping_method": { "id": "21", "description": "Standard Shipping", "price": { "currency": "USD", "value": 5.99, "number": 599, "symbol": "$" } }, "payment_summary": { "payment_type": "GooglePay" }, "total": { "currency": "USD", "value": 35.14, "number": 3514, "symbol": "$" }, "sub_total": { "currency": "USD", "value": 25, "number": 2500, "symbol": "$" }, "shipping_total": { "currency": "USD", "value": 5.99, "number": 599, "symbol": "$" }, "tax": { "currency": "USD", "value": 2.15, "number": 215, "symbol": "$" }, "fees": [ { "description": "Recycle fee", "currency": "USD", "value": 2.00, "number": 200, "symbol": "$" } ], "fee_total": { "currency": "USD", "value": 2.00, "number": 200, "symbol": "$" }, "cart_discount": { "currency": "USD", "value": 0, "number": 0, "symbol": "$" } } ``` ## Error Responses Errors return a JSON body with `code`, `error`, and `description`. Program against the `error` value — descriptions are human-readable and may change. **400 — BadRequest (nonce flow: missing address)** The Braintree nonce flow was selected but no `google_pay_address` was supplied, and the cart holds none. ```json { "code": 400, "error": "BadRequest", "description": "Missing Google Pay address." } ``` **400 — BadRequest (nonce flow: missing email)** The Braintree nonce flow was selected but no `email` was supplied, and the cart holds none. ```json { "code": 400, "error": "BadRequest", "description": "Missing email." } ``` **400 — BadRequest (Aurus Pay references incomplete)** `aurus_ott_ref` was sent without `aurus_prep` and `aurus_enonce`. ```json { "code": 400, "error": "BadRequest", "description": "Aurus Pay requires aurus_ott_ref, aurus_prep and aurus_enonce together." } ``` **400 — BadRequest** Required payment credentials are missing — neither a `google_pay_token` (token flow) nor a `nonce` (Braintree nonce flow) was provided. For the nonce flow, `email` and `google_pay_address` are also required. ```json { "code": 400, "error": "BadRequest", "description": "Missing Google Pay nonce. Provide nonce in request body or call /authorize first." } ``` **412 — MissingShippingMethod** A shipping method has not been selected on the cart yet. ```json { "code": 412, "error": "MissingShippingMethod", "description": "Shipping method needs to be set." } ``` **412 — CheckoutError** Merchant-side checkout failure — payment info or billing address was rejected. ```json { "code": 412, "error": "CheckoutError", "description": "Payment info or billing address invalid." } ``` **422 — CreditCardDeclined** The payment processor declined the payment. Ask the user for a different payment method. ```json { "code": 422, "error": "CreditCardDeclined", "description": "Credit card declined" } ``` ## Payment Processor Detection The merchant's payment processor determines which credential shape to send. You obtain the merchant's Google Pay configuration — including the publishable/tokenization key and the gateway identifier — when you set up the Google Pay SDK for the merchant (via your Google Pay `paymentDataRequest` gateway parameters). Detect the processor from that key's prefix: | Processor | Publishable Key Format | Credential shape | Required Fields | | --- | --- | --- | --- | | **Stripe** | `pk_test_...` or `pk_live_...` | Token flow | `google_pay_token` (`pm_...` / `tok_...`) | | **Adyen** (and other raw-token processors) | — | Token flow | `google_pay_token` (raw ECv2 blob) | | **Braintree** | `sandbox_...` or `production_...` | Nonce flow | `nonce`, `email`, `google_pay_address` | > **Note** > If you cannot reliably derive the processor from the client-side key, confirm the merchant's Google Pay gateway with the Firmly team rather than guessing — sending nonce-flow fields to a token-flow merchant (or vice versa) fails validation with `400 BadRequest`. --- ## Related Resources - [Google Pay Web Integration](https://developers.google.com/pay/api/web/overview) — Google's official documentation - [Stripe Payment Request API](https://stripe.com/docs/stripe-js/elements/payment-request-button) — Stripe's Google Pay integration - [Braintree Google Pay](https://developer.paypal.com/braintree/docs/guides/google-pay/overview) — Braintree's Google Pay integration **400 — InvalidToken** The `x-firmly-authorization` header is missing, empty, or not a well-formed JWT. Device-auth can also surface as `MissingAuthHeader` or `PartnerNotFound`; see [Authentication errors](/api-reference/errors-and-conventions#authentication) for the full set. ```json { "code": 400, "error": "InvalidToken", "description": "Jwt token is invalid." } ``` **401 — InvalidJWTToken** The device JWT is well-formed but its signature does not verify, or required claims are missing. ```json { "code": 401, "error": "InvalidJWTToken", "description": "Jwt token is invalid." } ``` **404 — CartNotFound** No active cart exists for this device on this domain. ```json { "code": 404, "error": "CartNotFound", "description": "Cart was not found." } ``` **404 — DomainNotFound** The `{domain}` path parameter does not match any merchant configured with Firmly, or the merchant has been disabled. ```json { "code": 404, "error": "DomainNotFound", "description": "This domain was not found in firmly servers." } ``` **404 — GatewayNotFound** Google Pay is not enabled as a payment gateway for this merchant. Check `payment_method_options` before offering it. ```json { "code": 404, "error": "GatewayNotFound", "description": "Payment gateway 'google-pay' not found" } ``` **503 — StoreUnavailable** The merchant's own API was unavailable or timed out. Retry with backoff. ```json { "code": 503, "error": "StoreUnavailable", "description": "Store temporarily unavailable. Please try again later." } ``` **429 — RateLimited** Too many requests from this device. Back off and retry after the `Retry-After` window — see [Rate Limits](/api-reference/rate-limits). ```json { "code": 429, "error": "RateLimited", "description": "Too many requests. Please try again later." } ``` --- # Complete Klarna Order `POST https://api.firmly.work/api/v1/domains/{domain}/express/klarna/complete-order` ## Overview Completes the checkout process by placing an order with the merchant using the Klarna authorization. This is the final step in the Klarna checkout flow. The endpoint validates the authorization token, places the order, and returns the order confirmation with the merchant's order number. Availability and the host this endpoint runs on are covered in the [Klarna Express Checkout](/api-reference/payment/express-checkout/klarna/) overview. > **Note** > **`authorization_token` rule.** If you already called [Authorize Klarna Checkout](/api-reference/payment/express-checkout/klarna/authorize), the token is stored in the session and you may omit it here. If you skipped the authorize step, pass `authorization_token` in the request body and this endpoint authorizes automatically before completing the order. In short: the token is required unless a prior authorize call already stored it. ## Authentication - `x-firmly-authorization` (string, required) — Device access token from [Browser Session](/api-reference/authentication/browser-session) ## Path Parameters - `domain` (string, required) — The merchant domain (e.g., "staging.luma.gift") ## Request Body - `attributes` (object, required) — Klarna payment attributes **Attributes** - `authorization_token` (string) — **Conditionally required.** The Klarna authorization token. Required unless a prior [Authorize](/api-reference/payment/express-checkout/klarna/authorize) call already stored it in the session — in that case it is retrieved automatically and may be omitted. - `transaction_token` (string) — Alternative to `authorization_token`. - `redirect_result` (string) — The result of a Klarna redirect flow. Also an accepted alternative: **any one** of the three satisfies the requirement, and each is forwarded to the merchant when supplied. ## Response Returns the order confirmation object. - `cart_id` (string) — Unique identifier for the cart - `platform_order_number` (string) — The order number from the merchant platform - `cart_status` (string) — Status of the cart (e.g., "submitted") - `submitted_at` (string) — ISO timestamp when the order was submitted - `display_name` (string) — Merchant's display name - `platform_id` (string) — Identifier of the merchant's underlying commerce platform. The literal value varies by merchant. - `shop_id` (string) — Merchant domain - `urls` (object) — Relevant URLs for the order **URLs** - `thank_you_page` (string) — URL to the merchant's order confirmation page - `line_items` (array) — Array of items in the order **Line Item Details** - `line_item_id` (string) — Unique identifier for the line item - `sku` (string) — Product SKU - `quantity` (number) — Quantity ordered - `description` (string) — Product description - `price` (object) — Unit price - `line_price` (object) — Total price for this line item - `image` (object) — Product image information - `shipping_info` (object) — Delivery address details - `billing_info` (object) — Billing address details - `shipping_method` (object) — Selected shipping method with pricing - `payment_summary` (object) — Summary of the Klarna payment **Payment Summary** - `payment_type` (string) — Always `"Klarna"` for this gateway - `attributes` (object) — Klarna session details - `session_id` (string) — Klarna payment session identifier - `authorization_token` (string) — The authorization token used for this order - `total` (object) — Grand total including all costs - `sub_total` (object) — Subtotal before shipping and tax - `shipping_total` (object) — Shipping cost - `tax` (object) — Tax amount - `cart_discount` (object) — Total discount applied ## Code Example **JavaScript** ```javascript const response = await fetch( 'https://api.firmly.work/api/v1/domains/staging.luma.gift/express/klarna/complete-order', { method: 'POST', headers: { 'x-firmly-authorization': authToken, 'Content-Type': 'application/json' }, body: JSON.stringify({ attributes: { authorization_token: 'klarna_auth_token_from_widget' } }) } ); const order = await response.json(); console.log('Order number:', order.platform_order_number); // Redirect to thank you page if (order.urls?.thank_you_page) { window.location.href = order.urls.thank_you_page; } ``` **Python** ```python import requests response = requests.post( 'https://api.firmly.work/api/v1/domains/staging.luma.gift/express/klarna/complete-order', headers={ 'x-firmly-authorization': auth_token, 'Content-Type': 'application/json' }, json={ 'attributes': { 'authorization_token': 'klarna_auth_token_from_widget' } } ) order = response.json() print(f"Order placed: {order['platform_order_number']}") print(f"Thank you page: {order['urls']['thank_you_page']}") ``` **cURL** ```bash curl -X POST https://api.firmly.work/api/v1/domains/staging.luma.gift/express/klarna/complete-order \ -H "x-firmly-authorization: YOUR_AUTH_TOKEN" \ -H "Content-Type: application/json" \ -d '{"attributes": {"authorization_token": "klarna_auth_token_from_widget"}}' ``` ## Response Example ```json { "cart_id": "9cf76530-1344-420f-9ca6-c7a96fb6db45", "platform_order_number": "6800018416", "cart_status": "submitted", "submitted_at": "2026-07-22T18:58:25.000Z", "display_name": "Example Store", "platform_id": "example_commerce", "shop_id": "staging.luma.gift", "urls": { "thank_you_page": "https://staging.luma.gift/order/confirmation" }, "line_items": [ { "line_item_id": "3e66bef5-43f5-4a80-8957-91c5c8233163", "sku": "MT12", "quantity": 1, "description": "Cassius Sparring Tank", "price": { "currency": "USD", "value": 18, "number": 1800, "symbol": "$" }, "line_price": { "currency": "USD", "value": 18, "number": 1800, "symbol": "$" }, "image": { "url": "https://staging.luma.gift/images/products/mt12-blue_main.jpg" }, "msrp": { "currency": "USD", "value": 21.6, "number": 2160, "symbol": "$" } } ], "shipping_info": { "first_name": "John", "last_name": "Smith", "email": "john@example.com", "phone": "(206) 555-1212", "address1": "123 Main St", "city": "Seattle", "state_or_province": "WA", "country": "US", "postal_code": "98101" }, "billing_info": { "first_name": "John", "last_name": "Smith", "email": "john@example.com", "phone": "(206) 555-1212", "address1": "123 Main St", "city": "Seattle", "state_or_province": "WA", "country": "US", "postal_code": "98101" }, "shipping_method": { "id": "s2_2_day", "description": "2-Day Shipping", "price": { "currency": "USD", "value": 12, "number": 1200, "symbol": "$" } }, "payment_summary": { "payment_type": "Klarna", "attributes": { "session_id": "kp_abc123def456", "authorization_token": "klarna_auth_token_from_widget" } }, "total": { "currency": "USD", "value": 34, "number": 3400, "symbol": "$" }, "sub_total": { "currency": "USD", "value": 18, "number": 1800, "symbol": "$" }, "shipping_total": { "currency": "USD", "value": 12, "number": 1200, "symbol": "$" }, "tax": { "currency": "USD", "value": 2, "number": 200, "symbol": "$" }, "fees": [ { "description": "Recycle fee", "currency": "USD", "value": 2, "number": 200, "symbol": "$" } ], "fee_total": { "currency": "USD", "value": 2, "number": 200, "symbol": "$" }, "cart_discount": { "currency": "USD", "value": 0, "number": 0, "symbol": "$" } } ``` --- ## Related Endpoints - [Start Klarna Checkout](/api-reference/payment/express-checkout/klarna/start) — Create Klarna session - [Authorize Klarna Checkout](/api-reference/payment/express-checkout/klarna/authorize) — Confirm authorization - [Complete Order (Credit Card)](/api-reference/payment/complete-order-v2) — Alternative credit card flow ## Error Responses Errors return a JSON body with `code`, `error`, and `description`. Program against the `error` value — descriptions are human-readable and may change. **400 — BadRequest** None of `authorization_token`, `transaction_token` or `redirect_result` was supplied, and the cart holds no authorization from a preceding [Authorize](/api-reference/payment/express-checkout/klarna/authorize) call. Any one of the three is enough to pass — note the message names only the first two. ```json { "code": 400, "error": "BadRequest", "description": "Missing Klarna authorization_token or transaction_token" } ``` **412 — CheckoutError** Merchant-side checkout failure — payment info, billing address, or cart state was rejected. ```json { "code": 412, "error": "CheckoutError", "description": "Payment info or billing address invalid." } ``` **412 — MissingShippingMethod** A shipping method has not been selected on the cart yet. ```json { "code": 412, "error": "MissingShippingMethod", "description": "Shipping method needs to be set." } ``` **412 — MissingTaxSync** Cart taxes have not been calculated yet. Refresh the cart and retry. ```json { "code": 412, "error": "MissingTaxSync", "description": "The taxes are not synced yet. Please refresh the cart and try again." } ``` **422 — CreditCardDeclined** Klarna declined the payment. Ask the user for a different payment method. ```json { "code": 422, "error": "CreditCardDeclined", "description": "Credit card declined" } ``` **400 — InvalidToken** The `x-firmly-authorization` header is missing, empty, or not a well-formed JWT. Device-auth can also surface as `MissingAuthHeader` or `PartnerNotFound`; see [Authentication errors](/api-reference/errors-and-conventions#authentication) for the full set. ```json { "code": 400, "error": "InvalidToken", "description": "Jwt token is invalid." } ``` **401 — InvalidJWTToken** The device JWT is well-formed but its signature does not verify, or required claims are missing. ```json { "code": 401, "error": "InvalidJWTToken", "description": "Jwt token is invalid." } ``` **404 — CartNotFound** No active cart exists for this device on this domain. ```json { "code": 404, "error": "CartNotFound", "description": "Cart was not found." } ``` **404 — DomainNotFound** The `{domain}` path parameter does not match any merchant configured with Firmly, or the merchant has been disabled. ```json { "code": 404, "error": "DomainNotFound", "description": "This domain was not found in firmly servers." } ``` **404 — GatewayNotFound** Klarna is not enabled as a payment gateway for this merchant. Check `payment_method_options` before offering it. ```json { "code": 404, "error": "GatewayNotFound", "description": "Payment gateway 'klarna' not found" } ``` **412 — OperationNotSupported** The merchant adapter does not implement Klarna express checkout. ```json { "code": 412, "error": "OperationNotSupported", "description": "This operation is not supported for this store." } ``` **503 — StoreUnavailable** The merchant's own API was unavailable or timed out. Retry with backoff. ```json { "code": 503, "error": "StoreUnavailable", "description": "Store temporarily unavailable. Please try again later." } ``` **429 — RateLimited** Too many requests from this device. Back off and retry after the `Retry-After` window — see [Rate Limits](/api-reference/rate-limits). ```json { "code": 429, "error": "RateLimited", "description": "Too many requests. Please try again later." } ``` --- # Complete Order `POST https://cc.firmly.work/api/v2/payment/domains/{domain}/complete-order` > **Note** > Use **complete-order** to finalize a cart you already built across previous calls (add-line-item, shipping, etc.). For the one-shot create-and-place path, use place-order instead. Completes the order for an existing cart on the device's session. Firmly retrieves the cart, decrypts the supplied JWE-encrypted credit card, calls the merchant's place-order flow, and returns the order confirmation. > **Note** > **Different host.** This endpoint is served from the payment host **`cc.firmly.work`** — not `api.firmly.work` where the cart endpoints live. ## Authentication - `x-firmly-authorization` (string, required) — Device access token from [Browser Session](/api-reference/authentication/browser-session) > **Note** > This endpoint also accepts **server-to-server (S2S) authentication** for backend integrations acting on behalf of a device: send `Authorization: Bearer ` (or the equivalent `x-firmly-authorization: `) together with `x-firmly-device-id`. See [Server-to-Server Authentication](/api-reference/authentication/server-to-server). ## Path Parameters - `domain` (string, required) — The merchant's domain (e.g. `staging.luma.gift`). ## Prerequisites Before calling this endpoint: - The cart must contain at least one line item. - Shipping info must be set ([Set Shipping Info](/api-reference/checkout/set-shipping-info)) — the cart's `payment_handle` is only present after that. - Any consents with `required: true` and `explicit: true` must have been signed via [Set Consents](/api-reference/checkout/set-consents). Unsigned required-explicit consents are rejected with `412 RequiredConsentsNotSigned`. ## Request Body - `encrypted_card` (string, required) — JWE-encrypted credit card object. Encrypt with the public key obtained from [Get Public Key](/api-reference/payment/get-public-key). Plaintext shape: ```json { "number": "4111111111111111", "name": "John Smith", "verification_value": "123", "month": "08", "year": "2026" } ``` - `number` — full PAN - `name` — cardholder name as printed on the card - `verification_value` — CVV / CVC / CID - `month` — expiry month, `1`–`12` (string or integer) - `year` — 4-digit expiry year (must not be in the past; string or integer) - `billing_info` (object, required) — Billing address. Same schema as Set Shipping Info. **billing_info fields** - `first_name` (string, required) — Buyer's first name. - `last_name` (string, required) — Buyer's last name. - `email` (string, required) — Email address. - `phone` (string, required) — Contact phone number. - `address1` (string, required) — Primary address line. - `city` (string, required) — City. - `state_or_province` (string) — State / province code. Required unless the merchant has the `shipping_state` relaxation enabled (see `shop_properties.optional_fields` on [Get Cart](/api-reference/cart-management/get-cart)) — used for countries whose address format has no state/province. - `country` (string, required) — Country code (ISO 3166-1 alpha-2, e.g. `US`). - `postal_code` (string, required) — ZIP / postal code. - `address2` (string) — Secondary address line. - `company` (string) — Company name. - `state_name` (string) — Full state / province name (when the merchant requires it in addition to the code). - `captcha_token` (string) — Captcha verification token. Only required when the merchant enforces a captcha challenge. ## Response The order confirmation with the Cart API structure. Guaranteed fields include `platform_order_number` (merchant-assigned order number), `cart_status` (`"submitted"` on success), `cart_id`, `line_items`, the resolved `shipping_info` / `billing_info`, and the money totals (`sub_total`, `tax`, `total`). Additional fields vary per merchant adapter. ```json { "cart_id": "9cf76530-1344-420f-9ca6-c7a96fb6db45", "cart_status": "submitted", "platform_order_number": "29185", "display_name": "Luma (Staging)", "platform_id": "example_commerce", "shop_id": "staging.luma.gift", "submitted_at": "2026-04-29T07:15:35.367Z", "line_items": [ { "line_item_id": "d290c5fa-0e91-462f-b53f-08d5b71ae532", "sku": "WS12-XS-Orange", "quantity": 1, "description": "Radiant Tee", "price": { "currency": "USD", "value": 22, "number": 2200, "symbol": "$" }, "line_price": { "currency": "USD", "value": 22, "number": 2200, "symbol": "$" }, "msrp": { "currency": "USD", "value": 26, "number": 2600, "symbol": "$" }, "image": { "url": "https://staging.luma.gift/radiant-tee.jpg", "alt": "Radiant Tee", "type": "default" } } ], "shipping_info": { "first_name": "John", "last_name": "Smith", "email": "john@example.com", "phone": "2065551212", "address1": "123 Main St", "city": "Seattle", "state_or_province": "WA", "country": "US", "postal_code": "98101" }, "billing_info": { "first_name": "John", "last_name": "Smith", "address1": "123 Main St", "city": "Seattle", "state_or_province": "WA", "country": "US", "postal_code": "98101" }, "sub_total": { "currency": "USD", "value": 22, "number": 2200, "symbol": "$" }, "tax": { "currency": "USD", "value": 2, "number": 200, "symbol": "$" }, "fees": [{ "description": "Recycle fee", "currency": "USD", "value": 2, "number": 200, "symbol": "$" }], "fee_total": { "currency": "USD", "value": 2, "number": 200, "symbol": "$" }, "total": { "currency": "USD", "value": 26, "number": 2600, "symbol": "$" } } ``` ## Code Example ```javascript const response = await fetch( 'https://cc.firmly.work/api/v2/payment/domains/staging.luma.gift/complete-order', { method: 'POST', headers: { 'x-firmly-authorization': accessToken, 'Content-Type': 'application/json' }, body: JSON.stringify({ encrypted_card: encryptedCardJWE, billing_info: { first_name: 'John', last_name: 'Smith', email: 'john@example.com', phone: '+12065551212', address1: '123 Main St', city: 'Seattle', state_or_province: 'WA', country: 'US', postal_code: '98101' } }) } ); const order = await response.json(); ``` ## Error Responses Errors return a JSON body with `code`, `error`, and `description`. Program against the `error` value — descriptions are human-readable and may change. **400 — MissingAuthHeader** The `x-firmly-authorization` header is missing or empty. ```json { "code": 400, "error": "MissingAuthHeader", "description": "x-firmly-authorization header is missing or invalid." } ``` **400 — InvalidToken** The authorization token is not a valid JWT structure. ```json { "code": 400, "error": "InvalidToken", "description": "Jwt token is invalid." } ``` **400 — MissingRequiredParameters** The cart is missing data needed to complete the order (e.g. no `payment_handle` because Set Shipping Info hasn't been called, or the merchant adapter signaled a missing prerequisite). ```json { "code": 400, "error": "MissingRequiredParameters", "description": "Cart does not have a payment handle" } ``` **401 — InvalidJWTToken** The device JWT signature does not verify, or required claims are missing. ```json { "code": 401, "error": "InvalidJWTToken", "description": "Jwt token is invalid." } ``` **404 — PartnerNotFound** The `appid` claim on the device JWT does not map to a known partner / tenant. ```json { "code": 404, "error": "PartnerNotFound", "description": "Partner not found." } ``` **404 — DomainNotFound** The `{domain}` path parameter does not match any merchant configured with Firmly, or the merchant has been disabled. ```json { "code": 404, "error": "DomainNotFound", "description": "This domain was not found in firmly servers." } ``` **404 — CartNotFound** No active cart exists for this device on this domain — the cart was never created, or it has expired. ```json { "code": 404, "error": "CartNotFound", "description": "Cart was not found." } ``` **409 — payment_challenge_required** Not a failure — the merchant's PSP requires interactive step-up verification (typically 3-D Secure) before the card can be authorized. The response body is a challenge envelope, not the standard error shape. Get the shopper through `challenge.url`, then call [Resume After Challenge](/api-reference/payment/complete-order-v2-resume) once. Only App IDs opted in to the challenge contract receive this. Others get `422 PaymentChallengeRequired` instead. ```json { "type": "payment_challenge_required", "challenge": { "challenge_id": "pi_3RXkQ2...", "method": "redirect", "url": "https://merchant.example.com/challenge?payment_id=...", "display": "popup", "expires_at": "2026-06-08T18:03:44.164Z" } } ``` **409 — NotEnoughStockError** Stock has become insufficient since the cart was built — typically a race between place-order and another customer purchasing the same items. ```json { "code": 409, "error": "NotEnoughStockError", "description": "Not enough stock." } ``` **409 — ShipmentNotAvailable** Shipping method or destination is no longer available for the cart (e.g. inventory moved to a different warehouse, address fell outside the eligible region). ```json { "code": 409, "error": "ShipmentNotAvailable", "description": "Shipment is not available." } ``` **412 — OperationNotSupported** The merchant's platform does not support this operation. ```json { "code": 412, "error": "OperationNotSupported", "description": "This operation is not supported for this store." } ``` **412 — CheckoutError** Merchant-side checkout failure that does not map to a more specific error (e.g. promotion validation failed at place-order time, cart total mismatch). ```json { "code": 412, "error": "CheckoutError", "description": "Checkout error." } ``` **412 — RequiredConsentsNotSigned** One or more `required && explicit` consents from [Get Consents](/api-reference/checkout/get-consents) were not signed via [Set Consents](/api-reference/checkout/set-consents) before this request. ```json { "code": 412, "error": "RequiredConsentsNotSigned", "description": "Required consents are not signed." } ``` **412 — CountryNotSupported** The `billing_info.country` is outside the supported set (currently `US` and `AU`). Firmly rejects the order before tokenization. ```json { "code": 412, "error": "CountryNotSupported", "description": "We don't currently support this country/region. Enter a new address and try again." } ``` **400 — InvalidInputBody** Request body fails schema validation. Confirm `encrypted_card` is a string and `billing_info` includes all required fields listed above. ```json { "code": 400, "error": "InvalidInputBody", "description": "The body is not processable" } ``` **422 — CreditCardDeclined** Card was declined by the PSP for a reason that the issuer did not categorize further. ```json { "code": 422, "error": "CreditCardDeclined", "description": "Credit card was declined." } ``` **422 — CreditCardInsufficientFunds** Issuer reported insufficient funds. ```json { "code": 422, "error": "CreditCardInsufficientFunds", "description": "Credit card has insufficient funds." } ``` **422 — CreditCardInvalidNumber** Card number failed PSP validation. ```json { "code": 422, "error": "CreditCardInvalidNumber", "description": "Credit card number is invalid." } ``` **422 — CreditCardInvalidSecurityCode** `verification_value` (CVV) failed PSP validation. ```json { "code": 422, "error": "CreditCardInvalidSecurityCode", "description": "Credit card security code is invalid." } ``` **422 — CreditCardInvalidExpiry** The supplied expiry is a valid month/year but the card has already expired (in the past). ```json { "code": 422, "error": "CreditCardInvalidExpiry", "description": "Credit card expiry is invalid." } ``` **422 — CreditCardInvalidExpiryDate** The expiry could not be parsed — the supplied `month`/`year` are malformed or do not form a valid date (as opposed to `CreditCardInvalidExpiry`, which is a well-formed but past expiry). ```json { "code": 422, "error": "CreditCardInvalidExpiryDate", "description": "Credit card expiry date is invalid." } ``` **422 — CreditCardInvalidExpiryMonth** Expiry month was rejected (not 1–12). ```json { "code": 422, "error": "CreditCardInvalidExpiryMonth", "description": "Credit card expiry month is invalid." } ``` **422 — CreditCardInvalidExpiryYear** Expiry year was rejected. ```json { "code": 422, "error": "CreditCardInvalidExpiryYear", "description": "Credit card expiry year is invalid." } ``` **422 — CreditCardInvalidPostalCode** AVS rejected the postal code supplied in `billing_info` against the card-on-file. ```json { "code": 422, "error": "CreditCardInvalidPostalCode", "description": "Credit card postal code is invalid." } ``` **422 — PaymentChallengeRequired** The merchant's PSP demanded interactive verification, but your App ID has not opted in to the payment-challenge contract — so the order fails closed rather than returning a challenge your client could not present. Contact Firmly to enable it. See [Resume After Challenge](/api-reference/payment/complete-order-v2-resume). ```json { "code": 422, "error": "PaymentChallengeRequired", "description": "This payment requires additional bank verification (3D Secure) that is not supported in this checkout. Please use a different card." } ``` **429 — RateLimited** The payment host has rate-limited the device for excessive place-order attempts. Wait and retry with backoff. ```json { "code": 429, "error": "RateLimited", "description": "Rate limited." } ``` **503 — StoreUnavailable** The merchant's API returned an unexpected response and the order could not be placed. Retry with backoff. ```json { "code": 503, "error": "StoreUnavailable", "description": "Store is unavailable." } ``` --- # Complete PayPal Express Order `POST https://api.firmly.work/api/v1/domains/{domain}/express/paypal/complete-order` ## Overview Places the order against the merchant using the PayPal authorization recorded by [Authorize](/api-reference/payment/express-checkout/paypal/authorize). This is the call that charges the buyer. On success the cart becomes an order: `cart_status` flips to `"submitted"` and the response carries the merchant's order number. Availability and the host this endpoint runs on are covered in the [PayPal Express Checkout](/api-reference/payment/express-checkout/paypal/) overview. > **Warning** > **This call consumes the session.** On success the device session is cleared. Calling it a second time returns `404 CartNotFound`, not a duplicate order. Before retrying a call that failed ambiguously, re-read the cart and check `cart_status` — see [Errors & Conventions](/api-reference/errors-and-conventions#idempotency). ## Prerequisites - [Start](/api-reference/payment/express-checkout/paypal/start) must have been called on this cart, and the buyer must have approved the payment in PayPal. - [Authorize](/api-reference/payment/express-checkout/paypal/authorize) is **optional** — see below. - Shipping info must be set. Without it this endpoint returns `412 MissingShippingInfo`. > **Note** > **You can skip Authorize.** If no authorization has been recorded on the cart, this endpoint performs it itself before placing the order. Calling Authorize first is the explicit path; going straight from Start to Complete Order is supported and is what production traffic commonly does. ## Authentication - `x-firmly-authorization` (string, required) — Device access token from [Browser Session](/api-reference/authentication/browser-session) ## Path Parameters - `domain` (string, required) — The merchant domain (e.g., "staging.luma.gift") ## Request Body - `attributes` (object, required) — The PayPal approval values **Attributes** - `payer_id` (string) — **Conditionally required.** The payer ID from the PayPal approval. Like `paypal_token`, it is read from the cart first, so it may be omitted when a preceding [Authorize](/api-reference/payment/express-checkout/paypal/authorize) call stored it on the same device session. Send it when you cannot rely on that. - `paypal_token` (string) — The EC token from [Start](/api-reference/payment/express-checkout/paypal/start). **Optional when the cart already holds it**: Firmly back-fills the token from the session created by Start, so a caller that has kept the same device session can send `payer_id` alone. Send it explicitly if you are not sure the session still holds it. - `tags` (array, optional) — Order tags, applied to the placed order ## Response Returns the submitted order. The shape is the cart, plus order fields — note there is **no `order_id`**; the merchant's identifier is `platform_order_number`. - `platform_order_number` (string) — The merchant's own order number. This is the identifier to show the buyer and to use in support. - `cart_status` (string) — `"submitted"` once the order is placed - `submitted_at` (string) — ISO 8601 timestamp of placement - `payment_summary` (object) — How the order was paid, mirroring `payment_method` - `billing_info` (object) — Billing address on the order. For PayPal this comes from the PayPal account and can differ from `shipping_info`. - `shipping_info` (object) — Delivery address - `line_items` (array) — Items on the order - `urls` (object) — Merchant URLs for the placed order, e.g. `thank_you_page` - `total` / `sub_total` / `tax` / `shipping_total` / `cart_discount` (object) — Order totals ## Code Example **JavaScript** ```javascript const response = await fetch( 'https://api.firmly.work/api/v1/domains/staging.luma.gift/express/paypal/complete-order', { method: 'POST', headers: { 'x-firmly-authorization': authToken, 'Content-Type': 'application/json' }, body: JSON.stringify({ attributes: { paypal_token: paypalToken, payer_id: payerID } }) } ); const order = await response.json(); if (response.ok) { showConfirmation(order.platform_order_number); } else { // PayPal rejections arrive here as 422 — see Error Responses showPaymentError(order.description); } ``` **Python** ```python import requests response = requests.post( 'https://api.firmly.work/api/v1/domains/staging.luma.gift/express/paypal/complete-order', headers={ 'x-firmly-authorization': auth_token, 'Content-Type': 'application/json' }, json={ 'attributes': { 'paypal_token': paypal_token, 'payer_id': payer_id } } ) order = response.json() if response.ok: print(order['platform_order_number'], order['cart_status']) ``` **cURL** ```bash curl -X POST https://api.firmly.work/api/v1/domains/staging.luma.gift/express/paypal/complete-order \ -H "x-firmly-authorization: YOUR_AUTH_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "attributes": { "paypal_token": "EC-XXXXXXXXXXXXXXXXX", "payer_id": "XXXXXXXXXXXXX" } }' ``` ## Response Example ```json { "cart_id": "e49f0dea-b65f-4f38-92c2-fa983d20f679", "platform_order_number": "62590", "cart_status": "submitted", "submitted_at": "2026-09-15T07:56:51.968Z", "line_items": [ { "line_item_id": "aeaefb09-abee-4b35-9215-63584cc02c21", "sku": "24-MB05", "base_sku": "24-MB05", "quantity": 1, "requires_shipping": true, "description": "Wayfarer Messenger Bag", "price": { "currency": "USD", "value": 45, "number": 4500, "symbol": "$" }, "line_price": { "currency": "USD", "value": 45, "number": 4500, "symbol": "$" }, "msrp": { "currency": "USD", "value": 45, "number": 4500, "symbol": "$" }, "image": { "url": "https://staging.luma.gift/wayfarer-messenger-bag.jpg", "alt": "Wayfarer Messenger Bag", "type": "default" } } ], "payment_summary": { "payment_type": "PayPal", "attributes": { "paypal_token": "EC-XXXXXXXXXXXXXXXXX", "payer_id": "XXXXXXXXXXXXX", "sandbox": true } }, "payment_method": { "payment_type": "PayPal", "attributes": { "paypal_token": "EC-XXXXXXXXXXXXXXXXX", "payer_id": "XXXXXXXXXXXXX", "sandbox": true } }, "shipping_info": { "first_name": "John", "last_name": "Smith", "email": "john@example.com", "phone": "2065551212", "address1": "123 Main St", "city": "Seattle", "state_or_province": "WA", "state_name": "Washington", "country": "US", "postal_code": "98101" }, "billing_info": { "first_name": "John", "last_name": "Smith", "email": "john@example.com", "phone": "2065551212", "address1": "123 Main St", "city": "Seattle", "state_or_province": "WA", "country": "US", "postal_code": "98101" }, "shipping_method": { "sku": "freeshipping_freeshipping", "description": "Standard", "price": { "currency": "USD", "value": 0, "number": 0, "symbol": "$" } }, "sub_total": { "currency": "USD", "value": 45, "number": 4500, "symbol": "$" }, "shipping_total": { "currency": "USD", "value": 0, "number": 0, "symbol": "$" }, "tax": { "currency": "USD", "value": 0, "number": 0, "symbol": "$" }, "total": { "currency": "USD", "value": 45, "number": 4500, "symbol": "$" }, "display_name": "Luma (Staging)", "shop_id": "staging.luma.gift" } ``` --- ## Related Endpoints - [Start](/api-reference/payment/express-checkout/paypal/start) — Open the PayPal session - [Authorize](/api-reference/payment/express-checkout/paypal/authorize) — Record the buyer's approval ## Error Responses Errors return a JSON body with `code`, `error`, and `description`. Program against the `error` value — descriptions are human-readable and may change. > **Warning** > **A PayPal rejection arrives as `422 CreditCardDeclined`.** The `error` value is misleading for this gateway — no credit card is involved. When the gateway is PayPal, treat `422 CreditCardDeclined` as "the payment was declined", read `description` for the merchant's own wording, and offer another payment method. The `description` on a PayPal decline is passed through from the merchant, so it varies between merchants. **422 — CreditCardDeclined (PayPal declined)** The merchant could not take the payment with PayPal. Despite the error name, this is the standard PayPal decline on this endpoint. Common causes: the buyer's PayPal account is unverified, the merchant's PayPal configuration is incomplete, or the cart total changed after the EC token was created. ```json { "code": 422, "error": "CreditCardDeclined", "description": "Unfortunately, we were unable to process your payment with PayPal. Please use a different form of payment to continue with your order" } ``` **400 — BadRequest (missing EC token)** No `paypal_token` was supplied and the cart holds none from a preceding Start or Authorize call. ```json { "code": 400, "error": "BadRequest", "description": "Missing PayPal EC Token" } ``` **400 — BadRequest (missing payer ID)** No `payer_id` was supplied and the cart holds none from a preceding Authorize call. ```json { "code": 400, "error": "BadRequest", "description": "Missing Payer ID" } ``` **400 — InvalidInputBody** The `attributes` object is missing or not an object. ```json { "code": 400, "error": "InvalidInputBody", "description": "At path: attributes -- Expected an object, but received: undefined" } ``` **409 — PaymentMethodNotAvailable** PayPal is no longer selectable on this cart. ```json { "code": 409, "error": "PaymentMethodNotAvailable", "description": "The payment method is not available. Please, choose a diferent one or try again later." } ``` **400 — MissingRequiredCookie** A cookie the merchant session depends on is absent, so the session transfer could not be completed. Redo the merchant session transfer, then retry. ```json { "code": 400, "error": "MissingRequiredCookie", "description": "Required cookie is missing to perform session transfer." } ``` **412 — MissingShippingInfo** Shipping info has not been set on the cart. ```json { "code": 412, "error": "MissingShippingInfo", "description": "Shipping info needs to be set." } ``` **412 — MissingShippingMethod** A shipping method has not been selected, on a merchant that does not default one. ```json { "code": 412, "error": "MissingShippingMethod", "description": "Shipping method needs to be set." } ``` **412 — MissingTaxSync** Taxes have not finished syncing. Re-read the cart and retry. ```json { "code": 412, "error": "MissingTaxSync", "description": "The taxes are not synced yet. Please refresh the cart and try again." } ``` **412 — CheckoutError** The merchant rejected the checkout payload. ```json { "code": 412, "error": "CheckoutError", "description": "Payment info or billing address invalid." } ``` **400 — InvalidToken** The `x-firmly-authorization` header is missing, empty, or not a well-formed JWT. Device-auth can also surface as `MissingAuthHeader` or `PartnerNotFound`; see [Authentication errors](/api-reference/errors-and-conventions#authentication) for the full set. ```json { "code": 400, "error": "InvalidToken", "description": "Jwt token is invalid." } ``` **401 — InvalidJWTToken** The device JWT is well-formed but its signature does not verify, or required claims are missing. ```json { "code": 401, "error": "InvalidJWTToken", "description": "Jwt token is invalid." } ``` **404 — CartNotFound** No active cart exists for this device on this domain. ```json { "code": 404, "error": "CartNotFound", "description": "Cart was not found." } ``` **404 — DomainNotFound** The `{domain}` path parameter does not match any merchant configured with Firmly, or the merchant has been disabled. ```json { "code": 404, "error": "DomainNotFound", "description": "This domain was not found in firmly servers." } ``` **404 — GatewayNotFound** PayPal is not enabled as a payment gateway for this merchant. Check `payment_method_options` before offering it. ```json { "code": 404, "error": "GatewayNotFound", "description": "Payment gateway 'paypal' not found" } ``` **412 — OperationNotSupported** The merchant adapter does not implement PayPal express checkout. ```json { "code": 412, "error": "OperationNotSupported", "description": "This operation is not supported for this store." } ``` **503 — StoreUnavailable** The merchant's own API was unavailable or timed out. Retry with backoff. ```json { "code": 503, "error": "StoreUnavailable", "description": "Store temporarily unavailable. Please try again later." } ``` **429 — RateLimited** Too many requests from this device. Back off and retry after the `Retry-After` window — see [Rate Limits](/api-reference/rate-limits). ```json { "code": 429, "error": "RateLimited", "description": "Too many requests. Please try again later." } ``` --- # Create Intent `POST https://api.firmly.work/api/v1/wallets/agentic-pay/intent` ## Overview After card enrollment is complete, call this endpoint to initiate a payment. Provide the transaction details (amount, currency, merchant info). Depending on the network and the enrollment state, the response is either a **challenge** the cardholder must complete in an iframe (then finalized with [Intent Challenge](/api-reference/agentic-pay/intent-challenge)), or the **`intent_id` directly** — ready for order placement with no further call. - **Enrollment required**: The flow must be fully enrolled (a `virtual_card_id` was returned from Verify Enrollment or Select Card) before creating an intent - **Two response shapes**: `{ flow_token, challenge }` when cardholder authorization is required (Visa; Mastercard by default), or `{ flow_token, intent_id }` when it is not (Discover always; Mastercard when the cardholder authenticated at enrollment moments earlier and that proof is still fresh). Branch on which key is present. - **Mandate details**: Transaction amount, currency, and merchant information are captured in the `mandate` object ## Authentication - `x-firmly-authorization` (string, required) — API token for authenticating the request ## Request Body - `flow_token` (string, required) — Flow token from a completed enrollment — the flow must be fully enrolled (a `virtual_card_id` was returned). - `secure_token` (string) — Secure token from a prior iframe handshake. Required if the enrollment used an iframe handshake. - `mandate` (object, required) — Transaction details for the payment intent **Required fields:** - `amount` (string): Transaction amount (e.g., `"585.49"`) - `currency_code` (string): ISO 4217 currency code (e.g., `"USD"`) **Optional fields:** - `currency_numeric` (string): ISO 4217 numeric currency code (e.g., `"840"`) - `merchant_name` (string): Display name for the merchant - `merchant_category` (string): Merchant category description - `merchant_category_code` (string): Merchant Category Code (MCC) - `description` (string): Transaction description shown to the cardholder - `consumer_prompt` (string): Custom message displayed during FIDO assertion - `quantity` (number): Item quantity - `ttl_seconds` (number): Time-to-live for the intent in seconds - `callback_uri` (string): Callback URI passed to the FIDO iframe > **Warning** > `amount` is the **authorized ceiling** for this intent. At [Wallet Complete Order](/api-reference/payment/wallet-complete-order) Firmly compares the **cart total on file** against this `amount` and rejects a higher capture with `400 BadRequest` before the network is called — the `additional_data.transaction` you send there is informational and does not change the amount checked. Set `amount` to the order total the cardholder is approving. ## Response The response is one of two shapes. Exactly one of `challenge` or `intent_id` is present. **Challenge required** (Visa; Mastercard by default): - `flow_token` (string) — Refreshed flow token for the subsequent [Intent Challenge](/api-reference/agentic-pay/intent-challenge) call - `challenge` (object) — FIDO assertion challenge for cardholder authorization **Properties:** - `type` (string): Challenge type, typically `embed_iframe` - `uri` (string): Iframe URI for the FIDO assertion flow - `iframeContext` (object): Additional context for configuring the iframe (when present). This object is passed through from the card network, so its keys follow the network's own casing rather than Firmly's snake_case convention. **No challenge** (Discover always; Mastercard when a fresh enrollment authentication can be reused): - `flow_token` (string) — Refreshed flow token to pass to [Wallet Complete Order](/api-reference/payment/wallet-complete-order) - `intent_id` (string) — Intent identifier for order placement. Skip `/intent/challenge` and place the order directly. ## Code Examples **cURL** ```bash curl --request POST \ --url https://api.firmly.work/api/v1/wallets/agentic-pay/intent \ --header 'Content-Type: application/json' \ --header 'x-firmly-authorization: YOUR_TOKEN' \ --data '{ "flow_token": "eyJhbGciOiJBMjU2S1ci...", "mandate": { "amount": "585.49", "currency_code": "USD", "merchant_name": "Example Store", "description": "Order #12345" } }' ``` **JavaScript** ```javascript const response = await fetch('https://api.firmly.work/api/v1/wallets/agentic-pay/intent', { method: 'POST', headers: { 'Content-Type': 'application/json', 'x-firmly-authorization': 'YOUR_TOKEN' }, body: JSON.stringify({ flow_token: 'eyJhbGciOiJBMjU2S1ci...', mandate: { amount: '585.49', currency_code: 'USD', merchant_name: 'Example Store', description: 'Order #12345' } }) }); const { flow_token, challenge } = await response.json(); // Render the FIDO assertion iframe using challenge.uri console.log('Challenge URI:', challenge.uri); ``` **Python** ```python import requests response = requests.post( 'https://api.firmly.work/api/v1/wallets/agentic-pay/intent', headers={ 'Content-Type': 'application/json', 'x-firmly-authorization': 'YOUR_TOKEN' }, json={ 'flow_token': 'eyJhbGciOiJBMjU2S1ci...', 'mandate': { 'amount': '585.49', 'currency_code': 'USD', 'merchant_name': 'Example Store', 'description': 'Order #12345' } } ) result = response.json() print('Challenge URI:', result['challenge']['uri']) ``` ## Response Examples Challenge required: ```json { "flow_token": "", "challenge": { "type": "embed_iframe", "uri": "https://sbx.vts.auth.visa.com/vts-auth/authenticate?apiKey=...", "iframeContext": { "endpoint": "L29hdXRoMi9hdXRob3JpemF0aW9u", "identifier": "59c3208baeadec4566181b18356a5e02", "payload": "eyJraWQiOiI0ZDkxZWY5MiIsImFsZyI6IlJTMjU2In0", "action": "AUTHENTICATE" } } } ``` No challenge — `intent_id` returned directly: ```json { "flow_token": "", "intent_id": "1-5C90F1500800b0be2dc0-e6cf-55d5-54e6-12d8519fad02" } ``` ## Error Responses | Code | Status | Description | | --------------------- | ------ | -------------------------------------------------------------- | | `BadRequest` | 400 | Invalid `flow_token` format or missing required mandate fields | | `BadRequest` | 400 | Card not enrolled — the flow is not fully enrolled (no `virtual_card_id` was returned) | | `ErrorServiceUnavailable` | 503 | Network intent creation failed or timed out | --- ## Related Endpoints - [Verify Enrollment](/api-reference/agentic-pay/verify-enrollment) — Complete card enrollment before creating an intent - [Intent Challenge](/api-reference/agentic-pay/intent-challenge) — Submit the FIDO assertion result to finalize the intent (only when the response carried a `challenge`) - [Wallet Complete Order](/api-reference/payment/wallet-complete-order) — Place the order once you hold an `intent_id` --- # Delete Card `POST https://api.firmly.work/api/v1/wallets/agentic-pay/cards/delete` ## Overview The Delete Card endpoint revokes a previously enrolled card on its network, so the stored `virtual_card_id` can no longer start a payment. Call it when the buyer removes a saved card from your surface, closes their account, or reports the card lost. There are two ways to identify the card: - **With a live `flow_token`** — preferred while you still hold a token from the current flow. Firmly reads the network and card from the token and marks the flow `card_deleted`. - **By `network` + `virtual_card_id`** — for out-of-band cleanup when the `flow_token` has already been discarded (for example, a buyer deleting a card from a settings page days later). The request is a `POST` rather than an HTTP `DELETE` because it carries a JSON body. > **Note** > **Retries are safe.** A `409 PaymentMethodNotAvailable` means the card is already gone — treat it as "already deleted", not as a failure. Once revoked, the `virtual_card_id` cannot be reused — the buyer must enroll the card again. ## Authentication - `x-firmly-authorization` (string, required) — API token for server-to-server authentication ## Request Body Supply **either** `flow_token` **or** both `network` and `virtual_card_id`. - `flow_token` (string) — Flow token from any earlier Agentic Pay response in this flow. When present, `network` and `virtual_card_id` are ignored. - `network` (string) — Card network: `"visa"`, `"mastercard"`, or `"discover"`. Required when `flow_token` is omitted. - `virtual_card_id` (string) — The `virtual_card_id` returned by [Enroll Card](/api-reference/agentic-pay/enroll). Required when `flow_token` is omitted. - `reason` (string) — Why the card is being removed. One of `"SUSPECTED_FRAUD"`, `"ACCOUNT_CLOSED"`, `"OTHER"`, `"DEFAULT"`. Recorded for audit. - `requestor` (string) — Who asked for the removal. One of `"CARDHOLDER"`, `"MERCHANT"`, `"ISSUER"`, `"WALLET"`. Recorded for audit. ## Response - `deleted` (boolean) — `true` when the network confirmed the revocation - `src_correlation_id` (string) — Network correlation reference for the delete. Returned for Mastercard; absent for Visa and Discover, whose delete calls return no reference. Keep it with your audit log. No refreshed `flow_token` is returned — no later Agentic Pay call accepts a token for a deleted card. ## Code Examples **cURL** ```bash curl --request POST \ --url https://api.firmly.work/api/v1/wallets/agentic-pay/cards/delete \ --header 'Content-Type: application/json' \ --header 'x-firmly-authorization: YOUR_API_TOKEN' \ --data '{ "network": "mastercard", "virtual_card_id": "cf90be5c86363de702ed19beec46e102", "reason": "ACCOUNT_CLOSED", "requestor": "CARDHOLDER" }' ``` **JavaScript** ```javascript const response = await fetch('https://api.firmly.work/api/v1/wallets/agentic-pay/cards/delete', { method: 'POST', headers: { 'Content-Type': 'application/json', 'x-firmly-authorization': 'YOUR_API_TOKEN' }, body: JSON.stringify({ network: 'mastercard', virtual_card_id: 'cf90be5c86363de702ed19beec46e102', reason: 'ACCOUNT_CLOSED', requestor: 'CARDHOLDER' }) }); const data = await response.json(); console.log(data.deleted); ``` **Python** ```python import requests response = requests.post( 'https://api.firmly.work/api/v1/wallets/agentic-pay/cards/delete', headers={ 'Content-Type': 'application/json', 'x-firmly-authorization': 'YOUR_API_TOKEN' }, json={ 'network': 'mastercard', 'virtual_card_id': 'cf90be5c86363de702ed19beec46e102', 'reason': 'ACCOUNT_CLOSED', 'requestor': 'CARDHOLDER' } ) data = response.json() print(data['deleted']) ``` ## Response Example ```json { "deleted": true, "src_correlation_id": "7f3c1d2e-9a4b-4c8d-b1e2-5f6a7b8c9d0e" } ``` ## Error Responses | Error Code | Status | Description | | ---------- | ------ | ----------- | | `MissingAuthHeader` | 400 | The `x-firmly-authorization` header is absent or malformed | | `InvalidAPIToken` | 400 | The API token was rejected (invalid or revoked) | | `InvalidInputBody` | 400 | A field has the wrong type, or `network` / `reason` / `requestor` is not one of the allowed values | | `BadRequest` | 400 | Neither `flow_token` nor `network` + `virtual_card_id` was supplied, or the `flow_token` is invalid or expired | | `PaymentMethodNotAvailable` | 409 | The card is already deleted or unknown to the network, or the network is not enabled for this destination | **400 — BadRequest** ```json { "code": 400, "error": "BadRequest", "description": "flow_token OR (network + virtual_card_id) required" } ``` **409 — PaymentMethodNotAvailable** ```json { "code": 409, "error": "PaymentMethodNotAvailable", "description": "Card token not found" } ``` --- ## Related Endpoints - [Enroll Card](/api-reference/agentic-pay/enroll) — Where the `virtual_card_id` comes from - [Select Card](/api-reference/agentic-pay/select-card) — Returns `409 PaymentMethodNotAvailable` for a card that has been deleted; fall back to `/enroll` - [Agentic Pay Overview](/api-reference/agentic-pay/) — Concepts and full endpoint list --- # Discovery The Firmly Discovery APIs help users find products across multiple merchant catalogs. These APIs power product search and filtering capabilities. ## Available Endpoints - [Search Products](/api-reference/discovery/search) — Search for products using keywords with filters for domains, price, availability, and variant attributes ## Key Concepts ### Discovery vs Catalog APIs | Discovery APIs | Catalog APIs | |----------------|--------------| | Search across **multiple** merchants | Query a **specific** merchant | | Keyword search with filters | Direct product retrieval | | Filters and facets | Exact lookups by handle/URL | | Aggregated product data | Real-time merchant data | Use **Discovery APIs** when: - Users are browsing or searching for products - You need to show products from multiple merchants - You want to filter by price, availability, or variants Use **[Catalog APIs](/api-reference/catalog/)** when: - You know the exact product and merchant - You need real-time availability/pricing - You're building a product detail page for a specific merchant ### Typical Search Flow ```text 1. User enters search query and selects filters ↓ 2. Search products (POST /api/v1/discovery/search) ↓ 3. Display results with previews ↓ 4. User selects a product ↓ 5. Catalog API fetches full product details ↓ 6. Cart API adds item to cart ``` Filter facets for the UI come from the `filter_options` block in the [Search](/api-reference/discovery/search) response (returned on the first page): variant options, domains, price range, and in-stock count, each with counts. ## Authentication Discovery endpoints support three authentication methods: | Method | Use Case | Headers | |--------|----------|---------| | [Browser Session](/api-reference/authentication/browser-session) | Client-side apps (browser, mobile) | `x-firmly-authorization` | | App ID | Trusted server-side clients that don't need a per-device session | `x-firmly-app-id` | | [Server-to-Server](/api-reference/authentication/server-to-server) | Backend services acting on behalf of devices | `x-firmly-authorization` + `x-firmly-device-id` | Choose **Browser Session** for direct client integrations. Choose **App ID** for trusted server-side clients that don't need a per-device session. Choose **Server-to-Server** when your backend needs to make Discovery API calls on behalf of a user's device. See [Search Products](/api-reference/discovery/search#authentication) for the per-method request examples. ## Domain Authorization Search results are limited to merchant domains associated with your account. Contact your account manager to request access to additional merchants. ## Rate Limits Discovery APIs are subject to Firmly's standard [rate limits](/api-reference/rate-limits). Contact support for higher limits if needed for production workloads. --- # Enroll Card `POST https://api.firmly.work/api/v1/wallets/agentic-pay/enroll` ## Overview The Enroll Card endpoint initiates card enrollment by submitting card details to the appropriate network (Visa, Mastercard, or Discover). Firmly detects the network automatically from the card's BIN. The response includes a `flow_token` for chaining subsequent calls, a `virtual_card_id` assigned by the network, and a list of `verification_methods` available for cardholder authentication. The verification methods returned depend on the card network (detected automatically). These may include an iframe handshake to capture a `secure_token`, OTP challenges, or FIDO2 iframe-based verification. ## Authentication - `x-firmly-authorization` (string, required) — API token for server-to-server authentication ## Request Body - `pan` (string, required) — Card number (PAN) - `expiry_month` (string, required) — Two-digit expiry month (e.g., `"03"`, `"12"`) - `expiry_year` (string, required) — Four-digit expiry year (e.g., `"2028"`) - `cvv` (string) — Card verification value - `cardholder_full_name` (string) — Full name as printed on the card - `consumer` (object) — Cardholder information for enrollment. **Required for Visa:** `consumer.email` is mandatory when the card is a Visa card (the network is auto-detected from the BIN) — Visa enrollment is rejected with `400 BadRequest` if it is missing. It is optional for Mastercard. **Fields:** - `first_name` (string) — Cardholder first name - `last_name` (string) — Cardholder last name - `email` (string) — Cardholder email address (**required for Visa**) - `phone` (string) — Cardholder phone number - `country_code` (string) — ISO country code (e.g., `"US"`, `"GB"`) ## Response - `flow_token` (string) — JWE-encrypted state token required for all subsequent calls in this enrollment flow - `virtual_card_id` (string) — Network-assigned card identifier for the enrolled card - `card_art` (object) — Card art metadata for rendering the card image. Optional — may not be returned on re-enrollment of the same card. Destinations should persist this from the initial response. See [Card Art](/api-reference/agentic-pay/card-art) for details. - `masked` (object) — Masked card details for rendering a saved-card UI. Destinations should persist this from the initial response for use with [Select Card](/api-reference/agentic-pay/select-card). **masked properties** - `masked.last4` (string) — Last four digits of the funding PAN - `masked.exp_month` (string) — Expiry month (e.g., `"12"`) - `masked.exp_year` (string) — Expiry year (e.g., `"2027"`) - `masked.brand` (string) — Card brand (`"visa"`, `"mastercard"`) - `masked.card_type` (string) — Card type (e.g., `"DEBIT"`, `"CREDIT"`) — Mastercard only - `masked.issuer_name` (string) — Issuing bank name — Mastercard only - `verification_methods` (array) — Available verification challenges for cardholder authentication **verification method properties** - `verification_methods[].id` (string) — Method identifier (e.g., `"OTP_SMS"`, `"OTP_EMAIL"`, `"MANAGED_AUTHENTICATION"`) - `verification_methods[].type` (string) — Method type: `"embed_iframe_handshake"`, `"embed_iframe"`, or `"otp"` - `verification_methods[].attributes` (object) — Method-specific data including `uri` and `next_steps` ## Code Examples **cURL** ```bash curl --request POST \ --url https://api.firmly.work/api/v1/wallets/agentic-pay/enroll \ --header 'Content-Type: application/json' \ --header 'x-firmly-authorization: YOUR_API_TOKEN' \ --data '{ "pan": "4111111111111111", "expiry_month": "03", "expiry_year": "2028", "cvv": "123", "cardholder_full_name": "Jane Doe", "consumer": { "first_name": "Jane", "last_name": "Doe", "email": "jane@example.com", "country_code": "US" } }' ``` **JavaScript** ```javascript const response = await fetch('https://api.firmly.work/api/v1/wallets/agentic-pay/enroll', { method: 'POST', headers: { 'Content-Type': 'application/json', 'x-firmly-authorization': 'YOUR_API_TOKEN' }, body: JSON.stringify({ pan: '4111111111111111', expiry_month: '03', expiry_year: '2028', cvv: '123', cardholder_full_name: 'Jane Doe', consumer: { first_name: 'Jane', last_name: 'Doe', email: 'jane@example.com', country_code: 'US' } }) }); const data = await response.json(); console.log(data.flow_token); console.log(data.verification_methods); ``` **Python** ```python import requests response = requests.post( 'https://api.firmly.work/api/v1/wallets/agentic-pay/enroll', headers={ 'Content-Type': 'application/json', 'x-firmly-authorization': 'YOUR_API_TOKEN' }, json={ 'pan': '4111111111111111', 'expiry_month': '03', 'expiry_year': '2028', 'cvv': '123', 'cardholder_full_name': 'Jane Doe', 'consumer': { 'first_name': 'Jane', 'last_name': 'Doe', 'email': 'jane@example.com', 'country_code': 'US' } } ) data = response.json() print(data['flow_token']) print(data['verification_methods']) ``` ## Response Example ```json { "flow_token": "", "virtual_card_id": "cf90be5c86363de702ed19beec46e102", "verification_methods": [ { "id": "VISA_IFRAME_HANDSHAKE", "type": "embed_iframe_handshake", "attributes": { "uri": "https://sbx.vts.auth.visa.com/vts-auth/authenticate?apiKey=...", "next_steps": [ "Load this iframe in the cardholder browser", "Capture sessionContext.secureToken from postMessage", "Send to /enroll/trigger as secure_token" ] } } ], "card_art": { "network": "visa", "url": "https://api.firmly.work/api/v1/wallets/agentic-pay/card-art/", "background_color": "#1A1A2E", "foreground_color": "#FFFFFF", "descriptor": "Test Bank 2" }, "masked": { "last4": "1111", "exp_month": "03", "exp_year": "2028", "brand": "visa" } } ``` ## Error Responses | Error Code | Status | Description | | ---------- | ------ | ----------- | | `MissingAuthHeader` | 400 | The `x-firmly-authorization` header is absent or malformed (empty or wrong shape). | | `InvalidInputBody` | 400 | Missing required fields (`pan`, `expiry_month`, `expiry_year`) or invalid format | | `InvalidAPIToken` | 400 | The header was present and well-formed, but the API token it carried was rejected (invalid or revoked). | | `PaymentMethodNotAvailable` | 409 | Card network not supported or not enabled for this destination | | `BadRequest` | 400 | The card data is incomplete for the selected network — it passed schema validation but a required credential is missing | **400 - Missing Auth Header** ```json { "code": 400, "error": "MissingAuthHeader", "description": "Missing or invalid x-firmly-authorization header" } ``` **422 - Invalid Input** ```json { "code": 400, "error": "InvalidInputBody", "description": "Request body validation failed: expiry_month is required" } ``` **400 - Invalid API Token** ```json { "code": 400, "error": "InvalidAPIToken", "description": "API token is invalid." } ``` **400 - Bad Request** ```json { "code": 400, "error": "BadRequest", "description": "Card data incomplete" } ``` **409 - Network Not Available** ```json { "code": 409, "error": "PaymentMethodNotAvailable", "description": "Card network is not supported or not enabled for this partner" } ``` --- ## Related Endpoints - [Trigger Enrollment](/api-reference/agentic-pay/trigger-enrollment) — Trigger a verification challenge after enrollment - [Agentic Pay Overview](/api-reference/agentic-pay/) — Concepts and full endpoint list --- # Errors & Conventions This is the canonical reference for how Firmly returns errors and how your code should respond to them. ## Error response shape Every error response uses the same envelope (the **REST envelope** — used by all endpoints except the UCP protocol bridge): ```json { "code": 409, "error": "NotEnoughStockError", "description": "The amount of the required item is not available in stock." } ``` | Field | Meaning | |---|---| | `code` | HTTP status code, repeated in the body | | `error` | Stable error name in PascalCase (e.g. `CartNotFound`, `NotEnoughStockError`) | | `description` | Human-readable message. On validation errors, often includes the failing field path (e.g. `"At path: items.0.add_to_cart_ref — Expected an object, but received: undefined"`) | The `description` field is safe to **log** verbatim. **Don't show it raw to buyers** — it can leak technical detail. Map to your own user-facing messaging. > **Warning** > **One endpoint doesn't follow this envelope.** [Get All Products](/api-reference/catalog/get-all-products) returns a bare `{"error": "Size is not valid: ..."}` (400, invalid `size`) — it carries no `code` or `description`. If you write one shared error handler against this envelope, special-case this response. ## Catalog by category ### Authentication | Name | HTTP | Cause | Recovery | |---|---|---|---| | `MissingAuthHeader` | 400 | `x-firmly-authorization` header missing or empty | Add the header | | `InvalidToken` | 400 | Token is not a valid JWT structure (malformed) | Re-bootstrap via `POST /api/v1/browser-session` | | `InvalidJWTToken` | 401 | JWT signature couldn't be verified | Bootstrap a new session, or pass the previous token to Browser Session to renew | | `PartnerNotFound` | 404 | The `appid` claim on the JWT doesn't map to a known partner | Usually means the token was issued against a different environment — re-bootstrap with the correct App ID | ### Routing & resource lookup | Name | HTTP | Cause | Recovery | |---|---|---|---| | `RouteNotFound` | 404 | The path doesn't match any handler | Check the URL — common cause is a wrong `/api/v1/` vs `/api/v2/` prefix | | `DomainNotFound` | 404 | The merchant `{domain}` parameter isn't a recognized merchant | Confirm the domain string from [Firmly](/contact) | | `CartNotFound` | 404 | No cart exists yet for this `device_id` + `domain` | Create a cart by calling `/cart/line-items` — cart is implicit | | `ProductNotFound` | 404 | The product ID / handle doesn't exist for this merchant | Re-search via `/api/v1/discovery/search` | | `ShipmentNotFound` | 404 | Specified shipment_id doesn't exist on the cart | Refresh the cart via `GET /cart` to get current shipment IDs | | `LineItemNotFound` | 404 | Line item ID doesn't exist | Refresh cart to get current line_item_ids | | `AddonNotFound` | 404 | Addon offer ID doesn't exist or isn't applicable | Re-read available offers from `cart.addons.offers[]` | ### Validation | Name | HTTP | Cause | Recovery | |---|---|---|---| | `InvalidInputQuery` | 400 | A **query-string** parameter failed validation — a bad value (`?flush_cart=1`) or an unrecognized key (`?utm_source=…`), since query schemas are strict. `description` names the failing parameter | Fix or drop the query parameter | | `InvalidInputBody` | 400 | Request **body** failed schema validation. `description` includes the failing field path (incl. wrong types, missing required fields, out-of-range quantity, etc.) | Fix the field and retry | | `InvalidInputBody` | 422 | Same name, different layer: the body is well-formed but the **merchant rejected it** — most often an add-on that does not exist or is not offered on this cart. `description` explains which value was rejected | Re-read the available add-ons and retry with a valid one | | `ErrorInvalidEmail` | 400 | Email format is invalid | Validate format before submission | | `InvalidShippingInfo` | 400 | Shipping address validation failed (missing fields, invalid postal code, etc.) | Read `description` for which field; fix and retry | | `InvalidPromoCode` | 409 | Promo code is invalid, expired, or non-stackable | Tell the user; suggest removing or replacing | | `CountryNotSupported` | 412 | Merchant doesn't ship to this country | Use a supported country, or surface "not deliverable" to user | | `OperationNotSupported` | 412 | The operation isn't enabled for this merchant (e.g. setting a fulfillment type the merchant doesn't offer). | Surface to the user, or fall back to the merchant's default. | | `NotImplemented` | 501 | The merchant's adapter doesn't implement this operation — e.g. `cart/shipments/get-availability` on a V1 adapter. | Skip the optional call. Shipping methods still come from `cart.shipments[].shipping_method_options`; `get-availability` only adds delivery dates / time slots / pickup. See [Shipping & Fulfillment](/api-reference/shipment-configuration/shipping-and-fulfillment). | | `PreconditionError` | 412 | Required prior step wasn't completed (e.g. complete-order before shipping is set) | Walk through the missing step | ### Inventory & merchant state | Name | HTTP | Cause | Recovery | |---|---|---|---| | `NotEnoughStockError` | 409 | Quantity exceeds current stock | Lower quantity or pick a different variant. Re-fetch the product to see current availability. | | `ShipmentNotAvailable` | 409 | Selected shipping method is no longer available for this address (e.g. inventory moved, region restriction) | Re-fetch the cart, surface the new options | | `ProductNotSupported` | 412 | Product can't be added to cart (type restriction, region, business rule) | Surface to user; check product eligibility | | `StoreUnavailable` | 503 | Merchant adapter is temporarily unreachable | Retry with exponential backoff (1s → 30s cap). If persistent, surface to user. | ### Server | Name | HTTP | Cause | Recovery | |---|---|---|---| | `UnprocessableEntity` | 422 | Request body was valid but couldn't be processed (downstream merchant call rejected the payload, or a pre-condition like postal code wasn't met) | Read `description`; most often resolved by re-fetching the cart | | `Unexpected` | 500 | Generic server error | Retry once with backoff. If persistent, [report it](/troubleshooting/reporting-an-issue) with the `CF-RAY` header and timestamp | ### Place-order specific (on `cc.firmly.work`) | Name | HTTP | Cause | Recovery | |---|---|---|---| | `MissingRequiredParameters` | 400 | Cart is missing data needed to place the order (e.g. no `payment_handle` because Set Shipping Info wasn't called) | Walk back through the checkout steps; ensure shipping is set | | `CheckoutError` | 412 | Merchant-side checkout failure (promo re-evaluation rejected, cart total mismatch, etc.) | Re-fetch the cart, surface the discrepancy to the user | | `RequiredConsentsNotSigned` | 412 | A `required && explicit` consent from [Get Consents](/api-reference/checkout/get-consents) wasn't signed before place-order | Show the consent, capture acceptance via [Set Consents](/api-reference/checkout/set-consents), retry | | `CreditCardDeclined` | 422 | Card declined by the PSP. Also returned when a **PayPal** express payment is declined, despite the name — see [Complete Order — PayPal](/api-reference/payment/express-checkout/paypal/complete-order). | Don't silently retry; ask the user for a different payment method. Log issuer reason (don't show to user). | | `CreditCardInsufficientFunds` | 422 | Issuer reported insufficient funds | Surface to user; offer a different card | | `CreditCardInvalidNumber` | 422 | Card number failed PSP validation | Re-collect card details | | `CreditCardInvalidSecurityCode` | 422 | CVV / `verification_value` failed PSP validation | Re-collect CVV | | `CreditCardInvalidExpiry` | 422 | Expiry combination is invalid or in the past (also: `CreditCardInvalidExpiryMonth` / `…Year` / `…Date` for finer-grained signals) | Re-collect expiry | | `CreditCardInvalidPostalCode` | 422 | AVS rejected the postal code in `billing_info` against the card on file | Re-collect billing postal code | | `RateLimited` | 429 | Payment host rate-limited the device for excessive place-order attempts | Back off and retry | ### Additional errors by name Every error the endpoint pages document, beyond the grouped tables above. The last column links to the page carrying the full cause-and-recovery detail for that call. | Name | HTTP | Cause | Documented on | |---|---|---|---| | `AllProductsNotFound` | 404 | No catalog snapshot is available for this merchant — the merchant has no published all-products feed. | [get-all-products](/api-reference/catalog/get-all-products) | | `BadRequest` | 400 | All of these conditions share the same `error` (`BadRequest`) and `code` (`400`), so the `description` is the only way to tell them apart. | [set-consents](/api-reference/checkout/set-consents) | | `CannotCreateCart` | 409 | The merchant system rejected creation of a new cart. | [add-line-item](/api-reference/cart-management/add-line-item) | | `CannotTransferSession` | 409 | The supplied `handle` could not be turned into a usable merchant session. | [session-transfer](/api-reference/session/session-transfer) | | `ClearPromoCodeNotAllowed` | 409 | The merchant's configuration disables API-driven promo-code clearing for this store. | [clear-promo-codes](/api-reference/promotions/clear-promo-codes) | | `CreditCardInvalidExpiryDate` | 422 | The expiry could not be parsed — the supplied `month`/`year` are malformed or do not form a valid date (as opposed to `CreditCardInvalidExpiry`, which is a well-formed but past expiry). | [complete-order-v2](/api-reference/payment/complete-order-v2) | | `CreditCardInvalidExpiryMonth` | 422 | Expiry month was rejected (not 1–12). | [complete-order-v2](/api-reference/payment/complete-order-v2) | | `CreditCardInvalidExpiryYear` | 422 | Expiry year was rejected. | [complete-order-v2](/api-reference/payment/complete-order-v2) | | `PaymentChallengeExpired` | 422 | The interactive verification window (3-D Secure or equivalent) closed before the shopper completed it, or the PSP invalidated the challenge. Terminal for that attempt. | [Resume After Challenge](/api-reference/payment/complete-order-v2-resume) | | `PaymentChallengeRequired` | 422 | The merchant's PSP demanded interactive verification, but the calling App ID has not opted in to the payment-challenge contract — so the order fails closed rather than returning a challenge the client could not present. Also returned on a post-authentication decline, or when no pending challenge exists for the session. | [complete-order-v2](/api-reference/payment/complete-order-v2), [Resume After Challenge](/api-reference/payment/complete-order-v2-resume) | | `ErrorInvalidAppId` | 400 | App-id-auth path: the supplied App ID is not recognized, or exceeds 512 characters. | [search](/api-reference/discovery/search) | | `ErrorMissingAppId` | 400 | App-id-auth path: `x-firmly-app-id` header is missing or empty. | [search](/api-reference/discovery/search) | | `ErrorStartExpressCheckout` | 400 | Firmly could not open the express-checkout session — the provider rejected the request, or the merchant adapter failed to translate it. | [Klarna — Start](/api-reference/payment/express-checkout/klarna/start), [PayPal — Start](/api-reference/payment/express-checkout/paypal/start) | | `ErrorSubmitExpressCheckout` | 400 | Authorization with the merchant failed — the provider rejected the token, or the merchant adapter could not submit the checkout. | [Klarna — Authorize](/api-reference/payment/express-checkout/klarna/authorize), [PayPal — Authorize](/api-reference/payment/express-checkout/paypal/authorize) | | `GatewayNotFound` | 404 | The express-checkout provider (Google Pay, Klarna or PayPal) is not enabled for this merchant. | [Google Pay](/api-reference/payment/express-checkout/google-pay/), [Klarna](/api-reference/payment/express-checkout/klarna/), [PayPal](/api-reference/payment/express-checkout/paypal/) | | `InvalidAPIToken` | 400 | Server-to-server path: the API token is missing, invalid, or has been revoked. | [search](/api-reference/discovery/search) | | `InvalidDeliveryDate` | 400 | The supplied `selected_date` and/or `selected_time_slot` is not available for this shipment. | [set-shipping-method](/api-reference/shipment-configuration/set-shipping-method) | | `InvalidFulfillmentType` | 400 | The supplied `fulfillment_type` is not in the target shipment's `fulfillment_type_options`. | [set-fulfillment-type](/api-reference/shipment-configuration/set-fulfillment-type) | | `InvalidRequest` | 400 | The `url` query parameter is missing or empty. | [get-product-from-url](/api-reference/catalog/get-product-from-url) | | `InvalidShipmentType` | 400 | The shipment's `fulfillment_type` is not one this endpoint can query, or the type is not supported by the merchant. | [get-availability](/api-reference/shipment-configuration/get-availability) | | `InvalidShippingMethod` | 400 | The supplied `shipping_method_id` is not in the shipment's `shipping_method_options`. | [set-shipping-method](/api-reference/shipment-configuration/set-shipping-method) | | `InvalidState` | 400 | The `state_or_province` value is not valid for the given `country` (e.g. `"ZZ"` for `country: "US"`). | [set-shipping-info](/api-reference/checkout/set-shipping-info) | | `LocationNotFound` | 404 | The supplied `location_id` is not a valid pickup location for this merchant. | [set-fulfillment-type](/api-reference/shipment-configuration/set-fulfillment-type) | | `MissingRequiredCookie` | 400 | A cookie the merchant session depends on is absent, so the session transfer could not be completed. | [PayPal — Complete Order](/api-reference/payment/express-checkout/paypal/complete-order) | | `MissingShippingInfo` | 412 | No shipping address is set on the cart, so it has no shipments to query. | [get-availability](/api-reference/shipment-configuration/get-availability) | | `MissingShippingMethod` | 412 | A shipping method has not been selected on the cart yet. | [Klarna — Complete Order](/api-reference/payment/express-checkout/klarna/complete-order) | | `MissingTaxSync` | 412 | Cart taxes have not been calculated yet. | [Klarna — Complete Order](/api-reference/payment/express-checkout/klarna/complete-order) | | `MultipleDiscountCodesNotSupported` | 409 | Setting shipping triggered a re-evaluation of cart promotions and the merchant rejected the combination of currently-applied discount codes. | [set-shipping-info](/api-reference/checkout/set-shipping-info) | | `NoLineItemError` | 412 | The merchant accepted the request but did not return a line item — typically indicates a product was silently rejected by merchant validation. | [add-line-item](/api-reference/cart-management/add-line-item) | | `PaymentMethodNotAvailable` | 409 | The requested wallet payment method is not available for this merchant. | [wallet-complete-order](/api-reference/payment/wallet-complete-order) | | `PostalCodeRequired` | 412 | The merchant requires a postal code before line items can be modified. | [update-line-item](/api-reference/cart-management/update-line-item) | | `ProductDiscontinued` | 410 | The product at the supplied `url` exists but has been discontinued by the merchant. | [get-product-from-url](/api-reference/catalog/get-product-from-url) | | `ProductUrlNotImplemented` | 404 | The merchant's adapter does not support resolving a product from a URL. | [get-product-from-url](/api-reference/catalog/get-product-from-url) | | `PromoNotAvailable` | 409 | The code exists but is not available for the current cart (e.g. minimum-purchase not met, product-restricted, customer-segment-restricted). | [add-promo-codes](/api-reference/promotions/add-promo-codes) | | `ShippingAddressNotSupported` | 409 | The supplied address is rejected by the merchant for reasons beyond country/state validation (e.g. APO/FPO, US territories, embargoed regions). | [set-shipping-info](/api-reference/checkout/set-shipping-info) | | `ShippingNotNeeded` | 400 | The cart contains only items that do not require shipping (e.g. digital-only). | [set-shipping-info](/api-reference/checkout/set-shipping-info) | | `Unauthorized` | 401 | The Server-to-Server credentials were rejected, or no authentication method (Browser Session, App ID, or Server-to-Server) accepted the request. | [search](/api-reference/discovery/search) | | `VariantNotFound` | 404 | The `url` requested a `?variant=` that is not among the product's variants. | [get-product-from-url](/api-reference/catalog/get-product-from-url) | ## Rate limits A `429` response means you've exceeded your tenant's rate limit. Honor the `Retry-After` header. For the full pattern, recommended retry logic, and how to design high-volume integrations, see **[Rate limits](/api-reference/rate-limits)**. ## Pagination Firmly uses two pagination styles depending on the endpoint. Discovery search returns a cursor in `next_page` when more results are available — pass it on the next request to walk forward. Catalog listing ([Get All Products](/api-reference/catalog/get-all-products)) uses page-number pagination instead: pass `page` and `size`, and read `page` / `size` / `totalPages` from the response's `metadata` object (with `products` as a sibling of `metadata`). For both patterns, page-size guidance, and cursor-expiry handling, see **[Pagination](/api-reference/pagination)**. ## Idempotency Pass an `Idempotency-Key` header (a UUID your code generates) on a mutation request routed through the UCP protocol bridge (see the scope note below). Reuse the same key when retrying the same attempt; generate a fresh key only for a new attempt. On a **UCP-routed** mutation, the first time the server sees a given key the mutation runs normally and the response is cached for **24 hours**; a retry with the same key returns the cached response, so the underlying operation runs at most once. This applies to the UCP bridge only — core REST endpoints do **not** deduplicate on the header (see the scope note below). ```http POST /api/v1/ucp/rest/domain/{domain}/checkout-sessions/{session_id}/complete Idempotency-Key: 7c2a8b1e-4f3d-4a1c-9e6b-2d0a8e7c1b3a ``` If the same key is reused with a **different request body**, the UCP bridge rejects the request with the UCP envelope code `idempotency_conflict` ("idempotency key reused with different parameters"). Either retry with the original body, or generate a new key for the new attempt. (This is UCP-bridge-only — there is no equivalent REST error, since core REST endpoints don't deduplicate on the header.) For the full key format and the conflict-detection fingerprint, see **[Idempotency](/solutions/agentic-commerce/protocols/ucp/idempotency)**. > **Note** > **Scope.** `Idempotency-Key` is currently honored only by the UCP protocol bridge (the integration path used by agentic / protocol-based clients). The core REST endpoints — `add-line-item`, `update-line-item`, `place-order`, `complete-order`, etc. — accept the header but do not deduplicate on it today; retrying re-runs the operation, so guard against duplicates client-side (for example, on a place-order failure, re-read the cart before deciding to retry). ## Recovery patterns for common failure modes ### Stock changed between discovery and place-order The classic race: showed the user a product, they confirmed, someone else bought it before you got to `place-order`. ```text add-line-item → OK set-shipping → OK place-order → 409 NotEnoughStockError ``` Recovery: re-fetch the product, surface the change ("only 1 left — want to proceed with 1 instead of 2?"), update the cart with the new quantity, then retry place-order. ### Payment declined ```text place-order → 422 CreditCardDeclined ``` Recovery: do not silently retry the same card. Tell the user the card was declined (without showing the issuer's reason verbatim — that can leak signals about valid card numbers). Offer a different payment method. (A `412 CheckoutError` is a distinct, merchant-side checkout failure — promo re-evaluation or a total mismatch — not a card decline.) ### Validation error with field path ```text set-shipping-info → 400 InvalidInputBody "At path: phone — Expected a string with a length between 10 and 13" ``` The `description` includes the failing field. Map it to a conversational ask ("what's the phone number with country code?") rather than echoing the raw error. ### Merchant adapter down An **adapter** is Firmly's connector for a merchant's commerce platform (see the [glossary](/resources/glossary#adapter)). Each implements only what its platform supports — hence `OperationNotSupported` / `NotImplemented` on some merchants. ```text add-line-item → 503 StoreUnavailable ``` Recovery: retry with exponential backoff. If persistent for >30 seconds, surface to user. ### get-availability not supported ```text get-availability → 501 NotImplemented ``` Some merchants (V1 adapters) don't implement this endpoint. This doesn't block checkout: `get-availability` only returns delivery dates, time slots, and pickup locations — never shipping methods. Shipping methods always come from `cart.shipments[].shipping_method_options`, populated inline after `set-shipping-info`. Treat a `501` as "no scheduled-delivery/pickup detail for this merchant" and proceed. See [Shipping & Fulfillment](/api-reference/shipment-configuration/shipping-and-fulfillment). ## UCP envelope (UCP protocol layer only) Consumers of the UCP protocol bridge see a different envelope. Documented here for completeness — most direct REST integrations never see it. ```json { "messages": [ { "type": "error", "code": "insufficient_stock", "content": "Product 'Example Item' has only 2 in stock", "severity": "requires_buyer_input", "field": "items[0].quantity" } ], "ucp": { "version": "1.0" } } ``` ### Severity → agent behavior (UCP only) | `severity` | Meaning | What your agent does | |---|---|---| | `recoverable` | Transient or auto-resolvable | Retry with backoff, or auto-correct | | `requires_buyer_input` | User must provide or change something | Ask the user, then retry | | `requires_buyer_review` | User must confirm something risky | Surface details, wait for explicit confirmation | | `unrecoverable` | Flow cannot continue on this path | Tell the user, offer an alternative | ### UCP code catalog | Category | Codes | |---|---| | Session | `session_not_found`, `session_expired`, `session_not_ready`, `session_already_completed`, `session_already_canceled` | | Validation | `validation_error`, `invalid_product`, `invalid_quantity`, `currency_mismatch`, `missing_required_field`, `missing_email`, `missing_shipping_address`, `missing_fulfillment_method` | | Inventory | `insufficient_stock`, `product_unavailable` | | Payment | `payment_declined`, `payment_invalid`, `payment_required` | | Catalog | `product_not_found`, `catalog_unavailable`, `merchant_not_found`, `ucp_disabled` | | Service | `idempotency_conflict`, `service_unavailable`, `internal_error` | ## Quick reference | Error name | HTTP | Quick fix | |---|---|---| | `MissingAuthHeader` | 400 | Add the auth header | | `InvalidToken` | 400 | Re-bootstrap session | | `InvalidJWTToken` | 401 | Re-bootstrap session | | `CartNotFound` | 404 | Create cart by adding an item | | `ProductNotFound` | 404 | Re-search via discovery | | `NotEnoughStockError` | 409 | Lower quantity or pick different variant | | `InvalidPromoCode` | 409 | Verify code; suggest alternatives | | `CountryNotSupported` | 412 | Use a supported country | | `OperationNotSupported` | 412 | Surface to user, or use the merchant default | | `NotImplemented` | 501 | Skip the optional call; read methods from `cart.shipments[].shipping_method_options` | | `InvalidInputBody` | 400 | Read `description`, fix the failing field | | `CreditCardDeclined` | 422 | Ask for a different payment method | | `StoreUnavailable` | 503 | Exponential backoff retry | | `Unexpected` | 500 | Retry once; if persistent [report it](/troubleshooting/reporting-an-issue) with the `CF-RAY` header | ## Need help? - [Support](mailto:firmlydocs@firmly.ai) — Contact support with the request ID + timestamp --- # Express Checkout Wallet and buy-now-pay-later flows, where the buyer authorizes payment in the provider's own widget and Firmly confirms the result. Pick the provider you're integrating — each provider page carries the shared setup and error handling for its sequence. - [Google Pay](/api-reference/payment/express-checkout/google-pay/) — single call; the wallet ceremony is client-side - [Klarna](/api-reference/payment/express-checkout/klarna/) — start → authorize → complete order - [PayPal](/api-reference/payment/express-checkout/paypal/) — start → authorize → complete order Availability is per merchant. Check the cart's `payment_method_options` before offering any of them; a provider the merchant has not enabled returns `404 GatewayNotFound`. --- # Get Active Carts `GET https://api.firmly.work/api/v2/carts/active` ## Overview This endpoint retrieves all active cart sessions across multiple merchant domains for the current device. It enables cross-domain cart access, allowing buyers to view and manage carts from different merchants in a unified experience. > **Note** > This is a global session endpoint that works across all merchant domains, not specific to a single domain. ## Authentication - `x-firmly-authorization` (string, required) — Device access token from [Browser Session](/api-reference/authentication/browser-session) - **Server-to-server (S2S) auth is not accepted** — this is a device-scoped session route. It requires a device JWT from [Browser Session](/api-reference/authentication/browser-session); the S2S secret is rejected. See [Server-to-Server Authentication](/api-reference/authentication/server-to-server). ## Query Parameters - `excludes` (string) — Comma-separated list of domain names to exclude from the results Example: `store1.example,store2.example` ## Response - `domains` (array) — List of domain names with an active cart on this device session (minus any passed in `excludes`). A domain stays in this list even if its cart could not be fetched on this call, so `domains` may contain more entries than `carts`. - `carts` (array) — Array of [ShoppingCart](/api-reference/cart-management/get-cart) objects for each domain whose cart was successfully fetched. May be shorter than `domains` when a domain's cart fetch failed — match entries by `shop_id`, not by array position. Each cart carries the full V2 cart schema: domain information, all shipments and addons, and current totals. > **Note** > These carts use the **V2 cart schema** (`schema_version: "2.0"`), where the tax total field is named `tax_total`. Some V1 / wallet payloads name the equivalent field `tax`; match the field name to the schema version of the response you are reading. ## Session Behavior ### Cross-Domain Management - Aggregates carts from all domains associated with the device session - Each cart maintains its own domain-specific state - Failed retrievals for individual domains don't fail the entire request. A domain whose cart cannot be fetched **still appears in the `domains` array** — only its cart is left out of the `carts` array. This most commonly happens when a merchant adapter is temporarily unreachable (its per-domain [Get Cart](/api-reference/cart-management/get-cart) would return `503 StoreUnavailable`); the failure is logged server-side and skipped rather than surfaced as an error entry. As a result, `carts` may be shorter than `domains` — match carts to domains by `shop_id` rather than by array position, and retry any missing domain via [Get Cart](/api-reference/cart-management/get-cart) if needed. ### Active Cart Criteria - Cart must have at least one line item - Cart session must not be expired - Empty carts are excluded from results ### Performance Considerations - Carts are retrieved in parallel for efficiency - Large numbers of active carts may increase response time - Use the `excludes` parameter to filter unwanted domains ## Examples **Get All Active Carts** ```bash curl -X GET 'https://api.firmly.work/api/v2/carts/active' \ -H 'x-firmly-authorization: ' \ -H 'Content-Type: application/json' ``` **Exclude Specific Domains** ```bash curl -X GET 'https://api.firmly.work/api/v2/carts/active?excludes=store1.example,store2.example' \ -H 'x-firmly-authorization: ' \ -H 'Content-Type: application/json' ``` **JavaScript** ```javascript const response = await fetch('https://api.firmly.work/api/v2/carts/active', { headers: { 'x-firmly-authorization': '', 'Content-Type': 'application/json' } }); const { domains, carts } = await response.json(); ``` **Python** ```python import requests response = requests.get( 'https://api.firmly.work/api/v2/carts/active', headers={ 'x-firmly-authorization': '', 'Content-Type': 'application/json' } ) data = response.json() domains = data['domains'] carts = data['carts'] ``` ## Response Example ```json { "domains": ["staging.luma.gift", "demo.luma.gift"], "carts": [ { "cart_id": "a5600193-2c13-3356-d063-711da63b7cd7", "platform_id": "example_commerce", "shop_id": "staging.luma.gift", "cart_status": "active", "line_items": [ { "line_item_id": "bd3710bc-97ef-408d-7382-43b7e5de712f", "sku": "MH07-XS-Gray", "base_sku": "MH07", "description": "Hero Hoodie", "quantity": 2, "price": { "currency": "USD", "value": 54.00, "number": 5400, "symbol": "$" }, "msrp": { "currency": "USD", "value": 64.00, "number": 6400, "symbol": "$" }, "line_price": { "currency": "USD", "value": 108.00, "number": 10800, "symbol": "$" }, "image": { "url": "https://cdn.staging.luma.gift/hero-hoodie.jpg", "alt": "Hero Hoodie", "type": "default" }, "requires_shipping": true } ], "shipments": [ { "shipment_id": "c2a3f9e8-ba80-8ea1-8762-e498097c8e35", "line_item_ids": ["bd3710bc-97ef-408d-7382-43b7e5de712f"], "fulfillment_type": { "id": "SHIP_TO_ADDRESS", "name": "Ship to Address", "description": "Standard shipping to your address" }, "shipping_method": { "id": "STANDARD_GROUND", "description": "Standard Ground", "price": { "currency": "USD", "value": 9.99, "number": 999, "symbol": "$" }, "estimated_delivery": "5-7 business days" } } ], "sub_total": { "currency": "USD", "value": 108.00, "number": 10800, "symbol": "$" }, "shipping_total": { "currency": "USD", "value": 9.99, "number": 999, "symbol": "$" }, "tax_total": { "currency": "USD", "value": 8.64, "number": 864, "symbol": "$" }, "fees": [{ "description": "Recycle fee", "currency": "USD", "value": 2.00, "number": 200, "symbol": "$" }], "fee_total": { "currency": "USD", "value": 2.00, "number": 200, "symbol": "$" }, "addon_total": { "currency": "USD", "value": 0, "number": 0, "symbol": "$" }, "total": { "currency": "USD", "value": 128.63, "number": 12863, "symbol": "$" }, "addons": { "offers": [], "selections": [] }, "schema_version": "2.0" }, { "cart_id": "8e24c496-0edc-b6a4-72bb-a83a9b3c4ac3", "platform_id": "example_commerce", "shop_id": "demo.luma.gift", "cart_status": "active", "line_items": [ { "line_item_id": "393005f1-18bb-ae90-7530-4b01fa6c6435", "sku": "WS12-XS-Orange", "base_sku": "WS12", "description": "Radiant Tee", "quantity": 1, "price": { "currency": "USD", "value": 22.00, "number": 2200, "symbol": "$" }, "msrp": { "currency": "USD", "value": 26.00, "number": 2600, "symbol": "$" }, "line_price": { "currency": "USD", "value": 22.00, "number": 2200, "symbol": "$" }, "image": { "url": "https://cdn.demo.luma.gift/radiant-tee.jpg", "alt": "Radiant Tee", "type": "default" }, "requires_shipping": true } ], "shipments": [ { "shipment_id": "51991844-d23c-f52c-e447-8cb2156782f3", "line_item_ids": ["393005f1-18bb-ae90-7530-4b01fa6c6435"], "fulfillment_type": { "id": "SHIP_TO_ADDRESS", "name": "Ship to Address", "description": "Standard shipping to your address" }, "shipping_method": { "id": "STANDARD_GROUND", "description": "Standard Ground", "price": { "currency": "USD", "value": 5.99, "number": 599, "symbol": "$" }, "estimated_delivery": "5-7 business days" } } ], "sub_total": { "currency": "USD", "value": 22.00, "number": 2200, "symbol": "$" }, "shipping_total": { "currency": "USD", "value": 5.99, "number": 599, "symbol": "$" }, "tax_total": { "currency": "USD", "value": 1.76, "number": 176, "symbol": "$" }, "fees": [{ "description": "Recycle fee", "currency": "USD", "value": 2.00, "number": 200, "symbol": "$" }], "fee_total": { "currency": "USD", "value": 2.00, "number": 200, "symbol": "$" }, "addon_total": { "currency": "USD", "value": 0, "number": 0, "symbol": "$" }, "total": { "currency": "USD", "value": 31.75, "number": 3175, "symbol": "$" }, "addons": { "offers": [], "selections": [] }, "schema_version": "2.0" } ] } ``` ## Use Cases ### Cart Switching - Show the buyer their active carts and let them resume any one - Each cart is scoped to its merchant and checks out independently ### Cart Recovery - Retrieve abandoned carts across domains - Implement cross-domain cart recovery flows - Track shopping behavior across merchants ### Analytics - Monitor active sessions across merchant network - Track cross-domain shopping patterns - Analyze cart abandonment by domain ## Error Responses Errors return a JSON body with `code`, `error`, and `description`. Program against the `error` value — descriptions are human-readable and may change. **400 — MissingAuthHeader** The `x-firmly-authorization` header is missing or empty. ```json { "code": 400, "error": "MissingAuthHeader", "description": "x-firmly-authorization header is missing or invalid." } ``` **400 — InvalidToken** The authorization token is not a valid JWT structure. ```json { "code": 400, "error": "InvalidToken", "description": "Jwt token is invalid." } ``` **401 — InvalidJWTToken** The device JWT signature does not verify, or required claims are missing. ```json { "code": 401, "error": "InvalidJWTToken", "description": "Jwt token is invalid." } ``` **404 — PartnerNotFound** The `appid` claim on the device JWT does not map to a known partner / tenant. ```json { "code": 404, "error": "PartnerNotFound", "description": "Partner not found." } ``` --- # Get Active Domains `GET https://api.firmly.work/api/v2/carts/active-domains` ## Overview This endpoint retrieves a list of all domain names (store identifiers) that have active cart sessions for the current authenticated device. This is useful for understanding which stores the user has active shopping sessions with. > **Note** > This endpoint returns only domain names, not full cart data. Use [Get Active Carts](/api-reference/session/get-active-carts) to retrieve full cart information. ## Authentication - `x-firmly-authorization` (string, required) — Device access token from [Browser Session](/api-reference/authentication/browser-session) - **Server-to-server (S2S) auth is not accepted** — this is a device-scoped session route. It requires a device JWT from [Browser Session](/api-reference/authentication/browser-session); the S2S secret is rejected. See [Server-to-Server Authentication](/api-reference/authentication/server-to-server). ## Request No request body or query parameters required. ## Response - `domains` (array) — Array of domain names (store identifiers) that have active sessions Example: `["staging.luma.gift", "demo.luma.gift", "shop.luma.gift"]` ## Session Behavior ### Active Domain Criteria - Domain must have an active cart session - Cart must contain at least one item - Session must not be expired ### Use Cases - Quick check for active shopping sessions - Pre-flight check before fetching full cart data - Building domain-specific UI elements - Analytics and session tracking ## Examples **cURL** ```bash curl -X GET 'https://api.firmly.work/api/v2/carts/active-domains' \ -H 'x-firmly-authorization: ' ``` **JavaScript** ```javascript const response = await fetch('https://api.firmly.work/api/v2/carts/active-domains', { headers: { 'x-firmly-authorization': '' } }); const { domains } = await response.json(); console.log('Active domains:', domains); ``` **Python** ```python import requests response = requests.get( 'https://api.firmly.work/api/v2/carts/active-domains', headers={ 'x-firmly-authorization': '' } ) data = response.json() active_domains = data['domains'] ``` ## Response Examples ### Multiple Active Domains ```json { "domains": [ "staging.luma.gift", "demo.luma.gift", "shop.luma.gift" ] } ``` ### Single Active Domain ```json { "domains": [ "staging.luma.gift" ] } ``` ### No Active Domains ```json { "domains": [] } ``` --- ## Related Endpoints - [Get Active Carts](/api-reference/session/get-active-carts) — Get full cart data for active sessions - [Get Cart](/api-reference/cart-management/get-cart) — Get cart for a specific domain ## Error Responses Errors return a JSON body with `code`, `error`, and `description`. Program against the `error` value — descriptions are human-readable and may change. **400 — MissingAuthHeader** The `x-firmly-authorization` header is missing or empty. ```json { "code": 400, "error": "MissingAuthHeader", "description": "x-firmly-authorization header is missing or invalid." } ``` **400 — InvalidToken** The authorization token is not a valid JWT structure. ```json { "code": 400, "error": "InvalidToken", "description": "Jwt token is invalid." } ``` **401 — InvalidJWTToken** The device JWT signature does not verify, or required claims are missing. ```json { "code": 401, "error": "InvalidJWTToken", "description": "Jwt token is invalid." } ``` **404 — PartnerNotFound** The `appid` claim on the device JWT does not map to a known partner / tenant. ```json { "code": 404, "error": "PartnerNotFound", "description": "Partner not found." } ``` --- # Get All Products `GET https://api.firmly.work/api/v1/domains-products/{merchant-domain}` Retrieves a paginated list of all products from a merchant's store. This endpoint returns product summaries with links to retrieve full details for each product. > **Note** > This endpoint uses **page-number pagination** (`page` + `size`), unlike [Discovery Search](/api-reference/discovery/search), which uses cursor-based pagination. Iterate by incrementing `page` up to `metadata.totalPages`. ## Authentication - `x-firmly-authorization` (string, required) — Device access token from [Browser Session](/api-reference/authentication/browser-session) ## Path Parameters - `merchant-domain` (string, required) — The domain of the merchant website (e.g., `staging.luma.gift`) ## Query Parameters - `page` (number, default `1`) — Page number for pagination - `size` (number, default `2000`) — Number of products per page. Valid values: `100`, `500`, `1000`, `2000` - `countryCode` (string, default `us`) — Country code for regional product availability. Case-insensitive — `us` and `US` are treated the same; the value is normalized and echoed back in `metadata.countryCode` (e.g. `US`). ## Response Returns an object with `metadata` describing the page and a `products` array. - `metadata` (object) — Page and source metadata. **Metadata** - `page` (integer) — Current page number (1-indexed) - `size` (integer) — Requested page size — echoes the `size` query parameter (one of `100`, `500`, `1000`, `2000`), not the count of products returned. On the final page the `products` array may be shorter than `size`. - `totalRecords` (integer) — Total products in the merchant catalog - `totalPages` (integer) — Total pages available at the current `size` - `domain` (string) — Merchant domain this catalog belongs to - `countryCode` (string) — ISO country code applied to this query - `startIndex` (integer) — Zero-indexed position of the first product on this page - `endIndex` (integer) — Zero-indexed position of the last product on this page - `generatedAt` (string) — ISO 8601 timestamp when the catalog snapshot was generated - `lastPullAt` (string) — ISO 8601 timestamp of the last upstream sync from the merchant - `version` (string) — Snapshot version identifier - `source` (string) — Source pipeline that generated the catalog (typically `get-all-products-workflow`) - `products` (array) — Array of product summaries. **Product Summary** - `handle` (string) — Product handle/identifier - `title` (string) — Product title - `pdp_url` (string) — Full URL to the product detail page on the merchant's site - `loc` (string) — Full URL to retrieve detailed product information via the [Get Product from URL](/api-reference/catalog/get-product-from-url) endpoint - `image` (object) — Primary product image — `{ "url": "..." }` ## Request Example ```bash curl --request GET \ --url 'https://api.firmly.work/api/v1/domains-products/staging.luma.gift?page=1&size=100' \ --header 'x-firmly-authorization: YOUR_AUTH_TOKEN' ``` ## Response Example ```json { "metadata": { "page": 1, "size": 100, "totalRecords": 132, "totalPages": 2, "domain": "staging.luma.gift", "countryCode": "US", "startIndex": 0, "endIndex": 99, "generatedAt": "2026-02-16T10:46:30.569Z", "lastPullAt": "2026-02-16T10:46:30.569Z", "version": "20260216T104629Z", "source": "generate-all-products" }, "products": [ { "handle": "radiant-tee", "title": "Radiant Tee", "pdp_url": "https://staging.luma.gift/radiant-tee.html", "loc": "https://api.firmly.work/api/v1/domains-pdp?url=https%3A%2F%2Fstaging.luma.gift%2Fradiant-tee.html", "image": { "url": "https://cdn.staging.luma.gift/products/radiant-tee-main.jpg" } }, { "handle": "hero-hoodie", "title": "Hero Hoodie", "pdp_url": "https://staging.luma.gift/hero-hoodie.html", "loc": "https://api.firmly.work/api/v1/domains-pdp?url=https%3A%2F%2Fstaging.luma.gift%2Fhero-hoodie.html", "image": { "url": "https://cdn.staging.luma.gift/products/hero-hoodie-main.jpg" } } ] } ``` > **Note** > Each product's `loc` is a ready-to-call [Get Product from URL](/api-reference/catalog/get-product-from-url) request. To get full details, either GET `loc` directly (with your auth header) or call [Get a Product](/api-reference/catalog/get-product) with the `handle`. ## Error Responses Errors return a JSON body with `code`, `error`, and `description`. Program against the `error` value — descriptions are human-readable and may change. > **Note** > The invalid-`size` error is the one exception: it returns `{ "error": "Size is not valid: valid values are 100, 500, 1000, 2000" }` with HTTP 400 and no `code`/`description`. **400 — Invalid size** `size` is not one of `100`, `500`, `1000`, `2000`. ```json { "error": "Size is not valid: valid values are 100, 500, 1000, 2000" } ``` **400 — MissingAuthHeader** The `x-firmly-authorization` header is missing or empty (when authenticating as a device). ```json { "code": 400, "error": "MissingAuthHeader", "description": "x-firmly-authorization header is missing or invalid." } ``` **400 — InvalidToken** The authorization token is not a valid JWT structure. ```json { "code": 400, "error": "InvalidToken", "description": "Jwt token is invalid." } ``` **401 — InvalidJWTToken** The device JWT signature does not verify, or required claims are missing. ```json { "code": 401, "error": "InvalidJWTToken", "description": "Jwt token is invalid." } ``` **404 — PartnerNotFound** The `appid` claim on the device JWT does not map to a known partner / tenant. ```json { "code": 404, "error": "PartnerNotFound", "description": "Partner not found." } ``` **404 — DomainNotFound** The `{merchant-domain}` does not match any merchant configured with Firmly, or the merchant has been disabled. ```json { "code": 404, "error": "DomainNotFound", "description": "This domain was not found in firmly servers." } ``` **404 — AllProductsNotFound** No catalog snapshot is available for this merchant — the merchant has no published all-products feed. ```json { "code": 404, "error": "AllProductsNotFound", "description": "All products not found." } ``` **412 — OperationNotSupported** The merchant's adapter does not support listing the full catalog. ```json { "code": 412, "error": "OperationNotSupported", "description": "This operation is not supported for this store." } ``` --- # Get Availability `POST https://api.firmly.work/api/v2/domains/{domain}/cart/shipments/get-availability` Returns availability data for a specific shipment. Despite the name, this is a **POST** request — the `shipment_id` is sent in a JSON request body, not as a query string. The response shape varies with the shipment's `fulfillment_type`: - `SCHEDULED_DELIVERY` → available dates with optional time slots, and optional delivery windows. - `PICKUP_IN_STORE` → list of pickup locations with optional pickup options (returned only for merchants that support in-store pickup). - `SHIP_TO_ADDRESS` → list of available delivery dates (where supported by the merchant). This endpoint is **V2-only**. V1 adapters return `501 NotImplemented`. ## Authentication - `x-firmly-authorization` (string, required) — Device access token from [Browser Session](/api-reference/authentication/browser-session) > **Note** > This endpoint also accepts **server-to-server (S2S) authentication** for backend integrations acting on behalf of a device: send `Authorization: Bearer ` (or the equivalent `x-firmly-authorization: `) together with `x-firmly-device-id`. See [Server-to-Server Authentication](/api-reference/authentication/server-to-server). ## Path Parameters - `domain` (string, required) — The merchant's domain (e.g. `staging.luma.gift`). ## Request Body - `shipment_id` (string, required) — Target shipment identifier (from `cart.shipments[].shipment_id`). ## Response One of three shapes, selected by the shipment's `fulfillment_type`. ### Scheduled-delivery shape > **Note** > Unlike the ship-to-address and pickup shapes, the scheduled-delivery response does **not** echo `shipment_id` — it contains only `fulfillment_type`, `available_dates`, and optional `delivery_windows`. - `fulfillment_type` (object) — Always `{ id: "SCHEDULED_DELIVERY", name, description }`. - `available_dates` (array, required) — Available dates the buyer can pick from. **AvailableDate properties** - `date` (string, required) — ISO date (`YYYY-MM-DD`). - `description` (string) — Optional human-readable description (e.g. "Premium delivery available"). - `time_slots` (array) — Optional list of time slots within the date. - `slot_id` (string) — Optional slot identifier — pass to [Set Shipping Method](/api-reference/shipment-configuration/set-shipping-method) as `selected_time_slot`. - `start_time` (object, required) — Slot start time. - `utc` (string, required) — ISO 8601 timestamp in UTC. - `local` (string, required) — Local time representation. - `local_timezone` (string, required) — IANA timezone of `local` (e.g. `America/New_York`). - `display` (string) — Optional pre-formatted display string. - `end_time` (object, required) — Slot end time. Same `{ utc, local, local_timezone, display? }` shape as `start_time`. - `description` (string) — Optional description (e.g. "Morning window"). - `price` (object) — Optional surcharge for this slot (Amount object). - `delivery_windows` (array) — Optional premium delivery windows. **DeliveryWindow properties** - `window_id` (string, required) — Window identifier. - `name` (string, required) — Window display name. - `description` (string, required) — Detailed description. - `price` (object, required) — Surcharge for the window (Amount). - `date_range` (object, required) — Range during which the window is offered. - `start_date` (string, required) — First date (`YYYY-MM-DD`). - `end_date` (string, required) — Last date (`YYYY-MM-DD`). ### Pickup shape Returned for `PICKUP_IN_STORE` shipments. - `shipment_id` (string, required) — The shipment identifier. - `fulfillment_type` (object) — Always `{ id: "PICKUP_IN_STORE", name, description }`. - `pickup_locations` (array, required) — Locations where the order can be picked up. Each location includes `location_id`, `name`, `address`, optional `phone`, optional `operating_hours`, optional `distance`, and a `pickup_options` array of `{ date, time_slots }` per location. - `pickup_options` (array) — Optional, cross-location pickup options. Each entry: `{ id, description, price? }`. ### Delivery shape Returned for `SHIP_TO_ADDRESS` shipments when the merchant exposes date selection. - `shipment_id` (string, required) — The shipment identifier. - `fulfillment_type` (object) — Always `{ id: "SHIP_TO_ADDRESS", name, description }`. - `available_dates` (array, required) — Same `AvailableDate` shape as the scheduled-delivery response above. ## Example Request ```bash curl -X POST https://api.firmly.work/api/v2/domains/staging.luma.gift/cart/shipments/get-availability \ -H "x-firmly-authorization: YOUR_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "shipment_id": "840b0477-b913-191a-2b4f-dc232a779f0c" }' ``` ## Response Example ```json { "fulfillment_type": { "id": "SCHEDULED_DELIVERY", "name": "Scheduled Delivery", "description": "Choose a delivery date and time" }, "available_dates": [ { "date": "2026-06-15", "description": "Premium delivery available", "time_slots": [ { "slot_id": "morning-premium", "start_time": { "utc": "2026-06-15T12:00:00.000Z", "local": "2026-06-15 08:00", "local_timezone": "America/New_York" }, "end_time": { "utc": "2026-06-15T16:00:00.000Z", "local": "2026-06-15 12:00", "local_timezone": "America/New_York" }, "description": "Morning premium delivery", "price": { "currency": "USD", "value": 19.99, "number": 1999, "symbol": "$" } } ] } ], "delivery_windows": [ { "window_id": "premium-week", "name": "Premium Delivery Window", "description": "White glove delivery with setup", "price": { "currency": "USD", "value": 199.99, "number": 19999, "symbol": "$" }, "date_range": { "start_date": "2026-06-15", "end_date": "2026-06-22" } } ] } ``` ## Prerequisites - Shipping address must be set on the cart ([Set Shipping Info](/api-reference/checkout/set-shipping-info)) — otherwise the cart has no shipments. - For scheduled-delivery or pickup results, the shipment must already carry the matching `fulfillment_type`. Use [Set Fulfillment Type](/api-reference/shipment-configuration/set-fulfillment-type) when the merchant default is different. ## Error Responses Errors return a JSON body with `code`, `error`, and `description`. Program against the `error` value — descriptions are human-readable and may change. **400 — MissingAuthHeader** The `x-firmly-authorization` header is missing or empty. ```json { "code": 400, "error": "MissingAuthHeader", "description": "x-firmly-authorization header is missing or invalid." } ``` **400 — InvalidToken** The authorization token is not a valid JWT structure. ```json { "code": 400, "error": "InvalidToken", "description": "Jwt token is invalid." } ``` **400 — InvalidAPIToken** The API token (server-to-server secret) is invalid or has been revoked. ```json { "code": 400, "error": "InvalidAPIToken", "description": "API token is invalid." } ``` **400 — BadRequest** Server-to-server auth was attempted but required headers are missing or malformed. ```json { "code": 400, "error": "BadRequest", "description": "Bad request." } ``` **400 — InvalidShipmentType** The shipment's `fulfillment_type` is not one this endpoint can query, or the type is not supported by the merchant. ```json { "code": 400, "error": "InvalidShipmentType", "description": "The specified shipment type is not valid or not supported." } ``` **401 — Unauthorized** The authorization token was rejected. ```json { "code": 401, "error": "Unauthorized", "description": "Unauthorized." } ``` **401 — InvalidJWTToken** The device JWT signature does not verify, or required claims are missing. ```json { "code": 401, "error": "InvalidJWTToken", "description": "Jwt token is invalid." } ``` **404 — PartnerNotFound** The `appid` claim on the device JWT does not map to a known partner / tenant. ```json { "code": 404, "error": "PartnerNotFound", "description": "Partner not found." } ``` **404 — DomainNotFound** The `{domain}` path parameter does not match any merchant configured with Firmly, or the merchant has been disabled. ```json { "code": 404, "error": "DomainNotFound", "description": "This domain was not found in firmly servers." } ``` **404 — CartNotFound** No cart exists for this device on this domain. ```json { "code": 404, "error": "CartNotFound", "description": "Cart was not found." } ``` **404 — ShipmentNotFound** The supplied `shipment_id` does not match any shipment on the current cart. ```json { "code": 404, "error": "ShipmentNotFound", "description": "Shipment not found." } ``` **412 — MissingShippingInfo** No shipping address is set on the cart, so it has no shipments to query. Call [Set Shipping Info](/api-reference/checkout/set-shipping-info) first — this is the common cause when `get-availability` is called before shipping is set. ```json { "code": 412, "error": "MissingShippingInfo", "description": "Shipping info needs to be set." } ``` **400 — InvalidInputBody** Request body fails schema validation. `shipment_id` must be a non-empty string. ```json { "code": 400, "error": "InvalidInputBody", "description": "The body is not processable" } ``` **422 — UnprocessableEntity** The request is well-formed but cannot be processed — typically the merchant API returned data that failed Firmly's validation. ```json { "code": 422, "error": "UnprocessableEntity", "description": "The given payload has unprocessable, invalid or non-existent data. Please check the data and try again." } ``` **501 — NotImplemented** The merchant adapter is V1 and does not implement availability queries. Pickup and scheduled-delivery features may not be available for this merchant. ```json { "code": 501, "error": "NotImplemented", "description": "Operation not implemented." } ``` **503 — StoreUnavailable** The merchant's API returned an unexpected response and the request could not be fulfilled. Retry with backoff. ```json { "code": 503, "error": "StoreUnavailable", "description": "Store is unavailable." } ``` --- # Get Card Art `GET https://api.firmly.work/api/v1/wallets/agentic-pay/card-art/{token}` ## Overview Returns the card art image (the visual card image from the issuing bank) for a card enrolled via Agentic Pay. The URL is returned in the `card_art.url` field of the [enroll](/api-reference/agentic-pay/enroll) response and in the [Wallet Complete Order](/api-reference/payment/wallet-complete-order) response (where it appears under `payment_summary.card_art`). No authentication header is needed — the HMAC-signed token in the URL path serves as authorization. > **Note** > Card art may not be returned on re-enrollment of the same card. Destinations should persist `card_art` from the initial enroll response. ## Authentication This endpoint requires no authentication. The `token` path parameter contains an HMAC-signed payload that serves as authorization. ## Path Parameters - `token` (string, required) — HMAC-signed compact token in the format `.`. Contains the network, image locator, and expiry. Generated by Firmly during enrollment. ## Response The response is binary image data with the following headers: - `content-type` (string) — `image/png` or `image/jpeg` depending on the card art source - `cache-control` (string) — `public, max-age=86400, immutable` - `x-firmly-card-art-source` (string) — Source identifier for the card art image ## Card Art Object Shape The `card_art` object returned by `/enroll` has this shape. Destinations should persist it from the initial enrollment for use in the saved-card UI: - `card_art.network` (string) — Card network (`visa`, `mastercard`, or `discover`) - `card_art.url` (string) — Full URL to this card-art endpoint with the signed token - `card_art.background_color` (string) — Hex color code for the card background (e.g., `#1A1F71`) - `card_art.foreground_color` (string) — Hex color code for the card foreground text (e.g., `#FFFFFF`) - `card_art.descriptor` (string) — Issuing bank descriptor (e.g., `"Test Bank 2"`) ## Code Examples **cURL** ```bash # Use the URL directly from the enroll or complete response curl -o card-art.png \ "https://api.firmly.work/api/v1/wallets/agentic-pay/card-art/eyJuIjoiVklTQSIsImx..." ``` **JavaScript** ```javascript // The card_art.url from the enroll/complete response can be used directly const enrollResponse = await enroll(cardDetails); const { card_art } = enrollResponse; // Drop directly into an img tag const img = document.createElement('img'); img.src = card_art.url; // Or fetch the image programmatically const response = await fetch(card_art.url); const contentType = response.headers.get('content-type'); const blob = await response.blob(); const imageUrl = URL.createObjectURL(blob); ``` **Python** ```python import requests # Use the URL from the enroll/complete response card_art_url = enroll_response["card_art"]["url"] response = requests.get(card_art_url) content_type = response.headers["content-type"] # Save to file extension = "png" if "png" in content_type else "jpeg" with open(f"card-art.{extension}", "wb") as f: f.write(response.content) ``` ## Response Example ```json Card Art Object (enroll-response fragment — not this endpoint's response) { "card_art": { "network": "visa", "url": "https://api.firmly.work/api/v1/wallets/agentic-pay/card-art/", "background_color": "#1A1A2E", "foreground_color": "#FFFFFF", "descriptor": "Test Bank 2" } } ``` > **Note** > This endpoint itself returns **binary image data** (`image/png` or `image/jpeg`) on success — not JSON. The JSON above is the `card_art` object as it appears in the enroll and complete responses; its `url` points here. ## How the Proxy Works The card-art endpoint acts as a secure proxy between the destination and the card network's asset service. Firmly fetches the image using its own network credentials, so destinations never need direct access to network asset APIs. The token has a default TTL of 1 hour. ## Error Responses Errors are returned as JSON, not as image data. | Error Code | Status | Description | | ---------- | ------ | ----------- | | `BadRequest` | 400 | Malformed token or locator host not allowed | | `Unauthorized` | 401 | Signature invalid or token expired | | `PaymentMethodNotAvailable` | 409 | Card art not found at the network (e.g., nonexistent Visa GUID) | **400 - Bad Request** ```json { "code": 400, "error": "BadRequest", "description": "Malformed token or locator host not allowed" } ``` **401 - Unauthorized** ```json { "code": 401, "error": "Unauthorized", "description": "Signature invalid or token expired" } ``` **409 - Card Art Not Found** ```json { "code": 409, "error": "PaymentMethodNotAvailable", "description": "Card art not found at the network" } ``` --- ## Related Endpoints - [Enroll Card](/api-reference/agentic-pay/enroll) — Enroll a card and receive the `card_art` object in the response - [Intent Challenge](/api-reference/agentic-pay/intent-challenge) — Complete a payment-level challenge for the intent --- # Get Cart `GET https://api.firmly.work/api/v2/domains/{domain}/cart` ## Overview The Get Cart endpoint retrieves the complete current state of a shopping cart, including: - All line items with product details and quantities - Multiple shipments with items grouped by fulfillment requirements - Complete pricing breakdown (subtotal, shipping, tax, addons, total) - Available addon offers and current selections - Cart-level metadata and schema version ## Authentication - `x-firmly-authorization` (string, required) — Device access token from [Browser Session](/api-reference/authentication/browser-session) > **Note** > This endpoint also accepts **server-to-server (S2S) authentication** for backend integrations acting on behalf of a device: send `Authorization: Bearer ` (or the equivalent `x-firmly-authorization: `) together with `x-firmly-device-id`. See [Server-to-Server Authentication](/api-reference/authentication/server-to-server). ## Path Parameters - `domain` (string, required) — Domain of the merchant website (e.g., `staging.luma.gift`) ## Response - `cart_id` (string) — Unique identifier for the shopping cart session - `platform_id` (string) — Identifier of the merchant's underlying commerce platform. The literal value varies by merchant and reflects the platform Firmly is integrated with. - `shop_id` (string) — Shop identifier (merchant domain, e.g., "staging.luma.gift") - `display_name` (string) — Merchant display name - `cart_status` (string) — Current cart status (e.g., "active") - `line_items` (array) — Array of products currently in the cart **Line Item Properties** - `line_item_id` (string) — Unique identifier for the line item - `platform_line_item_id` (string) — Platform-specific line item identifier - `sku` (string) — Product SKU identifier - `variant_description` (string) — Variant-specific description - `description` (string) — Product description - `base_sku` (string) — Base product SKU (parent of variants) - `quantity` (number) — Quantity of the item in cart - `price` (object) — Unit price information - `currency` (string) — Currency code (e.g., USD) - `value` (number) — Price as decimal - `number` (number) — Price in smallest currency unit - `symbol` (string) — Currency symbol - `line_price` (object) — Total price for this line (price × quantity) - `currency` (string) — Currency code (e.g., USD) - `value` (number) — Price as decimal - `number` (number) — Price in smallest currency unit - `symbol` (string) — Currency symbol - `msrp` (object) — Manufacturer's suggested retail price - `currency` (string) — Currency code (e.g., USD) - `value` (number) — Price as decimal - `number` (number) — Price in smallest currency unit - `symbol` (string) — Currency symbol - `image` (object) — Product image information - `url` (string) — Image URL - `type` (string) — Image size variant (e.g., `large`, `default`, `small`, `preview`) - `alt` (string) — Alternative text - `requires_shipping` (boolean) — Whether this item requires physical shipping - `discount` (object) — Per-unit discount applied to this line, when the merchant returns line-level discounts. Amount object (`currency`/`value`/`number`/`symbol`). Present only when the merchant exposes per-line discounts. - `line_discount` (object) — Total discount for this line (per-unit discount × quantity), when the merchant returns line-level discounts. Amount object. Present only when the merchant exposes per-line discounts. - `variant_handles` (array) — Variant configuration handles echoed back from the merchant (e.g. `["color:blue", "size:large"]`). Present when the underlying platform represents variants as a set of handles rather than a single SKU. - `properties` (object) — Merchant-specific custom line-item properties (e.g. monogramming text, gift-wrap selection, configurator state). Free-form key/value map. - `parent_line_item_id` (string) — For bundles or kits, the `line_item_id` of the parent item this row is a child of. - `line_item_tax` (object) — Per-line tax amount, when the merchant exposes line-level tax. Amount object (`currency`/`value`/`number`/`symbol`). - `shipments` (array) — Array of shipment groups, each containing line items with similar fulfillment requirements **Shipment Properties** - `shipment_id` (string) — Unique identifier for the shipment - `line_item_ids` (array) — Array of line item IDs included in this shipment - `fulfillment_type` (object) — Selected fulfillment method (automatically set to default) - `id` (string) — Fulfillment type identifier. One of: `SHIP_TO_ADDRESS`, `SCHEDULED_DELIVERY`, `PICKUP_IN_STORE`. - `name` (string) — Display name - `description` (string) — Detailed description - `fulfillment_type_options` (array) — Available fulfillment types for this shipment - `shipping_method_options` (array) — Available shipping methods for the selected fulfillment type - `shipping_method` (object) — Selected shipping method (defaults to cheapest available option) - `id` (string) — Shipping method identifier - `description` (string) — Shipping method description - `price` (object) — Shipping cost. Required unless `hide_price` is `true`. - `hide_price` (boolean) — When `true`, the merchant wants the price suppressed in the UI (e.g. "Calculated at checkout"). `price` may be omitted in this case. - `message` (string) — Optional merchant-supplied message about this shipping method (e.g. carrier note, eligibility caveat). - `estimated_delivery` (string) — Delivery timeframe - `notes` (string) — Special instructions or notes for this shipment - `selected_date` (string) — Selected delivery date for scheduled delivery (YYYY-MM-DD format) - `addons` (object) — Available addon services and current selections **Addon Properties** - `offers` (array) — Available addon options - `addon_id` (string) — Unique addon identifier - `display` (object) — Display information - `scope` (string) — Addon scope (CART or ITEM) - `price` (object) — Addon price - `selections` (array) — Currently selected addons - `sub_total` (object) — Subtotal of all line items - `shipping_total` (object) — Total shipping cost across all shipments - `tax_total` (object) — Total tax amount - `addon_total` (object) — Total cost of selected addons - `fees` (array) — Merchant-imposed fees (e.g. recycle, regulatory), if any **Fee Properties** - `description` (string) — Human-readable label for the fee (e.g. "Recycle fee") - `value` (number) — Decimal fee amount - `currency` (string) — ISO 4217 currency code - `number` (integer) — Value in smallest currency unit (cents) - `symbol` (string) — Currency symbol - `fee_total` (object) — Total of all fees - `total` (object) — Grand total including all costs - `shipping_info` (object) — Shipping address information (when address is set) **Shipping Info Properties** - `first_name` (string) — Recipient's first name - `last_name` (string) — Recipient's last name - `company` (string) — Company name (optional) - `email` (string) — Recipient's email address - `phone` (string) — Recipient's phone number - `address1` (string) — Street address line 1 - `address2` (string) — Street address line 2 (optional) - `city` (string) — City name - `state_or_province` (string) — State or province code - `state_name` (string) — Full state / province name, when the merchant returns it (optional) - `postal_code` (string) — Postal / ZIP code - `country` (string) — Country code (e.g., US, CA) - `billing_info` (object) — Billing address (when set via [Set Billing Info](/api-reference/checkout/set-billing-info)). Same shape as `shipping_info`. - `coupons` (array) — Promotion codes currently applied to the cart. Array of strings. Manage via the [Promotions](/api-reference/promotions/) endpoints. - `cart_discount` (object) — Total promotion / coupon discount applied to the cart. Amount object. - `cart_discount_breakdown` (array) — Per-promotion breakdown of `cart_discount`. Each entry has `label` (string) and `discount` (Amount). - `tax` (object) — Tax amount, V1 field name. **Either `tax` or `tax_total` may be present depending on the merchant's adapter** — both are optional on a V2 cart. Read them the way Firmly's own price checks do: prefer `tax_total`, fall back to `tax` (`tax_total ?? tax`). Don't assume only one exists. - `urls` (object, required) — Merchant URLs returned with the cart. The object is always present; its members are optional. **URL Properties** - `thank_you_page` (string) — URL to redirect the buyer to after a successful order. - `order_status_page` (string) — Merchant order-status page for the placed order, when the merchant provides one. - `shop_properties` (object) — Merchant payment / wallet capabilities, used by the drop-in to decide which buttons to render. **Shop Properties** - `paypal` (object) — PayPal configuration: `payment_enabled`, `express_enabled`, `clientId`, `merchantId`, `sandbox`, `intent`. - `klarna` (object) — Klarna configuration: `enabled`, `express_enabled`, `clientId`. - `google_pay` (object) — Google Pay configuration: `enabled`, `publishable_key`, `environment`. - `place_order_vault` (boolean) — Whether the merchant routes place-order through Firmly's payment host. - `optional_fields` (object) — Per-merchant relaxations such as `shipping_phone` (when phone is not required on shipping address). - `payment_handle` (string) — Payment handle identifier (when payment is configured) - `payment_method_options` (array) — Available payment methods for checkout **Payment Method Object** - `type` (string) — Payment method type (e.g., "CreditCard", "PayPal") - `wallet` (string) — Wallet identifier (e.g., "user", "paypal") - `session` (object) — Account/session state for this device at this merchant. All fields optional — a merchant adapter that doesn't support a signal simply omits it. **Session Properties** - `requires_login` (boolean) — The merchant requires the shopper to log in before checkout. - `is_email_registered` (boolean) — The email on the cart already has a merchant account. - `is_logged_in` (boolean) — The device session is currently logged into a merchant account. - `accepts_membership` (array) — Membership/loyalty programs the shopper can opt into at this merchant. Array of strings. - `accepts_otp` (array) — OTP delivery channels the merchant supports for this session: `email`, `phone`. - `notices` (array) — Cart notices providing information about cart state and issues **Notice Properties** - `code` (string) — Notice code identifier - `ITEM_NOT_SHIPPABLE` — Item cannot be shipped to selected address - `ITEM_OUT_OF_STOCK` — Item is out of stock - `PROMO_EXPIRED` — Promotion code has expired - `PROMO_NOT_APPLICABLE` — Promotion doesn't apply to cart - `SHIPPING_NOT_AVAILABLE` — Shipping method unavailable - `PRICE_INCREASED` — Item price has increased - `PRICE_DECREASED` — Item price has decreased - `severity` (string) — Notice severity level: `info`, `warning`, or `error` - `item_id` (string) — Line item ID if notice is item-specific - `details` (object) — Additional notice details **Details Properties** - `description` (string) — Detailed description of the notice - `promo_code` (string) — Affected promo code (for promo-related notices) - `old_value` (object) — Previous price (for price change notices) - `new_value` (object) — New price (for price change notices) - `reason` (string) — Reason for the notice - `schema_version` (string) — Cart schema version ("2.0") ## Code Examples **cURL** ```bash curl --request GET \ --url https://api.firmly.work/api/v2/domains/staging.luma.gift/cart \ --header 'x-firmly-authorization: YOUR_TOKEN' ``` **JavaScript** ```javascript const response = await fetch('https://api.firmly.work/api/v2/domains/staging.luma.gift/cart', { method: 'GET', headers: { 'x-firmly-authorization': 'YOUR_TOKEN' } }); const cart = await response.json(); console.log(cart); ``` **Python** ```python import requests response = requests.get( 'https://api.firmly.work/api/v2/domains/staging.luma.gift/cart', headers={ 'x-firmly-authorization': 'YOUR_TOKEN' } ) cart = response.json() print(cart) ``` **PHP** ```php "https://api.firmly.work/api/v2/domains/staging.luma.gift/cart", CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => [ "x-firmly-authorization: YOUR_TOKEN" ], ]); $response = curl_exec($curl); curl_close($curl); $cart = json_decode($response, true); print_r($cart); ?> ``` ## Response Example ```json { "cart_id": "a5600193-2c13-3356-d063-711da63b7cd7", "platform_id": "example_commerce", "shop_id": "staging.luma.gift", "display_name": "Luma Store", "cart_status": "active", "line_items": [ { "line_item_id": "bd3710bc-97ef-408d-7382-43b7e5de712f", "platform_line_item_id": "0", "sku": "MH07-XS-Gray", "variant_description": "Gray / XS", "description": "Hero Hoodie", "base_sku": "MH07", "quantity": 1, "price": { "currency": "USD", "value": 54.00, "number": 5400, "symbol": "$" }, "line_price": { "currency": "USD", "value": 54.00, "number": 5400, "symbol": "$" }, "msrp": { "currency": "USD", "value": 64.00, "number": 6400, "symbol": "$" }, "image": { "url": "https://staging.luma.gift/images/hero-hoodie.jpg", "type": "large", "alt": "Hero Hoodie in Gray" }, "requires_shipping": true } ], "shipments": [ { "shipment_id": "c2a3f9e8-ba80-8ea1-8762-e498097c8e35", "line_item_ids": ["bd3710bc-97ef-408d-7382-43b7e5de712f"], "fulfillment_type": { "id": "SCHEDULED_DELIVERY", "name": "Scheduled Delivery", "description": "White glove delivery with scheduled time" }, "fulfillment_type_options": [ { "id": "SHIP_TO_ADDRESS", "name": "Ship to Address", "description": "Standard shipping to customer address" }, { "id": "SCHEDULED_DELIVERY", "name": "Scheduled Delivery", "description": "White glove delivery with scheduled time" }, { "id": "PICKUP_IN_STORE", "name": "In-Store Pickup", "description": "Pick up at store location" } ], "shipping_method_options": [ { "id": "WHITE_GLOVE", "description": "White Glove Delivery Service", "price": { "currency": "USD", "value": 149.99, "number": 14999, "symbol": "$" }, "estimated_delivery": "Scheduled delivery" } ], "shipping_method": { "id": "WHITE_GLOVE", "description": "White Glove Delivery Service", "price": { "currency": "USD", "value": 149.99, "number": 14999, "symbol": "$" }, "estimated_delivery": "Scheduled delivery" }, "notes": "", "selected_date": "2025-07-14" } ], "addons": { "offers": [ { "addon_id": "shipping_protection", "display": { "name": "Shipping Protection", "description": "Protect your order against shipping damage" }, "scope": "CART", "coverage_mode": "PREDEFINED_GROUP", "price": { "currency": "USD", "value": 12.99, "number": 1299, "symbol": "$" } } ], "selections": [] }, "sub_total": { "currency": "USD", "value": 54.00, "number": 5400, "symbol": "$" }, "shipping_total": { "currency": "USD", "value": 149.99, "number": 14999, "symbol": "$" }, "tax_total": { "currency": "USD", "value": 5.40, "number": 540, "symbol": "$" }, "fees": [ { "description": "Recycle fee", "currency": "USD", "value": 2.00, "number": 200, "symbol": "$" } ], "fee_total": { "currency": "USD", "value": 2.00, "number": 200, "symbol": "$" }, "addon_total": { "currency": "USD", "value": 0.00, "number": 0, "symbol": "$" }, "total": { "currency": "USD", "value": 211.39, "number": 21139, "symbol": "$" }, "shipping_info": { "first_name": "John", "last_name": "Doe", "email": "john.doe@staging.luma.gift", "phone": "+1234567890", "address1": "123 Main Street", "address2": "Apt 4B", "city": "New York", "state_or_province": "NY", "postal_code": "10001", "country": "US" }, "payment_handle": "pay_01H2XVBR8C8JS5MQSFPJ8HF9SE", "payment_method_options": [ { "type": "CreditCard", "wallet": "user" }, { "type": "PayPal", "wallet": "paypal" } ], "notices": [], "schema_version": "2.0" } ``` ### Blocked cart (`item_not_shippable`) `cart_status` can also come back as one of the other values in the [ShoppingCartV2 schema](/resources/schemas/shopping-cart) — most notably `item_not_shippable`, which means checkout is blocked because an item in the cart can't ship to the current address. When that happens, `notices[]` carries the reason: ```json { "cart_status": "item_not_shippable", "notices": [ { "code": "ITEM_NOT_SHIPPABLE", "severity": "error", "item_id": "bd3710bc-97ef-408d-7382-43b7e5de712f", "details": { "description": "This item cannot be shipped to the selected address", "reason": "Shipping restrictions apply to this location" } } ] } ``` Resolve it by removing the item, changing the shipping address, or picking a different fulfillment option, then re-fetch the cart. --- ## Related Endpoints - [Add Line Item](/api-reference/cart-management/add-line-item) — Add items to cart - [Update Line Item](/api-reference/cart-management/update-line-item) — Modify cart items - [Clear Cart](/api-reference/cart-management/clear-cart) — Empty the cart ## Error Responses Errors return a JSON body with `code`, `error`, and `description`. Use the `error` value to drive client logic — descriptions are human-readable and may change. **400 — MissingAuthHeader** The `x-firmly-authorization` header is missing or empty. ```json { "code": 400, "error": "MissingAuthHeader", "description": "x-firmly-authorization header is missing or invalid." } ``` **400 — InvalidToken** The authorization token is not a valid JWT structure (malformed header/payload/signature segments). ```json { "code": 400, "error": "InvalidToken", "description": "Jwt token is invalid." } ``` **400 — InvalidAPIToken** The API token (server-to-server secret) is invalid or has been revoked. ```json { "code": 400, "error": "InvalidAPIToken", "description": "API token is invalid." } ``` **400 — BadRequest** Server-to-server auth was attempted but required headers (`x-firmly-authorization` plus `x-firmly-device-id`) are missing or malformed. ```json { "code": 400, "error": "BadRequest", "description": "Bad request." } ``` **401 — Unauthorized** The authorization token was rejected. ```json { "code": 401, "error": "Unauthorized", "description": "Unauthorized." } ``` **401 — InvalidJWTToken** The device JWT's signature does not verify against Firmly's JWT signing keys, or required claims are missing. ```json { "code": 401, "error": "InvalidJWTToken", "description": "Jwt token is invalid." } ``` **404 — PartnerNotFound** The `appid` claim on the device JWT does not map to a known partner / tenant. Often means the token was issued against a different environment. ```json { "code": 404, "error": "PartnerNotFound", "description": "Partner not found." } ``` **404 — DomainNotFound** The `{domain}` path parameter does not match any merchant configured with Firmly, or the merchant has been disabled. Verify the domain string (case-sensitive, no protocol or trailing slash). ```json { "code": 404, "error": "DomainNotFound", "description": "This domain was not found in firmly servers." } ``` **404 — CartNotFound** The session exists but no cart has been created yet for this device on this domain. Add an item via [Add Line Item](/api-reference/cart-management/add-line-item) to create one. ```json { "code": 404, "error": "CartNotFound", "description": "Cart was not found." } ``` **412 — OperationNotSupported** The merchant's platform does not support this operation. Some platform adapters do not implement every cart operation; check with [Firmly](/contact) whether this endpoint is available for the merchant. ```json { "code": 412, "error": "OperationNotSupported", "description": "This operation is not supported for this store." } ``` **422 — UnprocessableEntity** The request is well-formed but cannot be processed — typically a downstream merchant call returned data that fails Firmly's output validation, or a pre-condition (postal code, session bootstrap) is not yet satisfied. ```json { "code": 422, "error": "UnprocessableEntity", "description": "The given payload has unprocessable, invalid or non-existent data. Please check the data and try again." } ``` --- # Get Consents `GET https://api.firmly.work/api/v2/domains/{domain}/cart/consents` ## Overview Retrieves the current consent settings for a buyer's cart session. This endpoint returns all available consent options along with their current status, including whether they have been signed by the buyer. ## How Consent Management Works 1. **Session-Based**: Consents are stored on the cart session and persist until checkout completion. 2. **Type-Based**: Different consent types (marketing, terms, privacy) are supported. 3. **UI Placement**: Each consent carries a `ui_slot` hint for placement in your checkout UI. ## Authentication - `x-firmly-authorization` (string, required) — Device access token from [Browser Session](/api-reference/authentication/browser-session) > **Note** > This endpoint also accepts **server-to-server (S2S) authentication** for backend integrations acting on behalf of a device: send `Authorization: Bearer ` (or the equivalent `x-firmly-authorization: `) together with `x-firmly-device-id`. See [Server-to-Server Authentication](/api-reference/authentication/server-to-server). ## Path Parameters - `domain` (string, required) — Domain of the merchant website (e.g., `staging.luma.gift`) ## Response Returns a JSON **array** of consent objects (no top-level wrapper). Each item has the following fields: - `id` (string, required) — Unique identifier for the consent. - `ui_slot` (string, required) — UI placement hint. One of: - `UNDER_EMAIL_INPUT` — Display under the email field - `ABOVE_PLACE_ORDER_BUTTON` — Display above the place-order button - `text` (string, required) — Plain-text version of the consent (use for accessibility and as a fallback). - `html` (string) — Optional HTML version with rich formatting and links. Render this when present; fall back to `text` otherwise. - `type` (string, required) — Type of consent. One of: - `MARKETING` — Marketing communications - `TERMS_AND_CONDITIONS` — Terms of service - `PRIVACY_POLICY` — Privacy policy - `OTHER` — Anything that does not fit the above - `explicit` (boolean, required) — `true` when the buyer must take an explicit action (e.g. tick a checkbox); `false` when the consent is implicitly granted by completing checkout. - `required` (boolean, required) — Whether this consent must be accepted for checkout to complete. - `revokable` (boolean, required) — Whether the buyer can revoke this consent after signing. - `signed` (boolean, required) — Whether this consent is considered signed. Computed server-side as `signed = hasSignature OR (explicit === false AND required === true)` — so implicit-required consents return `signed: true` automatically without the buyer having explicitly accepted them. ## Code Examples **cURL** ```bash curl -X GET https://api.firmly.work/api/v2/domains/staging.luma.gift/cart/consents \ -H "x-firmly-authorization: YOUR_TOKEN" ``` **JavaScript** ```javascript const response = await fetch('https://api.firmly.work/api/v2/domains/staging.luma.gift/cart/consents', { method: 'GET', headers: { 'x-firmly-authorization': 'YOUR_TOKEN' } }); const consents = await response.json(); ``` **Python** ```python import requests response = requests.get( 'https://api.firmly.work/api/v2/domains/staging.luma.gift/cart/consents', headers={ 'x-firmly-authorization': 'YOUR_TOKEN' } ) consents = response.json() ``` **PHP** ```php $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, 'https://api.firmly.work/api/v2/domains/staging.luma.gift/cart/consents'); curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'x-firmly-authorization: YOUR_TOKEN' ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); $consents = json_decode($response, true); curl_close($ch); ``` ## Response Example ```json [ { "id": "f47ac10b-58cc-4372-a567-0e02b2c3d479", "ui_slot": "UNDER_EMAIL_INPUT", "text": "I would like to receive marketing emails about special offers and new products.", "type": "MARKETING", "explicit": true, "required": false, "revokable": true, "signed": false }, { "id": "6ba7b810-9dad-11d1-80b4-00c04fd430c8", "ui_slot": "ABOVE_PLACE_ORDER_BUTTON", "text": "I agree to the Terms of Service and Privacy Policy.", "html": "I agree to the Terms of Service and Privacy Policy.", "type": "TERMS_AND_CONDITIONS", "explicit": true, "required": true, "revokable": false, "signed": true } ] ``` ## Default Consent States If the merchant has not configured explicit consents but has set `marketing_consent_text` in their Firmly configuration, a single marketing consent is generated: - It is optional (`required: false`) and revokable (`revokable: true`) - No other consents are created by default If the merchant has configured neither explicit consents nor `marketing_consent_text`, the endpoint returns an empty array. ## Error Responses Errors return a JSON body with `code`, `error`, and `description`. Program against the `error` value — descriptions are human-readable and may change. **400 — MissingAuthHeader** The `x-firmly-authorization` header is missing or empty. ```json { "code": 400, "error": "MissingAuthHeader", "description": "x-firmly-authorization header is missing or invalid." } ``` **400 — InvalidToken** The authorization token is not a valid JWT structure. ```json { "code": 400, "error": "InvalidToken", "description": "Jwt token is invalid." } ``` **400 — InvalidAPIToken** The API token (server-to-server secret) is invalid or has been revoked. ```json { "code": 400, "error": "InvalidAPIToken", "description": "API token is invalid." } ``` **400 — BadRequest** Server-to-server auth was attempted but required headers are missing or malformed. ```json { "code": 400, "error": "BadRequest", "description": "Bad request." } ``` **401 — Unauthorized** The authorization token was rejected. ```json { "code": 401, "error": "Unauthorized", "description": "Unauthorized." } ``` **401 — InvalidJWTToken** The device JWT signature does not verify, or required claims are missing. ```json { "code": 401, "error": "InvalidJWTToken", "description": "Jwt token is invalid." } ``` **404 — PartnerNotFound** The `appid` claim on the device JWT does not map to a known partner / tenant. ```json { "code": 404, "error": "PartnerNotFound", "description": "Partner not found." } ``` **404 — DomainNotFound** The `{domain}` path parameter does not match any merchant configured with Firmly, or the merchant has been disabled. ```json { "code": 404, "error": "DomainNotFound", "description": "This domain was not found in firmly servers." } ``` **404 — CartNotFound** No cart exists for this device on this domain. Add an item first via [Add Line Item](/api-reference/cart-management/add-line-item). ```json { "code": 404, "error": "CartNotFound", "description": "Cart was not found." } ``` **412 — OperationNotSupported** The merchant's platform does not support this operation. ```json { "code": 412, "error": "OperationNotSupported", "description": "This operation is not supported for this store." } ``` --- # Get Postal Code `GET https://api.firmly.work/api/v2/carts/postal-code` ## Overview This endpoint retrieves the postal code preference for the current session. The postal code is used to determine shipping availability and calculate accurate shipping rates for items in the cart. > **Note** > This is a global session preference that applies across all merchant domains. ## Authentication - `x-firmly-authorization` (string, required) — Device access token from [Browser Session](/api-reference/authentication/browser-session) - **Server-to-server (S2S) auth is not accepted** — this is a device-scoped session route. It requires a device JWT from [Browser Session](/api-reference/authentication/browser-session); the S2S secret is rejected. See [Server-to-Server Authentication](/api-reference/authentication/server-to-server). ## Request No request body or query parameters required. ## Response - `postal_code` (string, required) — The postal code preference for the user session > **Note** > The response always includes a `postal_code` field; the value is an empty string when no postal code has been set. ## Session Behavior The postal code is a single global preference stored per device session: - Used for shipping availability checks and to let the merchant's platform calculate accurate tax - Applies across all merchant domains and is automatically applied to new cart sessions - Persists across page refreshes for the lifetime of the session ## Examples **cURL** ```bash curl -X GET 'https://api.firmly.work/api/v2/carts/postal-code' \ -H 'x-firmly-authorization: ' \ -H 'Content-Type: application/json' ``` **JavaScript** ```javascript const response = await fetch('https://api.firmly.work/api/v2/carts/postal-code', { headers: { 'x-firmly-authorization': '', 'Content-Type': 'application/json' } }); const { postal_code } = await response.json(); if (postal_code) { console.log('User postal code:', postal_code); } else { console.log('No postal code set'); } ``` **Python** ```python import requests response = requests.get( 'https://api.firmly.work/api/v2/carts/postal-code', headers={ 'x-firmly-authorization': '', 'Content-Type': 'application/json' } ) data = response.json() postal_code = data.get('postal_code') if postal_code: print(f'User postal code: {postal_code}') else: print('No postal code set') ``` ## Response Examples ### Postal Code Set ```json { "postal_code": "90210" } ``` ### No Postal Code Set ```json { "postal_code": "" } ``` ## Use Cases - **Shipping availability** — check whether items can ship to the buyer's location and filter shipping methods by postal code - **Tax calculation** — the postal code lets the **merchant's platform** calculate tax for the destination (applicable rates, order totals, and any multi-jurisdictional rules all come from the merchant; Firmly relays the result) - **User experience** — pre-fill shipping forms and remember the buyer's preference across the session --- ## Related Endpoints - [Set Postal Code](/api-reference/session/set-postal-code) — Update the postal code preference ## Error Responses Errors return a JSON body with `code`, `error`, and `description`. Program against the `error` value — descriptions are human-readable and may change. **400 — MissingAuthHeader** The `x-firmly-authorization` header is missing or empty. ```json { "code": 400, "error": "MissingAuthHeader", "description": "x-firmly-authorization header is missing or invalid." } ``` **400 — InvalidToken** The authorization token is not a valid JWT structure. ```json { "code": 400, "error": "InvalidToken", "description": "Jwt token is invalid." } ``` **401 — InvalidJWTToken** The device JWT signature does not verify, or required claims are missing. ```json { "code": 401, "error": "InvalidJWTToken", "description": "Jwt token is invalid." } ``` **404 — PartnerNotFound** The `appid` claim on the device JWT does not map to a known partner / tenant. ```json { "code": 404, "error": "PartnerNotFound", "description": "Partner not found." } ``` --- # Get Product from URL `GET https://api.firmly.work/api/v1/domains-pdp?url={pdp-url}` Retrieves product information from a merchant's product detail page (PDP) URL. This endpoint extracts and returns the same detailed product data as the [Get a Product](/api-reference/catalog/get-product) endpoint. ## Authentication This endpoint accepts either a device access token (Browser Session) or a [Server-to-Server](/api-reference/authentication/server-to-server) secret. - `x-firmly-authorization` (string, required) — Device access token from [Browser Session](/api-reference/authentication/browser-session) (client-side) or a Server-to-Server secret (backend). - `x-firmly-device-id` (string) — Required only on the Server-to-Server path — the device ID of the client this request is on behalf of. Maximum 256 characters; allowed characters are `a-z`, `A-Z`, `0-9`, `-`, `_`. ## Query Parameters - `url` (string, required) — The full merchant product page URL. Can be plain or URL-encoded. Examples: - `https://staging.luma.gift/radiant-tee.html` - `https://staging.luma.gift/hero-hoodie.html?variant=MH07-M-Orange` > **Note** > If the URL contains query parameters, encode it with percent encoding according to HTTP standards. - `postal_code` (string) — Postal code to customize pricing, inventory, or availability based on location. - `cache` (boolean, default `false`) — When `true`, allows the response to be served from Firmly's PDP cache (≈5-minute freshness) instead of fetching live from the merchant. ## Response Returns the same [Product Details](/api-reference/catalog/get-product#response) structure as the Get a Product endpoint. > **Note** > **Optional fields are omitted, not nulled.** Fields the merchant doesn't supply — `reviews`, `product_type`, `short_description`, `brand` — are absent from the response rather than returned as `null`. Check for the key before reading it. Some merchants also return extras such as `properties` and `ui_hints`. When the `url` includes a `?variant=` parameter, its value is matched against each returned variant's `sku`. Pass whatever the merchant's PDP uses to identify the variant — this is often a string SKU such as `WS12-XS-Orange`, though some merchants use a numeric variant id. It is compared as-is against each variant's `sku`. If the product has variants and none match, the response is `404 VariantNotFound` with an `available_variants` list. The check is skipped when the product has no variants. ## Request Example ```bash # Plain URL curl --request GET \ --url 'https://api.firmly.work/api/v1/domains-pdp?url=https://staging.luma.gift/radiant-tee.html' \ --header 'x-firmly-authorization: YOUR_AUTH_TOKEN' # URL with query parameters (encoded) curl --request GET \ --url 'https://api.firmly.work/api/v1/domains-pdp?url=https%3A%2F%2Fstaging.luma.gift%2Fhero-hoodie.html%3Fvariant%3DMH07-M-Orange' \ --header 'x-firmly-authorization: YOUR_AUTH_TOKEN' ``` ## Response Example ```json { "base_sku": "WS12", "title": "Radiant Tee", "handle": "radiant-tee", "description": "A comfortable and stylish tee perfect for any occasion", "product_type": "Tees", "images": [ { "url": "https://cdn.staging.luma.gift/products/radiant-tee-main.jpg", "type": "default" } ], "variant_option_values": [ { "display_name": "Size", "property_accessor": "size", "position": 0, "option_values": [ { "display_name": "Medium", "value": "M", "available": true } ] }, { "display_name": "Color", "property_accessor": "color", "position": 1, "option_values": [ { "display_name": "Orange", "value": "Orange", "available": true } ] } ], "variants": [ { "handle": "radiant-tee-m-orange", "sku": "WS12-M-Orange", "title": "Radiant Tee - M Orange", "display_name": "M / Orange", "add_to_cart_ref": { "variant_id": "WS12-M-Orange" }, "price": { "currency": "USD", "value": 22.00, "number": 2200, "symbol": "$" }, "available": true, "variant_option_list": ["M", "Orange"] } ], "reviews": { "total_reviews": 127, "average_rating": 4.5 } } ``` ## Error Responses Errors return a JSON body with `code`, `error`, and `description`. Program against the `error` value — descriptions are human-readable and may change. **400 — InvalidRequest** The `url` query parameter is missing or empty. ```json { "code": 400, "error": "InvalidRequest", "description": "Invalid request" } ``` **400 — MissingAuthHeader** The `x-firmly-authorization` header is missing or empty (when authenticating as a device). ```json { "code": 400, "error": "MissingAuthHeader", "description": "x-firmly-authorization header is missing or invalid." } ``` **400 — InvalidToken** The authorization token is not a valid JWT structure. ```json { "code": 400, "error": "InvalidToken", "description": "Jwt token is invalid." } ``` **400 — InvalidAPIToken** The API token (server-to-server secret) is invalid or has been revoked. ```json { "code": 400, "error": "InvalidAPIToken", "description": "API token is invalid." } ``` **400 — BadRequest** Server-to-server auth was attempted but required headers are missing or malformed. ```json { "code": 400, "error": "BadRequest", "description": "Bad request." } ``` **401 — Unauthorized** The authorization token was rejected. ```json { "code": 401, "error": "Unauthorized", "description": "Unauthorized." } ``` **401 — InvalidJWTToken** The device JWT signature does not verify, or required claims are missing. ```json { "code": 401, "error": "InvalidJWTToken", "description": "Jwt token is invalid." } ``` **404 — PartnerNotFound** The `appid` claim on the device JWT does not map to a known partner / tenant. ```json { "code": 404, "error": "PartnerNotFound", "description": "Partner not found." } ``` **404 — DomainNotFound** The host of the supplied `url` does not match any merchant configured with Firmly, or the merchant has been disabled. ```json { "code": 404, "error": "DomainNotFound", "description": "This domain was not found in firmly servers." } ``` **404 — ProductNotFound** The merchant adapter could not resolve a product at the supplied `url`. ```json { "code": 404, "error": "ProductNotFound", "description": "Product not found." } ``` **412 — ProductNotSupported** The product type is not supported by this merchant's adapter (e.g. some adapters reject gift cards, digital-only SKUs, or subscription items). ```json { "code": 412, "error": "ProductNotSupported", "description": "Product is not supported." } ``` **404 — VariantNotFound** The `url` requested a `?variant=` that is not among the product's variants. The response lists the available variants. ```json { "code": 404, "error": "VariantNotFound", "description": "Variant WS12-L-Orange not found. Available variants: WS12-M-Orange, WS12-S-White", "available_variants": [ { "sku": "WS12-M-Orange", "title": "Radiant Tee - M Orange", "handle": "radiant-tee-m-orange", "available": true }, { "sku": "WS12-S-White", "title": "Radiant Tee - S White", "handle": "radiant-tee-s-white", "available": true } ] } ``` **404 — ProductUrlNotImplemented** The merchant's adapter does not support resolving a product from a URL. ```json { "code": 404, "error": "ProductUrlNotImplemented", "description": "Product url is not implemented." } ``` **410 — ProductDiscontinued** The product at the supplied `url` exists but has been discontinued by the merchant. ```json { "code": 410, "error": "ProductDiscontinued", "description": "Product is discontinued." } ``` **412 — OperationNotSupported** The merchant's adapter does not support URL-based product resolution. ```json { "code": 412, "error": "OperationNotSupported", "description": "This operation is not supported for this store." } ``` **503 — StoreUnavailable** The merchant's site returned an unexpected response and the product could not be retrieved. Retry with backoff. ```json { "code": 503, "error": "StoreUnavailable", "description": "Store is unavailable." } ``` --- # Get Public Key `GET https://cc.firmly.work/api/v1/payment/key` > **Note** > The payment key endpoint is on `api/v1`, while order-completion endpoints on the same `cc.firmly.work` host are `api/v2`. This version straddle is expected — use the paths exactly as documented on each page. ## Overview This endpoint retrieves the current public key used for encrypting credit card data before sending it to Firmly's payment endpoints. The key supports multiple formats to accommodate different encryption libraries and platforms. > **Note** > **Different host.** This endpoint is served from the payment host **`cc.firmly.work`** — not `api.firmly.work` where the cart endpoints live. > **Note** > The public key is rotated periodically for security. You may cache the key briefly, but if encryption or a payment call fails with a decryption/key error, re-fetch the current key and retry once. This refetch-on-error pattern is safe regardless of cache age. ## Authentication This endpoint requires no authentication and is publicly accessible. ## Query Parameters - `format` (string, default `JWK`) — The format of the public key to return **Supported formats:** - `JWK` — JSON Web Key format (default) - `PEM` — Privacy Enhanced Mail format - `RSA` — PEM using RSAPublicKey format ## Response Headers - `x-firmly-kid` (string) — The key identifier (`kid`) — present for all formats ## Response Formats ### JWK Format (Default) Returns a JSON Web Key with the following properties: - `kid` (string) — Key identifier/version - `kty` (string) — Key type (always "RSA") - `n` (string) — RSA modulus component (Base64URL encoded) - `e` (string) — RSA exponent component (Base64URL encoded) - `use` (string) — Key usage (always "enc" for encryption) ### PEM Format Returns the public key in PEM format as plain text: - Content-Type: `text/plain` - Key ID available in `x-firmly-kid` header - Standard PEM header/footer with base64 encoded key ### RSA Format Returns the public key in RSA-specific PEM format: - Content-Type: `text/plain` - Key ID available in `x-firmly-kid` header - Uses RSA PUBLIC KEY header/footer ## Code Examples **Fetch JWK Format** ```javascript // Fetch the public key in JWK format (default) async function getPublicKey() { const response = await fetch('https://cc.firmly.work/api/v1/payment/key'); if (!response.ok) { throw new Error(`Failed to fetch public key: ${response.statusText}`); } const jwk = await response.json(); // jwk.kid is also returned in the x-firmly-kid response header. return jwk; } ``` **Fetch PEM Format** ```python import requests def get_public_key_pem(): """Fetch public key in PEM format""" response = requests.get( 'https://cc.firmly.work/api/v1/payment/key', params={'format': 'PEM'} ) if response.status_code != 200: raise Exception(f"Failed to fetch public key: {response.status_code}") # Key ID is returned in the x-firmly-kid header key_id = response.headers.get('x-firmly-kid') public_key_pem = response.text return public_key_pem, key_id ``` **cURL Examples** ```bash # Get JWK format (default) curl https://cc.firmly.work/api/v1/payment/key # Get PEM format curl https://cc.firmly.work/api/v1/payment/key?format=PEM # Get RSA format curl https://cc.firmly.work/api/v1/payment/key?format=RSA # Get PEM format and extract key ID from header curl -i https://cc.firmly.work/api/v1/payment/key?format=PEM | grep x-firmly-kid ``` **PHP Example** ```php ['method' => 'GET'] ]); $url = 'https://cc.firmly.work/api/v1/payment/key?format=PEM'; $response = file_get_contents($url, false, $context); // Extract key ID from headers foreach ($http_response_header as $header) { if (stripos($header, 'x-firmly-kid:') === 0) { $keyId = trim(substr($header, 13)); break; } } return ['pem' => $response, 'kid' => $keyId]; } ?> ``` ## Response Examples ### JWK Format Response ```json { "kid": "a81b2d581f2a42c09143eb6fdb918fff", "kty": "RSA", "n": "yURqBPP1k_kwMp8AiHeZya7zgO9ZulKrNvFYcQK2eIvkbl7VlhxYt6bnJ0urrUrJbuM_bbRg3yiwXtAN_BsHWTm6JwWSjRx3PQMIm0Yb-HGj2YM6moJ9YFACqtZB2zjkE98Q_TOhfAnYuoSIPsY3k9U1iJmi6gpaZ7E01QFGoRlAwB55yMETl3UT7uodGLRPBz_JGhRuDCJ1dVEfzcojUxOt7FFbRIGDGQzMTvmskRID3N50z6UwJOFwmP6N17qIMYCbr3IQg0fU75HsL-lChpA8m-EnvK0hL4CcNnBVqupxzhsKq2SSLigNBFC6J4gs3mV7L7qu1Q8u_Cg5tGVZiQ", "e": "AQAB", "use": "enc" } ``` ### PEM Format Response ```text -----BEGIN PUBLIC KEY----- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyURqBPP1k/kwMp8AiHeZ ya7zgO9ZulKrNvFYcQK2eIvkbl7VlhxYt6bnJ0urrUrJbuM/bbRg3yiwXtAN/BsH WTm6JwWSjRx3PQMIm0Yb+HGj2YM6moJ9YFACqtZB2zjkE98Q/TOhfAnYuoSIPsY3 k9U1iJmi6gpaZ7E01QFGoRlAwB55yMETl3UT7uodGLRPBz/JGhRuDCJ1dVEfzcoj UxOt7FFbRIGDGQzMTvmskRID3N50z6UwJOFwmP6N17qIMYCbr3IQg0fU75HsL+lC hpA8m+EnvK0hL4CcNnBVqupxzhsKq2SSLigNBFC6J4gs3mV7L7qu1Q8u/Cg5tGVZ iQIDAQAB -----END PUBLIC KEY----- ``` ### RSA Format Response ```text -----BEGIN RSA PUBLIC KEY----- MIIBCgKCAQEAyURqBPP1k/kwMp8AiHeZya7zgO9ZulKrNvFYcQK2eIvkbl7VlhxY t6bnJ0urrUrJbuM/bbRg3yiwXtAN/BsHWTm6JwWSjRx3PQMIm0Yb+HGj2YM6moJ9 YFACqtZB2zjkE98Q/TOhfAnYuoSIPsY3k9U1iJmi6gpaZ7E01QFGoRlAwB55yMET l3UT7uodGLRPBz/JGhRuDCJ1dVEfzcojUxOt7FFbRIGDGQzMTvmskRID3N50z6Uw JOFwmP6N17qIMYCbr3IQg0fU75HsL+lChpA8m+EnvK0hL4CcNnBVqupxzhsKq2SS LigNBFC6J4gs3mV7L7qu1Q8u/Cg5tGVZiQIDAQAB -----END RSA PUBLIC KEY----- ``` ## Encrypting the Card The payment endpoints expect `encrypted_card` to be a **JWE compact serialization string**, not a raw RSA ciphertext. Encrypt the card object with: - **Key-management algorithm (`alg`)**: `RSA-OAEP-256` - **Content-encryption algorithm (`enc`)**: `A256GCM` - **`kid`** in the JWE protected header — use the key's `kid` (also returned in the `x-firmly-kid` response header) The plaintext is the card object: ```json { "number": "4111111111111111", "name": "John Smith", "verification_value": "123", "month": "08", "year": "2026" } ``` **JavaScript (jose)** ```javascript import { importJWK, CompactEncrypt } from 'jose'; // jwk is the JWK object returned by GET /api/v1/payment/key async function encryptCard(card, jwk) { const key = await importJWK(jwk, 'RSA-OAEP-256'); return new CompactEncrypt(new TextEncoder().encode(JSON.stringify(card))) .setProtectedHeader({ alg: 'RSA-OAEP-256', enc: 'A256GCM', kid: jwk.kid }) .encrypt(key); } // Returns a JWE compact string: header..encrypted_key.iv.ciphertext.tag ``` **Python (jwcrypto)** ```python import json from jwcrypto import jwk, jwe # jwk_dict is the JWK returned by GET /api/v1/payment/key def encrypt_card(card, jwk_dict): key = jwk.JWK(**jwk_dict) protected = { "alg": "RSA-OAEP-256", "enc": "A256GCM", "kid": jwk_dict["kid"], } token = jwe.JWE( json.dumps(card).encode("utf-8"), recipient=key, protected=protected, ) return token.serialize(compact=True) ``` > **Note** > Use a maintained JOSE library (e.g. [`jose`](https://www.npmjs.com/package/jose) for JS/Node, [`jwcrypto`](https://jwcrypto.readthedocs.io/) for Python). Raw RSA-OAEP encryption (e.g. Web Crypto `crypto.subtle.encrypt` or `cryptography`'s `public_key.encrypt`) produces a plain ciphertext, **not** a JWE, and the payment endpoints will fail to decrypt it. ## Common Use Cases 1. **Credit Card Encryption**: Primary use is for encrypting credit card data for payment endpoints 2. **Tokenization**: Used with payment tokenization endpoints 3. **Secure Data Transmission**: Any sensitive data sent to Firmly payment endpoints ## Checkout Flow Integration This endpoint is the first step in the secure payment flow: ### Fetch Public Key Call this endpoint to get the current encryption key ### Encrypt Credit Card Encrypt the card object as a JWE (`RSA-OAEP-256` / `A256GCM`) with the fetched key. ### Complete Order Send the JWE string as `encrypted_card` to [Complete Order](/api-reference/payment/complete-order-v2) (or [Place Order](/api-reference/payment/place-order-v2)). ### Complete Example Flow ```javascript import { importJWK, CompactEncrypt } from 'jose'; // 1. Fetch the public key (JWK) const jwk = await fetch('https://cc.firmly.work/api/v1/payment/key').then((r) => r.json()); // 2. Encrypt the card as a JWE (RSA-OAEP-256 / A256GCM) const key = await importJWK(jwk, 'RSA-OAEP-256'); const encryptedCard = await new CompactEncrypt( new TextEncoder().encode(JSON.stringify({ number: '4111111111111111', name: 'John Smith', verification_value: '123', month: '08', year: '2026' })) ) .setProtectedHeader({ alg: 'RSA-OAEP-256', enc: 'A256GCM', kid: jwk.kid }) .encrypt(key); // 3. Complete the order const order = await fetch( 'https://cc.firmly.work/api/v2/payment/domains/staging.luma.gift/complete-order', { method: 'POST', headers: { 'x-firmly-authorization': accessToken, 'Content-Type': 'application/json' }, body: JSON.stringify({ encrypted_card: encryptedCard, billing_info: billingInfo }) } ).then((r) => r.json()); ``` --- ## Related Endpoints - [Complete Order](/api-reference/payment/complete-order-v2) — Complete checkout for an existing cart - [Place Order](/api-reference/payment/place-order-v2) — Create a cart and place an order in one call ## Error Responses This endpoint is public and returns the current key under normal operation. Failures are rare: a malformed `format` query parameter (client error) or a temporary inability to load the key (server error). | Code | HTTP | Trigger | |---|---|---| | `InvalidInputQuery` | 400 | The `format` query parameter is not one of `JWK`, `PEM`, `RSA` | | `StoreUnavailable` | 503 | The payment host could not load the current key. Retry with backoff. | --- # Get Shipping Methods `GET https://api.firmly.work/api/v1/domains/{domain}/cart/shipping-rates` Returns the list of shipping methods available for the cart, with their prices and estimated delivery timeframes. This is the **v1** way to read shipping methods as a standalone call. > **Note** > **v1 vs v2.** On the v2 flow, shipping methods are returned inline on the cart as `cart.shipments[].shipping_method_options` after [Set Shipping Info](/api-reference/checkout/set-shipping-info); you do not need a separate call. This endpoint is the explicit v1 equivalent, useful when the merchant is integrated on the v1 cart surface and does not populate `shipping_method_options` inline. > **Note** > Set the shipping address first ([Set Shipping Info](/api-reference/checkout/set-shipping-info)). Shipping rates are computed from the destination, so calling this before an address is set returns `412 MissingShippingInfo`. ## Authentication - `x-firmly-authorization` (string, required) — Device access token from [Browser Session](/api-reference/authentication/browser-session) > **Note** > This endpoint also accepts **server-to-server (S2S) authentication** for backend integrations acting on behalf of a device: send `Authorization: Bearer ` (or the equivalent `x-firmly-authorization: `) together with `x-firmly-device-id`. See [Server-to-Server Authentication](/api-reference/authentication/server-to-server). ## Path Parameters - `domain` (string, required) — The merchant's domain (e.g. `staging.luma.gift`). ## Response Returns a JSON **array** of shipping-method objects. - `sku` (string, required) — Shipping-method identifier. Use this value to select the method. (This is the method's `sku`; on the v2 surface the equivalent identifier is `shipping_method.id`.) - `description` (string, required) — Human-readable name of the shipping method (e.g. "Standard Shipping (5–7 days)"). - `price` (object, required) — Cost of the shipping method. Amount object. **Amount properties** - `currency` (string) — Currency code (e.g. `USD`). - `value` (number) — Price as a decimal. - `number` (number) — Price in the smallest currency unit. - `symbol` (string) — Currency symbol. - `estimated_delivery` (string) — Optional delivery timeframe (e.g. "3–5 business days"). ## Example Request ```bash curl --request GET \ --url https://api.firmly.work/api/v1/domains/staging.luma.gift/cart/shipping-rates \ --header 'x-firmly-authorization: YOUR_TOKEN' ``` ## Response Example ```json [ { "sku": "standard", "description": "Standard Shipping (5-7 days)", "price": { "currency": "USD", "value": 5.99, "number": 599, "symbol": "$" }, "estimated_delivery": "5-7 business days" }, { "sku": "express", "description": "Express Shipping (2-3 days)", "price": { "currency": "USD", "value": 14.99, "number": 1499, "symbol": "$" }, "estimated_delivery": "2-3 business days" } ] ``` ## Error Responses Errors return a JSON body with `code`, `error`, and `description`. Program against the `error` value — descriptions are human-readable and may change. **400 — MissingAuthHeader** The `x-firmly-authorization` header is missing or empty. ```json { "code": 400, "error": "MissingAuthHeader", "description": "x-firmly-authorization header is missing or invalid." } ``` **400 — InvalidToken** The authorization token is not a valid JWT structure. ```json { "code": 400, "error": "InvalidToken", "description": "Jwt token is invalid." } ``` **401 — InvalidJWTToken** The device JWT signature does not verify, or required claims are missing. ```json { "code": 401, "error": "InvalidJWTToken", "description": "Jwt token is invalid." } ``` **404 — DomainNotFound** The `{domain}` path parameter does not match any merchant configured with Firmly, or the merchant has been disabled. ```json { "code": 404, "error": "DomainNotFound", "description": "This domain was not found in firmly servers." } ``` **404 — CartNotFound** No cart exists for this device on this domain. ```json { "code": 404, "error": "CartNotFound", "description": "Cart was not found." } ``` **412 — MissingShippingInfo** Shipping rates were requested before a shipping address was set on the cart. Call [Set Shipping Info](/api-reference/checkout/set-shipping-info) first. ```json { "code": 412, "error": "MissingShippingInfo", "description": "Shipping info is missing." } ``` **503 — StoreUnavailable** The merchant's API returned an unexpected response and rates could not be fetched. Retry with backoff. ```json { "code": 503, "error": "StoreUnavailable", "description": "Store is unavailable." } ``` ## Related Endpoints - [Set Shipping Info](/api-reference/checkout/set-shipping-info) — Set the shipping address (required before rates are available) - [Set Shipping Method](/api-reference/shipment-configuration/set-shipping-method) — Select a shipping method for a shipment (v2) - [Get Availability](/api-reference/shipment-configuration/get-availability) — Delivery dates / pickup locations for scheduled or pickup fulfillment --- # Get a Product `GET https://api.firmly.work/api/v1/domains-products/{merchant-domain}/{product-handle}` ```text GET https://api.firmly.work/api/v1/domains-products/{merchant-domain}/{product-handle} ``` Gets comprehensive product information including variants, pricing, availability, and images. Use this endpoint to display product detail pages or product cards in your application. ## Authentication - `x-firmly-authorization` (string, required) — Device access token from [Browser Session](/api-reference/authentication/browser-session) ## Path Parameters - `merchant-domain` (string, required) — The domain of the merchant website (e.g., `staging.luma.gift`) - `product-handle` (string, required) — The product handle or identifier. This is typically the URL-friendly version of the product name. ## Query Parameters - `postal_code` (string) — Postal code to customize pricing, inventory, or availability based on location ## Response - `base_sku` (string, required) — The base (parent) SKU identifier for the product. - `title` (string, required) — The product title. - `handle` (string, required) — The product handle / identifier (URL-friendly). - `description` (string) — Product description. Often full HTML. - `short_description` (string) — Short description. May equal `description` when the merchant doesn't provide a separate short form. - `tags` (string[]) — Merchant-supplied tags / labels for the product. - `product_type` (string) — Merchant's category or type for the product. - `pdp_url` (string) — Full URL to the product detail page on the merchant's site. - `images` (object[]) — Product-level images. **Image** - `url` (string, required) — Image URL. - `alt` (string) — Alternative text. - `type` (string) — Image size variant. One of `preview`, `small`, `medium`, `large`, `default`, `video`. Defaults to `default`. - `aspect_ratio` (number) — Width-to-height ratio, when known. - `width` (integer) — Pixel width, when known. - `height` (integer) — Pixel height, when known. - `position` (integer) — Ordering position among the product's images. - `srcset` (object[]) — Alternate renditions of the same image (each with its own `url`, `alt`, `type`, `aspect_ratio`, `width`, `height`). - `variant_option_values` (object[], required) — The option axes a buyer chooses between (e.g. Size, Color), each with its selectable values. **Variant option axis** - `display_name` (string, required) — Display name of the axis (e.g. "Size", "Color"). - `property_accessor` (string, required) — Key used to reference this axis programmatically. - `position` (integer, required) — Display order of this axis. - `option_values` (object[], required) — Selectable values for this axis. - `display_name` (string, required) — Value label (e.g. "Blue", "Medium"). - `value` (string, required) — Internal value identifier. - `available` (boolean) — Whether this value is currently selectable. - `swatch` (object) — Swatch presentation for the value. - `url` (string) — Swatch image URL. - `rgb` (string) — Swatch color as an RGB / hex string. - `images` (object[]) — Images specific to this value (same Image shape as above). - `variants` (object[], required) — The concrete purchasable variants. **Variant** - `handle` (string, required) — Variant handle / identifier. - `display_name` (string, required) — Variant display name (e.g. "XS / Orange"). - `title` (string, required) — Variant title. - `sku` (string, required) — Variant SKU. - `add_to_cart_ref` (object, required) — Opaque reference for adding this variant to the cart. Pass the **entire object** as `add_to_cart_ref` in the [Add Line Item](/api-reference/cart-management/add-line-item) body — do not reconstruct it. It commonly contains `variant_id`, and may also carry `product_id`, `variant_handles`, or `properties` depending on the merchant. - `variant_option_list` (string[], required) — The option values that define this variant, in the axis order of `variant_option_values`. Each entry is a **`value`** from `variant_option_values[].option_values[]`, matched exactly — so `["M", "Orange"]` in the example below. These values are merchant-defined and are frequently opaque identifiers rather than readable labels (a live merchant may return `["5", "7"]` for the same variant), so never parse or display them. Use `display_name` for buyer-facing text, and look the entry up in `option_values` to find its label. - `description` (string) — Variant-specific description. - `available` (boolean) — Whether this variant is currently purchasable. - `price` (object) — Current price. - `currency` (string, required) — Currency code (e.g. "USD"). - `value` (number, required) — Price as a decimal. - `number` (integer, required) — Price in the smallest currency unit (e.g. cents). - `symbol` (string) — Currency symbol. - `msrp` (object) — Manufacturer's suggested retail price. Same shape as `price`. - `pdp_url` (string) — Direct URL to this variant's product page. - `variant_attributes` (object[]) — Merchant-defined key/value attributes for the variant. Each entry is `{ "key": string, "value": string }`. - `highlights` (string[]) — Short marketing highlights / bullet points. - `messages` (object[]) — Variant-level messages (promotions, stock warnings, badges, etc.). **Message** - `type` (string) — One of `promotion`, `stock`, `badge`, `banner`, `shipping`, `urgency`, `info`. - `text` (string, required) — Display text. - `images` (object[]) — Images specific to this variant (same Image shape as above). - `requires_shipping` (boolean) — Whether the variant ships physically. - `taxable` (boolean) — Whether the variant is taxable. - `weight` (number) — Variant weight. - `weight_unit` (string) — Unit for `weight`. - `modified_at` (string) — ISO 8601 timestamp of the variant's last update. - `max_purchase_quantity` (integer) — Per-SKU purchase cap the merchant enforces but may not show on its public PDP. When set, respect it before calling Add Line Item — exceeding it can cause a merchant-conditional add-line-item rejection. Absent / null means no override. - `show_quantity_selector` (boolean) — Hint for whether the UI should expose a quantity selector for this variant. - `option1 … option10` (string) — Positional option-value accessors — flat fields (`option1`, `option2`, … up to `option10`) holding each axis value, mirroring `variant_option_list`. Only as many as the product has axes are populated. - `properties` (object) — Structured product properties. **Properties** - `vendor` (string) — Vendor / brand name. - `product_family` (string) — Product family / grouping. - `product_attributes` (object) — Free-form merchant-specific attributes (e.g. dimensions, material). Schema varies by merchant — treat as an opaque key/value map. - `reviews` (object) — Aggregated review data. **Reviews** - `total_reviews` (integer, required) — Total number of reviews. - `average_rating` (number, required) — Average rating (typically 0–5). - `review_list_url` (string) — URL to the merchant's full review listing. - `review_list` (object[]) — Individual reviews. Each entry may include `reviewer_name`, `review_date` (ISO 8601), `rating`, `review_title`, `review_text`, `verified_purchase`, `helpful_votes`. - `rating_list` (object[]) — Per-star distribution. Each entry is `{ "rating": integer, "count": integer, "percentage": number }`. - `ui_hints` (object) — Rendering hints for the storefront UI. **UI Hints** - `no_variants` (boolean) — The product has no meaningful variants — render as a single item. - `no_options` (boolean) — The product has no selectable options — hide option pickers. - `domain` (string) — Merchant domain this product belongs to. - `domain_name` (string) — Merchant display name. ## Request Example ```bash curl --request GET \ --url 'https://api.firmly.work/api/v1/domains-products/staging.luma.gift/radiant-tee?postal_code=10001' \ --header 'x-firmly-authorization: YOUR_AUTH_TOKEN' ``` ## Response Example ```json { "base_sku": "WS12", "title": "Radiant Tee", "handle": "radiant-tee", "description": "A comfortable and stylish tee perfect for any occasion", "product_type": "Tees", "images": [ { "url": "https://cdn.staging.luma.gift/products/radiant-tee-main.jpg", "type": "default" } ], "variant_option_values": [ { "display_name": "Size", "property_accessor": "size", "position": 0, "option_values": [ { "display_name": "Small", "value": "S", "available": true }, { "display_name": "Medium", "value": "M", "available": true }, { "display_name": "Large", "value": "L", "available": false } ] }, { "display_name": "Color", "property_accessor": "color", "position": 1, "option_values": [ { "display_name": "White", "value": "WHITE", "available": true, "swatch": { "url": "https://cdn.staging.luma.gift/swatches/white.jpg" } }, { "display_name": "Orange", "value": "Orange", "available": true, "swatch": { "url": "https://cdn.staging.luma.gift/swatches/orange.jpg" } } ] } ], "variants": [ { "handle": "radiant-tee-m-orange", "sku": "WS12-M-Orange", "title": "Radiant Tee - M Orange", "display_name": "M / Orange", "add_to_cart_ref": { "variant_id": "WS12-M-Orange" }, "price": { "currency": "USD", "value": 22.00, "number": 2200, "symbol": "$" }, "msrp": { "currency": "USD", "value": 22.00, "number": 2200, "symbol": "$" }, "available": true, "variant_option_list": ["M", "Orange"], "images": [ { "url": "https://cdn.staging.luma.gift/products/radiant-tee-orange.jpg", "type": "default" } ], "messages": [ { "type": "promotion", "text": "20% off - Limited Time Offer" }, { "type": "stock", "text": "Only 3 left in stock" } ] }, { "handle": "radiant-tee-s-white", "sku": "WS12-S-White", "title": "Radiant Tee - S White", "display_name": "S / White", "add_to_cart_ref": { "variant_id": "WS12-S-White" }, "price": { "currency": "USD", "value": 22.00, "number": 2200, "symbol": "$" }, "msrp": { "currency": "USD", "value": 22.00, "number": 2200, "symbol": "$" }, "available": true, "variant_option_list": ["S", "WHITE"], "images": [ { "url": "https://cdn.staging.luma.gift/products/radiant-tee-white.jpg", "type": "default" } ] } ], "reviews": { "total_reviews": 127, "average_rating": 4.5 } } ``` ## Error Responses Errors return a JSON body with `code`, `error`, and `description`. Program against the `error` value — descriptions are human-readable and may change. **400 — MissingAuthHeader** The `x-firmly-authorization` header is missing or empty (when authenticating as a device). ```json { "code": 400, "error": "MissingAuthHeader", "description": "x-firmly-authorization header is missing or invalid." } ``` **400 — InvalidToken** The authorization token is not a valid JWT structure. ```json { "code": 400, "error": "InvalidToken", "description": "Jwt token is invalid." } ``` **401 — InvalidJWTToken** The device JWT signature does not verify, or required claims are missing. ```json { "code": 401, "error": "InvalidJWTToken", "description": "Jwt token is invalid." } ``` **404 — PartnerNotFound** The `appid` claim on the device JWT does not map to a known partner / tenant. ```json { "code": 404, "error": "PartnerNotFound", "description": "Partner not found." } ``` **404 — DomainNotFound** The `{merchant-domain}` does not match any merchant configured with Firmly, or the merchant has been disabled. ```json { "code": 404, "error": "DomainNotFound", "description": "This domain was not found in firmly servers." } ``` **404 — ProductNotFound** No product matches the supplied `{product-handle}` for this merchant. ```json { "code": 404, "error": "ProductNotFound", "description": "Product not found." } ``` **412 — OperationNotSupported** The merchant's adapter does not support this operation. ```json { "code": 412, "error": "OperationNotSupported", "description": "This operation is not supported for this store." } ``` **501 — NotImplemented** The merchant's adapter does not implement product-by-handle lookup. Use [Get Product from URL](/api-reference/catalog/get-product-from-url) where the merchant supports it. ```json { "code": 501, "error": "NotImplemented", "description": "Operation not implemented." } ``` --- # Google Pay Express Checkout Google Pay is a **single-call** express checkout. The wallet ceremony happens entirely client-side in the Google Pay sheet; there is no start or authorize call on the Firmly API. Once the sheet returns a payment token or nonce, hand it to: - **[Complete Order](/api-reference/payment/express-checkout/google-pay/complete-order)** — place the order with the Google Pay credential ## Checking availability Google Pay is enabled per merchant. Any cart response lists what the merchant supports: ```json "payment_method_options": [ { "type": "CreditCard", "wallet": "user" }, { "type": "GooglePay", "wallet": "google" } ] ``` If no `"type": "GooglePay"` entry is present, do not render the Google Pay button — the endpoint returns `404 GatewayNotFound`. The merchant's Google Pay configuration arrives on the cart as `shop_properties.google_pay` — see [Get Cart](/api-reference/cart-management/get-cart) for the full field list. > **Note** > **Different host.** The Google Pay express-checkout endpoint is served from **`api.firmly.work/api/v1/...`** — not the `cc.firmly.work/api/v2/` payment host used by the card [Complete Order](/api-reference/payment/complete-order-v2) endpoint. --- # Headless SDK ## Overview `@firmly/agentic-pay-sdk` is a browser SDK that wraps Firmly's Agentic Pay endpoints (`/enroll`, `/select-card`, `/enroll/trigger`, `/enroll/verify`, `/intent`, `/intent/challenge`, `/complete`, `/cards/delete`) behind a small, opinionated JavaScript API. It supports **Visa and Mastercard** cards. Discover enrollment has no browser ceremony, so drive it with the [REST endpoints](/api-reference/agentic-pay/) directly rather than through the SDK. It is **headless** — it ships no UI. Your application renders the checkout experience and calls the SDK methods; the SDK handles the network-specific mechanics (token state, the Mastercard / Visa authentication iframe, and the hand-off to Firmly's payment vault for order completion). > **Note** > The SDK returns the same shapes from `enrollCard` and `selectCard`, so the > intent → complete chain is identical for new and previously-enrolled cards. ## Creating a client > **Note** > `@firmly/agentic-pay-sdk` is provided by Firmly. ```js import { FirmlyAgenticPay } from '@firmly/agentic-pay-sdk'; const fap = new FirmlyAgenticPay({ baseUrl: 'https://api.firmly.work', apiToken: '' }); ``` ### `ClientConfig` These are the constructor inputs passed to `new FirmlyAgenticPay({ ... })`. - `baseUrl` (string, required) — Agentic Pay base URL, e.g. `https://api.firmly.work`. - `apiToken` (string, required) — API token provisioned by Firmly with Agentic Pay access. The SDK sends it as a standard `Authorization: Bearer ` header. (Firmly's endpoints accept the token either as `Authorization: Bearer` or in the raw `x-firmly-authorization` header; the SDK uses the bearer form.) Used on the enrollment and intent endpoints. - `iframeContainer` (Element) — Default DOM container for `registerPasskey` / `createIntent` to mount the network authentication iframe in. A per-call `container` override is also supported. - `iframeOrigins` (string[]) — Allow-list of origins permitted to send the result `postMessage`. **Required and non-empty** for `registerPasskey` and `createIntent` — an empty list would let any page forge an `iframe_result` and bypass cardholder authentication. Typical values: the Firmly bridge origin plus the network auth iframe origin (e.g. `['https://api.firmly.work', 'https://sandbox.src.mastercard.com']`). - `bridgeUrl` (string) — Default `callback_uri` for iframe flows — sent on `/enroll/trigger` (during `registerPasskey`) and on `/intent` (during `createIntent`). Firmly forwards this to the network's iframe, which redirects to it on completion — typically a Firmly-hosted bridge route that decodes the result and `postMessage`s it back to the SDK. - `vaultBaseUrl` (string) — Base URL for Firmly's payment vault (defaults to `baseUrl`). `completeOrder` calls the vault, which proxies internally into the service-binding-only `/complete` route. - `deviceToken` (string) — Device JWT for the payment vault's `deviceAuth` — required by `completeOrder`. Obtained from `/api/v1/browser-session`. Distinct from `apiToken`. - `merchantDomain` (string) — Default merchant domain for the vault's `/domains/:domain/wallet-complete-order` path. A per-call `domain` override is supported. - `timeoutMs` (number) — Per-**HTTP-request** timeout. Default `90000` ms. - `iframeTimeoutMs` (number) — How long `registerPasskey` / `createIntent` wait for the iframe `postMessage` result before rejecting. Distinct from `timeoutMs` (which is the HTTP request timeout). Default `90000` ms. ## The flow There are two entry points. **Choose one** based on whether the buyer is entering a new card or reusing a saved one — both return an `EnrollResult` and converge on the shared intent → complete chain below. - **Path A — enrollCard (new card)** — Submit the cardholder's PAN. Firmly detects the network, enrolls the card, and returns a `FlowSession` plus verification methods. Persist `virtualCardId`, `cardArt`, and `masked` for returning buyers. - **Path B — selectCard (saved card)** — For a returning buyer, call `selectCard` with the stored `virtualCardId` — no PAN re-entry. Returns the same shape as `enrollCard`. Once you have a `FlowSession` from either path, the rest of the flow is shared: ### Verify the cardholder For OTP methods, call `triggerOtp` then `verifyOtp`. For iframe methods, call `registerPasskey` — the SDK mounts the network iframe and resolves when the cardholder completes authentication. (A Mastercard saved card via `selectCard` produces its challenge in `createIntent` instead.) ### Create a payment intent — createIntent Create an intent bound to a mandate (amount + currency). The SDK handles the intent challenge iframe. When the wallet returns the `intent_id` without a challenge (Mastercard reusing a fresh enrollment authentication) the call resolves without mounting anything — but `iframeOrigins` and a `container` are still required up front, because the SDK cannot know in advance whether a challenge will be issued. ### Place the order — completeOrder Hand the flow to Firmly's payment vault, which retrieves the network token credentials and submits the order to the merchant. ## Methods | Method | Purpose | Auth | | ------ | ------- | ---- | | [`enrollCard`](/api-reference/headless-sdk/enroll-card) | Enroll a new card from its PAN | `apiToken` | | [`selectCard`](/api-reference/headless-sdk/select-card) | Start a payment from a previously-enrolled card | `apiToken` | | [`triggerOtp`](/api-reference/headless-sdk/trigger-otp) | Send an SMS / email OTP challenge | `apiToken` | | [`verifyOtp`](/api-reference/headless-sdk/verify-otp) | Submit the OTP code the cardholder entered | `apiToken` | | [`registerPasskey`](/api-reference/headless-sdk/register-passkey) | Run an iframe-based verification ceremony | `apiToken` | | [`createIntent`](/api-reference/headless-sdk/create-intent) | Create a payment intent for a mandate | `apiToken` | | [`completeOrder`](/api-reference/headless-sdk/complete-order) | Complete the order via Firmly's payment vault | `deviceToken` | | [`deleteCard`](/api-reference/headless-sdk/delete-card) | Revoke an enrolled card on the network | `apiToken` | ## Errors The SDK surfaces failures as rejected promises — `await` each call inside a `try` / `catch`. - **HTTP / API errors.** A non-2xx response from an Agentic Pay or vault endpoint rejects with an error whose message and, where available, structured `{ code, error, description }` payload mirror the underlying REST error envelope. Program against the `error` value, not the human-readable description. - **Timeouts.** `timeoutMs` bounds each HTTP request; `iframeTimeoutMs` bounds how long `registerPasskey` / `createIntent` wait for the iframe `postMessage`. Exceeding either rejects the call. - **Abort.** Passing an already-aborted (or later-aborted) `AbortSignal` via `options.signal` rejects the pending call. - **Configuration guards.** `registerPasskey` and `createIntent` reject up front if `iframeOrigins` is empty, or if no iframe `container` is available (neither `options.container` nor `ClientConfig.iframeContainer` is set). > **Note** > The exact SDK error class names are provided with the `@firmly/agentic-pay-sdk` > package types; catch broadly and branch on the `error` code carried on the > rejection. --- ## Related - [Agentic Pay Integration Guide](/solutions/agentic-commerce/agentic-pay-integration) — the same flow at the raw HTTP level - [Agentic Pay API Reference](/api-reference/agentic-pay/) — the underlying endpoints --- # Iframe Callback `GET https://api.firmly.work/api/v1/wallets/agentic-pay/iframe-callback` ## Overview `GET https://api.firmly.work/api/v1/wallets/agentic-pay/iframe-callback` Returns an HTML page that acts as a postMessage bridge for Agentic Pay iframe flows. When a network iframe completes a FIDO ceremony or authentication challenge, it redirects to this callback URL with the result encoded in query parameters. The page decodes the result and relays it to the parent window via `postMessage`. > **Warning** > This endpoint is not called by destinations directly. It is loaded by the network iframe as a redirect target during enrollment or intent challenge flows. ## Authentication This endpoint requires no authentication. ## Query Parameters These parameters are set by the network iframe redirect, not by the destination. - `origin` (string) — The origin this callback page will `postMessage` its result to. It must match a Firmly domain pattern (`https://*.firmly.work` in the sandbox) — this page is a Firmly-hosted bridge, not the partner's own page. > **Note** > Partners host their own checkout page, so this callback page does not `postMessage` directly to the partner window. It posts to the Firmly-hosted SDK bridge (whose origin matches `https://*.firmly.work`); the [Headless SDK](/api-reference/headless-sdk/) then relays the result to your page, validating the sender against the `iframeOrigins` allow-list you configure. If you integrate at the raw HTTP level without the SDK, you supply your own `callback_uri`/bridge and are responsible for the same origin validation. - `res` (string) — Base64-encoded JSON result from the network iframe containing the verification outcome. ## Response The response is an HTML page (`content-type: text/html`) that performs the following steps: 1. Validates the `origin` parameter against Firmly's domain allowlist 2. Decodes the base64 `res` parameter 3. Posts `{ type: 'agentic_pay_callback', result: decoded }` to the parent window via `postMessage` 4. On error, posts `{ type: 'agentic_pay_error', error: errorMessage }` instead ## How It Fits in the Flow This endpoint is typically used as the `callback_uri` parameter when triggering enrollment or intent challenges: ### Destination Triggers Challenge The destination calls `/enroll/trigger` (enrollment) or `/intent` (payment), which returns a verification URI for an iframe. (`/intent/challenge` consumes the iframe result — it does not hand out the URI.) ### Network Iframe Loads The cardholder completes the FIDO ceremony, 3DS challenge, or iframe handshake inside the network iframe. ### Redirect to Callback The network iframe redirects to this `/iframe-callback` endpoint with the result in query parameters. ### postMessage to Parent The callback page decodes the result and sends it to the parent window via `postMessage`. ### Parent Captures Result The parent window receives the message and forwards the result to the next API call (e.g., `/enroll/verify`). --- ## Related Endpoints - [Trigger Enrollment](/api-reference/agentic-pay/trigger-enrollment) — Returns the enrollment verification URI that may use this callback - [Create Intent](/api-reference/agentic-pay/create-intent) — Returns the payment verification URI that may use this callback - [Intent Challenge](/api-reference/agentic-pay/intent-challenge) — Consumes the iframe result relayed by this callback --- # Intent Challenge `POST https://api.firmly.work/api/v1/wallets/agentic-pay/intent/challenge` ## Overview After the cardholder completes the FIDO assertion in the iframe (rendered from the Create Intent response), submit the result to this endpoint. On success, it returns an `intent_id` that, together with the `flow_token`, is used to place the order via the vault. - **Final step**: This is the last call in the agentic pay flow before order placement - **Only when a challenge was issued**: If [Create Intent](/api-reference/agentic-pay/create-intent) returned `intent_id` instead of `challenge` (Discover; Mastercard reusing a fresh enrollment authentication), skip this endpoint and place the order directly - **FIDO assertion**: The `iframe_result` contains the `fidoBlob` and `assuranceData` captured via `postMessage` from the authentication iframe - **Order placement**: Use the returned `flow_token` and `intent_id` to complete the order through the wallet order endpoint ## Authentication - `x-firmly-authorization` (string, required) — API token for authenticating the request ## Request Body - `flow_token` (string, required) — Flow token from the Create Intent response - `type` (string, required) — Challenge type being submitted. Typically `embed_iframe` for FIDO assertion results. - `iframe_result` (object) — FIDO assertion result captured from the authentication iframe via `postMessage`. Required for the `embed_iframe` challenge `type` (the only documented type) — the assertion cannot be verified without it. **Properties:** - `fidoBlob` (string): FIDO credential assertion blob from the iframe - `assuranceData` (string): Assurance data from the iframe ## Response - `flow_token` (string) — Final flow token for use in order placement - `intent_id` (string) — Payment intent identifier to pass when completing the order (e.g., `"1-5C90F1500800b0be2dc0-e6cf-55d5-54e6-12d8519fad02"`) ## Code Examples **cURL** ```bash curl --request POST \ --url https://api.firmly.work/api/v1/wallets/agentic-pay/intent/challenge \ --header 'Content-Type: application/json' \ --header 'x-firmly-authorization: YOUR_TOKEN' \ --data '{ "flow_token": "eyJhbGciOiJBMjU2S1ci...", "type": "embed_iframe", "iframe_result": { "fidoBlob": "eyJraWQiOiI0ZDkxZWY5Mi...", "assuranceData": "dG9rZW5pemVkLWFzc2Vy..." } }' ``` **JavaScript** ```javascript const response = await fetch('https://api.firmly.work/api/v1/wallets/agentic-pay/intent/challenge', { method: 'POST', headers: { 'Content-Type': 'application/json', 'x-firmly-authorization': 'YOUR_TOKEN' }, body: JSON.stringify({ flow_token: 'eyJhbGciOiJBMjU2S1ci...', type: 'embed_iframe', iframe_result: { fidoBlob: 'eyJraWQiOiI0ZDkxZWY5Mi...', assuranceData: 'dG9rZW5pemVkLWFzc2Vy...' } }) }); const { flow_token, intent_id } = await response.json(); // Use flow_token and intent_id to place the order console.log('Intent ID:', intent_id); ``` **Python** ```python import requests response = requests.post( 'https://api.firmly.work/api/v1/wallets/agentic-pay/intent/challenge', headers={ 'Content-Type': 'application/json', 'x-firmly-authorization': 'YOUR_TOKEN' }, json={ 'flow_token': 'eyJhbGciOiJBMjU2S1ci...', 'type': 'embed_iframe', 'iframe_result': { 'fidoBlob': 'eyJraWQiOiI0ZDkxZWY5Mi...', 'assuranceData': 'dG9rZW5pemVkLWFzc2Vy...' } } ) result = response.json() print('Intent ID:', result['intent_id']) ``` ## Response Example ```json { "flow_token": "", "intent_id": "1-5C90F1500800b0be2dc0-e6cf-55d5-54e6-12d8519fad02" } ``` ## Error Responses | Code | Status | Description | | --------------------- | ------ | ------------------------------------------------------ | | `BadRequest` | 400 | Invalid `flow_token` format or missing required fields | | `BadRequest` | 400 | The FIDO assertion was rejected or the cardholder canceled the ceremony (the submitted `iframe_result` did not verify) | | `ErrorServiceUnavailable` | 503 | FIDO verification failed or timed out | A declined or user-canceled FIDO assertion returns a `400 BadRequest` rather than a success shape — no `intent_id` is issued. Prompt the cardholder to retry the assertion. --- ## Related Endpoints - [Create Intent](/api-reference/agentic-pay/create-intent) — Create the payment intent and receive the FIDO challenge - [Wallet Complete Order](/api-reference/payment/wallet-complete-order) — Place the order using the `flow_token` and `intent_id` --- # Klarna Express Checkout Klarna buy-now-pay-later is a three-call sequence on the `/express/klarna/…` paths. Call them in order: 1. **[Start](/api-reference/payment/express-checkout/klarna/start)** — create the Klarna session and get the `client_token` 2. **[Authorize](/api-reference/payment/express-checkout/klarna/authorize)** — confirm the buyer's authorization 3. **[Complete Order](/api-reference/payment/express-checkout/klarna/complete-order)** — place the order Between Start and Authorize the buyer approves the payment in the Klarna Payments widget, which returns an `authorization_token`. Nothing is charged until Complete Order. > **Note** > **Different host.** The Klarna express-checkout endpoints are served from **`api.firmly.work/api/v1/...`** — not the `cc.firmly.work/api/v2/` payment host used by the card [Complete Order](/api-reference/payment/complete-order-v2) endpoint. ## Checking availability Klarna is enabled per merchant, and most merchants do not have it. Any cart response lists what the merchant supports: ```json "payment_method_options": [ { "type": "CreditCard", "wallet": "user" }, { "type": "Klarna", "wallet": "klarna" } ] ``` If no `"type": "Klarna"` entry is present, do not offer Klarna — calling these endpoints returns `404 GatewayNotFound`. The examples on these pages use the sandbox merchant for shape; check `payment_method_options` for the merchant you are actually integrating rather than assuming Klarna is available. --- # Pagination Firmly uses two pagination styles, depending on the endpoint: - **Discovery search** uses **cursor-based pagination** — you walk the results by following the cursor returned with each page, not by computing offsets. - **Catalog listing** ([Get All Products](/api-reference/catalog/get-all-products)) uses **page-number pagination** — you request a specific `page` and `size`, and the response tells you the total number of pages. This page is the canonical reference for both patterns. ## Cursor-based pagination (discovery search) Each cursor-paginated response includes a cursor that, when passed to the next request, returns the next page of results. ```json { "products": [ { "...": "product 1" }, { "...": "product 2" } ], "next_page": "https://api.firmly.work/api/v1/discovery/search?cursor=eyJ...&page_size=20" } ``` To get the next page, use the cursor value: ```javascript const results = await searchProducts('leather sofa', { page_size: 20 }); if (results.next_page) { const cursor = new URL(results.next_page).searchParams.get('cursor'); const moreResults = await searchProducts('leather sofa', { cursor, page_size: 20 }); } ``` When there are no more results, `next_page` is absent (or null). Treat its absence as "end of results." ## Why cursor-based, not offset-based Cursor-based pagination is the modern standard because it handles concurrent insertions gracefully. With offset-based pagination, a product added or removed between requests can cause items to appear twice or get skipped. Cursors are stateful markers into the result set rather than numeric offsets. This is the same pattern most well-respected commerce APIs use. ## Page size (discovery search) The `page_size` parameter controls how many results come back in one discovery response. Reasonable values: | Use case | Suggested `page_size` | |---|---| | Conversational AI surfacing a few options | 3–5 | | List view in a UI | 10–20 | | Bulk catalog walk for indexing | 50–100 | Discovery search clamps `page_size` to the range `1`–`100`; a value outside that range is adjusted to the nearest bound rather than rejected. ## Page-number pagination (catalog listing) [Get All Products](/api-reference/catalog/get-all-products) returns the full catalog one page at a time. Instead of a cursor, you pass a `page` number and a `size`. The paging fields come back nested under a `metadata` object — `products` is a sibling of `metadata`, not nested inside it: ```json { "metadata": { "page": 1, "size": 2000, "totalRecords": 4200, "domain": "staging.luma.gift", "countryCode": "us", "totalPages": 3, "generatedAt": "2026-03-17T10:30:00.000Z", "startIndex": 0, "endIndex": 1999 }, "products": [ { "...": "product 1" }, { "...": "product 2" } ] } ``` `size` accepts one of `100`, `500`, `1000`, or `2000` (default `2000`). Walk the catalog by requesting `page` 1, 2, 3 … up to `metadata.totalPages`. There is no cursor and no `next_page` field on this endpoint. ## Walking the whole result set For a complete catalog walk, iterate until `next_page` is absent: ```javascript async function fetchAllProducts(query, pageSize = 50) { const all = []; let cursor = undefined; while (true) { const page = await searchProducts(query, { cursor, page_size: pageSize }); all.push(...page.products); if (!page.next_page) break; cursor = new URL(page.next_page).searchParams.get('cursor'); } return all; } ``` For very large result sets, this can be slow and consume rate budget. Consider: - Streaming results into your processing pipeline instead of accumulating in memory - Walking incrementally based on a need (top N matches) rather than the full set - Caching the discovery results briefly if you re-query the same thing See [Rate limits](/api-reference/rate-limits) for throughput considerations on bulk walks. ## Endpoints that paginate | Endpoint | Style | Page control | |---|---|---| | [Discovery search](/api-reference/discovery/search) | Cursor-based | `cursor` in body, `page_size` | | [Catalog get-all-products](/api-reference/catalog/get-all-products) | Page-number | `page` + `size` | [Get active carts](/api-reference/session/get-active-carts) and [Get active domains](/api-reference/session/get-active-domains) do not paginate — they return a single response scoped to the current session (typically small). ## Edge cases - **Empty results on first page** (discovery search): `products: []` plus no `next_page` — a successful "no matches" response, not an error - **Stale cursor**: discovery cursors are stateless `search_after` keys (a base64-encoded copy of the last row's sort values), not server-side sessions — they do **not** expire on a timer. A cursor stays usable indefinitely; the only caveat is that if the underlying catalog changes between pages, results may shift (see "Order changes between pages" above) - **Order changes between pages**: results may shift if the underlying catalog changes mid-walk. Don't rely on absolute ordering across pages --- ## Related - [Discovery search](/api-reference/discovery/search) — primary paginated endpoint - [Catalog list](/api-reference/catalog/get-all-products) — bulk catalog walk - [Rate limits](/api-reference/rate-limits) — throughput considerations for bulk pagination - [Errors & Conventions](/api-reference/errors-and-conventions) — handling pagination and validation errors --- # PayPal Express Checkout PayPal Express is a three-call sequence on the `/express/paypal/…` paths. Call them in order: 1. **[Start](/api-reference/payment/express-checkout/paypal/start)** — open a PayPal session and get the EC token 2. **[Authorize](/api-reference/payment/express-checkout/paypal/authorize)** — record the buyer's PayPal approval *(optional)* 3. **[Complete Order](/api-reference/payment/express-checkout/paypal/complete-order)** — place the order and charge the buyer Step 2 can be skipped: Complete Order authorizes on its own when no authorization has been recorded. Between Start and Authorize the buyer approves the payment in PayPal's own window; PayPal returns a **payer ID** that Authorize needs. Nothing is charged until Complete Order. > **Note** > **Different host.** The PayPal express-checkout endpoints are served from **`api.firmly.work/api/v1/...`** — not the `cc.firmly.work/api/v2/` payment host used by the card [Complete Order](/api-reference/payment/complete-order-v2) endpoint. > **Note** > **The merchant's PayPal account, not Firmly's.** The EC token is minted under the merchant's PayPal client ID, because the order is placed on the merchant's checkout and the funds settle to them. That has two consequences: PayPal must be enabled for that specific merchant, and the return URL your surface uses must be registered in that merchant's PayPal configuration before PayPal will complete. ## Checking availability PayPal is enabled per merchant. Any cart response lists what the merchant supports: ```json "payment_method_options": [ { "type": "CreditCard", "wallet": "user" }, { "type": "PayPal", "wallet": "paypal" } ] ``` If no `"type": "PayPal"` entry is present, do not render the PayPal button — calling these endpoints returns `404 GatewayNotFound`. The merchant's PayPal client credentials for the PayPal JS SDK arrive on the cart as `shop_properties.paypal` — see [Get Cart](/api-reference/cart-management/get-cart) for the full field list. --- # Payment The payment and order-placement endpoints. These run on the payment host `cc.firmly.work` — not `api.firmly.work` where the cart lives. Start with [Get Public Key](/api-reference/payment/get-public-key) to fetch the key you JWE-encrypt the card with, then use [Place Order](/api-reference/payment/place-order-v2) for the one-shot path or [Complete Order](/api-reference/payment/complete-order-v2) to finalize a cart you built across earlier calls. - [Express Checkout](/api-reference/payment/express-checkout/) - [Complete Order](/api-reference/payment/complete-order-v2) - [Get Public Key](/api-reference/payment/get-public-key) - [Place Order](/api-reference/payment/place-order-v2) - [Wallet Complete Order](/api-reference/payment/wallet-complete-order) - [Resume After Challenge](/api-reference/payment/complete-order-v2-resume/index.md) --- # Place Order `POST https://cc.firmly.work/api/v2/payment/domains/{domain}/place-order` > **Note** > Use **place-order** for the one-shot path: create the cart and place the order in a single call (it builds the cart from the items you pass). ## Overview Creates a new cart and places an order in a single atomic operation. Supports complex product references including variant handles and product IDs, and the full cart feature set (shipments, addons, multi-fulfillment). > **Note** > **Different host.** This endpoint is served from the payment host **`cc.firmly.work`** — not `api.firmly.work` where the cart endpoints live. ## Authentication - `x-firmly-authorization` (string, required) — Device access token from [Browser Session](/api-reference/authentication/browser-session) > **Note** > This endpoint also accepts **server-to-server (S2S) authentication** for backend integrations acting on behalf of a device: send `Authorization: Bearer ` (or the equivalent `x-firmly-authorization: `) together with `x-firmly-device-id`. See [Server-to-Server Authentication](/api-reference/authentication/server-to-server). ## Path Parameters - `domain` (string, required) — The merchant domain (e.g., "staging.luma.gift") ## Query Parameters - `sse` (string, default `false`) — Enable Server-Sent Events for real-time progress updates. Set to "true" to receive events. ## Request Body - `encrypted_card` (string, required) — JWE-encrypted credit card data using the public key from [Get Public Key](/api-reference/payment/get-public-key) endpoint - `billing_info` (object, required) — Billing address information (same structure as shipping_info) - `shipping_info` (object, required) — Shipping address information **Required fields:** - `first_name` (string): Buyer's first name - `last_name` (string): Buyer's last name - `email` (string): Email address - `phone` (string): Phone number - `address1` (string): Primary address line - `city` (string): City name - `state_or_province` (string): State/province code - `country` (string): Country code (ISO 3166-1 alpha-2, e.g. `US`) - `postal_code` (string): ZIP or postal code **Optional fields:** - `address2` (string): Secondary address line - `company` (string): Company name - `items` (array, required) — Array of items to add to cart **Item structure:** - `add_to_cart_ref` (object, required): Product reference - `variant_id` (string, required): Variant identifier - `product_id` (string, optional): Product identifier - `variant_handles` (array[string], optional): Variant handle path - `quantity` (number, required): Quantity to purchase (minimum: 1) - `captcha_token` (string) — Captcha verification token when required by merchant ## Response Returns an order confirmation with the Cart API structure — `cart_status: "submitted"`, a `platform_order_number`, line items, addresses, and money totals. ```json { "cart_id": "9cf76530-1344-420f-9ca6-c7a96fb6db45", "cart_status": "submitted", "platform_order_number": "29185", "display_name": "Luma (Staging)", "platform_id": "example_commerce", "shop_id": "staging.luma.gift", "submitted_at": "2026-04-29T07:15:35.367Z", "line_items": [ { "line_item_id": "d290c5fa-0e91-462f-b53f-08d5b71ae532", "sku": "WS12-XS-Orange", "quantity": 1, "description": "Radiant Tee", "price": { "currency": "USD", "value": 22, "number": 2200, "symbol": "$" }, "line_price": { "currency": "USD", "value": 22, "number": 2200, "symbol": "$" }, "msrp": { "currency": "USD", "value": 26, "number": 2600, "symbol": "$" }, "image": { "url": "https://staging.luma.gift/radiant-tee.jpg", "alt": "Radiant Tee", "type": "default" } } ], "shipping_info": { "first_name": "John", "last_name": "Smith", "email": "john@example.com", "phone": "2065551212", "address1": "123 Main St", "city": "Seattle", "state_or_province": "WA", "country": "US", "postal_code": "98101" }, "billing_info": { "first_name": "John", "last_name": "Smith", "address1": "123 Main St", "city": "Seattle", "state_or_province": "WA", "country": "US", "postal_code": "98101" }, "shipping_method": { "id": "standard_shipping", "description": "Standard Shipping", "price": { "currency": "USD", "value": 10, "number": 1000, "symbol": "$" } }, "sub_total": { "currency": "USD", "value": 22, "number": 2200, "symbol": "$" }, "shipping_total": { "currency": "USD", "value": 10, "number": 1000, "symbol": "$" }, "tax": { "currency": "USD", "value": 2, "number": 200, "symbol": "$" }, "fees": [{ "description": "Recycle fee", "currency": "USD", "value": 2, "number": 200, "symbol": "$" }], "fee_total": { "currency": "USD", "value": 2, "number": 200, "symbol": "$" }, "total": { "currency": "USD", "value": 36, "number": 3600, "symbol": "$" } } ``` ## Server-Sent Events When `sse=true`, the endpoint streams progress events. Each event has an event name and a `data:` line carrying a JSON payload: - `creating-cart` — Cart creation started - `item-added` — Item added to cart (includes cart data) - `shipping-updated` — Shipping info set (includes cart data) - `order-placed` — Order successfully placed (includes order data) - `error` — Error occurred. Unlike the non-SSE error responses, the `data:` payload **wraps** the error envelope under an `error` key — `{ "error": { code, error, description } }` (e.g. `{ "error": { "code": 422, "error": "CreditCardDeclined", "description": "Credit card declined" } }`). Program against `data.error.error`. ## Code Example **cURL** ```bash curl --request POST \ --url 'https://cc.firmly.work/api/v2/payment/domains/staging.luma.gift/place-order' \ --header 'x-firmly-authorization: YOUR_ACCESS_TOKEN' \ --header 'Content-Type: application/json' \ --data '{ "encrypted_card": "JWE_ENCRYPTED_CARD_DATA", "billing_info": { "first_name": "John", "last_name": "Smith", "email": "john@staging.luma.gift", "phone": "2065551212", "address1": "123 Main St", "city": "Seattle", "state_or_province": "WA", "country": "US", "postal_code": "98101" }, "shipping_info": { "first_name": "John", "last_name": "Smith", "email": "john@staging.luma.gift", "phone": "2065551212", "address1": "123 Main St", "city": "Seattle", "state_or_province": "WA", "country": "US", "postal_code": "98101" }, "items": [ { "add_to_cart_ref": { "variant_id": "WS12-XS-Orange", "product_id": "WS12", "variant_handles": ["radiant-tee", "xs-orange"] }, "quantity": 1 } ] }' ``` **JavaScript** ```javascript // Place order with complex product references const response = await fetch('https://cc.firmly.work/api/v2/payment/domains/staging.luma.gift/place-order', { method: 'POST', headers: { 'x-firmly-authorization': authToken, 'Content-Type': 'application/json' }, body: JSON.stringify({ encrypted_card: encryptedCard, billing_info: billingInfo, shipping_info: { first_name: 'John', last_name: 'Smith', email: 'john@staging.luma.gift', phone: '2065551212', address1: '123 Main St', city: 'Seattle', state_or_province: 'WA', country: 'US', postal_code: '98101' }, items: [ { add_to_cart_ref: { variant_id: 'WS12-XS-Orange', product_id: 'WS12', variant_handles: ['radiant-tee', 'xs-orange'] }, quantity: 1 } ] }) }); const order = await response.json(); ``` **Python** ```python import requests # Place order with complex product references response = requests.post( 'https://cc.firmly.work/api/v2/payment/domains/staging.luma.gift/place-order', headers={ 'x-firmly-authorization': auth_token, 'Content-Type': 'application/json', }, json={ 'encrypted_card': encrypted_card, 'billing_info': billing_info, 'shipping_info': { 'first_name': 'John', 'last_name': 'Smith', 'email': 'john@staging.luma.gift', 'phone': '2065551212', 'address1': '123 Main St', 'city': 'Seattle', 'state_or_province': 'WA', 'country': 'US', 'postal_code': '98101', }, 'items': [ { 'add_to_cart_ref': { 'variant_id': 'WS12-XS-Orange', 'product_id': 'WS12', 'variant_handles': ['radiant-tee', 'xs-orange'], }, 'quantity': 1, } ], }, ) order = response.json() ``` ## SSE Example The browser `EventSource` API only issues `GET` requests and cannot send custom headers or a request body, so it **cannot** be used with this endpoint. Consume the stream with `fetch` and read the response body directly, or use a library such as [`@microsoft/fetch-event-source`](https://www.npmjs.com/package/@microsoft/fetch-event-source) that adds POST/header/body support to the EventSource protocol. ```javascript // Consume the SSE stream with fetch + a streamed body reader. const response = await fetch( 'https://cc.firmly.work/api/v2/payment/domains/staging.luma.gift/place-order?sse=true', { method: 'POST', headers: { 'x-firmly-authorization': authToken, 'Content-Type': 'application/json', Accept: 'text/event-stream' }, body: JSON.stringify({ encrypted_card: encryptedCard, billing_info: billingInfo, shipping_info: shippingInfo, items: items }) } ); const reader = response.body.getReader(); const decoder = new TextDecoder(); let buffer = ''; // Parse one SSE message block (event: ... / data: ... separated by a blank line). function handleEvent(block) { let eventName = 'message'; const dataLines = []; for (const line of block.split('\n')) { if (line.startsWith('event:')) eventName = line.slice(6).trim(); else if (line.startsWith('data:')) dataLines.push(line.slice(5).trim()); } const data = dataLines.length ? JSON.parse(dataLines.join('\n')) : null; if (eventName === 'item-added') { console.log('Item added to cart:', data.cart); } else if (eventName === 'order-placed') { console.log('Order completed:', data.order.platform_order_number); } else if (eventName === 'error') { // SSE error payload wraps the envelope: { error: { code, error, description } } console.error('Place order failed:', data.error.error, data.error.description); } } while (true) { const { value, done } = await reader.read(); if (done) break; buffer += decoder.decode(value, { stream: true }); // SSE messages are separated by a blank line. let sep; while ((sep = buffer.indexOf('\n\n')) !== -1) { handleEvent(buffer.slice(0, sep)); buffer = buffer.slice(sep + 2); } } ``` --- ## Related Endpoints - [Get Public Key](/api-reference/payment/get-public-key) — Get encryption key - [Complete Order](/api-reference/payment/complete-order-v2) — Alternative flow with existing cart - [Add Line Item](/api-reference/cart-management/add-line-item) — Add items individually ## Error Responses Errors return a JSON body with `code`, `error`, and `description`. Program against the `error` value — descriptions are human-readable and may change. **400 — MissingAuthHeader** The `x-firmly-authorization` header is missing or empty. ```json { "code": 400, "error": "MissingAuthHeader", "description": "x-firmly-authorization header is missing or invalid." } ``` **400 — InvalidToken** The authorization token is not a valid JWT structure. ```json { "code": 400, "error": "InvalidToken", "description": "Jwt token is invalid." } ``` **401 — InvalidJWTToken** The device JWT signature does not verify, or required claims are missing. ```json { "code": 401, "error": "InvalidJWTToken", "description": "Jwt token is invalid." } ``` **404 — PartnerNotFound** The `appid` claim on the device JWT does not map to a known partner / tenant. ```json { "code": 404, "error": "PartnerNotFound", "description": "Partner not found." } ``` **404 — ProductNotFound** One or more `add_to_cart_ref` references no longer resolve at the merchant. ```json { "code": 404, "error": "ProductNotFound", "description": "Product not found." } ``` **404 — DomainNotFound** The `{domain}` path parameter does not match any merchant configured with Firmly, or the merchant has been disabled. ```json { "code": 404, "error": "DomainNotFound", "description": "This domain was not found in firmly servers." } ``` **409 — payment_challenge_required** Not a failure — the merchant's PSP requires interactive step-up verification (typically 3-D Secure). The body is a challenge envelope, not the standard error shape. Get the shopper through `challenge.url`, then call [Resume After Challenge](/api-reference/payment/complete-order-v2-resume) once. Only App IDs opted in to the challenge contract receive this; others get `422 PaymentChallengeRequired` instead. ```json { "type": "payment_challenge_required", "challenge": { "challenge_id": "pi_3RXkQ2...", "method": "redirect", "url": "https://merchant.example/challenge?payment_id=...", "display": "popup", "expires_at": "2026-06-08T18:03:44.164Z" } } ``` **409 — NotEnoughStockError** Stock for one or more items dropped below the requested quantity between the catalog read and the order placement. ```json { "code": 409, "error": "NotEnoughStockError", "description": "The amount of the required item is not available in stock." } ``` **412 — OperationNotSupported** The merchant's platform does not support cartless place-order. ```json { "code": 412, "error": "OperationNotSupported", "description": "This operation is not supported for this store." } ``` **412 — CountryNotSupported** The `billing_info.country` is outside the supported set (currently `US` and `AU`). Firmly rejects the order before tokenization. ```json { "code": 412, "error": "CountryNotSupported", "description": "We don't currently support this country/region. Enter a new address and try again." } ``` **400 — InvalidInputBody** Request body failed schema validation. Ensure `add_to_cart_ref`, `encrypted_card`, `shipping_info`, and `billing_info` are all present and well-formed. ```json { "code": 400, "error": "InvalidInputBody", "description": "The body is not processable" } ``` **422 — PaymentChallengeRequired** The PSP demanded interactive verification but the App ID has not opted in to the payment-challenge contract, so the order fails closed. See [Resume After Challenge](/api-reference/payment/complete-order-v2-resume). ```json { "code": 422, "error": "PaymentChallengeRequired", "description": "This payment requires additional bank verification (3D Secure) that is not supported in this checkout. Please use a different card." } ``` **422 — CreditCardDeclined** PSP declined the card. See [Complete Order](/api-reference/payment/complete-order-v2#error-responses) for the full set of `CreditCard*` variants (insufficient funds, invalid number / CVV / expiry, AVS postal-code mismatch). ```json { "code": 422, "error": "CreditCardDeclined", "description": "Credit card declined" } ``` **503 — StoreUnavailable** The merchant's API returned an unexpected response and the order could not be placed. Retry with backoff. ```json { "code": 503, "error": "StoreUnavailable", "description": "Store temporarily unavailable. Please try again later." } ``` --- # Promotions The Promotions API applies and clears promotional codes on a cart. Validation, discount calculation, and stacking rules are owned by the merchant's platform — Firmly forwards the codes and returns the resulting cart. ## Available Endpoints - [Add Promo Codes](/api-reference/promotions/add-promo-codes) — Apply one or more promotional codes to the cart. - [Clear Promo Codes](/api-reference/promotions/clear-promo-codes) — Remove all promotional codes from the cart. > **Note** > The merchant decides whether a code is valid, what discount it applies, and whether codes can be combined. Promo errors (`InvalidPromoCode`, `PromoNotAvailable`, `ClearPromoCodeNotAllowed`) come from the merchant, not from Firmly. ## Result on the Cart Applied codes appear in the cart's top-level `coupons` array (array of strings). Discount amounts surface in: - `cart_discount` — total discount applied to the cart - `cart_discount_breakdown` — per-promotion breakdown (when the merchant exposes it) - `line_items[].discount` and `line_items[].line_discount` — per-line amounts (when the merchant exposes them) > **Note** > `line_items[].discount` and `line_items[].line_discount` are not part of the base line-item schema in [Get Cart](/api-reference/cart-management/get-cart). They appear on `line_items[]` only when a merchant returns per-line discount amounts, so treat them as merchant-conditional and always null-check before reading them. Totals (`sub_total`, `tax_total`, `total`) are recalculated server-side after each add/clear. --- # Rate Limits Firmly's edge enforces rate limits on abuse-prone endpoints — those targeted by credential stuffing, OTP enumeration, and promo-code stuffing. Beyond those, throughput is governed by your tier rather than a public per-endpoint limit. ## What Firmly rate-limits today Aggressive limits apply on these endpoint categories: - `POST /api/v2/domains/{domain}/cart/promo-codes` (and related promo-submission paths) - Account sign-in endpoints on the Agentic Pay / account surface (`/join`, `/create-otp`, `/validate-otp`, `/unlock-start`, `/unlock-complete`, `/forgot-password`). These belong to account creation and sign-in, not the commerce Cart API, and are not documented individually in this reference. When a source IP exceeds the limit, the edge returns `HTTP 429` (`RateLimited`) and refuses further traffic until a cool-off window elapses. **Notable for developers**: the promo code submission endpoint is included. Agents that try many promo codes in quick succession (deal-hunting flows, code-stacking experiments) will hit this limit. Add a small delay between attempts or surface *"try again in a moment"* to the user. Specific thresholds and block durations are shared during commercial onboarding, scoped to your expected traffic profile. ## The 429 response ```text HTTP/1.1 429 Too Many Requests Retry-After: 10 ``` The `Retry-After` header gives the number of seconds to wait before the next attempt. **Always honor it.** ## How to react ```javascript async function callFirmlyWithBackoff(url, options) { const resp = await fetch(url, options); if (resp.status !== 429) return resp; const retryAfter = parseInt(resp.headers.get('Retry-After') || '10', 10); await new Promise(r => setTimeout(r, retryAfter * 1000)); return fetch(url, options); } ``` ## General commerce API throughput For the general commerce API (catalog, search, cart line items, checkout, payment, orders), specific throughput limits are **tier-dependent** and not enforced at the same level as the abuse-protection rule above. Contact [Firmly](/contact) for your account's allowance if you're planning sustained high-volume traffic. --- ## Related - [Errors & Conventions](/api-reference/errors-and-conventions) — the broader error catalog - [Idempotency](/solutions/agentic-commerce/protocols/ucp/idempotency) — how retries interact with mutation safety - [Pagination](/api-reference/pagination) — for reading long result lists without burning rate budget --- # Remove Addon `POST https://api.firmly.work/api/v2/domains/{domain}/cart/addons/_remove` `POST /api/v2/domains/{domain}/cart/addons/_remove` > **Note** > The path ends with the unusual `_remove` suffix — this is a distinct endpoint from [Add Addons](/api-reference/addon-management/add-addon) (`/cart/addons`), not a different HTTP method on the same path. Removes a single addon from `cart.addons.selections`. The request can target three granularities: - **Whole addon** — supply `addon_id` only. Removes the addon entirely (and all its children). - **One line item** — supply `addon_id` + `deselected_line_item_id`. Removes the addon from that line item only; other items keep it. - **One child** — supply `addon_id` + `deselected_child_id`. Deselects that child while leaving the parent (and other children) intact. To set the cart's addons in bulk (clear all, or replace), use [Add Addons](/api-reference/addon-management/add-addon). ## Authentication - `x-firmly-authorization` (string, required) — Device access token from [Browser Session](/api-reference/authentication/browser-session) > **Note** > This endpoint also accepts **server-to-server (S2S) authentication** for backend integrations acting on behalf of a device: send `Authorization: Bearer ` (or the equivalent `x-firmly-authorization: `) together with `x-firmly-device-id`. See [Server-to-Server Authentication](/api-reference/authentication/server-to-server). ## Path Parameters - `domain` (string, required) — The merchant's domain (e.g. `staging.luma.gift`). ## Request Body - `addon_id` (string, required) — The `addon_id` of the addon to remove from `cart.addons.selections`. - `deselected_line_item_id` (string) — Limit removal to one line item. Omit to remove the addon from every line item where it was attached. - `deselected_child_id` (string) — Limit removal to one child selection (when the addon has `child_offers`). ## Response Returns the full cart (same schema as [Get Cart](/api-reference/cart-management/get-cart)). After removal: - `cart.addons.selections` is updated. - `cart.addons.offers` may be re-evaluated (e.g. previously-locked offers become available again). - `cart.addon_total`, `cart.total` are recalculated. ## Examples **Remove a CART-scope addon** ```bash curl -X POST https://api.firmly.work/api/v2/domains/staging.luma.gift/cart/addons/_remove \ -H "x-firmly-authorization: YOUR_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "addon_id": "shipping_protection" }' ``` **Remove from one line item** ```bash curl -X POST https://api.firmly.work/api/v2/domains/staging.luma.gift/cart/addons/_remove \ -H "x-firmly-authorization: YOUR_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "addon_id": "extended_warranty", "deselected_line_item_id": "38d3f385-ea8d-8bb2-dcfc-759ac85af6ef" }' ``` **Remove one child of a tiered addon** ```bash curl -X POST https://api.firmly.work/api/v2/domains/staging.luma.gift/cart/addons/_remove \ -H "x-firmly-authorization: YOUR_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "addon_id": "extended_warranty", "deselected_child_id": "EW-2YR" }' ``` ## Response Example ```json { "cart_id": "a5600193-2c13-3356-d063-711da63b7cd7", "platform_id": "example_commerce", "shop_id": "staging.luma.gift", "cart_status": "active", "line_items": [ { "line_item_id": "761ff52b-8e6d-d373-fdf2-91a1a70df20c", "sku": "MH07-XS-Gray", "quantity": 1, "price": { "currency": "USD", "value": 54.0, "number": 5400, "symbol": "$" }, "line_price": { "currency": "USD", "value": 54.0, "number": 5400, "symbol": "$" }, "msrp": { "currency": "USD", "value": 64.8, "number": 6480, "symbol": "$" }, "image": { "url": "https://staging.luma.gift/mh07-xs-gray.jpg", "alt": "MH07-XS-Gray", "type": "default" } } ], "addons": { "offers": [ { "addon_id": "shipping_protection", "display": { "name": "Shipping Protection" }, "scope": "CART", "coverage_mode": "PREDEFINED_GROUP", "price": { "currency": "USD", "value": 12.99, "number": 1299, "symbol": "$" } } ], "selections": [] }, "sub_total": { "currency": "USD", "value": 54.0, "number": 5400, "symbol": "$" }, "fees": [ { "description": "Recycle fee", "currency": "USD", "value": 2.00, "number": 200, "symbol": "$" } ], "fee_total": { "currency": "USD", "value": 2.00, "number": 200, "symbol": "$" }, "addon_total": { "currency": "USD", "value": 0, "number": 0, "symbol": "$" }, "total": { "currency": "USD", "value": 56.00, "number": 5600, "symbol": "$" }, "schema_version": "2.0" } ``` ## Error Responses Errors return a JSON body with `code`, `error`, and `description`. Program against the `error` value — descriptions are human-readable and may change. **400 — MissingAuthHeader** The `x-firmly-authorization` header is missing or empty. ```json { "code": 400, "error": "MissingAuthHeader", "description": "x-firmly-authorization header is missing or invalid." } ``` **400 — InvalidToken** The authorization token is not a valid JWT structure. ```json { "code": 400, "error": "InvalidToken", "description": "Jwt token is invalid." } ``` **400 — InvalidAPIToken** The API token (server-to-server secret) is invalid or has been revoked. ```json { "code": 400, "error": "InvalidAPIToken", "description": "API token is invalid." } ``` **400 — BadRequest** Server-to-server auth was attempted but required headers are missing or malformed. ```json { "code": 400, "error": "BadRequest", "description": "Bad request." } ``` **401 — Unauthorized** The authorization token was rejected. ```json { "code": 401, "error": "Unauthorized", "description": "Unauthorized." } ``` **401 — InvalidJWTToken** The device JWT signature does not verify, or required claims are missing. ```json { "code": 401, "error": "InvalidJWTToken", "description": "Jwt token is invalid." } ``` **404 — PartnerNotFound** The `appid` claim on the device JWT does not map to a known partner / tenant. ```json { "code": 404, "error": "PartnerNotFound", "description": "Partner not found." } ``` **404 — DomainNotFound** The `{domain}` path parameter does not match any merchant configured with Firmly, or the merchant has been disabled. ```json { "code": 404, "error": "DomainNotFound", "description": "This domain was not found in firmly servers." } ``` **404 — CartNotFound** No cart exists for this device on this domain. ```json { "code": 404, "error": "CartNotFound", "description": "Cart was not found." } ``` **412 — OperationNotSupported** The merchant's platform does not support addon operations. ```json { "code": 412, "error": "OperationNotSupported", "description": "This operation is not supported for this store." } ``` **400 — InvalidInputBody** Request body fails schema validation. `addon_id` must be a string; the optional `deselected_line_item_id` / `deselected_child_id` must also be strings when present. ```json { "code": 400, "error": "InvalidInputBody", "description": "The body is not processable" } ``` **422 — InvalidInputBody** The body is well-formed, but the merchant rejected a value in it — typically an `addon_id` that is not selected on this cart, or a missing `deselected_line_item_id` on an item-scoped add-on. Same error name as the 400 above, raised one layer deeper, so branch on `code` and not on `error` alone. ```json { "code": 422, "error": "InvalidInputBody", "description": "deselected_line_item_id is required for ITEM-scoped addons" } ``` **422 — UnprocessableEntity** The supplied `addon_id` is not in `cart.addons.selections`, or `deselected_line_item_id` / `deselected_child_id` does not match a currently-selected item / child. ```json { "code": 422, "error": "UnprocessableEntity", "description": "The given payload has unprocessable, invalid or non-existent data. Please check the data and try again." } ``` **503 — StoreUnavailable** The merchant's API returned an unexpected response and the request could not be fulfilled. Retry with backoff. ```json { "code": 503, "error": "StoreUnavailable", "description": "Store is unavailable." } ``` --- # Resume After Challenge `POST https://cc.firmly.work/api/v2/payment/domains/{domain}/complete-order/resume` > **Note** > Call this only after [Complete Order](/api-reference/payment/complete-order-v2) or [Place Order](/api-reference/payment/place-order-v2) returned `409` with a `payment_challenge_required` envelope, and the shopper has finished verification. ## The challenge envelope When the issuer requires step-up verification (3-D Secure), the order is not failed — the `409` body is: ```json { "type": "payment_challenge_required", "challenge": { "challenge_id": "pi_3RXkQ2...", "method": "redirect", "url": "https://merchant.example/challenge?payment_id=...", "display": "popup", "expires_at": "2026-06-08T18:03:44.164Z" } } ``` `expires_at` is **optional** — it is present only when the PSP reports a timeout, and some adapters never set it. Do not key a client-side timeout on it; fall back to your own when it is absent. Send the shopper to `challenge.url` as `display` indicates. Adapters currently emit `popup` or `full_redirect`; `new_tab` is reserved and not emitted today. **Never in an iframe:** these pages forbid framing, and the post-challenge navigation breaks. Open it from a user gesture, or popup blockers intervene. ## Authentication Same as [Complete Order](/api-reference/payment/complete-order-v2#authentication) — a device access token, or server-to-server credentials. ## Path Parameters - `domain` (string, required) — The merchant's domain. Must match the original call. ## Request Body Empty. No card data is sent: the payment is already held against the cart session, and all resume state lives server-side. ## Response Call this **once**, when the shopper finishes. - `200` — the order is placed. Same shape as [Complete Order](/api-reference/payment/complete-order-v2#response). - `409` — the same envelope unchanged, meaning verification is still outstanding. Re-prompt and resume again on the next completion signal, until `expires_at`. > **Note** > Available only to App IDs opted in via `supports_payment_challenge`, on platforms whose adapter implements the contract. Everyone else gets `422 PaymentChallengeRequired` from the original call instead. [Contact Firmly](/contact) to enable it. ## Error Responses **422 — PaymentChallengeExpired** The challenge window closed before verification completed, or the PSP invalidated it. Terminal for this attempt — place the order again. ```json { "code": 422, "error": "PaymentChallengeExpired", "description": "The payment verification window has expired. Please place the order again." } ``` **422 — PaymentChallengeRequired** The App ID is not opted in, the merchant's adapter does not implement resume, the card was declined after authentication, or no challenge is pending for this session. ```json { "code": 422, "error": "PaymentChallengeRequired", "description": "This payment requires additional bank verification (3D Secure) that is not supported in this checkout. Please use a different card." } ``` **404 — CartNotFound** The cart session expired before resume was called. ```json { "code": 404, "error": "CartNotFound", "description": "Cart was not found." } ``` Authentication and domain errors match [Complete Order](/api-reference/payment/complete-order-v2#error-responses). --- # Search Products `POST https://api.firmly.work/api/v1/discovery/search` Search for products across merchant catalogs using keyword-based queries. Use filters to narrow results by domain, price, availability, and variant attributes. See [Search Behavior](#search-behavior) for how queries and filters are matched. The endpoint accepts both `POST` and `GET`. Send filtered searches as `POST` with `query`, `filters`, `page_size`, and `cursor` in the JSON body. The `GET` path reads only `query`, `page_size`, and `cursor` from the query string — it does **not** accept a `filters` parameter. The `next_page` URL returned for pagination is a ready-to-call `GET` link. > **Note** > **`filters` is `POST`-only.** There is no way to pass filters on the `GET` path. When you paginate, you do not resend filters at all — the opaque `cursor` returned in `next_page` already carries the first page's filter set, so following the `next_page` link (a `GET`) re-applies the same filters automatically. Always start a filtered search with `POST`. ## Authentication This endpoint supports three authentication methods. Any one of them is sufficient; pick the one that matches your integration shape. - `x-firmly-authorization` (string) — Device access token from [Browser Session](/api-reference/authentication/browser-session) (client-side) or a server-to-server secret (backend). Required for Browser Session and Server-to-Server. - `x-firmly-device-id` (string) — Required with Server-to-Server — the device ID of the client this request is on behalf of. Maximum 256 characters; allowed characters are `a-z`, `A-Z`, `0-9`, `-`, `_`. - `x-firmly-app-id` (string) — Required for App ID auth. The application identifier provided by [Firmly](/contact). **Browser Session** For client-side applications (browser, mobile). The token is the device JWT minted by [Browser Session Authentication](/api-reference/authentication/browser-session). ```bash curl -X POST https://api.firmly.work/api/v1/discovery/search \ -H "x-firmly-authorization: YOUR_ACCESS_TOKEN" \ -H "Content-Type: application/json" \ -d '{"query": "shoes"}' ``` **App ID** For trusted server-to-server clients that don't need a per-device session. Pass your App ID in the `x-firmly-app-id` header. No device token required. ```bash curl -X POST https://api.firmly.work/api/v1/discovery/search \ -H "x-firmly-app-id: YOUR_APP_ID" \ -H "Content-Type: application/json" \ -d '{"query": "shoes"}' ``` **Server-to-Server** For backend services acting on behalf of devices. See [Server-to-Server Authentication](/api-reference/authentication/server-to-server). ```bash curl -X POST https://api.firmly.work/api/v1/discovery/search \ -H "x-firmly-authorization: YOUR_S2S_SECRET" \ -H "x-firmly-device-id: DEVICE_ID" \ -H "Content-Type: application/json" \ -d '{"query": "shoes"}' ``` ## Request Body - `query` (string) — Search keyword(s). Optional if `filters` (or a `cursor` from a prior page) is provided — at least one of `query` or `filters` is required on the first page. A request with neither returns `400 BadRequest`. - `filters` (object) — Optional filters to narrow search results. **Filter Object** - `filters.domains` (string[]) — Array of merchant domains to search (e.g., `["staging.luma.gift", "merchant2.example"]`). When omitted, all merchants are searched. - `filters.min_price` (integer) — Minimum price filter in cents (e.g., `100000` for $1,000.00, `9999` for $99.99). Must be an integer. - `filters.max_price` (integer) — Maximum price filter in cents (e.g., `500000` for $5,000.00). Must be an integer. - `filters.in_stock` (boolean) — Filter to only show in-stock products. Set to `true` to enable. - `filters.variants` (array) — Array of variant filters. Each filter specifies an option name and allowed values. Available option names and values vary per merchant — read them from `filter_options` in the first-page response. See [Search Behavior](#search-behavior) for which options can be filtered on and how values are matched. - `filters.variants[].option` (string, required) — The variant option name (e.g., `"color"`, `"size"`, `"material"`). - `filters.variants[].values` (string[], required) — Array of allowed values for this option (e.g., `["Blue", "Black"]`). Matching is case-insensitive whole-value matching — `"Blue"` also matches a product's `"blue"`, but it does not match a different value like `"Navy"`. - `page_size` (number, default `20`) — Number of results per page. Clamped to the range `1`–`100`. - `cursor` (string) — Opaque pagination cursor. Omit for the first page; on subsequent requests pass the cursor carried in the previous response's `next_page` URL. The cursor also re-applies the first page's filters, so you don't resend `filters` when paginating. ## Response - `products` (array) — Array of product objects matching the search criteria. Returns empty array `[]` when no results found (HTTP 200). **Product Object** - `base_sku` (string) — Base SKU identifier for the product - `title` (string) — Product title - `brand` (string) — Brand name. `null` when the merchant data has no brand. - `handle` (string) — Product handle/slug - `description` (string) — Product description - `pdp_url` (string) — Full URL to the product detail page on the merchant's site - `domain` (string) — Merchant domain (e.g., `merchant.example`) - `domain_name` (string) — Merchant display name - `price_range` (object) — Price range for the product (accounts for variant pricing). All prices in USD cents. - `min` (integer) — Minimum price across all variants in cents (e.g., `249999` = $2,499.99 USD). Always an integer, never a string or decimal. - `max` (integer) — Maximum price across all variants in cents. Always an integer, never a string or decimal. - `has_available_variants` (boolean) — `true` if the product has at least one variant currently in stock. Always a boolean (`true`/`false`), never a string. - `images` (array) — Array of product images **Image Object** - `url` (string) — URL of the image - `type` (string) — Image size variant (e.g. `default`, `large`, `small`, `preview`) - `variants` (array) — The product's purchasable variants. **This is where the value you need to add an item to a cart lives** — each variant carries its own `add_to_cart_ref`, which is the required request body for [Add Line Item](/api-reference/cart-management/add-line-item). Pick a variant with `available: true`, then pass its `add_to_cart_ref` through unchanged. **Variant object** - `handle` (string, required) — Stable variant identifier. - `sku` (string, required) — Stock-keeping unit for this variant. This is what a `?variant=` URL parameter is matched against. - `title` (string, required) — Full variant title. - `display_name` (string, required) — Short label for the variant (e.g. `M / Orange`). - `available` (boolean) — Whether this variant is currently purchasable. **Filter on this before adding to a cart** — an unavailable variant is rejected at add-to-cart. - `add_to_cart_ref` (object, required) — Opaque reference passed straight to Add Line Item. Don't construct or modify it; echo back exactly what the catalog returned. - `price` (object) — Variant price (Amount: `number` in cents, `value`, `currency`, `symbol`). - `msrp` (object) — Manufacturer's suggested retail price (Amount). - `variant_option_list` (array, required) — The option values that identify this variant, in order (e.g. `["M", "Orange"]`). - `variant_attributes` (array) — Additional `{ key, value }` attributes the merchant exposes. - `images` (array) — Variant-specific images. - `pdp_url` (string) — Direct URL to this variant on the merchant's site. - `requires_shipping` (boolean) — Whether the variant needs physical shipping. - `variant_option_values` (array) — Available variant options (sizes, colors, etc.). - `tags` (array) — Product tags. - `average_rating` (number) — Aggregated average review rating. `null` when the product has no reviews. - `total_reviews` (number) — Total review count. `null` when the product has no reviews. - `page_size` (number) — Number of results returned on this page. - `filter_options` (object) — Available filter facets for the current query, computed over the **gated result pool** — the set of matching products remaining after domain-authorization filtering (i.e. only merchants your account is authorized for). **Returned on the first page only** (absent when paginating with a `cursor`). **Filter Options** - `variant_options` (object[]) — Variant facets: `[{ option, values: [{ value, count }] }]` (e.g. Color, Size). - `domains` (object[]) — Domain facets: `[{ domain, count }]`. There is no `domain_name` key here — unlike the product object, the facet's `domain` holds the merchant **display name** (e.g. `Test Merchant`), not the host. - `price_range` (object) — Min/max price across the result pool, in cents: `{ min, max }`. `null` when unavailable. - `in_stock_count` (number) — Number of in-stock products in the result pool. - `total_count` (number) — Total products in the gated result pool. - `time_taken_ms` (number) — Time taken to execute the search query in milliseconds - `next_page` (string) — Full URL to fetch the next page of results. Use this URL directly with your authorization header. `null` when there are no more results. ## Request Example ```bash Basic Search (Browser Session) curl --request POST \ --url 'https://api.firmly.work/api/v1/discovery/search' \ --header 'x-firmly-authorization: YOUR_ACCESS_TOKEN' \ --header 'Content-Type: application/json' \ --data '{ "query": "leather sofa" }' ``` ```bash Basic Search (Server-to-Server) curl --request POST \ --url 'https://api.firmly.work/api/v1/discovery/search' \ --header 'x-firmly-authorization: YOUR_S2S_SECRET' \ --header 'x-firmly-device-id: user-12345' \ --header 'Content-Type: application/json' \ --data '{ "query": "leather sofa" }' ``` ```bash Search with Filters curl --request POST \ --url 'https://api.firmly.work/api/v1/discovery/search' \ --header 'x-firmly-authorization: YOUR_ACCESS_TOKEN' \ --header 'Content-Type: application/json' \ --data '{ "query": "sofa", "filters": { "domains": ["staging.luma.gift"], "min_price": 100000, "max_price": 500000, "in_stock": true, "variants": [ { "option": "color", "values": ["Brown", "Tan"] } ] }, "page_size": 10 }' ``` ```bash Search Multiple Merchants curl --request POST \ --url 'https://api.firmly.work/api/v1/discovery/search' \ --header 'x-firmly-authorization: YOUR_ACCESS_TOKEN' \ --header 'Content-Type: application/json' \ --data '{ "query": "sofa", "filters": { "domains": ["merchant1.example", "merchant2.example", "merchant3.example"] }, "page_size": 20 }' ``` ```bash Pagination curl --request POST \ --url 'https://api.firmly.work/api/v1/discovery/search' \ --header 'x-firmly-authorization: YOUR_ACCESS_TOKEN' \ --header 'Content-Type: application/json' \ --data '{ "query": "leather sofa", "cursor": "", "page_size": 20 }' ``` ## Response Example ```json Success Response { "products": [ { "base_sku": "12345", "title": "Modern Leather Sofa", "brand": "Test Merchant", "handle": "modern-leather-sofa", "description": "A beautiful modern leather sofa perfect for any living room.", "pdp_url": "https://staging.luma.gift/products/modern-leather-sofa", "domain": "staging.luma.gift", "domain_name": "Test Merchant", "price_range": { "min": 249999, "max": 319999 }, "has_available_variants": true, "images": [ { "url": "https://cdn.staging.luma.gift/images/modern-leather-sofa.jpg", "type": "default" } ], "variants": [ { "handle": "modern-leather-sofa-brown", "sku": "12345-BROWN", "title": "Modern Leather Sofa - Brown", "display_name": "Brown", "available": true, "add_to_cart_ref": { "variant_id": "12345-BROWN" }, "price": { "currency": "USD", "value": 2499.99, "number": 249999, "symbol": "$" }, "variant_option_list": ["Brown"] } ], "variant_option_values": [], "tags": ["leather", "sofa", "modern", "living-room"], "average_rating": 4.6, "total_reviews": 212 } ], "page_size": 20, "time_taken_ms": 45, "next_page": "https://api.firmly.work/api/v1/discovery/search?query=leather+sofa&cursor=eyJjIjoiLi4uIn0&page_size=20", "filter_options": { "variant_options": [ { "option": "color", "values": [{ "value": "Brown", "count": 14 }, { "value": "Tan", "count": 9 }] } ], "domains": [{ "domain": "Test Merchant", "count": 23 }], "price_range": { "min": 199999, "max": 519999 }, "in_stock_count": 18, "total_count": 23 } } ``` ```json Last Page (no more results) { "products": [...], "page_size": 20, "time_taken_ms": 38, "next_page": null } ``` ```json Empty Results (HTTP 200) { "products": [], "page_size": 20, "time_taken_ms": 12, "next_page": null } ``` ## Usage Notes > **Note** > **Domain authorization**: Search results are limited to merchant domains associated with your account. Requests for unauthorized domains will return empty results. Contact your account manager to request access to additional merchants. > **Note** > **Domain filtering**: Use the `filters.domains` array to search specific merchants: > - Single merchant: `"domains": ["staging.luma.gift"]` > - Multiple merchants: `"domains": ["merchant1.example", "merchant2.example", "merchant3.example"]` > - All merchants: omit the `domains` field entirely > **Note** > **Pagination (cursor)**: The first page is the request with no `cursor`. When more results exist, the response returns a `next_page` URL whose `cursor` query param is an opaque token. To get the next page, either follow the `next_page` URL directly as a `GET` (with your auth header) or extract its `cursor` and send it in a `POST` body. The cursor carries the first page's filters, so you do not resend `filters` when paginating. `filter_options` is returned on the first page only. Stop when `next_page` is `null`. > **Note** > **Pricing**: All prices are integers in USD cents (not dollars). `"min_price": 100000` filters for $1,000.00+, and `price_range.min: 249999` means $2,499.99 USD. To display: `(price / 100).toFixed(2)`. > **Note** > **Data Types**: `price_range.min`, `price_range.max` are always integers in cents (e.g., `249999` for $2,499.99). `has_available_variants` is always a boolean (`true` or `false`). These are never returned as strings. ## Example: Search Implementation **JavaScript** ```javascript // Search with filters const searchProducts = async (query, options = {}) => { const body = { query }; // Build filters object const filters = {}; if (options.domains) filters.domains = options.domains; if (options.minPrice) filters.min_price = options.minPrice; if (options.maxPrice) filters.max_price = options.maxPrice; if (options.inStock) filters.in_stock = true; if (options.variants) filters.variants = options.variants; if (Object.keys(filters).length > 0) { body.filters = filters; } if (options.pageSize) body.page_size = options.pageSize; if (options.cursor) body.cursor = options.cursor; const response = await fetch( 'https://api.firmly.work/api/v1/discovery/search', { method: 'POST', headers: { 'x-firmly-authorization': authToken, 'Content-Type': 'application/json' }, body: JSON.stringify(body) } ); if (!response.ok) { const error = await response.json(); throw new Error(error.error || 'Search failed'); } return response.json(); }; // Usage - prices in cents (100000 = $1,000.00, 500000 = $5,000.00) const results = await searchProducts('leather sofa', { domains: ['staging.luma.gift', 'merchant2.example'], minPrice: 100000, maxPrice: 500000, inStock: true, variants: [ { option: 'color', values: ['Brown', 'Tan'] }, { option: 'size', values: ['Large', 'Sectional'] } ], pageSize: 20 }); // Check if there are results (empty array is valid, not an error) if (results.products.length === 0) { console.log('No products found matching your criteria'); } else { console.log(`Found ${results.products.length} products`); // Client-side sorting by price (low to high) const sortedByPrice = results.products.sort( (a, b) => a.price_range.min - b.price_range.min ); // Display price: convert cents to dollars. // toFixed(2) has no thousands separators, so 249999 -> "$2499.99". // For grouped output ("$2,499.99") use toLocaleString instead. const displayPrice = (cents) => `$${(cents / 100).toFixed(2)}`; console.log(displayPrice(results.products[0].price_range.min)); // e.g., "$2499.99" // Grouped: `$${(cents / 100).toLocaleString('en-US', { minimumFractionDigits: 2 })}` -> "$2,499.99" } // Pagination - use cursor from previous response if (results.next_page) { // Extract cursor from next_page URL or use it directly const nextPageUrl = new URL(results.next_page); const cursor = nextPageUrl.searchParams.get('cursor'); const nextResults = await searchProducts('leather sofa', { cursor, pageSize: 20 }); console.log(`Loaded ${nextResults.products.length} more products`); } ``` **Python** ```python import requests from urllib.parse import urlparse, parse_qs def search_products(query, *, domains=None, min_price=None, max_price=None, in_stock=False, variants=None, page_size=None, cursor=None): """Search the discovery index with filters and pagination.""" body = {'query': query} # Build filters object filters = {} if domains: filters['domains'] = domains if min_price: filters['min_price'] = min_price if max_price: filters['max_price'] = max_price if in_stock: filters['in_stock'] = True if variants: filters['variants'] = variants if filters: body['filters'] = filters if page_size: body['page_size'] = page_size if cursor: body['cursor'] = cursor response = requests.post( 'https://api.firmly.work/api/v1/discovery/search', headers={ 'x-firmly-authorization': auth_token, 'Content-Type': 'application/json', }, json=body, ) response.raise_for_status() return response.json() # Usage - prices in cents (100000 = $1,000.00, 500000 = $5,000.00) results = search_products( 'leather sofa', domains=['staging.luma.gift', 'merchant2.example'], min_price=100000, max_price=500000, in_stock=True, variants=[ {'option': 'color', 'values': ['Brown', 'Tan']}, {'option': 'size', 'values': ['Large', 'Sectional']}, ], page_size=20, ) # Check if there are results (empty array is valid, not an error) if not results['products']: print('No products found matching your criteria') else: print(f"Found {len(results['products'])} products") # Client-side sorting by price (low to high) sorted_by_price = sorted( results['products'], key=lambda p: p['price_range']['min'] ) # Display price: convert cents to dollars. # :.2f has no thousands separators, so 249999 -> "$2499.99". # For grouped output ("$2,499.99") use :,.2f instead. def display_price(cents): return f"${cents / 100:.2f}" print(display_price(results['products'][0]['price_range']['min'])) # e.g., "$2499.99" # Grouped: f"${cents / 100:,.2f}" -> "$2,499.99" # Pagination - use cursor from previous response if results.get('next_page'): # Extract cursor from next_page URL or use it directly parsed = urlparse(results['next_page']) cursor = parse_qs(parsed.query).get('cursor', [None])[0] next_results = search_products('leather sofa', cursor=cursor, page_size=20) print(f"Loaded {len(next_results['products'])} more products") ``` ## Search Behavior How the endpoint matches queries and filters. **Search matches keywords, not intent.** Your query is compared with the words the merchant publishes — title, brand, SKU, handle, tags, and category. So `running shoes` finds results, while `something to wear for a marathon` usually will not — it helps to send the words you would expect in a product name. Results are ordered by best match; there is no sort parameter, so you may want to re-sort on your side. **A SKU or handle works as a query.** These are matched as a whole string rather than split into words, so `ABC-123` finds that exact product, not everything containing `abc` or `123`. It works best sent on its own. **In-stock products get a little extra priority.** The lift is blended into the relevance score rather than applied on top, so a strong out-of-stock match still outranks a weak in-stock one, and nothing is removed. For a hard cut, use `filters.in_stock`. **Filters narrow the search.** A result has to satisfy both your `query` and your filters: `sofa` with `color: Brown` returns only brown sofas — the filter cannot add a product that does not match `sofa`, and the query cannot add one that is not brown. Relevance is judged among the products that qualify, so your top result is the best brown sofa rather than the best sofa. Send filters with the request rather than filtering a response yourself, so relevance is judged over the products you actually want. If a filtered search comes back empty, adjust the `query` before relaxing the filters. A request with filters and no `query` returns every matching product in a stable order, not ranked by relevance. **Filter values are matched against the merchant's own.** Values are compared literally, with no synonyms or unit conversion, so `Navy` will not match `Blue`. Matching is case-insensitive and whole-value: `blue` matches `Blue`, though not `Light Blue`. Within one option values are `OR`; across options they are `AND`. Merchants each name things their own way, so it is safest to read option names and values from `filter_options` and pass them back unchanged. Those counts describe the current query's matches, not the whole catalog. Any declared option can be filtered on — there is no fixed list. `size` is the one special case, covering shoe, clothing, shirt, and accessory sizing together. An option the merchant has not declared matches nothing, so the search comes back empty rather than unfiltered. **Prices and stock come from a catalog snapshot.** The index refreshes on a schedule rather than reading the merchant live, so price and availability can lag a little. It is best to treat results as a shortlist and confirm through the [Catalog API](/api-reference/catalog/) before showing a final price or adding to cart. **An empty result is not an error.** When nothing matches well enough, you receive HTTP `200` with an empty `products` list rather than an unrelated product. ## Error Responses Errors return a JSON body with `code`, `error`, and `description`. Program against the `error` value — descriptions are human-readable and may change. > **Note** > **No results is not an error.** When nothing matches, the API returns HTTP `200` with an empty `products` array (and `next_page: null`). **400 — BadRequest** One of: (a) the request `query` field is missing or empty; (b) server-to-server path: `x-firmly-device-id` header is missing, exceeds 256 characters, or contains characters outside `a-z`, `A-Z`, `0-9`, `-`, `_`. The `description` is specific to the failing case. ```json { "code": 400, "error": "BadRequest", "description": "Request Syntax is not correct." } ``` **400 — MissingAuthHeader** Device-auth path: `x-firmly-authorization` header is missing or empty. ```json { "code": 400, "error": "MissingAuthHeader", "description": "x-firmly-authorization header is missing or invalid." } ``` **400 — InvalidToken** Device-auth path: the token is not a valid JWT structure. ```json { "code": 400, "error": "InvalidToken", "description": "Jwt token is invalid." } ``` **400 — InvalidAPIToken** Server-to-server path: the API token is missing, invalid, or has been revoked. ```json { "code": 400, "error": "InvalidAPIToken", "description": "API token is invalid." } ``` **400 — ErrorMissingAppId** App-id-auth path: `x-firmly-app-id` header is missing or empty. ```json { "code": 400, "error": "ErrorMissingAppId", "description": "x-firmly-app-id header is missing or invalid." } ``` **400 — ErrorInvalidAppId** App-id-auth path: the supplied App ID is not recognized, or exceeds 512 characters. ```json { "code": 400, "error": "ErrorInvalidAppId", "description": "App ID is invalid." } ``` **401 — Unauthorized** The Server-to-Server credentials were rejected, or no authentication method (Browser Session, App ID, or Server-to-Server) accepted the request. ```json { "code": 401, "error": "Unauthorized", "description": "Caller is not authorized to make this call" } ``` **401 — InvalidJWTToken** Device-auth path: JWT signature could not be verified, or required claims are missing. ```json { "code": 401, "error": "InvalidJWTToken", "description": "The JWT token is invalid." } ``` **404 — PartnerNotFound** Device-auth path: the `appid` claim on the JWT does not map to a known partner. ```json { "code": 404, "error": "PartnerNotFound", "description": "Partner could not be found" } ``` **400 — InvalidInputBody** Request body failed schema validation (e.g. a filter field has the wrong type). The `description` includes the failing field path. ```json { "code": 400, "error": "InvalidInputBody", "description": "The body is not processable" } ``` **503 — StoreUnavailable** The search backend or a downstream dependency was unavailable. ```json { "code": 503, "error": "StoreUnavailable", "description": "Store temporarily unavailable. Please try again later." } ``` --- # Select Card `POST https://api.firmly.work/api/v1/wallets/agentic-pay/select-card` ## Overview The Select Card endpoint starts a payment flow from a stored card. It takes the `virtual_card_id` from a prior enrollment and returns the same shape as `/enroll` — a `flow_token` whose status is already `enrolled`, so verification is skipped — plus `verification_methods`. The existing handshake, intent, and order completion chain is reused unchanged. Destinations persist `card_art` and `masked` from the initial `/enroll` response for the saved-card UI. `/select-card` does not re-fetch card metadata. ## Authentication - `x-firmly-authorization` (string, required) — API token for authentication ## Request Body - `network` (string, required) — Card network: `"visa"`, `"mastercard"`, or `"discover"` - `virtual_card_id` (string, required) — The `virtual_card_id` returned from the original `/enroll` response - `consumer` (object) — Cardholder information. Required for Visa (`email` is mandatory for device binding — omitting it returns a `400`). Optional for Mastercard. **Fields:** - `email` (string) — Cardholder email address (required for Visa) - `country_code` (string) — ISO country code (e.g., `"US"`) ## Response Returns the same shape as `/enroll`. - `flow_token` (string) — Encrypted state token for subsequent calls (status: `enrolled`). - `virtual_card_id` (string) — Same `virtual_card_id` passed in the request. - `verification_methods` (array) — Available verification methods. Visa returns an `embed_iframe_handshake` (capture a `secure_token` before calling `/intent`). Mastercard and Discover return an empty array — proceed directly to `/intent`. - `card_art` (null) — Always `null` on `/select-card`. Use the `card_art` persisted from the original `/enroll` response. - `masked` (null) — Always `null` on `/select-card`. Use the `masked` details persisted from the original `/enroll` response. ## Code Examples **cURL** ```bash curl --request POST \ --url https://api.firmly.work/api/v1/wallets/agentic-pay/select-card \ --header 'Content-Type: application/json' \ --header 'x-firmly-authorization: YOUR_API_TOKEN' \ --data '{ "network": "visa", "virtual_card_id": "cf90be5c86363de702ed19beec46e102", "consumer": { "email": "jane@example.com", "country_code": "US" } }' ``` **JavaScript** ```javascript const response = await fetch('https://api.firmly.work/api/v1/wallets/agentic-pay/select-card', { method: 'POST', headers: { 'Content-Type': 'application/json', 'x-firmly-authorization': 'YOUR_API_TOKEN' }, body: JSON.stringify({ network: 'visa', virtual_card_id: 'cf90be5c86363de702ed19beec46e102', consumer: { email: 'jane@example.com', country_code: 'US' } }) }); const { flow_token, verification_methods } = await response.json(); // Continue with handshake → /intent → /intent/challenge → /wallet-complete-order ``` **Python** ```python import requests response = requests.post( 'https://api.firmly.work/api/v1/wallets/agentic-pay/select-card', headers={ 'Content-Type': 'application/json', 'x-firmly-authorization': 'YOUR_API_TOKEN' }, json={ 'network': 'visa', 'virtual_card_id': 'cf90be5c86363de702ed19beec46e102', 'consumer': { 'email': 'jane@example.com', 'country_code': 'US' } } ) data = response.json() # Continue with handshake → /intent → /intent/challenge → /wallet-complete-order print(data['flow_token']) print(data['verification_methods']) ``` ## Response Example ```json { "flow_token": "", "virtual_card_id": "cf90be5c86363de702ed19beec46e102", "verification_methods": [ { "id": "VISA_IFRAME_HANDSHAKE", "type": "embed_iframe_handshake", "attributes": { "uri": "https://sbx.vts.auth.visa.com/vts-auth/authenticate?apiKey=...", "next_steps": [ "Load this iframe in the cardholder browser", "Capture sessionContext.secureToken from postMessage", "Send to /intent as secure_token" ] } } ] } ``` ## Error Responses | Error Code | Status | Description | | ---------- | ------ | ----------- | | `BadRequest` | 400 | `network` or `virtual_card_id` missing, or `consumer.email` missing for a Visa card. | | `PaymentMethodNotAvailable` | 409 | Stored-card payment is not supported or not enabled for this network. | **400 - Missing Required Fields** ```json { "code": 400, "error": "BadRequest", "description": "network and virtual_card_id required" } ``` **400 - Missing Email (Visa)** ```json { "code": 400, "error": "BadRequest", "description": "consumer.email is required for Visa stored-card selection" } ``` **409 - Network Not Available** ```json { "code": 409, "error": "PaymentMethodNotAvailable", "description": "Stored-card payment not supported for this network" } ``` --- ## Related Endpoints - [Enroll Card](/api-reference/agentic-pay/enroll) — First-time card enrollment (requires PAN) - [Create Intent](/api-reference/agentic-pay/create-intent) — Next step after select-card --- # Server-to-Server Authentication ## Overview Server-to-Server (S2S) authentication enables your backend services to make authenticated API requests to Firmly APIs. This method is designed for backend integrations where your server communicates directly with Firmly's APIs. ## Required Headers - `x-firmly-authorization` (string, required) — Server-to-server secret token provisioned by Firmly. This is **not** your APPID — it is a dedicated secret mapped internally to your tenant for request isolation. You may send it either as `x-firmly-authorization: ` or as the standard `Authorization: Bearer ` — the two forms are equivalent. - `x-firmly-device-id` (string, required) — The device identifier of the client making the request. Your backend passes this through when making API calls on behalf of a client device. ### Device ID The `x-firmly-device-id` is used for cart isolation and session management. Pass through your client's device ID when making API calls on their behalf. ### Device ID Requirements | Rule | Requirement | |------|-------------| | Presence | Must be present and non-empty | | Max Length | 256 characters | | Allowed Characters | `a-z`, `A-Z`, `0-9`, `-`, `_` | **Valid Examples:** - `user-12345` - `session_abc123` - `82b10522-5483-4719-b599-6d78b12827f0` **Invalid Examples:** - Empty string - `user.id` (period not allowed) - `user id` (space not allowed) ## Code Examples **cURL** ```bash curl -X POST https://api.firmly.work/api/v1/discovery/search \ -H "x-firmly-authorization: YOUR_S2S_SECRET" \ -H "x-firmly-device-id: user-12345" \ -H "Content-Type: application/json" \ -d '{"query": "running shoes"}' ``` **JavaScript** ```javascript const response = await fetch('https://api.firmly.work/api/v1/discovery/search', { method: 'POST', headers: { 'x-firmly-authorization': s2sSecret, // S2S secret (not APPID) 'x-firmly-device-id': clientDeviceId, 'Content-Type': 'application/json' }, body: JSON.stringify({ query: 'running shoes' }) }); const results = await response.json(); ``` **Python** ```python import requests response = requests.post( 'https://api.firmly.work/api/v1/discovery/search', headers={ 'x-firmly-authorization': s2s_secret, # S2S secret (not APPID) 'x-firmly-device-id': client_device_id, 'Content-Type': 'application/json' }, json={'query': 'running shoes'} ) results = response.json() ``` ## Supported Endpoints Server-to-Server authentication is accepted across the **entire cart and checkout surface** — v1 and v2 — plus Discovery and read-only catalog. In practice this is the same set of routes a browser-session or App ID caller can reach, **minus the six device-scoped session routes** listed under "Not accepted" below. On every accepted route, send the S2S secret plus `x-firmly-device-id`. **Accepted** (S2S secret + `x-firmly-device-id`): - **Cart** — [Get Cart](/api-reference/cart-management/get-cart), [Add](/api-reference/cart-management/add-line-item) / [Update](/api-reference/cart-management/update-line-item) / [Clear](/api-reference/cart-management/clear-cart) line items, [Set Cart Attribution](/api-reference/cart-management/set-attribution) - **Checkout** — [Set Shipping Info](/api-reference/checkout/set-shipping-info), [Set Billing Info](/api-reference/checkout/set-billing-info), [Get](/api-reference/checkout/get-consents) / [Set](/api-reference/checkout/set-consents) Consents, shipping rates - **Promotions** — [Add](/api-reference/promotions/add-promo-codes) / [Clear](/api-reference/promotions/clear-promo-codes) Promo Codes - **Add-ons** — [Add](/api-reference/addon-management/add-addon) / [Remove](/api-reference/addon-management/remove-addon) Add-on - **Shipments** — [Set Fulfillment Type](/api-reference/shipment-configuration/set-fulfillment-type), [Set Shipping Method](/api-reference/shipment-configuration/set-shipping-method), [Get Availability](/api-reference/shipment-configuration/get-availability) - **Order & payment** — order reads, the payment handle, and the place-order / complete-order calls - **Discovery & catalog** — [Discovery Search](/api-reference/discovery/search), [Get Product from URL](/api-reference/catalog/get-product-from-url) **Not accepted — device JWT only.** These six device-scoped session routes require a device JWT; the S2S secret is rejected. Use [Browser Session](/api-reference/authentication/browser-session) auth instead: - [Get Active Carts](/api-reference/session/get-active-carts) - [Get Active Domains](/api-reference/session/get-active-domains) - [Get Postal Code](/api-reference/session/get-postal-code) - [Set Postal Code](/api-reference/session/set-postal-code) - [Session Transfer](/api-reference/session/session-transfer) - [Start Journey](/api-reference/affiliate/start-journey) > **Note** > Each endpoint's own Authentication and Error Responses sections remain the source of truth. If a page does not explicitly mention S2S, treat the boundary above as authoritative: S2S is accepted everywhere except the six device-scoped session routes. ## Next Steps - [Search Products](/api-reference/discovery/search) — Search for products using S2S auth ## Error Responses Errors return a JSON body with `code`, `error`, and `description`. Program against the `error` value — descriptions are human-readable and may change. **400 — BadRequest** The `x-firmly-device-id` header is missing, empty, exceeds 256 characters, or contains characters outside `a-z`, `A-Z`, `0-9`, `-`, `_`. ```json { "code": 400, "error": "BadRequest", "description": "Bad request." } ``` **400 — InvalidAPIToken** The S2S secret token is missing, malformed, or not recognized. ```json { "code": 400, "error": "InvalidAPIToken", "description": "API token is invalid." } ``` --- # Session Transfer `POST https://api.firmly.work/api/v2/domains/{domain}/session/transfer` Transfers an existing merchant-side session (the buyer's cart on the merchant's own store) into the Firmly cart for the current device. The merchant adapter resolves the supplied `handle` (and any `cookies`) into the merchant cart, Firmly imports its contents, and the response is the cart in V2 form. > **Note** > The `handle` is generated by Firmly's storefront integration (the buy-now button). Standard cart-API integrations don't call this directly. ## Authentication - `x-firmly-authorization` (string, required) — Device access token from [Browser Session](/api-reference/authentication/browser-session) - **Server-to-server (S2S) auth is not accepted** — this is a device-scoped session route. It requires a device JWT from [Browser Session](/api-reference/authentication/browser-session); the S2S secret is rejected. See [Server-to-Server Authentication](/api-reference/authentication/server-to-server). ## Path Parameters - `domain` (string, required) — The merchant's domain (e.g. `staging.luma.gift`). ## Request Body - `handle` (string, required) — Merchant session identifier. Always sent as a JSON **string**. Two forms are accepted: - **Plain string** — the merchant's session id directly (e.g. `"merchant-session-12345"`). - **JSON-stringified envelope** — a JSON object **stringified** before being placed in `handle`, used when a merchant integration needs to pass additional metadata. Fields the envelope may carry: | Field | Type | Meaning | | -------------- | ------ | ------- | | `handle` | string | The merchant session id. | | `token` | string | Security token shared with the merchant. Must be ≥ 36 characters. | | `merchantData` | object | Arbitrary metadata the merchant supplies to Firmly for the transfer. | | `version` | string | Script / integration version identifier. | Pre-stringify the envelope before sending — the wire value of `handle` must be a string, not a JSON object. - `cookies` (string[], required) — List of cookies the merchant adapter needs to validate / hydrate the session. **Always send this field as an array**, even when you have no cookies — pass an empty array (`[]`) in that case. Although it is technically optional in the request schema, omitting `cookies` entirely causes the request to fail, because the server folds it into the session fingerprint before validation runs. > **Warning** > Send `cookies` on every request — `[]` if you have none. Leaving the field out (rather than passing an empty array) results in a failed request. ## Response Returns the imported cart in the V2 shape — same schema as [Get Cart](/api-reference/cart-management/get-cart). ## Examples **Plain handle** ```bash curl -X POST https://api.firmly.work/api/v2/domains/staging.luma.gift/session/transfer \ -H "x-firmly-authorization: YOUR_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "handle": "external-session-12345", "cookies": ["session_cookie_value"] }' ``` **Stringified envelope** ```bash curl -X POST https://api.firmly.work/api/v2/domains/staging.luma.gift/session/transfer \ -H "x-firmly-authorization: YOUR_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "handle": "{\"handle\":\"external-session-12345\",\"token\":\"a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0\",\"version\":\"2.0\",\"merchantData\":{\"source\":\"mobile-app\"}}", "cookies": ["session_cookie_value"] }' ``` **JavaScript** ```javascript // Plain handle const response = await fetch( 'https://api.firmly.work/api/v2/domains/staging.luma.gift/session/transfer', { method: 'POST', headers: { 'x-firmly-authorization': 'YOUR_TOKEN', 'Content-Type': 'application/json' }, body: JSON.stringify({ handle: 'external-session-12345', cookies: ['session_cookie_value'] }) } ); // Stringified envelope const envelope = { handle: 'external-session-12345', token: 'a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0', version: '2.0', merchantData: { source: 'mobile-app' } }; const responseWithMeta = await fetch( 'https://api.firmly.work/api/v2/domains/staging.luma.gift/session/transfer', { method: 'POST', headers: { 'x-firmly-authorization': 'YOUR_TOKEN', 'Content-Type': 'application/json' }, body: JSON.stringify({ handle: JSON.stringify(envelope), cookies: ['session_cookie_value'] }) } ); const cart = await responseWithMeta.json(); ``` **Python** ```python import json import requests # Plain handle response = requests.post( 'https://api.firmly.work/api/v2/domains/staging.luma.gift/session/transfer', headers={ 'x-firmly-authorization': 'YOUR_TOKEN', 'Content-Type': 'application/json' }, json={ 'handle': 'external-session-12345', 'cookies': ['session_cookie_value'] } ) # Stringified envelope envelope = { 'handle': 'external-session-12345', 'token': 'a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0', 'version': '2.0', 'merchantData': {'source': 'mobile-app'} } response_with_meta = requests.post( 'https://api.firmly.work/api/v2/domains/staging.luma.gift/session/transfer', headers={ 'x-firmly-authorization': 'YOUR_TOKEN', 'Content-Type': 'application/json' }, json={ 'handle': json.dumps(envelope), 'cookies': ['session_cookie_value'] } ) cart = response_with_meta.json() ``` ## Error Responses Errors return a JSON body with `code`, `error`, and `description`. Program against the `error` value — descriptions are human-readable and may change. **400 — MissingAuthHeader** The `x-firmly-authorization` header is missing or empty. ```json { "code": 400, "error": "MissingAuthHeader", "description": "x-firmly-authorization header is missing or invalid." } ``` **400 — InvalidToken** The authorization token is not a valid JWT structure. ```json { "code": 400, "error": "InvalidToken", "description": "Jwt token is invalid." } ``` **401 — InvalidJWTToken** The device JWT signature does not verify, or required claims are missing. ```json { "code": 401, "error": "InvalidJWTToken", "description": "Jwt token is invalid." } ``` **404 — PartnerNotFound** The `appid` claim on the device JWT does not map to a known partner / tenant. ```json { "code": 404, "error": "PartnerNotFound", "description": "Partner not found." } ``` **404 — DomainNotFound** The `{domain}` path parameter does not match any merchant configured with Firmly, or the merchant has been disabled. ```json { "code": 404, "error": "DomainNotFound", "description": "This domain was not found in firmly servers." } ``` **409 — CannotTransferSession** The supplied `handle` could not be turned into a usable merchant session. Common causes: invalid handle, expired or revoked session on the merchant side, or a `token` shorter than the required 36 characters when an envelope is sent. ```json { "code": 409, "error": "CannotTransferSession", "description": "Required information to perform session transfer is not available." } ``` **409 — NotEnoughStockError** The merchant cart was retrieved, but one or more line items have insufficient stock to import. ```json { "code": 409, "error": "NotEnoughStockError", "description": "Not enough stock." } ``` **412 — NoLineItemError** The transferred cart is empty (the merchant returned a cart with no line items). ```json { "code": 412, "error": "NoLineItemError", "description": "No line item." } ``` **412 — OperationNotSupported** The merchant adapter does not implement session transfer. ```json { "code": 412, "error": "OperationNotSupported", "description": "This operation is not supported for this store." } ``` **400 — InvalidInputBody** Request body fails schema validation. `handle` must be a string; `cookies` must be an array of strings when present. ```json { "code": 400, "error": "InvalidInputBody", "description": "The body is not processable" } ``` --- # Session The Session API provides endpoints for managing shopping sessions across multiple merchant domains and storing postal code preferences for shipping calculations. ## Available Endpoints ### Active Cart Management - [Get Active Domains](/api-reference/session/get-active-domains) — Retrieve a list of domains where the user has active carts - [Get Active Carts](/api-reference/session/get-active-carts) — Retrieve all active shopping carts across multiple domains ### Postal Code Management - [Get Postal Code](/api-reference/session/get-postal-code) — Retrieve the stored postal code preference - [Set Postal Code](/api-reference/session/set-postal-code) — Update the postal code preference for shipping calculations ### Session Transfer - [Session Transfer](/api-reference/session/session-transfer) — Transfer an external merchant session to Firmly's cart system ## Core Concepts ### Multi-Domain Cart Tracking The session endpoints enable tracking of shopping carts across multiple merchant domains: - **Active Domains**: Quickly check which merchants have active carts - **Active Carts**: Retrieve full cart data for all active sessions - **Exclude Filtering**: Filter out specific domains when retrieving active carts ### Postal Code Preference A single postal code preference is stored per device session and used for: - Shipping cost calculations - Merchant tax-rate determination - Delivery availability checks > **Note** > The postal code is a global preference that applies to all merchant carts in the session. When no postal code has been set, [Get Postal Code](/api-reference/session/get-postal-code) returns an empty string (`""`) for the `postal_code` field. ### How session transfer works The session transfer endpoint enables migrating existing merchant sessions to Firmly's cart system. This is useful for: - Transitioning from native checkout to Firmly - Preserving cart contents during platform migration - Maintaining shopping continuity ## Authentication All session endpoints require device authentication using the `x-firmly-authorization` header. See the [Authentication Guide](/api-reference/authentication/browser-session) for details on obtaining access tokens. ## Use Cases - **Multi-merchant shopping** — track and manage carts across stores via [Get Active Domains](/api-reference/session/get-active-domains) and [Get Active Carts](/api-reference/session/get-active-carts). - **Shipping calculations** — stage a postal code via [Set Postal Code](/api-reference/session/set-postal-code) for accurate shipping quotes before the buyer enters a full address. - **Cart recovery** — import an in-flight merchant session via [Session Transfer](/api-reference/session/session-transfer) to preserve cart contents across platforms. --- # Set Billing Info `POST https://api.firmly.work/api/v2/domains/{domain}/cart/billing-info` ## Overview Stages a billing address on the cart before the place-order call. > **Note** > This endpoint is **optional and merchant-dependent**. The typical flow passes `billing_info` directly in the body of [Place Order](/api-reference/payment/place-order-v2) or [Complete Order](/api-reference/payment/complete-order-v2). Use this endpoint when integrating with a merchant whose platform requires billing info to be present on the cart before payment authorization. ## Authentication - `x-firmly-authorization` (string, required) — Device access token from [Browser Session](/api-reference/authentication/browser-session) > **Note** > This endpoint also accepts **server-to-server (S2S) authentication** for backend integrations acting on behalf of a device: send `Authorization: Bearer ` (or the equivalent `x-firmly-authorization: `) together with `x-firmly-device-id`. See [Server-to-Server Authentication](/api-reference/authentication/server-to-server). ## Path Parameters - `domain` (string, required) — Domain of the merchant website (e.g., `staging.luma.gift`) ## Request Body - `first_name` (string, required) — Buyer's first name for billing - `last_name` (string, required) — Buyer's last name for billing - `address1` (string, required) — Primary billing address line - `address2` (string) — Secondary billing address line (apartment, suite, etc.) - `city` (string, required) — Billing city name - `state_or_province` (string, required) — Billing state or province code (e.g., "CA", "NY") or full name - `postal_code` (string, required) — Billing ZIP or postal code - `country` (string, required) — Billing country code in ISO 3166-1 alpha-2 format (e.g., "US", "CA") - `phone` (string, required) — Billing contact phone number - `email` (string, required) — Billing contact email address ## Response Returns a complete [ShoppingCart](/api-reference/cart-management/get-cart) object with updated billing information. The cart totals remain unchanged as billing address doesn't affect shipping or tax calculations. ## When to Use Call this endpoint only when the merchant's checkout flow requires billing info on the cart prior to place-order. This is **not the default checkout pattern** — for most merchants, billing info travels with the place-order request. If you're unsure whether your merchant needs it: when the merchant requires billing on the cart, calling place-order without this step fails with an `OperationNotSupported`-class error; otherwise you can skip this endpoint and pass `billing_info` in the place-order body. ## Code Examples **cURL** ```bash curl -X POST https://api.firmly.work/api/v2/domains/staging.luma.gift/cart/billing-info \ -H "x-firmly-authorization: YOUR_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "first_name": "Jane", "last_name": "Doe", "address1": "456 Billing Street", "address2": "Suite 100", "city": "Billing City", "state_or_province": "NY", "postal_code": "10001", "country": "US", "phone": "555-987-6543", "email": "jane.doe@staging.luma.gift" }' ``` **JavaScript** ```javascript const billingInfo = { first_name: "Jane", last_name: "Doe", address1: "456 Billing Street", address2: "Suite 100", city: "Billing City", state_or_province: "NY", postal_code: "10001", country: "US", phone: "555-987-6543", email: "jane.doe@staging.luma.gift" }; const response = await fetch('https://api.firmly.work/api/v2/domains/staging.luma.gift/cart/billing-info', { method: 'POST', headers: { 'x-firmly-authorization': 'YOUR_TOKEN', 'Content-Type': 'application/json' }, body: JSON.stringify(billingInfo) }); const updatedCart = await response.json(); ``` **Python** ```python import requests billing_info = { "first_name": "Jane", "last_name": "Doe", "address1": "456 Billing Street", "address2": "Suite 100", "city": "Billing City", "state_or_province": "NY", "postal_code": "10001", "country": "US", "phone": "555-987-6543", "email": "jane.doe@staging.luma.gift" } response = requests.post( 'https://api.firmly.work/api/v2/domains/staging.luma.gift/cart/billing-info', headers={ 'x-firmly-authorization': 'YOUR_TOKEN', 'Content-Type': 'application/json' }, json=billing_info ) updated_cart = response.json() ``` **PHP** ```php $billingInfo = [ 'first_name' => 'Jane', 'last_name' => 'Doe', 'address1' => '456 Billing Street', 'address2' => 'Suite 100', 'city' => 'Billing City', 'state_or_province' => 'NY', 'postal_code' => '10001', 'country' => 'US', 'phone' => '555-987-6543', 'email' => 'jane.doe@staging.luma.gift' ]; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, 'https://api.firmly.work/api/v2/domains/staging.luma.gift/cart/billing-info'); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'x-firmly-authorization: YOUR_TOKEN', 'Content-Type: application/json' ]); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($billingInfo)); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); $updatedCart = json_decode($response, true); curl_close($ch); ``` ## Response Example ```json { "line_items": [ { "line_item_id": "a02a3e67-b50e-8dcd-5970-8fff52117e43", "sku": "WS12-XS-Orange", "description": "Radiant Tee", "quantity": 2, "price": { "currency": "USD", "value": 22.0, "number": 2200, "symbol": "$" }, "line_price": { "currency": "USD", "value": 44.0, "number": 4400, "symbol": "$" }, "msrp": { "currency": "USD", "value": 26.4, "number": 2640, "symbol": "$" }, "image": { "url": "https://staging.luma.gift/radiant-tee.jpg", "alt": "Radiant Tee", "type": "default" } } ], "shipments": [ { "shipment_id": "8568658c-bee9-9666-4547-a545fe27391b", "line_item_ids": [ "a02a3e67-b50e-8dcd-5970-8fff52117e43" ], "fulfillment_type": { "id": "SHIP_TO_ADDRESS", "name": "Ship to Address", "description": "Standard shipping to your address" }, "shipping_method": { "id": "STANDARD_GROUND", "description": "Standard Ground (5-7 business days)", "price": { "currency": "USD", "value": 9.99, "number": 999, "symbol": "$" }, "estimated_delivery": "5-7 business days" } } ], "shipping_info": { "first_name": "John", "last_name": "Smith", "address1": "123 Main Street", "address2": "Apt 4B", "city": "Anytown", "state_or_province": "CA", "postal_code": "12345", "country": "US", "phone": "555-123-4567", "email": "john.smith@staging.luma.gift" }, "billing_info": { "first_name": "Jane", "last_name": "Doe", "address1": "456 Billing Street", "address2": "Suite 100", "city": "Billing City", "state_or_province": "NY", "postal_code": "10001", "country": "US", "phone": "555-987-6543", "email": "jane.doe@staging.luma.gift" }, "sub_total": { "currency": "USD", "value": 44.0, "number": 4400, "symbol": "$" }, "shipping_total": { "currency": "USD", "value": 9.99, "number": 999, "symbol": "$" }, "tax_total": { "currency": "USD", "value": 4.4, "number": 440, "symbol": "$" }, "fees": [ { "description": "Recycle fee", "currency": "USD", "value": 2.00, "number": 200, "symbol": "$" } ], "fee_total": { "currency": "USD", "value": 2.00, "number": 200, "symbol": "$" }, "total": { "currency": "USD", "value": 60.39, "number": 6039, "symbol": "$" }, "schema_version": "2.0" } ``` ## Checkout Flow Integration The typical checkout flow does **not** include this endpoint: 1. [Add Items to Cart](/api-reference/cart-management/add-line-item) 2. [Set Shipping Info](/api-reference/checkout/set-shipping-info) 3. [Set Consents](/api-reference/checkout/set-consents) — when applicable 4. [Place Order](/api-reference/payment/place-order-v2) — `billing_info` is passed in this request body Insert this endpoint between steps 2 and 4 **only** if your merchant integration requires billing info to be staged on the cart in advance. ## Error Responses Errors return a JSON body with `code`, `error`, and `description`. Program against the `error` value — descriptions are human-readable and may change. **400 — MissingAuthHeader** The `x-firmly-authorization` header is missing or empty. ```json { "code": 400, "error": "MissingAuthHeader", "description": "x-firmly-authorization header is missing or invalid." } ``` **400 — InvalidToken** The authorization token is not a valid JWT structure. ```json { "code": 400, "error": "InvalidToken", "description": "Jwt token is invalid." } ``` **400 — InvalidAPIToken** The API token (server-to-server secret) is invalid or has been revoked. ```json { "code": 400, "error": "InvalidAPIToken", "description": "API token is invalid." } ``` **400 — BadRequest** Server-to-server auth was attempted but required headers are missing or malformed. ```json { "code": 400, "error": "BadRequest", "description": "Bad request." } ``` **400 — InvalidState** The `state_or_province` value is not valid for the given `country`. ```json { "code": 400, "error": "InvalidState", "description": "Invalid state." } ``` **401 — Unauthorized** The authorization token was rejected. ```json { "code": 401, "error": "Unauthorized", "description": "Unauthorized." } ``` **401 — InvalidJWTToken** The device JWT signature does not verify, or required claims are missing. ```json { "code": 401, "error": "InvalidJWTToken", "description": "Jwt token is invalid." } ``` **404 — PartnerNotFound** The `appid` claim on the device JWT does not map to a known partner / tenant. ```json { "code": 404, "error": "PartnerNotFound", "description": "Partner not found." } ``` **404 — DomainNotFound** The `{domain}` path parameter does not match any merchant configured with Firmly, or the merchant has been disabled. ```json { "code": 404, "error": "DomainNotFound", "description": "This domain was not found in firmly servers." } ``` **404 — CartNotFound** No cart exists for this device on this domain. Add an item first via [Add Line Item](/api-reference/cart-management/add-line-item). ```json { "code": 404, "error": "CartNotFound", "description": "Cart was not found." } ``` **412 — CountryNotSupported** The merchant does not accept billing addresses in the supplied `country`. ```json { "code": 412, "error": "CountryNotSupported", "description": "Country is not supported." } ``` **412 — OperationNotSupported** The merchant's platform does not support staging billing info on the cart. For these merchants, billing info must be passed in the place-order request body instead. ```json { "code": 412, "error": "OperationNotSupported", "description": "This operation is not supported for this store." } ``` **400 — InvalidInputBody** Request body fails schema validation. Ensure all required fields are present and well-formed. ```json { "code": 400, "error": "InvalidInputBody", "description": "The body is not processable" } ``` --- # Set Cart Attribution `PUT https://api.firmly.work/api/v2/domains/{domain}/cart/attribution` ## Overview The Set Cart Attribution endpoint records where the cart came from — the campaign, the referring surface, and the traffic source — and binds that context to the cart session. The values persist for the life of the session and are carried through to the merchant's order metadata when the order is placed, so downstream attribution and conversion reporting can credit the right source. - **Set it once, early.** Call it as soon as the attribution context is known — typically right after the first add-to-cart, before checkout. The values stay bound to the session for its lifetime. - **All fields are optional.** Send whichever of the four fields you have. Later calls overwrite the values from earlier calls on the same session. - **Returns the current cart.** The response is the full cart state (same schema as [Get Cart](/api-reference/cart-management/get-cart)); attribution itself is stored on the session, not echoed as cart line data. ## Authentication - `x-firmly-authorization` (string, required) — Device access token from [Browser Session](/api-reference/authentication/browser-session) > **Note** > This endpoint also accepts **server-to-server (S2S) authentication** for backend integrations acting on behalf of a device: send `Authorization: Bearer ` (or the equivalent `x-firmly-authorization: `) together with `x-firmly-device-id`. See [Server-to-Server Authentication](/api-reference/authentication/server-to-server). ## Path Parameters - `domain` (string, required) — Domain of the merchant website (e.g., `staging.luma.gift`) ## Request Body - `attribution` (object, required) — Attribution context to bind to the cart session. Every field is an optional string — send the ones you have. There are exactly four fields; no others are read. **Fields (all optional):** - `utm` (string): The campaign query string as captured from the entry URL — e.g. `utm_source=partner&utm_medium=cpc&utm_campaign=spring_launch`. Also the natural carrier for an ad platform's click identifier (`fbclid`, `gclid`, `ttclid`, `epik`) when you fold it into the same query string. - `referrer_url` (string): The URL the buyer came from — the ad, article, or referring page that drove the click. - `referral_code` (string): A stable source identifier — a publisher ID, affiliate code, or partner code used to credit the traffic source. - `landing_page` (string): The URL the buyer landed on to begin the purchase. ## Response Returns the current shopping cart — same schema as [Get Cart](/api-reference/cart-management/get-cart). The attribution values are stored on the cart session and travel through to the merchant's order metadata at order placement; they are not returned as separate fields on the cart body. ## Code Examples **cURL** ```bash curl --request PUT \ --url https://api.firmly.work/api/v2/domains/staging.luma.gift/cart/attribution \ --header 'Content-Type: application/json' \ --header 'x-firmly-authorization: YOUR_TOKEN' \ --data '{ "attribution": { "utm": "utm_source=partner&utm_medium=cpc&utm_campaign=spring_launch", "referrer_url": "https://ads.example.com/c/abc123", "referral_code": "PARTNER-XYZ", "landing_page": "https://staging.luma.gift/p/SKU-1?utm_source=partner" } }' ``` **JavaScript** ```javascript const response = await fetch('https://api.firmly.work/api/v2/domains/staging.luma.gift/cart/attribution', { method: 'PUT', headers: { 'Content-Type': 'application/json', 'x-firmly-authorization': 'YOUR_TOKEN' }, body: JSON.stringify({ attribution: { utm: 'utm_source=partner&utm_medium=cpc&utm_campaign=spring_launch', referrer_url: 'https://ads.example.com/c/abc123', referral_code: 'PARTNER-XYZ', landing_page: 'https://staging.luma.gift/p/SKU-1?utm_source=partner' } }) }); const cart = await response.json(); console.log(cart); ``` **Python** ```python import requests response = requests.put( 'https://api.firmly.work/api/v2/domains/staging.luma.gift/cart/attribution', headers={ 'Content-Type': 'application/json', 'x-firmly-authorization': 'YOUR_TOKEN' }, json={ 'attribution': { 'utm': 'utm_source=partner&utm_medium=cpc&utm_campaign=spring_launch', 'referrer_url': 'https://ads.example.com/c/abc123', 'referral_code': 'PARTNER-XYZ', 'landing_page': 'https://staging.luma.gift/p/SKU-1?utm_source=partner' } } ) cart = response.json() print(cart) ``` **PHP** ```php [ 'utm' => 'utm_source=partner&utm_medium=cpc&utm_campaign=spring_launch', 'referrer_url' => 'https://ads.example.com/c/abc123', 'referral_code' => 'PARTNER-XYZ', 'landing_page' => 'https://staging.luma.gift/p/SKU-1?utm_source=partner' ] ]; curl_setopt_array($curl, [ CURLOPT_URL => "https://api.firmly.work/api/v2/domains/staging.luma.gift/cart/attribution", CURLOPT_RETURNTRANSFER => true, CURLOPT_CUSTOMREQUEST => "PUT", CURLOPT_HTTPHEADER => [ "Content-Type: application/json", "x-firmly-authorization: YOUR_TOKEN" ], CURLOPT_POSTFIELDS => json_encode($data) ]); $response = curl_exec($curl); curl_close($curl); $cart = json_decode($response, true); print_r($cart); ?> ``` ## Response Example ```json { "cart_id": "a5600193-2c13-3356-d063-711da63b7cd7", "platform_id": "example_commerce", "shop_id": "staging.luma.gift", "display_name": "Luma Store", "cart_status": "active", "line_items": [ { "line_item_id": "bd3710bc-97ef-408d-7382-43b7e5de712f", "sku": "SKU-1", "quantity": 1, "description": "Luma Explorer Backpack", "price": { "currency": "USD", "value": 79, "number": 7900, "symbol": "$" }, "line_price": { "currency": "USD", "value": 79, "number": 7900, "symbol": "$" }, "msrp": { "currency": "USD", "value": 95, "number": 9500, "symbol": "$" }, "image": { "url": "https://staging.luma.gift/luma-explorer-backpack.jpg", "alt": "Luma Explorer Backpack", "type": "default" } } ], "shipments": [], "sub_total": { "currency": "USD", "value": 79, "number": 7900, "symbol": "$" }, "fees": [{ "description": "Recycle fee", "currency": "USD", "value": 2, "number": 200, "symbol": "$" }], "fee_total": { "currency": "USD", "value": 2, "number": 200, "symbol": "$" }, "total": { "currency": "USD", "value": 81, "number": 8100, "symbol": "$" }, "addons": { "offers": [], "selections": [] }, "schema_version": "2.0" } ``` --- ## Related Endpoints - [Get Cart](/api-reference/cart-management/get-cart) — View current cart state and full response schema - [Add Line Item](/api-reference/cart-management/add-line-item) — Add items to the cart - [Place Order](/api-reference/payment/place-order-v2) — Attribution set here rides through to order metadata ## Error Responses Errors return a JSON body with `code`, `error`, and `description`. Program against the `error` value — descriptions are human-readable and may change. **400 — MissingAuthHeader** The `x-firmly-authorization` header is missing or empty. ```json { "code": 400, "error": "MissingAuthHeader", "description": "x-firmly-authorization header is missing or invalid." } ``` **400 — InvalidToken** The authorization token is not a valid JWT structure. ```json { "code": 400, "error": "InvalidToken", "description": "Jwt token is invalid." } ``` **400 — InvalidAPIToken** The API token (server-to-server secret) is invalid or has been revoked. ```json { "code": 400, "error": "InvalidAPIToken", "description": "API token is invalid." } ``` **400 — BadRequest** Server-to-server auth was attempted but the required headers (`x-firmly-authorization` plus `x-firmly-device-id`) are missing or malformed. ```json { "code": 400, "error": "BadRequest", "description": "Bad request." } ``` **401 — Unauthorized** The authorization token was rejected. ```json { "code": 401, "error": "Unauthorized", "description": "Unauthorized." } ``` **401 — InvalidJWTToken** The device JWT signature does not verify, or required claims are missing. ```json { "code": 401, "error": "InvalidJWTToken", "description": "Jwt token is invalid." } ``` **404 — PartnerNotFound** The `appid` claim on the device JWT does not map to a known partner / tenant — typically a token from a different environment. ```json { "code": 404, "error": "PartnerNotFound", "description": "Partner not found." } ``` **404 — DomainNotFound** The `{domain}` path parameter does not match any merchant configured with Firmly, or the merchant has been disabled. Verify the domain string (case-sensitive, no protocol or trailing slash). ```json { "code": 404, "error": "DomainNotFound", "description": "This domain was not found in firmly servers." } ``` **404 — CartNotFound** No cart exists for this device on this domain. Add an item first — attribution attaches to an existing cart session. ```json { "code": 404, "error": "CartNotFound", "description": "Cart was not found." } ``` **412 — OperationNotSupported** The merchant's platform does not support this operation. Check with [Firmly](/contact) whether this endpoint is available for the merchant. ```json { "code": 412, "error": "OperationNotSupported", "description": "This operation is not supported for this store." } ``` **400 — InvalidInputBody** The request body failed schema validation — for example, a field sent as a non-string value. The `description` names the failing field. ```json { "code": 400, "error": "InvalidInputBody", "description": "The body is not processable" } ``` --- # Set Consents `PUT https://api.firmly.work/api/v2/domains/{domain}/cart/consents` ## Overview Updates the consent preferences for a buyer's cart session. Grants or revokes consent for the IDs returned by [Get Consents](/api-reference/checkout/get-consents). Each grant captures a server-side signature for compliance. > **Note** > This endpoint is **optional and merchant-dependent**. Call it only when [Get Consents](/api-reference/checkout/get-consents) returns a non-empty array for the cart — most merchants do not configure consents and you can skip this step entirely. ## Authentication - `x-firmly-authorization` (string, required) — Device access token from [Browser Session](/api-reference/authentication/browser-session) > **Note** > This endpoint also accepts **server-to-server (S2S) authentication** for backend integrations acting on behalf of a device: send `Authorization: Bearer ` (or the equivalent `x-firmly-authorization: `) together with `x-firmly-device-id`. See [Server-to-Server Authentication](/api-reference/authentication/server-to-server). ## Path Parameters - `domain` (string, required) — Domain of the merchant website (e.g., `staging.luma.gift`) ## Request Body - `consents` (object[], required) — Array of consent updates to apply. Each entry references a consent returned by [Get Consents](/api-reference/checkout/get-consents). **Consent update properties** - `id` (string, required) — Unique identifier of the consent to update — must match an `id` returned by Get Consents. - `revoke` (boolean, default `false`) — Set to `true` to revoke a previously granted consent. Omit or set to `false` to grant. ## Response Returns an updated array of all consent objects with the same structure as the [Get Consents](/api-reference/checkout/get-consents) response, reflecting the changes made. ## Code Examples ### Grant Single Consent **cURL** ```bash curl -X PUT https://api.firmly.work/api/v2/domains/staging.luma.gift/cart/consents \ -H "x-firmly-authorization: YOUR_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "consents": [ { "id": "f47ac10b-58cc-4372-a567-0e02b2c3d479" } ] }' ``` **JavaScript** ```javascript const response = await fetch('https://api.firmly.work/api/v2/domains/staging.luma.gift/cart/consents', { method: 'PUT', headers: { 'x-firmly-authorization': 'YOUR_TOKEN', 'Content-Type': 'application/json' }, body: JSON.stringify({ consents: [ { id: 'f47ac10b-58cc-4372-a567-0e02b2c3d479' } ] }) }); const updatedConsents = await response.json(); ``` **Python** ```python import requests response = requests.put( 'https://api.firmly.work/api/v2/domains/staging.luma.gift/cart/consents', headers={ 'x-firmly-authorization': 'YOUR_TOKEN', 'Content-Type': 'application/json' }, json={ 'consents': [ { 'id': 'f47ac10b-58cc-4372-a567-0e02b2c3d479' } ] } ) updated_consents = response.json() ``` **PHP** ```php $data = [ 'consents' => [ [ 'id' => 'f47ac10b-58cc-4372-a567-0e02b2c3d479' ] ] ]; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, 'https://api.firmly.work/api/v2/domains/staging.luma.gift/cart/consents'); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT'); curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'x-firmly-authorization: YOUR_TOKEN', 'Content-Type: application/json' ]); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); $updatedConsents = json_decode($response, true); curl_close($ch); ``` ### Revoke Consent **cURL** ```bash curl -X PUT https://api.firmly.work/api/v2/domains/staging.luma.gift/cart/consents \ -H "x-firmly-authorization: YOUR_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "consents": [ { "id": "f47ac10b-58cc-4372-a567-0e02b2c3d479", "revoke": true } ] }' ``` **JavaScript** ```javascript const response = await fetch('https://api.firmly.work/api/v2/domains/staging.luma.gift/cart/consents', { method: 'PUT', headers: { 'x-firmly-authorization': 'YOUR_TOKEN', 'Content-Type': 'application/json' }, body: JSON.stringify({ consents: [ { id: 'f47ac10b-58cc-4372-a567-0e02b2c3d479', revoke: true } ] }) }); ``` ### Update Multiple Consents **cURL** ```bash curl -X PUT https://api.firmly.work/api/v2/domains/staging.luma.gift/cart/consents \ -H "x-firmly-authorization: YOUR_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "consents": [ { "id": "f47ac10b-58cc-4372-a567-0e02b2c3d479" }, { "id": "6ba7b810-9dad-11d1-80b4-00c04fd430c8" }, { "id": "8c9e3f12-4567-8901-2345-678901234567", "revoke": true } ] }' ``` **JavaScript** ```javascript const response = await fetch('https://api.firmly.work/api/v2/domains/staging.luma.gift/cart/consents', { method: 'PUT', headers: { 'x-firmly-authorization': 'YOUR_TOKEN', 'Content-Type': 'application/json' }, body: JSON.stringify({ consents: [ { id: 'f47ac10b-58cc-4372-a567-0e02b2c3d479' }, // Grant { id: '6ba7b810-9dad-11d1-80b4-00c04fd430c8' }, // Grant { id: '8c9e3f12-4567-8901-2345-678901234567', revoke: true } // Revoke ] }) }); ``` ## Response Example ```json [ { "id": "f47ac10b-58cc-4372-a567-0e02b2c3d479", "ui_slot": "UNDER_EMAIL_INPUT", "text": "I would like to receive marketing emails about special offers and new products.", "type": "MARKETING", "explicit": true, "required": false, "revokable": true, "signed": true }, { "id": "6ba7b810-9dad-11d1-80b4-00c04fd430c8", "ui_slot": "ABOVE_PLACE_ORDER_BUTTON", "text": "I agree to the Terms of Service and Privacy Policy.", "html": "I agree to the Terms of Service and Privacy Policy.", "type": "TERMS_AND_CONDITIONS", "explicit": true, "required": true, "revokable": false, "signed": true } ] ``` ## Consent Rules - Consents with `explicit: true` require an opt-in action from the buyer; sending the `id` (without `revoke`) records that opt-in. - Required consents must be signed before placing an order — `place-order` rejects the request if any `required && explicit` consent is unsigned. - Only consents with `revokable: true` can be revoked. Sending `revoke: true` for a non-revokable consent fails the entire request with `400 BadRequest` (the description identifies the offending IDs). ## Error Responses Errors return a JSON body with `code`, `error`, and `description`. Program against the `error` value — descriptions are human-readable and may change. **400 — MissingAuthHeader** The `x-firmly-authorization` header is missing or empty. ```json { "code": 400, "error": "MissingAuthHeader", "description": "x-firmly-authorization header is missing or invalid." } ``` **400 — InvalidToken** The authorization token is not a valid JWT structure. ```json { "code": 400, "error": "InvalidToken", "description": "Jwt token is invalid." } ``` **400 — InvalidAPIToken** The API token (server-to-server secret) is invalid or has been revoked. ```json { "code": 400, "error": "InvalidAPIToken", "description": "API token is invalid." } ``` **400 — BadRequest** All of these conditions share the same `error` (`BadRequest`) and `code` (`400`), so the `description` is the only way to tell them apart. Unlike consent-object descriptions (which are merchant-authored display text and may change), these `BadRequest` descriptions are Firmly-emitted and stable enough to branch on. Prefer matching on a stable substring (e.g. `invalid`, `non revokable`, `no consents`) rather than the whole string: - **No consents available** — the session has no consents to sign. Call [Get Consents](/api-reference/checkout/get-consents) first. ```json { "code": 400, "error": "BadRequest", "description": "There are no consents to sign" } ``` - **Unknown consent IDs** — one or more `id`s in the request body do not match any consent from Get Consents. Description lists the offending IDs. ```json { "code": 400, "error": "BadRequest", "description": "The consents , are invalid." } ``` - **Attempt to revoke a non-revokable consent** — at least one consent has `revokable: false`. Description lists the offending IDs. ```json { "code": 400, "error": "BadRequest", "description": "The consents are non revokable" } ``` - **Server-to-server auth headers missing or malformed** (different code path, same wire error). ```json { "code": 400, "error": "BadRequest", "description": "Bad request." } ``` **401 — Unauthorized** The authorization token was rejected. ```json { "code": 401, "error": "Unauthorized", "description": "Unauthorized." } ``` **401 — InvalidJWTToken** The device JWT signature does not verify, or required claims are missing. ```json { "code": 401, "error": "InvalidJWTToken", "description": "Jwt token is invalid." } ``` **404 — PartnerNotFound** The `appid` claim on the device JWT does not map to a known partner / tenant. ```json { "code": 404, "error": "PartnerNotFound", "description": "Partner not found." } ``` **404 — DomainNotFound** The `{domain}` path parameter does not match any merchant configured with Firmly, or the merchant has been disabled. ```json { "code": 404, "error": "DomainNotFound", "description": "This domain was not found in firmly servers." } ``` **412 — OperationNotSupported** The merchant's platform does not support this operation. ```json { "code": 412, "error": "OperationNotSupported", "description": "This operation is not supported for this store." } ``` **400 — InvalidInputBody** Request body fails schema validation. Each entry under `consents` must have a `string` `id`; `revoke` is optional and boolean. ```json { "code": 400, "error": "InvalidInputBody", "description": "The body is not processable" } ``` --- # Set Fulfillment Type `POST https://api.firmly.work/api/v2/domains/{domain}/cart/shipments/fulfillment-type` Switch a shipment's fulfillment type. Each shipment exposes the values you can set via its `fulfillment_type_options` array. The shipment is initialized with the merchant's default after [Set Shipping Info](/api-reference/checkout/set-shipping-info); call this endpoint only when the buyer wants a different option. ## Authentication - `x-firmly-authorization` (string, required) — Device access token from [Browser Session](/api-reference/authentication/browser-session) > **Note** > This endpoint also accepts **server-to-server (S2S) authentication** for backend integrations acting on behalf of a device: send `Authorization: Bearer ` (or the equivalent `x-firmly-authorization: `) together with `x-firmly-device-id`. See [Server-to-Server Authentication](/api-reference/authentication/server-to-server). ## Path Parameters - `domain` (string, required) — The merchant's domain (e.g. `staging.luma.gift`). ## Request Body - `shipment_id` (string, required) — Target shipment identifier (from the cart's `shipments[].shipment_id`). - `fulfillment_type` (string, required) — New fulfillment method. One of: - `SHIP_TO_ADDRESS` - `SCHEDULED_DELIVERY` - `PICKUP_IN_STORE` Must also be present in the target shipment's `fulfillment_type_options`; otherwise the request returns `400 InvalidFulfillmentType`. - `location_id` (string) — Store location identifier. Required when `fulfillment_type` is `PICKUP_IN_STORE`. ## Response Returns the full cart — same schema as [Get Cart](/api-reference/cart-management/get-cart). The target shipment's `fulfillment_type` is updated (and, for `PICKUP_IN_STORE`, its `selected_location`); `shipping_method_options` are refreshed for the new type and cart totals are recalculated. - `shipments` (object[]) — The cart's shipments. Each shipment has the shape below. **Shipment** - `shipment_id` (string, required) — Unique shipment identifier. - `platform_shipment_id` (string) — Merchant-side shipment identifier, when available. - `line_item_ids` (string[], required) — IDs of the line items grouped into this shipment. - `fulfillment_type` (object, required) — The selected fulfillment type. - `id` (string, required) — One of `SHIP_TO_ADDRESS`, `SCHEDULED_DELIVERY`, `PICKUP_IN_STORE`. - `name` (string, required) — Display name. - `description` (string, required) — Description. - `fulfillment_type_options` (object[]) — Fulfillment types available for this shipment (same shape as `fulfillment_type`). - `shipping_method_options` (object[]) — Shipping methods available for the selected fulfillment type (same shape as `shipping_method`). - `shipping_method` (object) — The selected shipping method, when one is set. **shipping_method** - `id` (string, required) — Method identifier. - `description` (string, required) — Method description. - `price` (object) — Cost (Amount). Required unless `hide_price` is `true`. - `hide_price` (boolean) — When `true`, suppress the price in the UI. - `message` (string) — Optional merchant note about this method. - `estimated_delivery` (string) — Delivery estimate. - `selected_location` (object) — Pickup location — present for `PICKUP_IN_STORE`. **selected_location** - `location_id` (string, required) — Location identifier. - `name` (string, required) — Location name. - `address` (object, required) — Location address (same fields as a shipping address). - `phone` (string) — Location phone number. - `operating_hours` (object[]) — Per-day hours: `{ day, open_time, close_time, is_closed? }`. - `distance` (object) — Distance from the buyer: `{ value, unit, formatted }`. - `pickup_options` (object[]) — Available pickup dates/slots: `{ date, time_slots }`. - `selected_date` (string) — Selected delivery date for `SCHEDULED_DELIVERY` (`YYYY-MM-DD`). - `selected_time_slot` (object) — Selected time slot for `SCHEDULED_DELIVERY`: `{ slot_id?, start_time, end_time, description?, price? }`. - `pickup_option` (object) — Selected pickup option: `{ id, description, price? }`. - `notes` (string) — Delivery notes for this shipment. - `shipping_total` (object) — Total shipping cost across all shipments (Amount). - `tax_total` (object) — Total tax (Amount). - `total` (object) — Grand total (Amount). ## Examples **Switch to Standard Shipping** ```bash curl -X POST https://api.firmly.work/api/v2/domains/staging.luma.gift/cart/shipments/fulfillment-type \ -H "x-firmly-authorization: YOUR_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "shipment_id": "8568658c-bee9-9666-4547-a545fe27391b", "fulfillment_type": "SHIP_TO_ADDRESS" }' ``` **Switch to Scheduled Delivery** ```bash curl -X POST https://api.firmly.work/api/v2/domains/staging.luma.gift/cart/shipments/fulfillment-type \ -H "x-firmly-authorization: YOUR_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "shipment_id": "840b0477-b913-191a-2b4f-dc232a779f0c", "fulfillment_type": "SCHEDULED_DELIVERY" }' ``` **Switch to Store Pickup** ```bash curl -X POST https://api.firmly.work/api/v2/domains/staging.luma.gift/cart/shipments/fulfillment-type \ -H "x-firmly-authorization: YOUR_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "shipment_id": "8568658c-bee9-9666-4547-a545fe27391b", "fulfillment_type": "PICKUP_IN_STORE", "location_id": "store-downtown-001" }' ``` The response below corresponds to the **Switch to Standard Shipping** example above — the target shipment's `fulfillment_type` is now `SHIP_TO_ADDRESS`. ## Response Example ```json { "cart_id": "a5600193-2c13-3356-d063-711da63b7cd7", "platform_id": "example_commerce", "shop_id": "staging.luma.gift", "display_name": "Luma Store", "cart_status": "active", "line_items": [ { "line_item_id": "c62279b9-3a72-0bbd-1377-be0033ad23dd", "platform_line_item_id": "0", "sku": "MH07-XS-Gray", "description": "Hero Hoodie", "base_sku": "MH07", "quantity": 2, "price": { "currency": "USD", "value": 49.99, "number": 4999, "symbol": "$" }, "line_price": { "currency": "USD", "value": 99.98, "number": 9998, "symbol": "$" }, "msrp": { "currency": "USD", "value": 49.99, "number": 4999, "symbol": "$" }, "image": { "url": "https://cdn.staging.luma.gift/hero-hoodie.jpg", "alt": "Hero Hoodie", "type": "default" }, "requires_shipping": true } ], "shipments": [ { "shipment_id": "8568658c-bee9-9666-4547-a545fe27391b", "line_item_ids": ["c62279b9-3a72-0bbd-1377-be0033ad23dd"], "fulfillment_type": { "id": "SHIP_TO_ADDRESS", "name": "Ship to Address", "description": "Standard shipping to your address" }, "fulfillment_type_options": [ { "id": "SHIP_TO_ADDRESS", "name": "Ship to Address", "description": "Standard shipping to your address" }, { "id": "SCHEDULED_DELIVERY", "name": "Scheduled Delivery", "description": "Choose a delivery date and time" } ], "shipping_method_options": [ { "id": "STANDARD_GROUND", "description": "Standard Ground", "price": { "currency": "USD", "value": 9.99, "number": 999, "symbol": "$" }, "estimated_delivery": "5-7 business days" }, { "id": "EXPRESS_2DAY", "description": "2-Day Express", "price": { "currency": "USD", "value": 19.99, "number": 1999, "symbol": "$" }, "estimated_delivery": "2 business days" } ], "shipping_method": null, "notes": "" } ], "sub_total": { "currency": "USD", "value": 99.98, "number": 9998, "symbol": "$" }, "shipping_total": { "currency": "USD", "value": 0, "number": 0, "symbol": "$" }, "tax_total": { "currency": "USD", "value": 8.00, "number": 800, "symbol": "$" }, "fees": [ { "description": "Recycle fee", "currency": "USD", "value": 2.00, "number": 200, "symbol": "$" } ], "fee_total": { "currency": "USD", "value": 2.00, "number": 200, "symbol": "$" }, "total": { "currency": "USD", "value": 109.98, "number": 10998, "symbol": "$" }, "addons": { "offers": [], "selections": [] }, "addon_total": { "currency": "USD", "value": 0, "number": 0, "symbol": "$" }, "payment_method_options": [ { "type": "CreditCard", "wallet": "user" }, { "type": "PayPal", "wallet": "paypal" } ], "schema_version": "2.0" } ``` ## Multi-Shipment Each shipment in the cart carries its own `fulfillment_type`. A cart with multiple shipments can mix types — for example, heavy items on `SCHEDULED_DELIVERY` while small items ship via `SHIP_TO_ADDRESS`, or items picked up at different store locations. Call this endpoint once per shipment. ## Next Steps - `SHIP_TO_ADDRESS` or `SCHEDULED_DELIVERY` → [Set Shipping Method](/api-reference/shipment-configuration/set-shipping-method) (pass `selected_date` / `selected_time_slot` for `SCHEDULED_DELIVERY`). - `SCHEDULED_DELIVERY` (before the above) → [Get Availability](/api-reference/shipment-configuration/get-availability) to retrieve eligible dates and time slots. - `PICKUP_IN_STORE` → no further call required; `location_id` is already set in this request. ## Error Responses Errors return a JSON body with `code`, `error`, and `description`. Program against the `error` value — descriptions are human-readable and may change. **400 — MissingAuthHeader** The `x-firmly-authorization` header is missing or empty. ```json { "code": 400, "error": "MissingAuthHeader", "description": "x-firmly-authorization header is missing or invalid." } ``` **400 — InvalidToken** The authorization token is not a valid JWT structure. ```json { "code": 400, "error": "InvalidToken", "description": "Jwt token is invalid." } ``` **400 — InvalidAPIToken** The API token (server-to-server secret) is invalid or has been revoked. ```json { "code": 400, "error": "InvalidAPIToken", "description": "API token is invalid." } ``` **400 — BadRequest** Server-to-server auth was attempted but required headers are missing or malformed. ```json { "code": 400, "error": "BadRequest", "description": "Bad request." } ``` **400 — InvalidFulfillmentType** The supplied `fulfillment_type` is not in the target shipment's `fulfillment_type_options`. ```json { "code": 400, "error": "InvalidFulfillmentType", "description": "Invalid fulfillment type." } ``` **401 — Unauthorized** The authorization token was rejected. ```json { "code": 401, "error": "Unauthorized", "description": "Unauthorized." } ``` **401 — InvalidJWTToken** The device JWT signature does not verify, or required claims are missing. ```json { "code": 401, "error": "InvalidJWTToken", "description": "Jwt token is invalid." } ``` **404 — PartnerNotFound** The `appid` claim on the device JWT does not map to a known partner / tenant. ```json { "code": 404, "error": "PartnerNotFound", "description": "Partner not found." } ``` **404 — DomainNotFound** The `{domain}` path parameter does not match any merchant configured with Firmly, or the merchant has been disabled. ```json { "code": 404, "error": "DomainNotFound", "description": "This domain was not found in firmly servers." } ``` **404 — CartNotFound** No cart exists for this device on this domain. ```json { "code": 404, "error": "CartNotFound", "description": "Cart was not found." } ``` **404 — ShipmentNotFound** The supplied `shipment_id` does not match any shipment on the current cart. Re-read the cart to obtain a current id. ```json { "code": 404, "error": "ShipmentNotFound", "description": "Shipment not found." } ``` **404 — LocationNotFound** The supplied `location_id` is not a valid pickup location for this merchant. Returned only when `fulfillment_type` is `PICKUP_IN_STORE`. ```json { "code": 404, "error": "LocationNotFound", "description": "Location not found." } ``` **412 — OperationNotSupported** The merchant's platform does not support this operation. ```json { "code": 412, "error": "OperationNotSupported", "description": "This operation is not supported for this store." } ``` **400 — InvalidInputBody** Request body fails schema validation. Ensure `shipment_id` is a non-empty string and `fulfillment_type` is one of `SHIP_TO_ADDRESS`, `SCHEDULED_DELIVERY`, `PICKUP_IN_STORE`. ```json { "code": 400, "error": "InvalidInputBody", "description": "The body is not processable" } ``` **422 — UnprocessableEntity** The request is well-formed but cannot be processed — typically because the merchant API rejected the fulfillment-type change for a reason not covered by the more specific errors above. ```json { "code": 422, "error": "UnprocessableEntity", "description": "The given payload has unprocessable, invalid or non-existent data. Please check the data and try again." } ``` **501 — NotImplemented** The merchant adapter is V1 and does not support this endpoint. Use V2 endpoints, or set the fulfillment configuration via [Set Shipping Method](/api-reference/shipment-configuration/set-shipping-method) where supported. ```json { "code": 501, "error": "NotImplemented", "description": "Operation not implemented." } ``` **503 — StoreUnavailable** The merchant's API returned an unexpected response and the request could not be fulfilled. Retry with backoff. ```json { "code": 503, "error": "StoreUnavailable", "description": "Store is unavailable." } ``` --- # Set Postal Code `POST https://api.firmly.work/api/v2/carts/postal-code` Stores a postal code on the global session for the authenticated device. The value is reused across every merchant cart on this session; it is **not** scoped to a specific domain. This endpoint takes no `{domain}` parameter. The postal code is consumed by per-merchant endpoints that gate behavior on it (e.g. [Add Line Item](/api-reference/cart-management/add-line-item) returns `412 PostalCodeRequired` for merchants that require a postal code before adding items). ## Authentication - `x-firmly-authorization` (string, required) — Device access token from [Browser Session](/api-reference/authentication/browser-session) - **Server-to-server (S2S) auth is not accepted** — this is a device-scoped session route. It requires a device JWT from [Browser Session](/api-reference/authentication/browser-session); the S2S secret is rejected. See [Server-to-Server Authentication](/api-reference/authentication/server-to-server). ## Request Body - `postal_code` (string, required) — The postal code to store. No format validation is enforced server-side — pass the value the merchant expects (US ZIP, Canadian / UK postcode, etc.). ## Response - `postal_code` (string) — The value that was stored. ## Examples **cURL** ```bash curl -X POST https://api.firmly.work/api/v2/carts/postal-code \ -H "x-firmly-authorization: YOUR_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "postal_code": "90210" }' ``` **JavaScript** ```javascript const response = await fetch('https://api.firmly.work/api/v2/carts/postal-code', { method: 'POST', headers: { 'x-firmly-authorization': 'YOUR_TOKEN', 'Content-Type': 'application/json' }, body: JSON.stringify({ postal_code: '90210' }) }); const { postal_code } = await response.json(); ``` **Python** ```python import requests response = requests.post( 'https://api.firmly.work/api/v2/carts/postal-code', headers={ 'x-firmly-authorization': 'YOUR_TOKEN', 'Content-Type': 'application/json' }, json={'postal_code': '90210'} ) data = response.json() ``` ## Response Example ```json { "postal_code": "90210" } ``` ## Error Responses Errors return a JSON body with `code`, `error`, and `description`. Program against the `error` value — descriptions are human-readable and may change. **400 — MissingAuthHeader** The `x-firmly-authorization` header is missing or empty. ```json { "code": 400, "error": "MissingAuthHeader", "description": "x-firmly-authorization header is missing or invalid." } ``` **400 — InvalidToken** The authorization token is not a valid JWT structure. ```json { "code": 400, "error": "InvalidToken", "description": "Jwt token is invalid." } ``` **401 — InvalidJWTToken** The device JWT signature does not verify, or required claims are missing. ```json { "code": 401, "error": "InvalidJWTToken", "description": "Jwt token is invalid." } ``` **404 — PartnerNotFound** The `appid` claim on the device JWT does not map to a known partner / tenant. ```json { "code": 404, "error": "PartnerNotFound", "description": "Partner not found." } ``` **400 — InvalidInputBody** The request body failed schema validation — `postal_code` is missing, `null`, or not a string. ```json { "code": 400, "error": "InvalidInputBody", "description": "The body is not processable" } ``` --- # Set Shipping Info `POST https://api.firmly.work/api/v2/domains/{domain}/cart/shipping-info` ## Overview Sets buyer shipping information for cart delivery. The endpoint validates the address, calculates shipping costs based on available shipping methods, and updates cart totals. It supports multi-shipment scenarios where different items may ship from different locations. ## Authentication - `x-firmly-authorization` (string, required) — Device access token from [Browser Session](/api-reference/authentication/browser-session) > **Note** > This endpoint also accepts **server-to-server (S2S) authentication** for backend integrations acting on behalf of a device: send `Authorization: Bearer ` (or the equivalent `x-firmly-authorization: `) together with `x-firmly-device-id`. See [Server-to-Server Authentication](/api-reference/authentication/server-to-server). ## Path Parameters - `domain` (string, required) — Domain of the merchant website (e.g., `staging.luma.gift`) ## Request Body - `first_name` (string, required) — Buyer's first name - `last_name` (string, required) — Buyer's last name - `address1` (string, required) — Primary address line (street address) - `address2` (string) — Secondary address line (apartment, suite, unit, etc.) - `city` (string, required) — City name - `state_or_province` (string, required) — State or province code (e.g., "CA", "NY") or full name - `postal_code` (string, required) — ZIP or postal code - `country` (string, required) — Country code in ISO 3166-1 alpha-2 format (e.g., "US", "CA") - `phone` (string, required) — Contact phone number for delivery - `email` (string, required) — Contact email address ## Response Returns a complete [ShoppingCart](/api-reference/cart-management/get-cart) object with: - Updated shipping information - Calculated shipping costs per shipment - Updated tax calculations based on shipping address - Recalculated cart totals ## Multi-Shipment Behavior The shipping address applies to all shipments in the cart. Key behaviors: 1. **Address Application**: The provided address is used for all shipments 2. **Shipping Calculation**: Each shipment's shipping cost is calculated independently 3. **Tax**: The merchant's platform recalculates tax for the shipping destination and returns it in the cart 4. **Validation**: Address is validated against merchant's supported regions ## Code Examples **cURL** ```bash curl -X POST https://api.firmly.work/api/v2/domains/staging.luma.gift/cart/shipping-info \ -H "x-firmly-authorization: YOUR_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "first_name": "John", "last_name": "Smith", "address1": "123 Main Street", "address2": "Apt 4B", "city": "Anytown", "state_or_province": "CA", "postal_code": "12345", "country": "US", "phone": "555-123-4567", "email": "john.smith@staging.luma.gift" }' ``` **JavaScript** ```javascript const shippingInfo = { first_name: "John", last_name: "Smith", address1: "123 Main Street", address2: "Apt 4B", city: "Anytown", state_or_province: "CA", postal_code: "12345", country: "US", phone: "555-123-4567", email: "john.smith@staging.luma.gift" }; const response = await fetch('https://api.firmly.work/api/v2/domains/staging.luma.gift/cart/shipping-info', { method: 'POST', headers: { 'x-firmly-authorization': 'YOUR_TOKEN', 'Content-Type': 'application/json' }, body: JSON.stringify(shippingInfo) }); const updatedCart = await response.json(); ``` **Python** ```python import requests shipping_info = { "first_name": "John", "last_name": "Smith", "address1": "123 Main Street", "address2": "Apt 4B", "city": "Anytown", "state_or_province": "CA", "postal_code": "12345", "country": "US", "phone": "555-123-4567", "email": "john.smith@staging.luma.gift" } response = requests.post( 'https://api.firmly.work/api/v2/domains/staging.luma.gift/cart/shipping-info', headers={ 'x-firmly-authorization': 'YOUR_TOKEN', 'Content-Type': 'application/json' }, json=shipping_info ) updated_cart = response.json() ``` **PHP** ```php $shippingInfo = [ 'first_name' => 'John', 'last_name' => 'Smith', 'address1' => '123 Main Street', 'address2' => 'Apt 4B', 'city' => 'Anytown', 'state_or_province' => 'CA', 'postal_code' => '12345', 'country' => 'US', 'phone' => '555-123-4567', 'email' => 'john.smith@staging.luma.gift' ]; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, 'https://api.firmly.work/api/v2/domains/staging.luma.gift/cart/shipping-info'); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'x-firmly-authorization: YOUR_TOKEN', 'Content-Type: application/json' ]); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($shippingInfo)); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); $updatedCart = json_decode($response, true); curl_close($ch); ``` ## Response Example ```json { "line_items": [ { "line_item_id": "a02a3e67-b50e-8dcd-5970-8fff52117e43", "sku": "WS12-XS-Orange", "description": "Radiant Tee", "quantity": 2, "price": { "currency": "USD", "value": 22.0, "number": 2200, "symbol": "$" }, "line_price": { "currency": "USD", "value": 44.0, "number": 4400, "symbol": "$" }, "msrp": { "currency": "USD", "value": 26.4, "number": 2640, "symbol": "$" }, "image": { "url": "https://staging.luma.gift/radiant-tee.jpg", "alt": "Radiant Tee", "type": "default" } } ], "shipments": [ { "shipment_id": "8568658c-bee9-9666-4547-a545fe27391b", "line_item_ids": [ "a02a3e67-b50e-8dcd-5970-8fff52117e43" ], "fulfillment_type": { "id": "SHIP_TO_ADDRESS", "name": "Ship to Address", "description": "Standard shipping to your address" }, "shipping_method": { "id": "STANDARD_GROUND", "description": "Standard Ground (5-7 business days)", "price": { "currency": "USD", "value": 9.99, "number": 999, "symbol": "$" }, "estimated_delivery": "5-7 business days" } } ], "shipping_info": { "first_name": "John", "last_name": "Smith", "address1": "123 Main Street", "address2": "Apt 4B", "city": "Anytown", "state_or_province": "CA", "postal_code": "12345", "country": "US", "phone": "555-123-4567", "email": "john.smith@staging.luma.gift" }, "sub_total": { "currency": "USD", "value": 44.0, "number": 4400, "symbol": "$" }, "shipping_total": { "currency": "USD", "value": 9.99, "number": 999, "symbol": "$" }, "tax_total": { "currency": "USD", "value": 4.4, "number": 440, "symbol": "$" }, "fees": [ { "description": "Recycle fee", "currency": "USD", "value": 2.00, "number": 200, "symbol": "$" } ], "fee_total": { "currency": "USD", "value": 2.00, "number": 200, "symbol": "$" }, "total": { "currency": "USD", "value": 60.39, "number": 6039, "symbol": "$" }, "schema_version": "2.0" } ``` --- ## Related Operations After setting shipping information, typical next steps include: - [Set Billing Info](/api-reference/checkout/set-billing-info) — Add billing address - [Set Consents](/api-reference/checkout/set-consents) — Update consent preferences - [Complete Order](/api-reference/payment/complete-order-v2) — Complete the purchase ## Error Responses Errors return a JSON body with `code`, `error`, and `description`. Program against the `error` value — descriptions are human-readable and may change. **400 — MissingAuthHeader** The `x-firmly-authorization` header is missing or empty. ```json { "code": 400, "error": "MissingAuthHeader", "description": "x-firmly-authorization header is missing or invalid." } ``` **400 — InvalidToken** The authorization token is not a valid JWT structure. ```json { "code": 400, "error": "InvalidToken", "description": "Jwt token is invalid." } ``` **400 — InvalidAPIToken** The API token (server-to-server secret) is invalid or has been revoked. ```json { "code": 400, "error": "InvalidAPIToken", "description": "API token is invalid." } ``` **400 — BadRequest** Server-to-server auth was attempted but required headers are missing or malformed. ```json { "code": 400, "error": "BadRequest", "description": "Bad request." } ``` **400 — InvalidShippingInfo** Address fields fail merchant-level validation (e.g. PO Box where prohibited, line length exceeded, format rejected by the merchant). ```json { "code": 400, "error": "InvalidShippingInfo", "description": "Invalid shipping info." } ``` **400 — InvalidState** The `state_or_province` value is not valid for the given `country` (e.g. `"ZZ"` for `country: "US"`). ```json { "code": 400, "error": "InvalidState", "description": "Invalid state." } ``` **400 — ErrorInvalidEmail** The `email` field is not a syntactically valid email address. ```json { "code": 400, "error": "ErrorInvalidEmail", "description": "Invalid email." } ``` **400 — ShippingNotNeeded** The cart contains only items that do not require shipping (e.g. digital-only). Skip this endpoint. ```json { "code": 400, "error": "ShippingNotNeeded", "description": "Shipping is not needed." } ``` **401 — Unauthorized** The authorization token was rejected. ```json { "code": 401, "error": "Unauthorized", "description": "Unauthorized." } ``` **401 — InvalidJWTToken** The device JWT signature does not verify, or required claims are missing. ```json { "code": 401, "error": "InvalidJWTToken", "description": "Jwt token is invalid." } ``` **404 — PartnerNotFound** The `appid` claim on the device JWT does not map to a known partner / tenant. ```json { "code": 404, "error": "PartnerNotFound", "description": "Partner not found." } ``` **404 — DomainNotFound** The `{domain}` path parameter does not match any merchant configured with Firmly, or the merchant has been disabled. ```json { "code": 404, "error": "DomainNotFound", "description": "This domain was not found in firmly servers." } ``` **404 — CartNotFound** No cart exists for this device on this domain. Add an item first via [Add Line Item](/api-reference/cart-management/add-line-item). ```json { "code": 404, "error": "CartNotFound", "description": "Cart was not found." } ``` **409 — ShipmentNotAvailable** No shipping method is available for the supplied address — usually because the merchant does not ship to that region or the cart contents are restricted there. > **Tip** > `ShipmentNotAvailable` is about the address: retry with a different address. `ShippingAddressNotSupported` (below) is the same signal for an unsupported address, whereas item-level restrictions surface as `412 ProductNotSupported` — for those, remove the restricted item rather than changing the address. ```json { "code": 409, "error": "ShipmentNotAvailable", "description": "Shipment is not available." } ``` **409 — ShippingAddressNotSupported** The supplied address is rejected by the merchant for reasons beyond country/state validation (e.g. APO/FPO, US territories, embargoed regions). Retry with a different address. ```json { "code": 409, "error": "ShippingAddressNotSupported", "description": "Shipping address is not supported." } ``` **409 — MultipleDiscountCodesNotSupported** Setting shipping triggered a re-evaluation of cart promotions and the merchant rejected the combination of currently-applied discount codes. Remove one or more promos and retry. ```json { "code": 409, "error": "MultipleDiscountCodesNotSupported", "description": "Multiple discount codes are not supported." } ``` **409 — NotEnoughStockError** One or more line items no longer have enough stock after the shipping update. Lower the quantity or remove the item, then retry. ```json { "code": 409, "error": "NotEnoughStockError", "description": "The amount of the required item is not available in stock." } ``` **412 — CountryNotSupported** The merchant does not ship to the supplied `country`. Use one of the merchant's supported countries. ```json { "code": 412, "error": "CountryNotSupported", "description": "Country is not supported." } ``` **412 — ProductNotSupported** One or more items in the cart cannot be shipped to the supplied address (e.g. age-restricted, hazardous, region-locked). ```json { "code": 412, "error": "ProductNotSupported", "description": "Product is not supported." } ``` **412 — NoLineItemError** The cart is empty after the merchant call — typically the merchant rejected the cart contents on shipping update. Refresh cart state. ```json { "code": 412, "error": "NoLineItemError", "description": "No line item." } ``` **412 — OperationNotSupported** The merchant's platform does not support this operation. ```json { "code": 412, "error": "OperationNotSupported", "description": "This operation is not supported for this store." } ``` **400 — InvalidInputBody** Request body fails schema validation. Ensure all required fields (`first_name`, `last_name`, `address1`, `city`, `state_or_province`, `postal_code`, `country`, `phone`, `email`) are present and well-formed. ```json { "code": 400, "error": "InvalidInputBody", "description": "The body is not processable" } ``` **429 — RateLimited** Too many requests in a short window. Back off and retry, honoring the `Retry-After` header. ```json { "code": 429, "error": "RateLimited", "description": "Too many requests. Please try again later." } ``` **503 — StoreUnavailable** The merchant's API returned an unexpected response and the request could not be fulfilled. Retry with backoff. ```json { "code": 503, "error": "StoreUnavailable", "description": "Store is unavailable." } ``` --- # Set Shipping Method `POST https://api.firmly.work/api/v2/domains/{domain}/cart/shipment/methods` Select a shipping method on a specific shipment. The cart returned in the response carries updated shipping cost, tax, and totals. After [Set Shipping Info](/api-reference/checkout/set-shipping-info), each shipment is initialized with the merchant's default method; call this endpoint when the buyer wants a different one — and, for `SCHEDULED_DELIVERY` shipments, to record the selected date/time slot. ## Authentication - `x-firmly-authorization` (string, required) — Device access token from [Browser Session](/api-reference/authentication/browser-session) > **Note** > This endpoint also accepts **server-to-server (S2S) authentication** for backend integrations acting on behalf of a device: send `Authorization: Bearer ` (or the equivalent `x-firmly-authorization: `) together with `x-firmly-device-id`. See [Server-to-Server Authentication](/api-reference/authentication/server-to-server). ## Path Parameters - `domain` (string, required) — The merchant's domain (e.g. `staging.luma.gift`). ## Request Body - `shipment_id` (string, required) — Target shipment identifier (from the cart's `shipments[].shipment_id`). - `shipping_method_id` (string, required) — ID of the method to select. Must match an entry in the shipment's `shipping_method_options[*].id`. - `notes` (string) — Optional delivery instructions for this shipment. - `selected_date` (string) — For `SCHEDULED_DELIVERY` shipments — the chosen date in `YYYY-MM-DD` format. - `selected_time_slot` (string) — For `SCHEDULED_DELIVERY` shipments — the chosen time-slot identifier (the `slot_id` from [Get Availability](/api-reference/shipment-configuration/get-availability)). Send the `slot_id` string here; the response echoes the full slot object back on the shipment's `selected_time_slot`. ## Response Returns the full cart — same schema as [Get Cart](/api-reference/cart-management/get-cart). The target shipment's `shipping_method` is set (plus `notes`, and `selected_date` / `selected_time_slot` for `SCHEDULED_DELIVERY`); cart totals are recalculated. - `shipments` (object[]) — The cart's shipments. Each shipment has the shape below. **Shipment** - `shipment_id` (string, required) — Unique shipment identifier. - `platform_shipment_id` (string) — Merchant-side shipment identifier, when available. - `line_item_ids` (string[], required) — IDs of the line items grouped into this shipment. - `fulfillment_type` (object, required) — The selected fulfillment type: `{ id, name, description }`, where `id` is one of `SHIP_TO_ADDRESS`, `SCHEDULED_DELIVERY`, `PICKUP_IN_STORE`. - `fulfillment_type_options` (object[]) — Fulfillment types available for this shipment (same shape as `fulfillment_type`). - `shipping_method` (object) — The selected shipping method. - `id` (string, required) — Method identifier. - `description` (string, required) — Method description. - `price` (object) — Cost (Amount). Required unless `hide_price` is `true`. - `hide_price` (boolean) — When `true`, suppress the price in the UI. - `message` (string) — Optional merchant note about this method. - `estimated_delivery` (string) — Delivery estimate. - `shipping_method_options` (object[]) — Shipping methods available for this shipment (same shape as `shipping_method`). - `selected_location` (object) — Pickup location — present for `PICKUP_IN_STORE`. `{ location_id, name, address, phone?, operating_hours?, distance?, pickup_options }`. - `selected_date` (string) — Selected delivery date for `SCHEDULED_DELIVERY` (`YYYY-MM-DD`). - `selected_time_slot` (object) — Selected time slot for `SCHEDULED_DELIVERY`: `{ slot_id?, start_time, end_time, description?, price? }`. - `pickup_option` (object) — Selected pickup option: `{ id, description, price? }`. - `notes` (string) — Delivery notes persisted on this shipment. - `shipping_total` (object) — Total shipping cost across all shipments (Amount). - `tax_total` (object) — Total tax (Amount). - `total` (object) — Grand total (Amount). > **Note** > Shipping method IDs are merchant-defined and case-sensitive. Always use a value taken from the current cart's `shipping_method_options`. > **Note** > This route is singular — `/cart/shipment/methods` — while its sibling shipment routes are plural (`/cart/shipments/fulfillment-type`, `/cart/shipments/get-availability`). This is intentional; do not "correct" it to `/cart/shipments/methods` or you will get a 404. ## Examples **Express 2-Day** ```bash curl -X POST https://api.firmly.work/api/v2/domains/staging.luma.gift/cart/shipment/methods \ -H "x-firmly-authorization: YOUR_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "shipment_id": "8568658c-bee9-9666-4547-a545fe27391b", "shipping_method_id": "express-2day", "notes": "Please leave at front door if no answer" }' ``` **Scheduled Delivery** ```bash curl -X POST https://api.firmly.work/api/v2/domains/staging.luma.gift/cart/shipment/methods \ -H "x-firmly-authorization: YOUR_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "shipment_id": "840b0477-b913-191a-2b4f-dc232a779f0c", "shipping_method_id": "white-glove-setup", "selected_date": "2026-06-15", "selected_time_slot": "morning-premium", "notes": "Please call 30 minutes before delivery" }' ``` ## Response Example ```json { "cart_id": "a5600193-2c13-3356-d063-711da63b7cd7", "platform_id": "example_commerce", "shop_id": "staging.luma.gift", "cart_status": "active", "line_items": [ { "line_item_id": "c62279b9-3a72-0bbd-1377-be0033ad23dd", "sku": "WS12-XS-Orange", "description": "Radiant Tee", "quantity": 2, "price": { "currency": "USD", "value": 22.0, "number": 2200, "symbol": "$" }, "line_price": { "currency": "USD", "value": 44.0, "number": 4400, "symbol": "$" }, "msrp": { "currency": "USD", "value": 26.4, "number": 2640, "symbol": "$" }, "image": { "url": "https://staging.luma.gift/radiant-tee.jpg", "alt": "Radiant Tee", "type": "default" } } ], "shipments": [ { "shipment_id": "8568658c-bee9-9666-4547-a545fe27391b", "line_item_ids": [ "c62279b9-3a72-0bbd-1377-be0033ad23dd" ], "fulfillment_type": { "id": "SHIP_TO_ADDRESS", "name": "Ship to Address", "description": "Standard shipping to your address" }, "shipping_method_options": [ { "id": "standard-ground", "description": "Standard Ground Shipping", "price": { "currency": "USD", "value": 9.99, "number": 999, "symbol": "$" }, "estimated_delivery": "5-7 business days" }, { "id": "express-2day", "description": "Express 2-Day Shipping", "price": { "currency": "USD", "value": 19.99, "number": 1999, "symbol": "$" }, "estimated_delivery": "2 business days" } ], "shipping_method": { "id": "express-2day", "description": "Express 2-Day Shipping", "price": { "currency": "USD", "value": 19.99, "number": 1999, "symbol": "$" }, "estimated_delivery": "2 business days" }, "notes": "Please leave at front door if no answer" } ], "sub_total": { "currency": "USD", "value": 44.0, "number": 4400, "symbol": "$" }, "shipping_total": { "currency": "USD", "value": 19.99, "number": 1999, "symbol": "$" }, "tax_total": { "currency": "USD", "value": 4.4, "number": 440, "symbol": "$" }, "fees": [ { "description": "Recycle fee", "currency": "USD", "value": 2.00, "number": 200, "symbol": "$" } ], "fee_total": { "currency": "USD", "value": 2.00, "number": 200, "symbol": "$" }, "total": { "currency": "USD", "value": 70.39, "number": 7039, "symbol": "$" }, "schema_version": "2.0" } ``` ## Error Responses Errors return a JSON body with `code`, `error`, and `description`. Program against the `error` value — descriptions are human-readable and may change. **400 — MissingAuthHeader** The `x-firmly-authorization` header is missing or empty. ```json { "code": 400, "error": "MissingAuthHeader", "description": "x-firmly-authorization header is missing or invalid." } ``` **400 — InvalidToken** The authorization token is not a valid JWT structure. ```json { "code": 400, "error": "InvalidToken", "description": "Jwt token is invalid." } ``` **400 — InvalidAPIToken** The API token (server-to-server secret) is invalid or has been revoked. ```json { "code": 400, "error": "InvalidAPIToken", "description": "API token is invalid." } ``` **400 — BadRequest** Server-to-server auth was attempted but required headers are missing or malformed. ```json { "code": 400, "error": "BadRequest", "description": "Bad request." } ``` **400 — InvalidShippingMethod** The supplied `shipping_method_id` is not in the shipment's `shipping_method_options`. ```json { "code": 400, "error": "InvalidShippingMethod", "description": "Invalid shipping method." } ``` **400 — InvalidDeliveryDate** The supplied `selected_date` and/or `selected_time_slot` is not available for this shipment. ```json { "code": 400, "error": "InvalidDeliveryDate", "description": "Invalid delivery date." } ``` **401 — Unauthorized** The authorization token was rejected. ```json { "code": 401, "error": "Unauthorized", "description": "Unauthorized." } ``` **401 — InvalidJWTToken** The device JWT signature does not verify, or required claims are missing. ```json { "code": 401, "error": "InvalidJWTToken", "description": "Jwt token is invalid." } ``` **404 — PartnerNotFound** The `appid` claim on the device JWT does not map to a known partner / tenant. ```json { "code": 404, "error": "PartnerNotFound", "description": "Partner not found." } ``` **404 — DomainNotFound** The `{domain}` path parameter does not match any merchant configured with Firmly, or the merchant has been disabled. ```json { "code": 404, "error": "DomainNotFound", "description": "This domain was not found in firmly servers." } ``` **404 — CartNotFound** No cart exists for this device on this domain. ```json { "code": 404, "error": "CartNotFound", "description": "Cart was not found." } ``` **404 — ShipmentNotFound** The supplied `shipment_id` does not match any shipment on the current cart. Refresh cart state and retry with a current id. ```json { "code": 404, "error": "ShipmentNotFound", "description": "Shipment not found." } ``` **409 — MultipleDiscountCodesNotSupported** Setting the shipping method triggered re-evaluation of cart promotions and the merchant rejected the combined discount codes currently applied. ```json { "code": 409, "error": "MultipleDiscountCodesNotSupported", "description": "Multiple discount codes are not supported." } ``` **409 — NotEnoughStockError** One or more line items no longer have enough stock to fulfill the selected method. Lower the quantity or remove the item, then retry. ```json { "code": 409, "error": "NotEnoughStockError", "description": "The amount of the required item is not available in stock." } ``` **412 — MissingShippingInfo** Shipping address is not yet set on the cart. Call [Set Shipping Info](/api-reference/checkout/set-shipping-info) first. ```json { "code": 412, "error": "MissingShippingInfo", "description": "Shipping info is missing." } ``` **412 — OperationNotSupported** The merchant's platform does not support this operation. ```json { "code": 412, "error": "OperationNotSupported", "description": "This operation is not supported for this store." } ``` **400 — InvalidInputBody** Request body fails schema validation. `shipment_id` and `shipping_method_id` must be non-empty strings. ```json { "code": 400, "error": "InvalidInputBody", "description": "The body is not processable" } ``` **422 — UnprocessableEntity** The request is well-formed but cannot be processed — typically the merchant API rejected the method change for a reason not covered by the more specific errors above. ```json { "code": 422, "error": "UnprocessableEntity", "description": "The given payload has unprocessable, invalid or non-existent data. Please check the data and try again." } ``` **429 — RateLimited** Too many requests in a short window. Back off and retry, honoring the `Retry-After` header. ```json { "code": 429, "error": "RateLimited", "description": "Too many requests. Please try again later." } ``` **503 — StoreUnavailable** The merchant's API returned an unexpected response and the request could not be fulfilled. Retry with backoff. ```json { "code": 503, "error": "StoreUnavailable", "description": "Store is unavailable." } ``` --- # Shipment Configuration The Shipment Configuration API provides endpoints to manage how shipments are fulfilled and delivered. ## Overview This API allows you to: - **Set Fulfillment Type**: Configure how each shipment will be fulfilled (standard shipping, scheduled delivery, or in-store pickup) - **Set Shipping Method**: Select the shipping method for a shipment — including scheduled date / time slot when applicable - **Get Availability**: Query available dates and time slots for scheduled delivery > **Note** > Set Fulfillment Type and Get Availability are **V2-only** — they return `501 NotImplemented` for V1 adapters. Set Shipping Method is available on both V1 and V2. ## Available Endpoints - [Set Fulfillment Type](/api-reference/shipment-configuration/set-fulfillment-type) — Configure how each shipment will be fulfilled - [Set Shipping Method](/api-reference/shipment-configuration/set-shipping-method) — Select shipping method (and scheduled date/time slot when applicable) - [Get Availability](/api-reference/shipment-configuration/get-availability) — Check available dates for scheduled delivery ## Fulfillment Types Each shipment can be configured with one of these fulfillment types: ### SHIP_TO_ADDRESS Standard shipping to the buyer's address. Requires a shipping method to be selected. ### SCHEDULED_DELIVERY Delivery with appointment scheduling. Use [Get Availability](/api-reference/shipment-configuration/get-availability) to fetch eligible dates / time slots, then pass them to [Set Shipping Method](/api-reference/shipment-configuration/set-shipping-method). ### PICKUP_IN_STORE Buyer pickup at a store location (availability depends on merchant support). The pickup `location_id` is passed in the same [Set Fulfillment Type](/api-reference/shipment-configuration/set-fulfillment-type) call. ## Prerequisite [Set Shipping Info](/api-reference/checkout/set-shipping-info) must be called first. Until then, the cart has `shipments: []` and the endpoints on this page have nothing to operate on. ## Workflow ### Set Shipping Info Call [Set Shipping Info](/api-reference/checkout/set-shipping-info) to populate the cart's `shipments` array. The response carries the initial `fulfillment_type` and `shipping_method` the merchant selected for each shipment. ### (Optional) Set Fulfillment Type Change the fulfillment type for a shipment if the merchant default isn't what the buyer wants. For `PICKUP_IN_STORE`, include `location_id` in the same request. ### (Optional) Configure Delivery - **SHIP_TO_ADDRESS** — Call [Set Shipping Method](/api-reference/shipment-configuration/set-shipping-method) with `shipping_method_id` if the buyer wants a different method than the merchant default. - **SCHEDULED_DELIVERY** — Call [Get Availability](/api-reference/shipment-configuration/get-availability) to retrieve eligible dates/time slots, then [Set Shipping Method](/api-reference/shipment-configuration/set-shipping-method) with `shipping_method_id` plus `selected_date` and/or `selected_time_slot`. - **PICKUP_IN_STORE** — Already handled in Set Fulfillment Type via `location_id`; no additional call required for the pickup itself. ## Defaults When shipments are first created (after Set Shipping Info), each shipment is initialized with whatever `fulfillment_type` and `shipping_method` the merchant returns. The buyer-facing UI typically only needs to call the Set endpoints when the buyer wants to change those defaults. > **Note** > Shipments are created and grouped by the merchant's system based on its own fulfillment rules. Firmly provides a standardized interface to configure those merchant-defined shipments — not to create or split them client-side. - [Shipping & Fulfillment](/api-reference/shipment-configuration/shipping-and-fulfillment/index.md) - [Get Shipping Methods](/api-reference/shipment-configuration/get-shipping-methods/index.md) --- # Shipping & Fulfillment ## Overview The Cart API organizes items into **shipments**, with each shipment having a **fulfillment type** (how it's delivered to the buyer). A single cart can have multiple shipments, each with a different fulfillment type — enabling complex checkout experiences across all merchant platforms with a consistent API. > **Note** > Shipments reflect the merchant's fulfillment structure, standardized through Firmly's API for consistent integration across platforms. ## What are Shipments? Shipments represent groups of items that fulfill together. Common shipment scenarios: - Items from different warehouse locations - Products from multiple vendors - Mixed fulfillment types (shipping, pickup, scheduled delivery) - Items with different delivery requirements ## Cart structure with shipments ```json { "cart_id": "1d6af01a-08ec-59f7-8dc6-abd6f6eeed25", "line_items": [ { "line_item_id": "0ef341c8-4a05-ce7c-4530-d100b60cbc2a", "sku": "WIDGET-001", "quantity": 1, "price": { "currency": "USD", "value": 22.0, "number": 2200, "symbol": "$" }, "line_price": { "currency": "USD", "value": 22.0, "number": 2200, "symbol": "$" }, "msrp": { "currency": "USD", "value": 26.4, "number": 2640, "symbol": "$" }, "image": { "url": "https://staging.luma.gift/widget-001.jpg", "alt": "WIDGET-001", "type": "default" } }, { "line_item_id": "bb175284-a800-5a33-96ac-a642cd3952ce", "sku": "GADGET-002", "quantity": 2, "price": { "currency": "USD", "value": 22.0, "number": 2200, "symbol": "$" }, "line_price": { "currency": "USD", "value": 44.0, "number": 4400, "symbol": "$" }, "msrp": { "currency": "USD", "value": 26.4, "number": 2640, "symbol": "$" }, "image": { "url": "https://staging.luma.gift/gadget-002.jpg", "alt": "GADGET-002", "type": "default" } } ], "shipments": [ { "shipment_id": "f33fc75a-2694-230f-b615-d358eb4a6543", "line_item_ids": [ "0ef341c8-4a05-ce7c-4530-d100b60cbc2a", "bb175284-a800-5a33-96ac-a642cd3952ce" ], "fulfillment_type": { "id": "SHIP_TO_ADDRESS", "name": "Ship to Address" }, "fulfillment_type_options": [ { "id": "SHIP_TO_ADDRESS", "name": "Ship to Address" }, { "id": "SCHEDULED_DELIVERY", "name": "Scheduled Delivery" } ], "shipping_method_options": [ { "id": "standard", "description": "Standard Ground (5-7 days)", "price": { "currency": "USD", "value": 9.99, "number": 999, "symbol": "$" } } ], "shipping_method": { "id": "standard", "description": "Standard Ground (5-7 days)", "price": { "currency": "USD", "value": 9.99, "number": 999, "symbol": "$" } } } ] } ``` ### Line item assignment The `line_item_ids` array maps items to their respective shipments: ```mermaid graph LR subgraph "Cart Items" I1[Sofa - item_1] I2[Pillow - item_2] I3[Table - item_3] end subgraph "Shipments" S1[Shipment 1
Standard Delivery] S2[Shipment 2
Scheduled Delivery] end I1 --> S2 I2 --> S1 I3 --> S2 ``` ## Automatic Shipment Assignment When items are added to the cart via [Add Line Item](/api-reference/cart-management/add-line-item), Firmly automatically organizes them into shipments — clients do not assign items to shipments manually: 1. **Groups compatible items** — items with similar fulfillment requirements are placed in the same shipment. 2. **Creates new shipments** — items with different fulfillment requirements get separate shipments. 3. **Inherits options** — each new shipment is initialized with the fulfillment-type and shipping-method options available for its items. ### Example: Mixed Cart Adding a large sofa (requires scheduled delivery) to a cart that already contains small accessories (standard shipping) yields two shipments: ```json { "shipments": [ { "shipment_id": "c48f90db-5f40-56e7-01fa-5d7e6bc142e0", "line_item_ids": ["4ad19ada-4361-e123-c076-2312af81fd06"], "fulfillment_type": { "id": "SCHEDULED_DELIVERY" } }, { "shipment_id": "3f1685b5-e89c-2801-4ddf-ec367b5f0951", "line_item_ids": ["cf13aa70-f5d0-9302-6ab1-159b0f56a8dd", "b1de78d0-6be8-8214-a2d1-4188503a59c2"], "fulfillment_type": { "id": "SHIP_TO_ADDRESS" } } ] } ``` Clients can then call [Set Fulfillment Type](/api-reference/shipment-configuration/set-fulfillment-type) or [Set Shipping Method](/api-reference/shipment-configuration/set-shipping-method) per shipment to refine the selection. ## Fulfillment Types Each shipment has a fulfillment type that determines how the items will be delivered. Available fulfillment types vary by merchant — always check the `fulfillment_type_options` array on the shipment to see what's currently available. ### SHIP_TO_ADDRESS Standard shipping to a buyer-provided address. The most common fulfillment type. | Aspect | Detail | |---|---| | **Model** | Traditional e-commerce shipping | | **Methods** | Multiple shipping methods available (standard, express, overnight) | | **Cost** | Calculated based on destination and method | | **Default** | Yes — used if no other type is specified | | **Use cases** | Most retail products, items not requiring special handling, residential or commercial addresses | ### SCHEDULED_DELIVERY Date- and time-specific delivery for items requiring coordination with the buyer. | Aspect | Detail | |---|---| | **Model** | Buyer selects specific delivery date + optional time slot | | **Service level** | Higher-touch — often includes white glove or installation | | **Use cases** | Furniture, large appliances, items requiring installation, perishable goods | ### PICKUP_IN_STORE Buyer picks up items at a physical store location. > **Note** > PICKUP_IN_STORE is selectable only if the merchant supports it. When available, it appears in the shipment's `fulfillment_type_options` and can be set via [Set Fulfillment Type](/api-reference/shipment-configuration/set-fulfillment-type) with a `location_id`. Merchants that do not support pickup will not list it in `fulfillment_type_options` — always check that array before offering it. | Aspect | Detail | |---|---| | **Model** | Buyer selects pickup location and optional time slot | | **Cost** | No shipping cost | | **Speed** | Often same-day fulfillment | | **Use cases** | Buy online, pick up in store (BOPIS); urgent orders; in-store inventory | ## Setting the fulfillment type ```bash curl -X POST 'https://api.firmly.work/api/v2/domains/staging.luma.gift/cart/shipments/fulfillment-type' \ -H 'x-firmly-authorization: YOUR_ACCESS_TOKEN' \ -H 'Content-Type: application/json' \ -d '{ "shipment_id": "a2dfd593-7d99-e0ff-c7a4-1fe2f8cf208c", "fulfillment_type": "SCHEDULED_DELIVERY" }' ``` ### Fields cleared on transition When changing fulfillment types, related fields are automatically reset: | From → To | Fields Cleared | New Requirements | |-----------|----------------|------------------| | Any → `SHIP_TO_ADDRESS` | `selected_location`, `selected_date`, `selected_time_slot` | Shipping method selection | | Any → `SCHEDULED_DELIVERY` | `selected_location`, `selected_date`, `selected_time_slot` | Date/time selection | | Any → `PICKUP_IN_STORE` | `selected_date`, `selected_time_slot` | Store location selection | ## Shipping methods (for SHIP_TO_ADDRESS) Each shipment provides its own shipping options: ```json { "shipment_id": "a2dfd593-7d99-e0ff-c7a4-1fe2f8cf208c", "shipping_method_options": [ { "id": "standard", "description": "Standard Ground (5-7 days)", "price": { "value": 9.99, "currency": "USD", "number": 999, "symbol": "$" } }, { "id": "express", "description": "Express (2 days)", "price": { "value": 29.99, "currency": "USD", "number": 2999, "symbol": "$" } } ] } ``` > **Note** > `shipping_method_options` is always populated on each shipment in the cart response after `set-shipping-info` — this is the source of available shipping methods. `get-availability` is a separate, optional endpoint that returns delivery dates, time slots, and pickup locations (not shipping methods), and returns `501 NotImplemented` on merchants whose adapters don't support it. ## Typical flow ### Get the cart, inspect shipments[] After adding items + setting a shipping address, `cart.shipments[]` is populated. Each shipment has its own `shipment_id` and `fulfillment_type_options`. ### For each shipment, pick a fulfillment type Check `fulfillment_type_options`. If you want a non-default type, call `POST /cart/shipments/fulfillment-type` per shipment. ### Configure the chosen type - SHIP_TO_ADDRESS → set shipping method via `POST /cart/shipment/methods` - SCHEDULED_DELIVERY → pick a delivery date + time slot - PICKUP_IN_STORE → set pickup location (only when the merchant lists it in `fulfillment_type_options`) > **Note** > The shipping-method route is singular — `/cart/shipment/methods` — while its siblings are plural (`/cart/shipments/fulfillment-type`, `/cart/shipments/get-availability`). This is intentional; do not "correct" the singular path or you will get a 404. ### Place the order With all shipments configured, call `place-order`. Firmly submits each shipment to the merchant per its fulfillment type. --- ## Related - [Cart Lifecycle](/api-reference/cart-management/cart-lifecycle) — cart states and what operations work in each - [Set Fulfillment Type](/api-reference/shipment-configuration/set-fulfillment-type) — endpoint reference - [Set Shipping Method](/api-reference/shipment-configuration/set-shipping-method) — endpoint reference - [Get Availability](/api-reference/shipment-configuration/get-availability) — endpoint reference (note: merchant-conditional) - [Shipment Configuration overview](/api-reference/shipment-configuration/) — all shipment endpoints --- # Standard cart Cart operations for the [Standard flow](/api-reference/standard-flow/) (`/api/v1`). The cart is created implicitly on the first add — a `GET` before anything is added returns `404 CartNotFound`. Every response is the full cart, so you rarely need a separate `GET`. All calls are on `https://api.firmly.work` and require the `x-firmly-authorization` header (the token from [Browser Session](/api-reference/authentication/browser-session)). `{domain}` is the merchant domain, e.g. `staging.luma.gift`. ## Get cart `GET /api/v1/domains/{domain}/cart` Returns the current cart. Returns `404 CartNotFound` before the first item is added. ```bash curl --request GET \ --url https://api.firmly.work/api/v1/domains/staging.luma.gift/cart \ --header 'x-firmly-authorization: YOUR_TOKEN' ``` **Response** — the cart, with line items and totals resolved from the merchant catalog. Every money field is an object with `currency`, `value` (decimal), `number` (smallest unit), and `symbol`. ```json { "cart_id": "255fc5bd-b2d5-40c1-9040-eba8e1284a92", "cart_status": "active", "line_items": [ { "line_item_id": "380c6749-dc4f-7c63-f049-847e3862f396", "sku": "MH09-S-Blue", "description": "Abominable Hoodie", "quantity": 1, "price": { "currency": "USD", "value": 69, "number": 6900, "symbol": "$" }, "line_price": { "currency": "USD", "value": 69, "number": 6900, "symbol": "$" }, "msrp": { "currency": "USD", "value": 82.8, "number": 8280, "symbol": "$" }, "image": { "url": "https://staging.luma.gift/abominable-hoodie.jpg", "alt": "Abominable Hoodie", "type": "default" } } ], "sub_total": { "currency": "USD", "value": 69, "number": 6900, "symbol": "$" }, "shipping_total": { "currency": "USD", "value": 0, "number": 0, "symbol": "$" }, "fees": [ { "description": "Recycle fee", "currency": "USD", "value": 2, "number": 200, "symbol": "$" } ], "fee_total": { "currency": "USD", "value": 2, "number": 200, "symbol": "$" }, "total": { "currency": "USD", "value": 71, "number": 7100, "symbol": "$" }, "payment_method_options": [ { "type": "CreditCard", "wallet": "user" }, { "type": "PayPal", "wallet": "paypal" } ] } ``` ## Add a line item `POST /api/v1/domains/{domain}/cart/line-items` Adds a product, creating the cart if one doesn't exist. Pass the `add_to_cart_ref` straight from a [catalog](/api-reference/catalog/) product variant. - `add_to_cart_ref` (object, required) — `{ "variant_id": "..." }` from the catalog. - `quantity` (integer, required) — minimum 1. ```bash curl --request POST \ --url https://api.firmly.work/api/v1/domains/staging.luma.gift/cart/line-items \ --header 'Content-Type: application/json' \ --header 'x-firmly-authorization: YOUR_TOKEN' \ --data '{ "add_to_cart_ref": { "variant_id": "24-MB05" }, "quantity": 1 }' ``` ## Update quantity `PUT /api/v1/domains/{domain}/cart/line-items/{productId}` Sets a line item's quantity. **Quantity `0` removes the item.** - `quantity` (integer, required) — `0` or greater. ```bash curl --request PUT \ --url https://api.firmly.work/api/v1/domains/staging.luma.gift/cart/line-items/24-MB05 \ --header 'Content-Type: application/json' \ --header 'x-firmly-authorization: YOUR_TOKEN' \ --data '{ "quantity": 2 }' ``` ## Clear the cart `DELETE /api/v1/domains/{domain}/cart/line-items` Removes all items. ```bash curl --request DELETE \ --url https://api.firmly.work/api/v1/domains/staging.luma.gift/cart/line-items \ --header 'x-firmly-authorization: YOUR_TOKEN' ``` ## Apply promo codes `POST /api/v1/domains/{domain}/cart/promo-codes` Applies one or more promo codes (1–10). `DELETE` on the same path clears them. - `promo_codes` (array of strings, required) — 1 to 10 codes. ```bash curl --request POST \ --url https://api.firmly.work/api/v1/domains/staging.luma.gift/cart/promo-codes \ --header 'Content-Type: application/json' \ --header 'x-firmly-authorization: YOUR_TOKEN' \ --data '{ "promo_codes": ["WELCOME10"] }' ``` ## Set attribution `PUT /api/v1/domains/{domain}/cart/attribution` Attach affiliate / UTM attribution so the order is credited to your destination. - `attribution` (object, required) — with optional `utm` (string, e.g. `utm_source=partner&utm_medium=cpc`), `referrer_url`, `referral_code`, `landing_page`. ```bash curl --request PUT \ --url https://api.firmly.work/api/v1/domains/staging.luma.gift/cart/attribution \ --header 'Content-Type: application/json' \ --header 'x-firmly-authorization: YOUR_TOKEN' \ --data '{ "attribution": { "utm": "utm_source=partner&utm_campaign=spring", "referral_code": "PARTNER123" } }' ``` ## Errors Errors return `{ code, error, description }`; program against `error`. Common cases: `CartNotFound` (404, get before first add), `ProductNotFound` (404, stale `variant_id`), `NotEnoughStockError` (409), `PostalCodeRequired` (412). See [Errors & Conventions](/api-reference/errors-and-conventions) for the full catalog. ## Next - [Standard checkout](/api-reference/standard-flow/checkout) — Add the shipping and billing addresses - [Try it live](/api-explorer/) — Run these calls against the sandbox --- # Standard checkout Address, shipping, and consent steps for the [Standard flow](/api-reference/standard-flow/) (`/api/v1`). Run these after the cart has items and before placing the order. Each call returns the updated cart. All calls are on `https://api.firmly.work` with the `x-firmly-authorization` header. `{domain}` is the merchant domain, e.g. `staging.luma.gift`. ## Set the shipping address `POST /api/v1/domains/{domain}/cart/shipping-info` Sets the delivery address. Setting it lets the merchant calculate shipping rates and tax. The body is an address: ```json { "first_name": "Ada", "last_name": "Lovelace", "email": "ada@example.com", "phone": "5125550100", "address1": "1 Infinite Loop", "city": "Austin", "state_or_province": "TX", "country": "US", "postal_code": "78701" } ``` ```bash curl --request POST \ --url https://api.firmly.work/api/v1/domains/staging.luma.gift/cart/shipping-info \ --header 'Content-Type: application/json' \ --header 'x-firmly-authorization: YOUR_TOKEN' \ --data @address.json ``` ## Get shipping rates `GET /api/v1/domains/{domain}/cart/shipping-rates` Returns the available shipping methods for the cart. Set the shipping address first. ```bash curl --request GET \ --url https://api.firmly.work/api/v1/domains/staging.luma.gift/cart/shipping-rates \ --header 'x-firmly-authorization: YOUR_TOKEN' ``` **Response** — an array of shipping methods, each with a `sku`, `description`, and `price`: ```json [ { "sku": "freeshipping_freeshipping", "description": "Standard", "price": { "currency": "USD", "value": 0, "number": 0, "symbol": "$" } }, { "sku": "flatrate_flatrate", "description": "Expedited", "price": { "currency": "USD", "value": 4, "number": 400, "symbol": "$" } } ] ``` ## Set the shipping method `POST /api/v1/domains/{domain}/cart/shipping-method` Selects one of the methods returned by shipping rates. - `shipping_method` (string, required) — the `sku` of the chosen method from shipping rates. ```bash curl --request POST \ --url https://api.firmly.work/api/v1/domains/staging.luma.gift/cart/shipping-method \ --header 'Content-Type: application/json' \ --header 'x-firmly-authorization: YOUR_TOKEN' \ --data '{ "shipping_method": "freeshipping_freeshipping" }' ``` ## Set the billing address `POST /api/v1/domains/{domain}/cart/billing-info` Same address shape as shipping. Send it when billing differs from shipping (or to confirm it explicitly). ```bash curl --request POST \ --url https://api.firmly.work/api/v1/domains/staging.luma.gift/cart/billing-info \ --header 'Content-Type: application/json' \ --header 'x-firmly-authorization: YOUR_TOKEN' \ --data @address.json ``` ## Consents `POST /api/v1/domains/{domain}/cart/consents` returns the consents the merchant requires. `PUT` on the same path records the shopper's choices. - `consents` (array, required) — each `{ "id": "...", "revoke": false }`. ```bash curl --request PUT \ --url https://api.firmly.work/api/v1/domains/staging.luma.gift/cart/consents \ --header 'Content-Type: application/json' \ --header 'x-firmly-authorization: YOUR_TOKEN' \ --data '{ "consents": [ { "id": "terms_and_conditions" } ] }' ``` ## Errors Errors return `{ code, error, description }`; program against `error`. Common cases: `CartNotFound` (404), `InvalidInputBody` (400, address missing a required field), `OperationNotSupported` (412). See [Errors & Conventions](/api-reference/errors-and-conventions) for the full catalog. ## Next - [Standard order](/api-reference/standard-flow/place-order) — Encrypt the card and place the order - [Try it live](/api-explorer/) — Run these calls against the sandbox --- # Standard flow The **Standard flow** is Firmly's single-merchant checkout — bootstrap a session, build a cart against one known merchant, add an address, and place the order. It runs on `/api/v1` and is the right fit for **most integrations**. > **Note** > Need split shipments across items, delivery scheduling or pickup, add-ons and protection plans, or ZIP-coverage gating before checkout? Those belong to the **Advanced flow** (`/api/v2`) — see [Cart Management](/api-reference/cart-management/) and [Checkout](/api-reference/checkout/). The Advanced flow is available only when the merchant's platform supports it; most merchants run Standard. Authentication, catalog, and discovery are **shared** by both flows — the Standard flow differs only in its cart, checkout, and order calls. ## The flow 1. **Bootstrap a session** — [Browser Session](/api-reference/authentication/browser-session) exchanges your App ID for an `access_token`. 2. **Find a product** — [Catalog](/api-reference/catalog/): list, search, or fetch product detail (with a `variant_id`). 3. **Build the cart** — [Standard cart](/api-reference/standard-flow/cart): add items, change quantities, apply promo codes. 4. **Add addresses** — [Standard checkout](/api-reference/standard-flow/checkout): shipping address, shipping method, billing address, consents. 5. **Place the order** — [Standard order](/api-reference/standard-flow/place-order): one call, or complete an existing cart. ## Endpoints All cart and checkout calls are on `https://api.firmly.work`; order calls are on `https://cc.firmly.work`. Every call is authenticated with `x-firmly-authorization` (the token from Browser Session). | Stage | Operation | Method · Path | |---|---|---| | Cart | Get cart | `GET /api/v1/domains/{domain}/cart` | | Cart | Add line item | `POST /api/v1/domains/{domain}/cart/line-items` | | Cart | Update quantity | `PUT /api/v1/domains/{domain}/cart/line-items/{productId}` | | Cart | Clear cart | `DELETE /api/v1/domains/{domain}/cart/line-items` | | Cart | Apply promo codes | `POST /api/v1/domains/{domain}/cart/promo-codes` | | Cart | Clear promo codes | `DELETE /api/v1/domains/{domain}/cart/promo-codes` | | Cart | Set attribution | `PUT /api/v1/domains/{domain}/cart/attribution` | | Checkout | Set shipping address | `POST /api/v1/domains/{domain}/cart/shipping-info` | | Checkout | Get shipping rates | `GET /api/v1/domains/{domain}/cart/shipping-rates` | | Checkout | Set shipping method | `POST /api/v1/domains/{domain}/cart/shipping-method` | | Checkout | Set billing address | `POST /api/v1/domains/{domain}/cart/billing-info` | | Checkout | Get required consents | `POST /api/v1/domains/{domain}/cart/consents` | | Checkout | Record consents | `PUT /api/v1/domains/{domain}/cart/consents` | | Order | Place order (one-shot) | `POST /api/v1/payment/domains/{domain}/place-order` | | Order | Complete order | `POST /api/v1/payment/domains/{domain}/complete-order` | > **Tip** > Every endpoint here is live in the [API Explorer](/api-explorer/) — browse the full request and response schema and try each call against the sandbox merchant. This section shows the flow; the Explorer is the exhaustive per-field reference. ## Build it - [Standard cart](/api-reference/standard-flow/cart) — Add items, change quantities, apply promo codes - [Standard checkout](/api-reference/standard-flow/checkout) — Shipping address and method, billing, consents - [Standard order](/api-reference/standard-flow/place-order) — Encrypt the card and place the order - [Runnable guide](/cookbook/standard-checkout-guide) — The whole flow end-to-end in ~90 lines of Node --- # Standard order The payment and order step for the [Standard flow](/api-reference/standard-flow/). These calls are on the payment host `https://cc.firmly.work` and require the `x-firmly-authorization` header. `{domain}` is the merchant domain, e.g. `staging.luma.gift`. ## Encrypt the card first The card is never sent in the clear. Fetch the merchant's public key, then JWE-encrypt the card details **inside your own process** and send the resulting token as `encrypted_card`. 1. `GET /api/v1/payment/key` → the public key ([Get Public Key](/api-reference/payment/get-public-key)). 2. Encrypt the card as a JWE with that key. 3. Send the JWE as `encrypted_card` in the calls below. > **Note** > The JWE step needs a little code. The [Standard Checkout Guide](/cookbook/standard-checkout-guide) is a complete, runnable script that fetches the key, encrypts the test card, and places an order against this sandbox. ## Place an order (one-shot) `POST /api/v1/payment/domains/{domain}/place-order` Builds the cart from `items` and pays in a single call — the "buy now" path when you already know exactly what the shopper wants. - `encrypted_card` (string, required) — the JWE token. - `shipping_info` (object, required) — shipping address. - `billing_info` (object, required) — billing address. - `items` (array, required) — each `{ "variant_id": "...", "quantity": 1 }`. - `captcha_token` (string, optional) — bot-protection token when required. ```bash curl --request POST \ --url https://cc.firmly.work/api/v1/payment/domains/staging.luma.gift/place-order \ --header 'Content-Type: application/json' \ --header 'x-firmly-authorization: YOUR_TOKEN' \ --data '{ "encrypted_card": "", "shipping_info": { "first_name": "Ada", "last_name": "Lovelace", "email": "ada@example.com", "phone": "5125550100", "address1": "1 Infinite Loop", "city": "Austin", "state_or_province": "TX", "country": "US", "postal_code": "78701" }, "billing_info": { "first_name": "Ada", "last_name": "Lovelace", "email": "ada@example.com", "phone": "5125550100", "address1": "1 Infinite Loop", "city": "Austin", "state_or_province": "TX", "country": "US", "postal_code": "78701" }, "items": [ { "variant_id": "24-MB05", "quantity": 1 } ] }' ``` **Response** — the placed cart, `cart_status: "submitted"`, carrying `platform_order_number`, `submitted_at`, and the confirmed totals. ## Complete an existing cart `POST /api/v1/payment/domains/{domain}/complete-order` Pays for and finalizes the cart you already built through the [cart](/api-reference/standard-flow/cart) and [checkout](/api-reference/standard-flow/checkout) steps — the incremental path. - `encrypted_card` (string, required) — the JWE token. - `billing_info` (object, required) — billing address. - `captcha_token` (string, optional). ```bash curl --request POST \ --url https://cc.firmly.work/api/v1/payment/domains/staging.luma.gift/complete-order \ --header 'Content-Type: application/json' \ --header 'x-firmly-authorization: YOUR_TOKEN' \ --data '{ "encrypted_card": "", "billing_info": { "first_name": "Ada", "last_name": "Lovelace", "email": "ada@example.com", "phone": "5125550100", "address1": "1 Infinite Loop", "city": "Austin", "state_or_province": "TX", "country": "US", "postal_code": "78701" } }' ``` **Response** — the completed cart, `cart_status: "submitted"`, carrying `platform_order_number`, `submitted_at`, and the confirmed totals. ## Errors Errors return `{ code, error, description }`; program against `error`. Common cases: `InvalidInputBody` (400, missing `encrypted_card` / addresses / items), `CartNotFound` (404, on complete-order with no cart), payment declines. See [Errors & Conventions](/api-reference/errors-and-conventions) for the full catalog. ## Next - [Standard Checkout Guide](/cookbook/standard-checkout-guide) — Runnable end-to-end script, including the JWE step - [Try it live](/api-explorer/) — Run the order calls against the sandbox --- # Start Journey `POST https://api.firmly.work/api/v1/carts/affiliate/start-journey` ## Overview Start Journey is the **BYO (Bring Your Own Link) endpoint**. It resolves the partner-supplied affiliate link, captures the attribution details, and stores them in the device session. The response returns the resolved merchant URL, network, and click identifier. > **Warning** > **Firmly's drop-in calls this endpoint automatically.** Direct use is intended only for partner integrations enabled by Firmly. Standard merchant integrations should not call it. ## Integration rules - Call once, as early as practical, when the shopper arrives after clicking an affiliate link. - Send the affiliate link itself as the `url` value. Start Journey follows it to resolve the merchant page and attribution details. - Do not call it for managed attribution or ordinary, non-affiliate landings. - Do not retry blindly; repeating the request can register the click again. - Treat the journey as attributed only when both `network` and `click_id` are present. `success` alone is not an attribution signal. ## Authentication Establish a device session using [Browser Session](/api-reference/authentication/browser-session) before calling Start Journey. Partner integrations enabled by Firmly should send the resulting token in `x-firmly-authorization`; Firmly-hosted surfaces may use their established browser session. `x-firmly-authorization` (string, required) — device authentication token identifying the shopping session. > **Warning** > Start Journey accepts device-session authentication only. Server-to-Server credentials are not accepted. ## Request Send a JSON body with `Content-Type: application/json`. The `url` field is the affiliate link supplied by the partner. `url` (string, required) — the affiliate link to resolve. Send the original tracking link, not the merchant page URL after the link has been followed. ## Request Example ```bash curl --request POST \ --url https://api.firmly.work/api/v1/carts/affiliate/start-journey \ --header 'x-firmly-authorization: YOUR_TOKEN' \ --header 'Content-Type: application/json' \ --data '{"url":"https://www.anrdoezrs.net/click-100-15?url=https%3A%2F%2Fmerchant.example%2Fproduct%2F123"}' ``` > **Note** > Firmly may retain the submitted URL and associated tracking data as part of the session's attribution state. Do not include customer names, email addresses, payment information, or other unnecessary personal data in the URL. Invoke tracking only in accordance with your privacy and consent obligations. ## Response When processing completes normally, the response contains: | Field | Type | Meaning | |---|---|---| | `success` | boolean | `true` when a final merchant URL was resolved. This does not mean attribution was captured or commission will be approved. | | `network` | string or null | Detected affiliate network, or `null` when none was detected. | | `click_id` | string or null | Affiliate click identifier, or `null` when none was found. Treat the journey as attributed only when both `network` and `click_id` are non-null. | | `buyer_id` | string or null | Network-provided visitor identifier, when available. Informational only. | | `sub_affiliate` | string or null | Content-monetization service identified at the start of the link chain, when applicable. Informational only. | | `final_url` | string or null | Final merchant URL reached from the supplied URL, or `null` when no merchant page was resolved. | ## Response Example ```json { "success": true, "network": "cj", "click_id": "abc123def456", "buyer_id": null, "sub_affiliate": null, "final_url": "https://merchant.example/product/123" } ``` ### No attribution detected The merchant page resolved, but the URL did not contain a supported attribution signal: ```json { "success": true, "network": null, "click_id": null, "buyer_id": null, "sub_affiliate": null, "final_url": "https://merchant.example/product/123" } ``` ### Degraded response If the downstream attribution service returns a non-success or unreadable response, Start Journey returns a smaller best-effort result: ```json { "success": false, "network": null, "click_id": null, "final_url": null } ``` `buyer_id` and `sub_affiliate` are omitted from this degraded shape. Transport, session, validation, and other unexpected failures can instead produce an HTTP error. If affiliate tracking fails, the shopper can still browse and complete checkout. ## Error responses | Status | Error | Meaning | |---|---|---| | 400 | `InvalidInputBody` | `url` is missing, not a string, or the body is not valid JSON. | | 400 | `MissingAuthHeader` / `InvalidToken` | The device session credential is missing or malformed. | | 401 | `InvalidJWTToken` | The supplied device token failed verification or has expired. | | 404 | `PartnerNotFound` | The partner associated with the device credential could not be resolved. | | 404 | `DomainNotFound` | The resolved merchant is unavailable to the authenticated partner; attribution is not recorded. | | 500 | `Unexpected` | An unexpected service or session failure occurred. Do not automatically replay the affiliate URL. | ## Related - [Affiliate overview](/api-reference/affiliate/) — business flow and attribution boundaries - [Browser Session](/api-reference/authentication/browser-session) — establish the required device session - [Place Order](/api-reference/payment/place-order-v2) — complete the shopping flow --- # Start Klarna Checkout `POST https://api.firmly.work/api/v1/domains/{domain}/express/klarna/start` ## Overview Initiates a Klarna checkout by creating a payment session with Klarna. Returns the cart enriched with a `payment_method` object containing the `client_token`, `session_id`, and available `payment_method_categories` needed to render the Klarna Payments widget on the client. Availability and the host this endpoint runs on are covered in the [Klarna Express Checkout](/api-reference/payment/express-checkout/klarna/) overview. ## Authentication - `x-firmly-authorization` (string, required) — Device access token from [Browser Session](/api-reference/authentication/browser-session) ## Path Parameters - `domain` (string, required) — The merchant domain (e.g., "staging.luma.gift") ## Prerequisites Before calling this endpoint: - A cart must already exist for `{domain}` on this device session (created via [Browser Session](/api-reference/authentication/browser-session) → [Add Line Item](/api-reference/cart-management/add-line-item)) and hold at least one line item. A missing cart returns `404 CartNotFound`. - Shipping info should be set ([Set Shipping Info](/api-reference/checkout/set-shipping-info)) so the cart total is accurate before the Klarna session is created; the authorize step requires the cart to be in a ready state. ## Request Body - `attributes` (object) — Optional gateway-specific attributes. Can be an empty object or omitted entirely for standard Klarna checkout. ## Response Returns the cart enriched with the Klarna payment method details. - `cart_id` (string) — Unique identifier for the cart - `line_items` (array) — Array of items in the cart - `payment_method` (object) — Klarna payment method details **Payment Method** - `payment_type` (string) — Always `"Klarna"` for this gateway - `attributes` (object) — Klarna session credentials - `session_id` (string) — Klarna payment session identifier - `client_token` (string) — Token used to initialize the Klarna Payments SDK on the client - `payment_method_categories` (array) — Available Klarna payment options (e.g., `pay_later`, `pay_over_time`, `pay_now`). Each entry contains `identifier`, `name`, and `asset_urls`. - `shipping_info` (object) — Delivery address details - `shipping_method` (object) — Selected shipping method with pricing - `total` (object) — Grand total including all costs - `sub_total` (object) — Subtotal before shipping and tax - `tax` (object) — Tax amount ## Code Example **JavaScript** ```javascript const response = await fetch( 'https://api.firmly.work/api/v1/domains/staging.luma.gift/express/klarna/start', { method: 'POST', headers: { 'x-firmly-authorization': authToken, 'Content-Type': 'application/json' }, body: JSON.stringify({}) } ); const cart = await response.json(); // Extract Klarna credentials for the widget const { session_id, client_token, payment_method_categories } = cart.payment_method.attributes; // Initialize Klarna Payments SDK with client_token Klarna.Payments.init({ client_token }); ``` **Python** ```python import requests response = requests.post( 'https://api.firmly.work/api/v1/domains/staging.luma.gift/express/klarna/start', headers={ 'x-firmly-authorization': auth_token, 'Content-Type': 'application/json' }, json={} ) cart = response.json() klarna_attrs = cart['payment_method']['attributes'] session_id = klarna_attrs['session_id'] client_token = klarna_attrs['client_token'] categories = klarna_attrs['payment_method_categories'] ``` **cURL** ```bash curl -X POST https://api.firmly.work/api/v1/domains/staging.luma.gift/express/klarna/start \ -H "x-firmly-authorization: YOUR_AUTH_TOKEN" \ -H "Content-Type: application/json" \ -d '{}' ``` ## Response Example ```json { "cart_id": "9cf76530-1344-420f-9ca6-c7a96fb6db45", "line_items": [ { "line_item_id": "3e66bef5-43f5-4a80-8957-91c5c8233163", "sku": "MT12", "quantity": 1, "description": "Cassius Sparring Tank", "price": { "currency": "USD", "value": 18, "number": 1800, "symbol": "$" }, "line_price": { "currency": "USD", "value": 18, "number": 1800, "symbol": "$" }, "msrp": { "currency": "USD", "value": 21.6, "number": 2160, "symbol": "$" }, "image": { "url": "https://staging.luma.gift/cassius-sparring-tank.jpg", "alt": "Cassius Sparring Tank", "type": "default" } } ], "payment_method": { "payment_type": "Klarna", "attributes": { "session_id": "kp_abc123def456", "client_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...", "payment_method_categories": [ { "identifier": "pay_later", "name": "Pay later", "asset_urls": { "descriptive": "https://x.klarnacdn.net/payment-method/assets/badges/generic/klarna.svg", "standard": "https://x.klarnacdn.net/payment-method/assets/badges/generic/klarna.svg" } }, { "identifier": "pay_over_time", "name": "Financing", "asset_urls": { "descriptive": "https://x.klarnacdn.net/payment-method/assets/badges/generic/klarna.svg", "standard": "https://x.klarnacdn.net/payment-method/assets/badges/generic/klarna.svg" } } ] } }, "shipping_info": { "first_name": "John", "last_name": "Smith", "email": "john@example.com", "phone": "2065551212", "address1": "123 Main St", "city": "Seattle", "state_or_province": "WA", "country": "US", "postal_code": "98101" }, "shipping_method": { "id": "standard_shipping", "description": "Standard Shipping", "price": { "currency": "USD", "value": 10, "number": 1000, "symbol": "$" } }, "total": { "currency": "USD", "value": 32, "number": 3200, "symbol": "$" }, "sub_total": { "currency": "USD", "value": 18, "number": 1800, "symbol": "$" }, "shipping_total": { "currency": "USD", "value": 10, "number": 1000, "symbol": "$" }, "tax": { "currency": "USD", "value": 2, "number": 200, "symbol": "$" }, "fees": [ { "description": "Recycle fee", "currency": "USD", "value": 2, "number": 200, "symbol": "$" } ], "fee_total": { "currency": "USD", "value": 2, "number": 200, "symbol": "$" } } ``` --- ## Related Endpoints - [Authorize Klarna Checkout](/api-reference/payment/express-checkout/klarna/authorize) — Confirm Klarna authorization - [Complete Klarna Order](/api-reference/payment/express-checkout/klarna/complete-order) — Finalize the order ## Error Responses Errors return a JSON body with `code`, `error`, and `description`. Program against the `error` value — descriptions are human-readable and may change. **400 — ErrorStartExpressCheckout** Firmly could not create a Klarna payment session — either Klarna rejected the request or the merchant adapter failed to translate it. ```json { "code": 400, "error": "ErrorStartExpressCheckout", "description": "Could not start checkout." } ``` **400 — InvalidToken** The `x-firmly-authorization` header is missing, empty, or not a well-formed JWT. Device-auth can also surface as `MissingAuthHeader` or `PartnerNotFound`; see [Authentication errors](/api-reference/errors-and-conventions#authentication) for the full set. ```json { "code": 400, "error": "InvalidToken", "description": "Jwt token is invalid." } ``` **401 — InvalidJWTToken** The device JWT is well-formed but its signature does not verify, or required claims are missing. ```json { "code": 401, "error": "InvalidJWTToken", "description": "Jwt token is invalid." } ``` **404 — CartNotFound** No active cart exists for this device on this domain. ```json { "code": 404, "error": "CartNotFound", "description": "Cart was not found." } ``` **404 — DomainNotFound** The `{domain}` path parameter does not match any merchant configured with Firmly, or the merchant has been disabled. ```json { "code": 404, "error": "DomainNotFound", "description": "This domain was not found in firmly servers." } ``` **404 — GatewayNotFound** Klarna is not enabled as a payment gateway for this merchant. Check `payment_method_options` before offering it. ```json { "code": 404, "error": "GatewayNotFound", "description": "Payment gateway 'klarna' not found" } ``` **412 — OperationNotSupported** The merchant adapter does not implement Klarna express checkout. ```json { "code": 412, "error": "OperationNotSupported", "description": "This operation is not supported for this store." } ``` **503 — StoreUnavailable** The merchant's own API was unavailable or timed out. Retry with backoff. ```json { "code": 503, "error": "StoreUnavailable", "description": "Store temporarily unavailable. Please try again later." } ``` **429 — RateLimited** Too many requests from this device. Back off and retry after the `Retry-After` window — see [Rate Limits](/api-reference/rate-limits). ```json { "code": 429, "error": "RateLimited", "description": "Too many requests. Please try again later." } ``` --- # Start PayPal Express Checkout `POST https://api.firmly.work/api/v1/domains/{domain}/express/paypal/start` ## Overview Opens a PayPal Express Checkout session against the merchant's own PayPal account. Returns the cart enriched with a `payment_method` object carrying the PayPal **EC token** — the value the buyer's PayPal approval is tied to, and the value you pass back to [Authorize](/api-reference/payment/express-checkout/paypal/authorize). Availability and the host this endpoint runs on are covered in the [PayPal Express Checkout](/api-reference/payment/express-checkout/paypal/) overview. ## Authentication - `x-firmly-authorization` (string, required) — Device access token from [Browser Session](/api-reference/authentication/browser-session) ## Path Parameters - `domain` (string, required) — The merchant domain (e.g., "staging.luma.gift") ## Prerequisites - **PayPal must be enabled for this merchant** — see [Checking availability](/api-reference/payment/express-checkout/paypal/#checking-availability). A merchant without PayPal returns `404 GatewayNotFound`. - A cart must already exist for `{domain}` on this device session (created via [Browser Session](/api-reference/authentication/browser-session) → [Add Line Item](/api-reference/cart-management/add-line-item)) and hold at least one line item. A missing cart returns `404 CartNotFound`. - Shipping info should be set ([Set Shipping Info](/api-reference/checkout/set-shipping-info)) so the cart total is final before the PayPal session is created. The EC token is bound to the amount at the time it is created, so changing the total afterwards can cause the merchant to reject the order at complete-order. ## Request Body - `attributes` (object) — Optional gateway-specific attributes. Send an empty object, or omit the body entirely, for standard PayPal express checkout. ## Response Returns the cart, enriched with the PayPal session details. - `cart_id` (string) — Unique identifier for the cart - `line_items` (array) — Array of items in the cart - `payment_method` (object) — PayPal session details **Payment Method** - `payment_type` (string) — The gateway label; case varies by merchant - `attributes` (object) — PayPal session values - `paypal_token` (string \| null) — The PayPal EC token (e.g., `EC-XXXXXXXXXXXXXXXXX`), and the value you carry into Authorize and Complete Order. It can be `null` when no PayPal session could be opened with the merchant — the call still returns `200`, so check the field before continuing (see below). - `url` (string) — The PayPal approval URL for the token. Present on most merchants; treat as optional. - `sandbox` (boolean) — Whether the merchant's PayPal account is in sandbox mode. Present on most merchants; treat as optional. - `requires_review` (boolean) — Merchant-specific; present only on some adapters. - `shop_properties` (object) — Merchant-level configuration. `shop_properties.paypal` carries the PayPal client credentials your surface needs to render the PayPal button — `clientId`, and where the merchant's integration supplies them, `merchantId`, `sandbox`, `intent` and `integration_version`. See [Get Cart](/api-reference/cart-management/get-cart) for the full field list. - `payment_method_options` (array) — Payment methods this merchant supports - `shipping_info` (object) — Delivery address details - `shipping_method` (object) — Selected shipping method with pricing - `total` / `sub_total` / `tax` / `shipping_total` (object) — Cart totals > **Warning** > **A `200` does not guarantee a token.** This endpoint can return `200` with `paypal_token: null` and a `url` ending in `token=null`, rather than an error, when no PayPal session could be opened with the merchant. Credentials being present in `shop_properties.paypal` is not a guarantee — check the token itself. Treat a null token as "PayPal unavailable for this merchant right now": do not call Authorize, which would fail with `400 BadRequest — Missing PayPal EC Token`, and fall back to another payment method. ## Code Example **JavaScript** ```javascript const response = await fetch( 'https://api.firmly.work/api/v1/domains/staging.luma.gift/express/paypal/start', { method: 'POST', headers: { 'x-firmly-authorization': authToken, 'Content-Type': 'application/json' }, body: JSON.stringify({}) } ); const cart = await response.json(); // The EC token is the value the buyer's PayPal approval binds to const paypalToken = cart.payment_method.attributes.paypal_token; if (!paypalToken) { // PayPal is not usable on this merchant right now — offer another method throw new Error('No PayPal token returned for this merchant'); } // Client credentials for the PayPal JS SDK live on the cart, not in your config const { clientId, sandbox } = cart.shop_properties.paypal; ``` **Python** ```python import requests response = requests.post( 'https://api.firmly.work/api/v1/domains/staging.luma.gift/express/paypal/start', headers={ 'x-firmly-authorization': auth_token, 'Content-Type': 'application/json' }, json={} ) cart = response.json() paypal_token = cart['payment_method']['attributes']['paypal_token'] client_id = cart['shop_properties']['paypal']['clientId'] ``` **cURL** ```bash curl -X POST https://api.firmly.work/api/v1/domains/staging.luma.gift/express/paypal/start \ -H "x-firmly-authorization: YOUR_AUTH_TOKEN" \ -H "Content-Type: application/json" \ -d '{}' ``` ## Response Example ```json { "cart_id": "a8e61139-3045-470f-b211-90820e862335", "line_items": [ { "line_item_id": "d2d196b2-733c-457a-a7c9-001b68517807", "sku": "MT12", "base_sku": "MT12", "quantity": 1, "requires_shipping": true, "description": "Cassius Sparring Tank", "price": { "currency": "USD", "value": 18, "number": 1800, "symbol": "$" }, "line_price": { "currency": "USD", "value": 18, "number": 1800, "symbol": "$" }, "msrp": { "currency": "USD", "value": 21.6, "number": 2160, "symbol": "$" }, "image": { "url": "https://staging.luma.gift/cassius-sparring-tank.jpg", "alt": "Cassius Sparring Tank", "type": "default" } } ], "payment_method": { "payment_type": "paypal", "attributes": { "paypal_token": "EC-XXXXXXXXXXXXXXXXX", "url": "https://www.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=EC-XXXXXXXXXXXXXXXXX", "sandbox": false } }, "payment_method_options": [ { "type": "CreditCard", "wallet": "user" }, { "type": "PayPal", "wallet": "paypal" } ], "shop_properties": { "paypal": { "clientId": "YOUR_MERCHANT_PAYPAL_CLIENT_ID", "sandbox": false, "intent": "order", "integration_version": "v2" }, "order_status_supported": true }, "shipping_info": { "first_name": "John", "last_name": "Smith", "email": "john@example.com", "phone": "2065551212", "address1": "123 Main St", "city": "Seattle", "state_or_province": "WA", "state_name": "Washington", "country": "US", "postal_code": "98101" }, "shipping_method": { "sku": "standard_shipping", "description": "Standard Shipping", "price": { "currency": "USD", "value": 10, "number": 1000, "symbol": "$" } }, "sub_total": { "currency": "USD", "value": 18, "number": 1800, "symbol": "$" }, "shipping_total": { "currency": "USD", "value": 10, "number": 1000, "symbol": "$" }, "tax": { "currency": "USD", "value": 2, "number": 200, "symbol": "$" }, "total": { "currency": "USD", "value": 30, "number": 3000, "symbol": "$" }, "cart_status": "active", "display_name": "Luma (Staging)", "shop_id": "staging.luma.gift" } ``` ## Next Steps `start` does not charge anything. Between this call and [Authorize](/api-reference/payment/express-checkout/paypal/authorize), the buyer approves the payment in PayPal's own window — you either load the PayPal JS SDK with the `clientId` from `shop_properties.paypal` and let it drive the approval, or send the buyer to the `url` returned above. PayPal returns a **payer ID** on approval. That payer ID plus the `paypal_token` are what Authorize needs. --- ## Related Endpoints - [Authorize](/api-reference/payment/express-checkout/paypal/authorize) — Confirm the buyer's PayPal approval - [Complete Order](/api-reference/payment/express-checkout/paypal/complete-order) — Place the order ## Error Responses Errors return a JSON body with `code`, `error`, and `description`. Program against the `error` value — descriptions are human-readable and may change. **400 — InvalidInputBody** The request body is present but not a JSON object. ```json { "code": 400, "error": "InvalidInputBody", "description": "The body is not processable" } ``` **400 — ErrorStartExpressCheckout** Firmly could not open a PayPal session — either PayPal rejected the request or the merchant adapter failed to translate it. ```json { "code": 400, "error": "ErrorStartExpressCheckout", "description": "Could not start checkout." } ``` **400 — InvalidToken** The `x-firmly-authorization` header is missing, empty, or not a well-formed JWT. Device-auth can also surface as `MissingAuthHeader` or `PartnerNotFound`; see [Authentication errors](/api-reference/errors-and-conventions#authentication) for the full set. ```json { "code": 400, "error": "InvalidToken", "description": "Jwt token is invalid." } ``` **401 — InvalidJWTToken** The device JWT is well-formed but its signature does not verify, or required claims are missing. ```json { "code": 401, "error": "InvalidJWTToken", "description": "Jwt token is invalid." } ``` **404 — CartNotFound** No active cart exists for this device on this domain. ```json { "code": 404, "error": "CartNotFound", "description": "Cart was not found." } ``` **404 — DomainNotFound** The `{domain}` path parameter does not match any merchant configured with Firmly, or the merchant has been disabled. ```json { "code": 404, "error": "DomainNotFound", "description": "This domain was not found in firmly servers." } ``` **404 — GatewayNotFound** PayPal is not enabled as a payment gateway for this merchant. Check `payment_method_options` before offering it. ```json { "code": 404, "error": "GatewayNotFound", "description": "Payment gateway 'paypal' not found" } ``` **412 — OperationNotSupported** The merchant adapter does not implement PayPal express checkout. ```json { "code": 412, "error": "OperationNotSupported", "description": "This operation is not supported for this store." } ``` **503 — StoreUnavailable** The merchant's own API was unavailable or timed out. Retry with backoff. ```json { "code": 503, "error": "StoreUnavailable", "description": "Store temporarily unavailable. Please try again later." } ``` **429 — RateLimited** Too many requests from this device. Back off and retry after the `Retry-After` window — see [Rate Limits](/api-reference/rate-limits). ```json { "code": 429, "error": "RateLimited", "description": "Too many requests. Please try again later." } ``` --- # Trigger Enrollment `POST https://api.firmly.work/api/v1/wallets/agentic-pay/enroll/trigger` ## Overview The Trigger Enrollment endpoint initiates a specific verification challenge for a card enrollment that was started via the [Enroll Card](/api-reference/agentic-pay/enroll) endpoint. The caller selects a `method_id` from the verification methods returned by `/enroll` and triggers the corresponding challenge. The response has two possible shapes: - **Challenge returned**: The cardholder must complete a verification step (OTP code entry or iframe interaction) - **Short-circuit**: The device is already bound to this card, and enrollment completes immediately with a `virtual_card_id` ## Authentication - `x-firmly-authorization` (string, required) — API token for server-to-server authentication ## Request Body - `flow_token` (string, required) — JWE-encrypted flow token returned from the `/enroll` response - `method_id` (string, required) — Verification method ID from the `/enroll` response (e.g., `"OTP_SMS"`, `"OTP_EMAIL"`, `"MANAGED_AUTHENTICATION"`, `"VISA_IFRAME_HANDSHAKE"`) - `callback_uri` (string) — Callback URI for iframe-based verification methods. The iframe will redirect to this URI upon completion. - `secure_token` (string) — Secure token captured from the iframe handshake via postMessage. Required when the enrollment included an `embed_iframe_handshake` verification method. ## Response The response takes one of two shapes depending on whether a challenge is required. ### Shape 1: Challenge Returned - `flow_token` (string) — Updated JWE-encrypted flow token for the next call in the enrollment flow - `challenge` (object) — The verification challenge the cardholder must complete **challenge properties** - `challenge.type` (string) — Challenge type: `"otp"` for one-time password or `"embed_iframe"` for iframe-based verification - `challenge.uri` (string) — Iframe URI for `embed_iframe` type challenges. Load this in the cardholder's browser. ### Shape 2: Short-Circuit (Device Already Bound) - `flow_token` (string) — Updated JWE-encrypted flow token - `virtual_card_id` (string) — Network-assigned card identifier. Presence of this field indicates the card is already enrolled on this device and no further verification is needed. ## Code Examples **cURL** ```bash curl --request POST \ --url https://api.firmly.work/api/v1/wallets/agentic-pay/enroll/trigger \ --header 'Content-Type: application/json' \ --header 'x-firmly-authorization: YOUR_API_TOKEN' \ --data '{ "flow_token": "eyJhbGciOiJBMjU2S1ci...", "method_id": "OTP_SMS" }' ``` **JavaScript** ```javascript const response = await fetch('https://api.firmly.work/api/v1/wallets/agentic-pay/enroll/trigger', { method: 'POST', headers: { 'Content-Type': 'application/json', 'x-firmly-authorization': 'YOUR_API_TOKEN' }, body: JSON.stringify({ flow_token: 'eyJhbGciOiJBMjU2S1ci...', method_id: 'OTP_SMS' }) }); const data = await response.json(); if (data.virtual_card_id) { // Short-circuit: device already bound, no challenge needed console.log('Card already enrolled:', data.virtual_card_id); } else { // Challenge returned: present to cardholder console.log('Challenge type:', data.challenge.type); } ``` **Python** ```python import requests response = requests.post( 'https://api.firmly.work/api/v1/wallets/agentic-pay/enroll/trigger', headers={ 'Content-Type': 'application/json', 'x-firmly-authorization': 'YOUR_API_TOKEN' }, json={ 'flow_token': 'eyJhbGciOiJBMjU2S1ci...', 'method_id': 'OTP_SMS' } ) data = response.json() if 'virtual_card_id' in data: # Short-circuit: device already bound print(f"Card already enrolled: {data['virtual_card_id']}") else: # Challenge returned print(f"Challenge type: {data['challenge']['type']}") ``` ### With Iframe Handshake If the `/enroll` response included an `embed_iframe_handshake` verification method, load the iframe, capture the `secure_token` via postMessage, and include it here. In this case the `method_id` is `"VISA_IFRAME_HANDSHAKE"` — `secure_token` accompanies that method specifically (the other `method_id` values, such as `"OTP_SMS"`, do not carry a `secure_token`). **cURL** ```bash curl --request POST \ --url https://api.firmly.work/api/v1/wallets/agentic-pay/enroll/trigger \ --header 'Content-Type: application/json' \ --header 'x-firmly-authorization: YOUR_API_TOKEN' \ --data '{ "flow_token": "", "method_id": "VISA_IFRAME_HANDSHAKE", "secure_token": "captured-from-iframe-postmessage" }' ``` **JavaScript** ```javascript const response = await fetch('https://api.firmly.work/api/v1/wallets/agentic-pay/enroll/trigger', { method: 'POST', headers: { 'Content-Type': 'application/json', 'x-firmly-authorization': 'YOUR_API_TOKEN' }, body: JSON.stringify({ flow_token: '', method_id: 'VISA_IFRAME_HANDSHAKE', secure_token: 'captured-from-iframe-postmessage' }) }); const data = await response.json(); console.log(data.challenge); ``` ## Response Example ```json Shape 1 — Challenge Returned { "flow_token": "", "challenge": { "type": "otp" } } ``` ```json Shape 2 — Short-Circuit (Device Already Bound) { "flow_token": "", "virtual_card_id": "cf90be5c86363de702ed19beec46e102" } ``` ## Error Responses | Error Code | Status | Description | | ---------- | ------ | ----------- | | `BadRequest` | 400 | `secure_token` is required for Visa iframe handshake methods | | `BadRequest` | 400 | Invalid or expired `flow_token` format | | `ErrorServiceUnavailable` | 503 | Network provider (Visa/Mastercard) temporarily unavailable | **400 - Missing Secure Token (Visa)** ```json { "code": 400, "error": "BadRequest", "description": "secure_token is required for VISA_IFRAME_HANDSHAKE method (capture from iframe postMessage)" } ``` **400 - Invalid Flow Token** ```json { "code": 400, "error": "BadRequest", "description": "Invalid or expired flow_token" } ``` **503 - Service Unavailable** ```json { "code": 503, "error": "ErrorServiceUnavailable", "description": "Network provider temporarily unavailable. Retry after a short delay." } ``` --- ## Related Endpoints - [Enroll Card](/api-reference/agentic-pay/enroll) — Start enrollment and get available verification methods - [Agentic Pay Overview](/api-reference/agentic-pay/) — Concepts and full endpoint list --- # Update Line Item `PUT https://api.firmly.work/api/v2/domains/{domain}/cart/line-items/{lineItemId}` ## Overview The Update Line Item endpoint modifies the quantity of an existing product in the cart. Key features include: - **Quantity Modification**: Update item quantities or remove items by setting quantity to 0 - **Automatic Recalculation**: All pricing and shipment information is automatically updated - **Shipment Preservation**: Items remain in their assigned shipments after quantity updates - **Addon Adjustment**: Addon offers may change based on new cart totals ## Authentication - `x-firmly-authorization` (string, required) — Device access token from [Browser Session](/api-reference/authentication/browser-session) > **Note** > This endpoint also accepts **server-to-server (S2S) authentication** for backend integrations acting on behalf of a device. Instead of the `x-firmly-authorization` device token, send `Authorization: Bearer ` (your Firmly API token) together with `x-firmly-device-id` identifying the target device. This is the path behind the `InvalidAPIToken` and S2S `BadRequest` errors listed below. ## Path Parameters - `domain` (string, required) — Domain of the merchant website (e.g., `staging.luma.gift`) - `lineItemId` (string, required) — Unique identifier of the line item to update. This is the `line_item_id` value from `line_items[]` in the cart (the path segment is camelCase; the field in the cart body is snake_case `line_item_id`). ## Request Body - `quantity` (number, required) — New quantity for the line item (minimum 0, set to 0 to remove the item) - `variant_handles` (string[]) — Optional variant configuration handles, for platforms that identify a line's variant by a set of handles rather than a single SKU (e.g. `["color:blue", "size:large"]`). Passed through to the merchant adapter when resolving which variant to update. ## Response Returns the complete updated shopping cart. See [Get Cart](/api-reference/cart-management/get-cart) for full response schema. ### Update Behavior: - **Quantity \> 0**: Updates the item quantity and recalculates pricing - **Quantity = 0**: Removes the item from the cart and its shipment - **Empty Shipments**: Shipments with no remaining items are automatically removed ## Code Examples **cURL** ```bash curl --request PUT \ --url https://api.firmly.work/api/v2/domains/staging.luma.gift/cart/line-items/item_01H2XVBR8C8JS5MQSFPJ8HF9SB \ --header 'Content-Type: application/json' \ --header 'x-firmly-authorization: YOUR_TOKEN' \ --data '{ "quantity": 2 }' ``` **JavaScript** ```javascript const response = await fetch('https://api.firmly.work/api/v2/domains/staging.luma.gift/cart/line-items/item_01H2XVBR8C8JS5MQSFPJ8HF9SB', { method: 'PUT', headers: { 'Content-Type': 'application/json', 'x-firmly-authorization': 'YOUR_TOKEN' }, body: JSON.stringify({ quantity: 2 }) }); const cart = await response.json(); console.log(cart); ``` **Python** ```python import requests response = requests.put( 'https://api.firmly.work/api/v2/domains/staging.luma.gift/cart/line-items/item_01H2XVBR8C8JS5MQSFPJ8HF9SB', headers={ 'Content-Type': 'application/json', 'x-firmly-authorization': 'YOUR_TOKEN' }, json={ 'quantity': 2 } ) cart = response.json() print(cart) ``` **PHP** ```php 2 ]; curl_setopt_array($curl, [ CURLOPT_URL => "https://api.firmly.work/api/v2/domains/staging.luma.gift/cart/line-items/item_01H2XVBR8C8JS5MQSFPJ8HF9SB", CURLOPT_RETURNTRANSFER => true, CURLOPT_CUSTOMREQUEST => "PUT", CURLOPT_HTTPHEADER => [ "Content-Type: application/json", "x-firmly-authorization: YOUR_TOKEN" ], CURLOPT_POSTFIELDS => json_encode($data) ]); $response = curl_exec($curl); curl_close($curl); $cart = json_decode($response, true); print_r($cart); ?> ``` ## Example Scenarios ### Increase Quantity Update an item from quantity 1 to 2. Request: ```json { "quantity": 2 } ``` Response (truncated — the full cart is returned): ```json { "line_items": [ { "line_item_id": "bd3710bc-97ef-408d-7382-43b7e5de712f", "platform_line_item_id": "e67bf7d1-ec90-4714-b44c-de044cd7daf7", "sku": "MH07-XS-Gray", "base_sku": "MH07", "description": "Hero Hoodie - Gray XS", "quantity": 2, "price": { "currency": "USD", "value": 54.00, "number": 5400, "symbol": "$" }, "line_price": { "currency": "USD", "value": 108.00, "number": 10800, "symbol": "$" }, "msrp": { "currency": "USD", "value": 54.00, "number": 5400, "symbol": "$" }, "image": { "url": "https://cdn.staging.luma.gift/product/hero-hoodie.jpg", "type": "default" }, "requires_shipping": true } ], "sub_total": { "currency": "USD", "value": 108.00, "number": 10800, "symbol": "$" } } ``` ### Remove Item Set quantity to 0 to remove an item. Request: ```json { "quantity": 0 } ``` Response — line item dropped, totals re-zeroed: ```json { "line_items": [], "shipments": [], "sub_total": { "currency": "USD", "value": 0, "number": 0, "symbol": "$" } } ``` ## Response Example ```json { "cart_id": "a5600193-2c13-3356-d063-711da63b7cd7", "platform_id": "example_commerce", "shop_id": "staging.luma.gift", "display_name": "Luma Store", "cart_status": "active", "line_items": [ { "line_item_id": "bd3710bc-97ef-408d-7382-43b7e5de712f", "sku": "MH07-XS-Gray", "base_sku": "MH07", "description": "Hero Hoodie - Gray XS", "quantity": 2, "price": { "currency": "USD", "value": 54.0, "number": 5400, "symbol": "$" }, "line_price": { "currency": "USD", "value": 108.0, "number": 10800, "symbol": "$" }, "msrp": { "currency": "USD", "value": 64.8, "number": 6480, "symbol": "$" }, "image": { "url": "https://staging.luma.gift/hero-hoodie-gray-xs.jpg", "alt": "Hero Hoodie - Gray XS", "type": "default" } } ], "shipments": [ { "shipment_id": "d22998b9-d331-c3f7-ca55-6d70072dd1fb", "line_item_ids": [ "bd3710bc-97ef-408d-7382-43b7e5de712f" ], "fulfillment_type": { "id": "SHIP_TO_ADDRESS", "name": "Ship to Address", "description": "Standard shipping to customer address" }, "shipping_method": { "id": "STANDARD_GROUND", "description": "Standard Ground Shipping", "price": { "currency": "USD", "value": 49.99, "number": 4999, "symbol": "$" }, "estimated_delivery": "5-7 business days" } } ], "addons": { "offers": [ { "addon_id": "bulk_discount", "display": { "name": "Bulk Purchase Discount", "description": "Save 5% on orders with 2+ items" }, "scope": "CART", "coverage_mode": "PREDEFINED_GROUP", "price": { "currency": "USD", "value": -5.4, "number": -540, "symbol": "$" } } ], "selections": [] }, "sub_total": { "currency": "USD", "value": 108.0, "number": 10800, "symbol": "$" }, "shipping_total": { "currency": "USD", "value": 49.99, "number": 4999, "symbol": "$" }, "tax_total": { "currency": "USD", "value": 10.8, "number": 1080, "symbol": "$" }, "fees": [ { "description": "Recycle fee", "currency": "USD", "value": 2.00, "number": 200, "symbol": "$" } ], "fee_total": { "currency": "USD", "value": 2.00, "number": 200, "symbol": "$" }, "addon_total": { "currency": "USD", "value": 0.0, "number": 0, "symbol": "$" }, "total": { "currency": "USD", "value": 170.79, "number": 17079, "symbol": "$" }, "schema_version": "2.0" } ``` --- ## Related Endpoints - [Get Cart](/api-reference/cart-management/get-cart) — View current cart state - [Add Line Item](/api-reference/cart-management/add-line-item) — Add new items to cart - [Clear Cart](/api-reference/cart-management/clear-cart) — Empty the entire cart ## Error Responses Errors return a JSON body with `code`, `error`, and `description`. Program against the `error` value — descriptions are human-readable and may change. **400 — MissingAuthHeader** The `x-firmly-authorization` header is missing or empty. ```json { "code": 400, "error": "MissingAuthHeader", "description": "x-firmly-authorization header is missing or invalid." } ``` **400 — InvalidToken** The authorization token is not a valid JWT structure. ```json { "code": 400, "error": "InvalidToken", "description": "Jwt token is invalid." } ``` **400 — InvalidAPIToken** The API token (server-to-server secret) is invalid or has been revoked. ```json { "code": 400, "error": "InvalidAPIToken", "description": "API token is invalid." } ``` **400 — BadRequest** Server-to-server auth was attempted but the required headers (`x-firmly-authorization` plus `x-firmly-device-id`) are missing or malformed. ```json { "code": 400, "error": "BadRequest", "description": "Bad request." } ``` **401 — Unauthorized** The authorization token was rejected. ```json { "code": 401, "error": "Unauthorized", "description": "Unauthorized." } ``` **401 — InvalidJWTToken** The device JWT signature does not verify, or required claims are missing. ```json { "code": 401, "error": "InvalidJWTToken", "description": "Jwt token is invalid." } ``` **404 — PartnerNotFound** The `appid` claim on the device JWT does not map to a known partner / tenant — typically a token from a different environment. ```json { "code": 404, "error": "PartnerNotFound", "description": "Partner not found." } ``` **404 — DomainNotFound** The `{domain}` path parameter does not match any merchant configured with Firmly, or the merchant has been disabled. Verify the domain string (case-sensitive, no protocol or trailing slash). ```json { "code": 404, "error": "DomainNotFound", "description": "This domain was not found in firmly servers." } ``` **404 — ProductNotFound** The supplied `lineItemId` does not map to an item in the current cart. Refresh the cart via [Get Cart](/api-reference/cart-management/get-cart) to obtain current line item IDs and retry. > **Note** > An unknown `lineItemId` on this endpoint returns `404 ProductNotFound` — not the `NoLineItemError` used elsewhere for cart-empty conditions. Branch on both `error` and `code` when handling missing-item cases. ```json { "code": 404, "error": "ProductNotFound", "description": "Product not found." } ``` **409 — NotEnoughStockError** The requested `quantity` exceeds available inventory for the underlying variant. Reduce the quantity or wait for restock. ```json { "code": 409, "error": "NotEnoughStockError", "description": "Not enough stock." } ``` **412 — OperationNotSupported** The merchant's platform does not support this operation. Check with [Firmly](/contact) whether this endpoint is available for the merchant. ```json { "code": 412, "error": "OperationNotSupported", "description": "This operation is not supported for this store." } ``` **412 — ProductNotSupported** The line item references a product type that is not supported by this merchant's integration (e.g. some merchants reject subscription items or digital goods on update). ```json { "code": 412, "error": "ProductNotSupported", "description": "Product is not supported." } ``` **412 — PostalCodeRequired** The merchant requires a postal code before line items can be modified. Call [Set Postal Code](/api-reference/session/set-postal-code), then retry. ```json { "code": 412, "error": "PostalCodeRequired", "description": "Postal code is required." } ``` **400 — InvalidInputBody** Request body fails schema validation. Ensure `quantity` is present and is an integer `>= 0` (use `0` to remove the line item). ```json { "code": 400, "error": "InvalidInputBody", "description": "The body is not processable" } ``` --- # Verify Enrollment `POST https://api.firmly.work/api/v1/wallets/agentic-pay/enroll/verify` ## Overview Completes a verification step during card enrollment. This endpoint may be called multiple times in sequence — first with an OTP code, then with a FIDO registration result. The response indicates whether enrollment is complete or another verification step is needed. - **OTP verification**: Submit the one-time passcode sent to the cardholder - **FIDO registration**: Submit the iframe result captured via `postMessage` from the network authentication iframe - **Multi-step flow**: After OTP verification succeeds, the response may return a FIDO registration challenge as the next required step ## Authentication - `x-firmly-authorization` (string, required) — API token for authenticating the request ## Request Body - `flow_token` (string, required) — Flow token returned from the previous enrollment step (Trigger Enrollment or a prior Verify Enrollment call) - `type` (string, required) — Verification type being submitted. One of: - `otp` — One-time passcode verification - `embed_iframe` — FIDO iframe registration result - `value` (string) — The OTP code entered by the cardholder. Required when `type` is `otp`. - `iframe_result` (object) — FIDO registration result captured from the authentication iframe via `postMessage`. Required when `type` is `embed_iframe`. **Properties:** - `fidoBlob` (string): FIDO credential blob from the iframe - `assuranceData` (string): Assurance data from the iframe ## Response The response takes one of two shapes depending on whether enrollment is complete. ### Shape 1 — More Verification Needed Returned when additional verification steps remain (e.g., FIDO registration after OTP). - `flow_token` (string) — Refreshed flow token for the next verification call - `verification_methods` (array) — Array of remaining verification steps the cardholder must complete **Item properties:** - `id` (string): Verification method identifier (e.g., `FIDO_REGISTER`) - `type` (string): Challenge delivery type (e.g., `embed_iframe`) - `attributes` (object): Contains `uri`, `endpoint`, `identifier`, and `payload` for rendering the FIDO iframe ### Shape 2 — Enrollment Complete Returned when all verification steps are satisfied and the card is enrolled. - `flow_token` (string) — Final flow token to use when creating a payment intent - `virtual_card_id` (string) — Identifier confirming the card has been successfully enrolled ## Code Examples **cURL** ```bash # OTP verification curl --request POST \ --url https://api.firmly.work/api/v1/wallets/agentic-pay/enroll/verify \ --header 'Content-Type: application/json' \ --header 'x-firmly-authorization: YOUR_TOKEN' \ --data '{ "flow_token": "eyJhbGciOiJBMjU2S1ci...", "type": "otp", "value": "123456" }' ``` **JavaScript** ```javascript // OTP verification const response = await fetch('https://api.firmly.work/api/v1/wallets/agentic-pay/enroll/verify', { method: 'POST', headers: { 'Content-Type': 'application/json', 'x-firmly-authorization': 'YOUR_TOKEN' }, body: JSON.stringify({ flow_token: 'eyJhbGciOiJBMjU2S1ci...', type: 'otp', value: '123456' }) }); const result = await response.json(); if (result.virtual_card_id) { console.log('Enrollment complete:', result.virtual_card_id); } else { console.log('Next step:', result.verification_methods[0].id); } ``` **Python** ```python import requests # OTP verification response = requests.post( 'https://api.firmly.work/api/v1/wallets/agentic-pay/enroll/verify', headers={ 'Content-Type': 'application/json', 'x-firmly-authorization': 'YOUR_TOKEN' }, json={ 'flow_token': 'eyJhbGciOiJBMjU2S1ci...', 'type': 'otp', 'value': '123456' } ) result = response.json() if 'virtual_card_id' in result: print('Enrollment complete:', result['virtual_card_id']) else: print('Next step:', result['verification_methods'][0]['id']) ``` ## Response Example ```json Shape 1 — More Verification Needed { "flow_token": "", "verification_methods": [ { "id": "FIDO_REGISTER", "type": "embed_iframe", "attributes": { "uri": "https://sbx.vts.auth.visa.com/vts-auth/register?apiKey=...", "endpoint": "L3JlZ2lzdGVy", "identifier": "59c3208baeadec4566181b18356a5e02", "payload": "eyJraWQiOiI0ZDkxZWY5MiIsImFsZyI6IlJTMjU2In0" } } ] } ``` ```json Shape 2 — Enrollment Complete { "flow_token": "", "virtual_card_id": "cf90be5c86363de702ed19beec46e102" } ``` ## Error Responses | Code | Status | Description | | --------------------- | ------ | ---------------------------------------------------- | | `BadRequest` | 400 | Invalid `flow_token` format or missing required fields | | `BadRequest` | 400 | Incorrect OTP code submitted by the cardholder — the network (VTS) surfaces a wrong OTP as a `400 BadRequest`, not a distinct `InvalidOtp` literal | | `ErrorServiceUnavailable` | 503 | Network verification service failed or timed out | **400 - Bad Request** ```json { "code": 400, "error": "BadRequest", "description": "Invalid or expired flow_token" } ``` **400 - Incorrect OTP** A wrong OTP on the Agentic Pay path surfaces as a `400 BadRequest` carrying the network (VTS) message — there is no distinct `InvalidOtp` literal on this path. Branch on `400 BadRequest` and prompt the cardholder to re-enter the code. (The legacy `InvalidOtp` literal is a `401` on the older click-to-pay flow, not this one.) ```json { "code": 400, "error": "BadRequest", "description": "The OTP code is incorrect. Ask the cardholder to re-enter it." } ``` **503 - Service Unavailable** ```json { "code": 503, "error": "ErrorServiceUnavailable", "description": "Network verification service temporarily unavailable. Retry after a short delay." } ``` --- ## Related Endpoints - [Trigger Enrollment](/api-reference/agentic-pay/trigger-enrollment) — Start the enrollment flow and receive the initial challenge - [Create Intent](/api-reference/agentic-pay/create-intent) — Create a payment intent after enrollment is complete --- # Wallet Complete Order `POST https://cc.firmly.work/api/v2/payment/domains/{domain}/wallet-complete-order` > **Note** > Use **complete-order** to finalize a cart you already built across previous calls (add-line-item, shipping, etc.). For the one-shot create-and-place path, use place-order instead. ## Overview Completes checkout using wallet-provided payment credentials. For Agentic Pay, Firmly retrieves network token credentials (PAN, expiry, cryptogram) from the wallet, then tokenizes with the merchant's PSP and places the order. This endpoint supports multiple wallet types. This page focuses on the **Agentic Pay** flow. > **Note** > **Prerequisite — the cart must already exist.** This endpoint completes an > existing cart; it does not create one. Before calling it you must have a cart > for `{domain}` (tied to the same device session) that already holds line items > and shipping info. Set that up first with > [Browser Session](/api-reference/authentication/browser-session) → > [Add Line Item](/api-reference/cart-management/add-line-item) → > [Set Shipping Info](/api-reference/checkout/set-shipping-info). A cart without a > payment handle returns `MissingRequiredParameters`. ## Authentication This endpoint uses the same `deviceAuth` strategy as the card [Complete Order](/api-reference/payment/complete-order-v2) endpoint — a single device JWT in the `x-firmly-authorization` header. On this device-JWT path, the App ID and device ID are carried as claims inside that JWT; they are **not** separate request headers. - `x-firmly-authorization` (string, required) — Device authentication token (JWT) from [Browser Session](/api-reference/authentication/browser-session) ## Path Parameters - `domain` (string, required) — The merchant domain (e.g., "staging.luma.gift") ## Request Body - `wallet` (string, required) — Wallet type. One of: `visa`, `paze`, `mastercard-unified`, `agentic-pay`, `samsung-wallet`. Use `agentic-pay` for every Agentic Pay order regardless of card network — Visa, Mastercard, and Discover alike; the network travels inside the `flow_token`, and `visa` / `mastercard-unified` are the separate Click to Pay wallets, not Agentic Pay. - `additional_data` (object, optional) — Wallet-specific payment data (required for Agentic Pay). For Agentic Pay, provide: - `flow_token` (string, required) — Flow token from the [Intent Challenge](/api-reference/agentic-pay/intent-challenge) response - `intent_id` (string) — Intent ID from the Intent Challenge response - `transaction` (object) — Capture details: `amount` and `currency_code` (the capture; `amount` must be ≤ the authorized `mandate.amount`), plus optional `merchant_name`, `merchant_url`, and `merchant_country_code`. **Submitting an `amount` greater than the `mandate.amount` authorized at [Create Intent](/api-reference/agentic-pay/create-intent)** is rejected with a `400 BadRequest` before the network is called. The amount compared against the mandate is the **cart total on file**, not the value you send here — `transaction` is informational and cannot lower the checked amount. - `billing_info` (object) — Billing address. Used as fallback if the network does not return billing data with the credentials. **Required for `samsung-wallet`.** **Fields:** - `first_name` (string) — Buyer's first name - `last_name` (string) — Buyer's last name - `email` (string) — Email address - `phone` (string) — Phone number - `address1` (string) — Primary address line - `city` (string) — City - `state_or_province` (string) — State/province code - `country` (string) — Country code (ISO 3166-1 alpha-2, e.g. `US`) - `postal_code` (string) — ZIP or postal code - `credit_card_id` (string) — Card identifier from the wallet (required for `visa`, `paze`, `mastercard-unified`; not needed for `agentic-pay` or `samsung-wallet`) - `encrypted_card` (string) — Samsung network-token JWE (required for `samsung-wallet`; not used by the other wallet types) - `captcha_token` (string) — Captcha verification token when required by the merchant ## Response Returns either a CVV requirement or the submitted cart. ### CVV Required (early return) When the wallet requires CVV verification before completing, the endpoint returns early without placing the order: ```json { "cvv_required": true } ``` Collect the CVV from the cardholder and re-call this same `wallet-complete-order` endpoint with the CVV supplied in the request body to finish placing the order. The initial call is not retried automatically — you must issue a second request once the CVV is available. > **Note** > Submit the CVV on the follow-up call in the `verification_value` field — a JWE-encrypted string (encrypted the same way as the card handle, using the public key from [Get Public Key](/api-reference/payment/get-public-key)). ### Order Placed (success) Returns the full cart object with `cart_status: "submitted"` and a `platform_order_number`. - `cart_status` (string) — Cart status — `"submitted"` on success - `platform_order_number` (string) — Merchant-assigned order number - `cart_id` (string) — Firmly cart identifier - `line_items` (array) — Array of items in the order - `total` (object) — Order total with `currency`, `value`, `number`, `symbol` - `billing_info` (object) — Billing address used for the order - `shipping_info` (object) — Shipping address for the order - `payment_summary` (object) — Payment details. For Agentic Pay orders this also carries the persisted `card_art` and `masked` so receipts/order views can render the **funding card** (distinct from the top-level `last_four`, which is the network token). **payment_summary properties** - `payment_summary.payment_type` (string) — e.g. `"CreditCard"` - `payment_summary.last_four` (string) — Last four of the network token - `payment_summary.month` (integer) — Expiry month - `payment_summary.year` (integer) — Expiry year - `payment_summary.card_type` (string) — Card brand (e.g. `"Visa"`, `"Mastercard"`) - `payment_summary.card_art` (object) — Issuer card art `{ network, url, background_color, foreground_color, descriptor }` (Agentic Pay). See [Card Art](/api-reference/agentic-pay/card-art). - `payment_summary.masked` (object) — Funding-card display fields `{ last4, exp_month, exp_year, brand, card_type, issuer_name }` (Agentic Pay). `card_type` and `issuer_name` are Mastercard only. ## Code Example **JavaScript** ```javascript const response = await fetch( 'https://cc.firmly.work/api/v2/payment/domains/staging.luma.gift/wallet-complete-order', { method: 'POST', headers: { 'x-firmly-authorization': deviceJwt, 'Content-Type': 'application/json' }, body: JSON.stringify({ wallet: 'agentic-pay', additional_data: { flow_token: flowToken, intent_id: intentId, transaction: { amount: '585.49', currency_code: 'USD', merchant_name: 'My Store' } }, billing_info: { first_name: 'John', last_name: 'Smith', address1: '123 Main St', city: 'San Francisco', state_or_province: 'CA', country: 'US', postal_code: '94105', email: 'john@example.com', phone: '4155551212' } }) } ); const order = await response.json(); console.log('Order number:', order.platform_order_number); ``` **Python** ```python import requests response = requests.post( 'https://cc.firmly.work/api/v2/payment/domains/staging.luma.gift/wallet-complete-order', headers={ 'x-firmly-authorization': device_jwt, 'Content-Type': 'application/json' }, json={ 'wallet': 'agentic-pay', 'additional_data': { 'flow_token': flow_token, 'intent_id': intent_id, 'transaction': { 'amount': '585.49', 'currency_code': 'USD' } }, 'billing_info': { 'first_name': 'John', 'last_name': 'Smith', 'address1': '123 Main St', 'city': 'San Francisco', 'state_or_province': 'CA', 'country': 'US', 'postal_code': '94105', 'email': 'john@example.com', 'phone': '4155551212' } } ) order = response.json() ``` **cURL** ```bash curl -X POST https://cc.firmly.work/api/v2/payment/domains/staging.luma.gift/wallet-complete-order \ -H "x-firmly-authorization: DEVICE_JWT" \ -H "Content-Type: application/json" \ -d '{ "wallet": "agentic-pay", "additional_data": { "flow_token": "eyJhbGci...", "intent_id": "1-5C90F150...", "transaction": { "amount": "585.49", "currency_code": "USD" } }, "billing_info": { "first_name": "John", "last_name": "Smith", "address1": "123 Main St", "city": "San Francisco", "state_or_province": "CA", "country": "US", "postal_code": "94105", "email": "john@example.com", "phone": "4155551212" } }' ``` ## Response Example ```json { "display_name": "Luma (Staging)", "cart_status": "submitted", "platform_id": "example_commerce", "shop_id": "staging.luma.gift", "cart_id": "4dbaf295-93d1-452b-a7e5-a5965ca2871d", "submitted_at": "2026-04-29T07:15:35.367Z", "platform_order_number": "29185", "line_items": [ { "line_item_id": "d290c5fa-0e91-462f-b53f-08d5b71ae532", "sku": "Product-SKU", "quantity": 1, "description": "Product Name", "price": { "currency": "USD", "value": 1, "number": 100, "symbol": "$" }, "line_price": { "currency": "USD", "value": 1, "number": 100, "symbol": "$" }, "msrp": { "currency": "USD", "value": 1.2, "number": 120, "symbol": "$" }, "image": { "url": "https://staging.luma.gift/product-name.jpg", "alt": "Product Name", "type": "default" } } ], "shipping_info": { "first_name": "John", "last_name": "Doe", "address1": "500 Howard St", "city": "San Francisco", "state_or_province": "CA", "country": "US", "postal_code": "94105", "email": "john@example.com", "phone": "14155550134" }, "billing_info": { "first_name": "John", "last_name": "Doe", "address1": "500 Howard St", "city": "San Francisco", "state_or_province": "CA", "country": "US", "postal_code": "94105" }, "total": { "currency": "USD", "value": 1, "number": 100, "symbol": "$" }, "sub_total": { "currency": "USD", "value": 1, "number": 100, "symbol": "$" }, "tax": { "currency": "USD", "value": 0, "number": 0, "symbol": "$" }, "payment_summary": { "payment_type": "AgenticPay", "last_four": "4444", "month": 12, "year": 2030, "card_type": "Mastercard", "card_art": { "network": "mastercard", "url": "https://api.firmly.work/api/v1/wallets/agentic-pay/card-art/", "background_color": "#1A1F71", "foreground_color": "#FFFFFF", "descriptor": "Test Bank 2" }, "masked": { "last4": "4595", "exp_month": "12", "exp_year": "2030", "brand": "mastercard", "card_type": "DEBIT", "issuer_name": "Test Bank 2" } } } ``` > **Note** > For Agentic Pay, `payment_type` is `"AgenticPay"` and `payment_summary` > carries the persisted `card_art` and `masked` funding-card details. Note that > the top-level `last_four` (`"4444"`) is the **network token**, while > `masked.last4` (`"4595"`) is the **funding card** the cardholder sees. ## Error Responses Errors return a JSON body with `code`, `error`, and `description`. Program against the `error` value — descriptions are human-readable and may change. **400 — BadRequest** The `wallet` field is missing or is not one of the supported wallet identifiers, or (Agentic Pay) the cart total exceeds the authorized `mandate.amount` — the mandate check rejects the charge before the network is called. ```json { "code": 400, "error": "BadRequest", "description": "Unsupported wallet identifier." } ``` **400 — InvalidToken** The authorization token is not a valid JWT structure, or it has expired. ```json { "code": 400, "error": "InvalidToken", "description": "Jwt token is invalid." } ``` **400 — MissingRequiredParameters** The cart is missing data needed to complete the order (e.g. no `payment_handle` because Set Shipping Info has not been called). ```json { "code": 400, "error": "MissingRequiredParameters", "description": "Cart does not have a payment handle" } ``` **401 — InvalidJWTToken** The device JWT signature does not verify, or required claims are missing. ```json { "code": 401, "error": "InvalidJWTToken", "description": "Jwt token is invalid." } ``` **404 — CartNotFound** No active cart exists for this device on this domain. ```json { "code": 404, "error": "CartNotFound", "description": "Cart was not found." } ``` **409 — PaymentMethodNotAvailable** The requested wallet payment method is not available for this merchant. ```json { "code": 409, "error": "PaymentMethodNotAvailable", "description": "Payment method not available." } ``` **412 — CheckoutError** Merchant-side checkout failure — payment info or billing address was rejected. ```json { "code": 412, "error": "CheckoutError", "description": "Payment info or billing address invalid." } ``` **412 — CountryNotSupported** The `billing_info.country` is outside the supported set (currently `US` and `AU`). Firmly rejects the order before tokenization. ```json { "code": 412, "error": "CountryNotSupported", "description": "We don't currently support this country/region. Enter a new address and try again." } ``` **400 — InvalidInputBody** Request body failed schema validation. ```json { "code": 400, "error": "InvalidInputBody", "description": "The body is not processable" } ``` **422 — CreditCardDeclined** Payment was declined by the network / PSP. ```json { "code": 422, "error": "CreditCardDeclined", "description": "Credit card declined" } ``` **422 — CreditCardInvalidNumber** Card number failed PSP validation. ```json { "code": 422, "error": "CreditCardInvalidNumber", "description": "Credit card number is invalid." } ``` --- ## Related Endpoints - [Intent Challenge](/api-reference/agentic-pay/intent-challenge) — Get the flow_token and intent_id - [Browser Session](/api-reference/authentication/browser-session) — Get device JWT for authentication - [Complete Order](/api-reference/payment/complete-order-v2) — Alternative flow with encrypted card data --- # completeOrder ## Overview `completeOrder` finishes the payment. It hands the flow to **Firmly's payment vault**, which proxies into the service-binding-only `/complete` route, fetches the network token credentials, and submits the order to the merchant. > **Note** > The `/complete` route is intentionally **not** callable from the browser — the > payment vault is the only path. `completeOrder` authenticates with `deviceToken` > (a JWT from [`POST /api/v1/browser-session`](/api-reference/authentication/browser-session)), > **not** the `apiToken`, because the vault routes use a different auth strategy. ## Signature ```js const order = await fap.completeOrder(session, options); ``` ## Parameters - `session` (FlowSession, required) — A session with both `flow_token` and `intentId` set — i.e. `createIntent` has already run. - `options.domain` (string) — Merchant domain for the order. Set here **or** as `ClientConfig.merchantDomain` — one of the two must be provided. - `options.deviceTokenOverride` (string) — Device JWT for the vault's `deviceAuth`. Set here **or** as `ClientConfig.deviceToken` — one of the two must be provided. Mint via [`POST /api/v1/browser-session`](/api-reference/authentication/browser-session). - `options.billingInfo` (object) — Forwarded to vault as `billing_info`. Required when the agentic-pay handler cannot fall back to a billing address from the network token — vault's place-order step validates the billing country and throws when it is missing. - `options.captchaToken` (string) — Forwarded to vault as `captcha_token` — some merchants require it. - `options.additional` (object) — Extra fields merged into vault's `additional_data` object (e.g. `card_art`). - `options.signal` (AbortSignal) — Abort the request. ## Returns `Promise` — the [Wallet Complete Order](/api-reference/payment/wallet-complete-order) response, passed through verbatim. See that page for the full response schema. It is the placed **cart** — `cart_id`, `cart_status: "submitted"`, a `platform_order_number`, the `total`, and a `payment_summary` (which carries the `card_art`). ```json Truncated success payload { "cart_id": "4dbaf295-93d1-452b-a7e5-a5965ca2871d", "cart_status": "submitted", "platform_order_number": "29185", "total": { "currency": "USD", "value": 88.99, "number": 8899, "symbol": "$" }, "payment_summary": { "card_type": "Visa", "card_art": { "url": "https://api.firmly.work/api/v1/wallets/agentic-pay/card-art/" } } } ``` ### Failure modes The call rejects (does not resolve) when the vault cannot place the order. Two common cases: - **Missing billing country.** If the agentic-pay handler cannot fall back to a billing address from the network token, the vault's place-order step validates the billing country and throws when it is absent. Pass `options.billingInfo` with a `country` to avoid this. - **Captcha rejection.** Some merchants require a captcha; a missing or rejected `options.captchaToken` is surfaced as a failure from the vault. Supply a valid token when the merchant requires one. ## Example ```js const order = await fap.completeOrder(session, { domain: 'staging.luma.gift', deviceTokenOverride: browserSessionJwt, billingInfo: { first_name: 'Jane', last_name: 'Doe', country: 'US' // ... } }); console.log('Order placed:', order); ``` > **Tip** > Cleaner: set `deviceToken` and `merchantDomain` once on `ClientConfig` at > construction, and omit `deviceTokenOverride` / `domain` from the per-call > options. --- ## Related - [`createIntent`](/api-reference/headless-sdk/create-intent) — must run first - [Wallet Complete Order API](/api-reference/payment/wallet-complete-order) — the underlying order-placement endpoint --- # createIntent ## Overview `createIntent` creates a payment intent bound to a **mandate** (the transaction amount, currency, and merchant details). It runs the intent challenge and returns an `intentId` once the cardholder is authenticated. For Mastercard, the payment challenge (the `MANAGED_AUTHENTICATION` iframe) is produced here — so `createIntent` mounts an iframe and needs a `container`. ## Signature ```js const result = await fap.createIntent(session, mandate, options); ``` ## Parameters - `session` (FlowSession, required) — A verified session from `registerPasskey` / `verifyOtp` / `selectCard`. - `mandate` (object, required) — The transaction the cardholder is authorizing. **Required fields:** - `amount` (string) — Transaction amount. - `currency_code` (string) — ISO currency code (e.g. `"USD"`, `"AUD"`). **Optional fields:** - `merchant_name` — Merchant display name. - `currency_numeric` — ISO numeric currency code. - `merchant_category` / `merchant_category_code` - `description`, `consumer_prompt` - `quantity`, `ttl_seconds` - `callback_uri` — overrides `ClientConfig.bridgeUrl` for this intent (used by Mastercard's TAS authenticate step). - `options.container` (Element) — DOM element to mount the intent challenge iframe in. Required whenever this call mounts an iframe — i.e. for **Mastercard**, where the payment challenge (`MANAGED_AUTHENTICATION`) is produced here. For **Visa**, the FIDO assertion iframe is also driven from this step, so provide a `container` (or set `ClientConfig.iframeContainer`). The iframe is only skipped when the network short-circuits (e.g. a re-authenticated Visa flow that returns the intent directly). - `options.secureToken` (string) — **Visa only, optional override.** For Visa the SDK auto-mints a fresh `secureToken` via an iframe re-handshake (`_mintVisaSecureToken`), so you normally omit this. Supply it only to short-circuit the handshake (e.g. tests, replayed flows, or environments where the iframe cannot mount). Ignored for Mastercard. - `options.callbackUri` (string) — Overrides the default `bridgeUrl`. - `options.apiTokenOverride` (string) — Override the `apiToken` for this call. - `options.signal` (AbortSignal) — Abort the iframe wait. ## Returns `Promise` - `session` (FlowSession) — The advanced session — now holds `intentId`. - `intentId` (string) — The created payment intent identifier. Pass `session` to `completeOrder`. ## Example ```js // `session` is the verified session from registerPasskey / verifyOtp / selectCard. const { session: intentSession, intentId } = await fap.createIntent( session, { amount: '36.99', currency_code: 'AUD', merchant_name: 'Sydney Zoo Shop' }, { container: document.getElementById('mc-iframe-slot') } ); // Pass intentSession forward to completeOrder. ``` --- ## Related - [`completeOrder`](/api-reference/headless-sdk/complete-order) — place the order - [Create Intent API](/api-reference/agentic-pay/create-intent) - [Intent Challenge](/api-reference/agentic-pay/intent-challenge) --- # deleteCard ## Overview `deleteCard` revokes a previously enrolled card on its network, so the stored `virtualCardId` can no longer start a payment. Use it when the buyer removes a saved card from your surface. It wraps the REST [Delete Card](/api-reference/agentic-pay/delete-card) endpoint. Two call shapes, matching the endpoint: - **With a live `FlowSession`** — pass `{ session }` while you still hold the session from the current flow. - **Partner-direct cleanup** — pass `{ network, virtualCardId }` when the session is long gone (for example, a settings page where the buyer deletes a card enrolled days earlier). > **Note** > **Retries are safe.** A rejection with the REST [`PaymentMethodNotAvailable` (409)](/api-reference/agentic-pay/delete-card#error-responses) > means the card is already gone — treat it as "already deleted". A revoked `virtualCardId` cannot be reused; > the buyer must run [`enrollCard`](/api-reference/headless-sdk/enroll-card) again. ## Signature ```js const result = await fap.deleteCard(input, options); ``` ## Parameters - `input.session` (FlowSession) — A live session from `enrollCard` / `selectCard`. When set, `network` and `virtualCardId` are ignored. - `input.network` (string) — `'visa'`, `'mastercard'`, or `'discover'`. Required when `session` is omitted. - `input.virtualCardId` (string) — The `virtualCardId` from an earlier `EnrollResult`. Required when `session` is omitted. - `input.reason` (string) — `'SUSPECTED_FRAUD'` | `'ACCOUNT_CLOSED'` | `'OTHER'` | `'DEFAULT'`. Recorded by the network for audit. - `input.requestor` (string) — `'CARDHOLDER'` | `'MERCHANT'` | `'ISSUER'` | `'WALLET'`. Recorded by the network for audit. - `options.apiTokenOverride` (string) — Per-call bearer override. - `options.signal` (AbortSignal) — Abort the request. ## Returns `Promise<{ deleted: boolean, srcCorrelationId: string | null }>` - `deleted` — `true` when the network confirmed the revocation - `srcCorrelationId` — Network correlation reference when the network returns one, otherwise `null` The `session`, if supplied, is **not** refreshed — no later SDK call accepts a session for a deleted card. ## Example ```js // Buyer removes a saved card from your settings page — no live session. const { deleted } = await fap.deleteCard({ network: savedCard.network, virtualCardId: savedCard.virtualCardId, reason: 'ACCOUNT_CLOSED', requestor: 'CARDHOLDER' }); if (deleted) removeFromSavedCards(savedCard.virtualCardId); ``` --- ## Related - [Delete Card API](/api-reference/agentic-pay/delete-card) — the underlying endpoint - [`selectCard`](/api-reference/headless-sdk/select-card) — rejects with `PaymentMethodNotAvailable` for a deleted card --- # enrollCard ## Overview `enrollCard` submits a card's details to Firmly's Network Token Router. Firmly detects the network from the BIN, enrolls the card, and returns a `FlowSession` plus the `verificationMethods` available for cardholder authentication. Persist `virtualCardId`, `cardArt`, and `masked` from the result — they are used to render a saved-card UI and to call [`selectCard`](/api-reference/headless-sdk/select-card) for returning buyers. ## Signature ```js const result = await fap.enrollCard(input, options); ``` ## Parameters > **Note** > `enrollCard` input fields use snake_case (`expiry_month`, `cardholder_full_name`) to mirror the raw [Enroll Card API](/api-reference/agentic-pay/enroll) body. This differs from `selectCard`, whose `input.virtualCardId` is camelCase — the SDK intentionally keeps each method's input shape aligned with how the value is used (raw enroll body vs. the durable SDK handle). - `input.pan` (string, required) — Card number (PAN). - `input.expiry_month` (string, required) — Two-digit expiry month (e.g. `"03"`, `"12"`). - `input.expiry_year` (string, required) — Four-digit expiry year (e.g. `"2030"`). - `input.cvv` (string) — Card verification value. - `input.cardholder_full_name` (string) — Full name as printed on the card. - `input.consumer` (object) — Cardholder information. **Fields:** `first_name`, `last_name`, `email`, `phone`, `country_code` — all strings, all optional. - `options` (object) — Optional `CallOptions`: `apiTokenOverride` (string), `signal` (AbortSignal). ## Returns `Promise` - `session` (FlowSession) — Flow session — pass it to the next call in the chain. Treat it as mostly opaque, but it does expose a small surface: - `session.network` — the detected network (`"visa"` / `"mastercard"`), readable for branching your UI (as the example below does). - `session.serialize()` — returns a plain, JSON-serializable snapshot of the session (including `cardArt`) so you can persist it and later restore the session for a returning buyer. See [`selectCard`](/api-reference/headless-sdk/select-card) for the returning-buyer path. - `virtualCardId` (string | null) — Durable network-assigned card identifier (`null` if the network did not return one). Persist it — it is the handle passed to `selectCard`. - `verificationMethods` (array) — Verification challenges the card supports. Empty array if none were returned. **VerificationMethod** - `id` (string) — Method identifier (e.g. `"MANAGED_AUTHENTICATION"` for Mastercard, `"VISA_IFRAME_HANDSHAKE"` for Visa). - `type` (string) — `"otp"`, `"embed_iframe"`, or `"embed_iframe_handshake"`. - `attributes` (object) — Method-specific data (e.g. `uri`). - `cardArt` (CardArt | null) — Issuer card art. **Captured at enroll time only** — re-enrolling the same PAN may return `null` (the network caches enrollments), and `selectCard` never re-fetches it. Persist the `cardArt` object itself alongside `masked` and `virtualCardId` (as `saveCard({ cardArt, masked })` shows below), or capture the whole session via `session.serialize()`. Fall back to a placeholder when `null`. - `masked` (MaskedCard | null) — Masked card details for rendering a saved-card chip. `null` when the network omits it. **MaskedCard** - `last4` (string) — Last four digits of the funding PAN (not the network token). - `exp_month` (string) — Two-digit expiry month. - `exp_year` (string) — Four-digit expiry year. - `brand` (string) — `"visa"` or `"mastercard"`. - `card_type` (string) — `"DEBIT"` / `"CREDIT"` — Mastercard only. - `issuer_name` (string) — Issuer / bank descriptor (e.g. `"Test Bank 2"`) — Mastercard only. ## Example ```js import { FirmlyAgenticPay } from '@firmly/agentic-pay-sdk'; const fap = new FirmlyAgenticPay({ baseUrl: 'https://api.firmly.work', apiToken: '' }); const { session, virtualCardId, verificationMethods, cardArt, masked } = await fap.enrollCard({ pan: '4111111111111111', expiry_month: '12', expiry_year: '2030', cvv: '123' }); // Persist for returning customers — selectCard does not re-fetch these. saveCard({ network: session.network, virtualCardId, cardArt, masked }); ``` --- ## Related - [`selectCard`](/api-reference/headless-sdk/select-card) — pay with a saved card - [`triggerOtp`](/api-reference/headless-sdk/trigger-otp) / [`registerPasskey`](/api-reference/headless-sdk/register-passkey) — next step - [Enroll Card API](/api-reference/agentic-pay/enroll) — the underlying endpoint --- # registerPasskey ## Overview `registerPasskey` handles iframe-based verification (passkey / FIDO2 / 3DS / Mastercard `MANAGED_AUTHENTICATION`). It wraps three wallet calls plus the iframe lifecycle into a single SDK call: ### Trigger Posts to `/enroll/trigger` with the chosen method and `callback_uri`. ### Mount the iframe The wallet returns `{ challenge: { type: 'embed_iframe', uri } }`. The SDK mounts an iframe pointed at `uri` in your `container`. ### Wait for the result The SDK waits for a `postMessage` from the iframe (Visa direct) or the bridge page (Mastercard redirect → bridge → postMessage). ### Verify Posts to `/enroll/verify` and returns the `virtualCardId`. > **Note** > On a Visa `AUTHENTICATE` re-enrollment the wallet may return a > `virtual_card_id` directly — the SDK short-circuits and skips the iframe. ## Signature ```js const result = await fap.registerPasskey(session, methodId, options); ``` ## Parameters - `session` (FlowSession, required) — The session from `enrollCard`. - `methodId` (string, required) — An iframe-type method `id` from `verificationMethods` (e.g. `"MANAGED_AUTHENTICATION"` for Mastercard, `"VISA_IFRAME_HANDSHAKE"` for Visa). - `options.container` (Element) — DOM element to mount the iframe in. Falls back to `ClientConfig.iframeContainer` — one of the two must be set. - `options.callbackUri` (string) — Overrides the default `bridgeUrl`. - `options.timeoutMs` (number) — Per-call iframe timeout override. - `options.apiTokenOverride` (string) — Override the `apiToken` for this call. - `options.signal` (AbortSignal) — Abort the iframe wait. > **Warning** > `ClientConfig.iframeOrigins` must be a **non-empty allow-list** of origins > permitted to send the result `postMessage`. The SDK throws otherwise — an empty > list would let any origin forge an `iframe_result` and bypass cardholder > authentication. ## Returns `Promise` - `session` (FlowSession) — The advanced session. - `virtualCardId` (string | null) — Set when the wallet completed enrollment. - `verificationMethods` (array | null) — Returned when the wallet asks for additional verification. ## Example ```js const { session, verificationMethods } = await fap.enrollCard({ /* ... */ }); const method = verificationMethods.find((m) => m.id === 'MANAGED_AUTHENTICATION') || verificationMethods.find((m) => m.type === 'embed_iframe'); const { virtualCardId } = await fap.registerPasskey(session, method.id, { container: document.getElementById('mc-iframe-slot') }); ``` --- ## Related - [`createIntent`](/api-reference/headless-sdk/create-intent) — next step - [Verify Enrollment API](/api-reference/agentic-pay/verify-enrollment) - [iframe Callback](/api-reference/agentic-pay/iframe-callback) --- # selectCard ## Overview `selectCard` re-establishes a payable session for a card the cardholder enrolled earlier. It takes the durable `virtualCardId` from a prior [`enrollCard`](/api-reference/headless-sdk/enroll-card) result — **no PAN re-entry** — and returns the same `EnrollResult` shape, so the rest of the flow (`createIntent` → `completeOrder`) is identical. > **Note** > `cardArt` and `masked` are **not** re-fetched by `selectCard` (no network > metadata call) — both come back `null`. Render the saved card from the data > your application persisted at first enroll. On a revoked token the call **rejects** (it does not resolve with an error value) — the SDK throws `ErrorPaymentMethodNotAvailable`, which corresponds to the REST [`PaymentMethodNotAvailable` (409)](/api-reference/agentic-pay/select-card#error-responses). Catch it and fall back to `enrollCard` (collect the PAN again). ## Signature ```js const result = await fap.selectCard(input, options); ``` ## Parameters - `input.network` (string, required) — `"visa"` or `"mastercard"` — the network the stored card belongs to. - `input.virtualCardId` (string, required) — The durable handle from a prior `enrollCard` / `selectCard` result. Note the casing: this is camelCase `virtualCardId` (the SDK-level handle), whereas `enrollCard`'s card-detail inputs use snake_case (`expiry_month`) to mirror the raw enroll body, and the raw REST endpoints use snake_case `virtual_card_id`. - `input.consumer` (object) — Cardholder identity. `email` is **required for Visa** (the wallet re-binds the consumer identity from it); optional for Mastercard. - `options` (object) — Optional `CallOptions`: `apiTokenOverride`, `signal`. ## Returns `Promise` — the same shape as [`enrollCard`](/api-reference/headless-sdk/enroll-card): `{ session, virtualCardId, verificationMethods, cardArt, masked }`. `cardArt` and `masked` are always `null` here — use the values you persisted at enroll time. > **Warning** > For **Mastercard**, `verificationMethods` is empty — the payment challenge is > produced by `createIntent`, not a separate verification step. For **Visa**, the > result contains the iframe handshake method. ## Example ```js // returning customer — no PAN const selected = await fap.selectCard({ network: 'mastercard', virtualCardId: savedCard.virtualCardId // consumer.email required for Visa }); // Capture and forward the advanced session from each step. const intent = await fap.createIntent(selected.session, mandate, { container }); await fap.completeOrder(intent.session, { billingInfo }); ``` --- ## Related - [`enrollCard`](/api-reference/headless-sdk/enroll-card) — enroll a new card - [`createIntent`](/api-reference/headless-sdk/create-intent) — next step - [Select Card API](/api-reference/agentic-pay/select-card) — the underlying endpoint --- # triggerOtp ## Overview `triggerOtp` starts an OTP-style verification. The wallet sends the challenge code to the cardholder out of band (SMS / email). Call [`verifyOtp`](/api-reference/headless-sdk/verify-otp) once the cardholder enters it. Use this for verification methods with `type: "otp"` from `enrollCard`'s `verificationMethods`. For iframe-based methods, use [`registerPasskey`](/api-reference/headless-sdk/register-passkey) instead. > **Note** > **Visa.** For a Visa session the OTP trigger requires a `secure_token`, which the SDK auto-mints via an iframe handshake — so a Visa `triggerOtp` needs a `container` (via `options.container` or `ClientConfig.iframeContainer`) and a non-empty `ClientConfig.iframeOrigins`. Pass `options.secureToken` to skip the auto-handshake. Mastercard sessions ignore both. ## Signature ```js const result = await fap.triggerOtp(session, methodId, options); ``` ## Parameters - `session` (FlowSession, required) — The session from `enrollCard`. - `methodId` (string, required) — One of the `id` values from `enrollCard`'s `verificationMethods`. - `options` (object) — Optional `CallOptions`: `apiTokenOverride`, `signal`. For **Visa** also `container` (Element, to mount the auto-handshake iframe) and `secureToken` (string, to supply a token and skip the handshake). ## Returns `Promise` - `session` (FlowSession) — The advanced session — pass it to `verifyOtp`. - `challengeType` (string) — The challenge type reported by the wallet (defaults to `"otp"`). `null` when the wallet short-circuits and returns a `virtualCardId` directly. - `challenge` (object) — The wallet challenge object when one is returned (otherwise `null`). - `virtualCardId` (string) — Present when the wallet completes verification immediately without a further challenge; otherwise `null`. When set, enrollment is done — skip to `createIntent`. ## Example ```js const { session, verificationMethods } = await fap.enrollCard({ /* ... */ }); const otp = verificationMethods.find((m) => m.type === 'otp'); // Capture the advanced session — pass THIS to verifyOtp, not the pre-trigger one. const triggered = await fap.triggerOtp(session, otp.id); // The cardholder receives the code out of band — collect it, then: const { virtualCardId } = await fap.verifyOtp(triggered.session, codeTheUserEntered); ``` ## Errors The call rejects (not resolves) on failure — wrap it in `try` / `catch`. - **Unknown / non-OTP `methodId`.** Passing an `id` that is not an `otp`-type method from `enrollCard`'s `verificationMethods` is rejected. Use [`registerPasskey`](/api-reference/headless-sdk/register-passkey) for iframe-type methods. - **503 from the network.** If the underlying verification service is unavailable, the call rejects with the REST `ErrorServiceUnavailable` (503) error surfaced through the SDK — retry after a short delay. - **Timeout / abort.** Bounded by `timeoutMs`; an aborted `options.signal` also rejects the call. --- ## Related - [`verifyOtp`](/api-reference/headless-sdk/verify-otp) — submit the code - [`registerPasskey`](/api-reference/headless-sdk/register-passkey) — iframe-based verification - [Trigger Enrollment API](/api-reference/agentic-pay/trigger-enrollment) --- # verifyOtp ## Overview `verifyOtp` submits the OTP code the cardholder typed. On success, the `FlowSession` holds the new `virtualCardId` and the enrollment is complete. If the wallet requires further verification, the result returns additional `verificationMethods` instead of a `virtualCardId`. ## Signature ```js const result = await fap.verifyOtp(session, code, options); ``` ## Parameters - `session` (FlowSession, required) — The session from `triggerOtp`. - `code` (string, required) — The OTP code the cardholder entered. - `options` (object) — Optional `CallOptions`: `apiTokenOverride`, `signal`. ## Returns `Promise` - `session` (FlowSession) — The advanced session. - `virtualCardId` (string | null) — Set when verification completed enrollment. `null` when more verification is required. - `verificationMethods` (array | null) — Returned (instead of `virtualCardId`) when the wallet asks for additional verification. `null` otherwise. ## Example ```js // `session` here is the advanced session returned by triggerOtp. const { session: verifiedSession, virtualCardId, verificationMethods } = await fap.verifyOtp(session, codeTheUserEntered); if (virtualCardId) { // Enrollment complete — continue to createIntent with verifiedSession. } else if (verificationMethods) { // The wallet asked for another verification step — carry verifiedSession forward. } ``` ## Errors - **Wrong OTP code (`400 BadRequest`).** An incorrect code is treated as a failure: the call **rejects** with a REST `400 BadRequest` error surfaced through the SDK — the network (VTS) reports a wrong OTP as `BadRequest`, not a distinct `InvalidOtp` literal on this path. It does **not** resolve with a `null` `virtualCardId`. Catch it and prompt the cardholder to re-enter the code (you may call `triggerOtp` again to resend). A `null` `virtualCardId` on a *resolved* result means enrollment needs a further step (see `verificationMethods`), not a bad code. - **503 / timeout / abort.** As with the other calls, an unavailable service, an exceeded `timeoutMs`, or an aborted `options.signal` reject the promise. > **Note** > Confirm the exact rejection class for the wrong-code path against the > `@firmly/agentic-pay-sdk` package types before branching on the class name; > branch on the `error` code (`BadRequest`, `400`) carried on the rejection. --- ## Related - [`triggerOtp`](/api-reference/headless-sdk/trigger-otp) — send the code - [`createIntent`](/api-reference/headless-sdk/create-intent) — next step - [Verify Enrollment API](/api-reference/agentic-pay/verify-enrollment) --- # Contact us The Firmly docs team triages questions, bug reports, feedback, and scoping inquiries that come in through this page. Send an email to: ## firmlydocs@firmly.ai We reply, typically within one business day. ## When to email firmlydocs@firmly.ai | You're here because… | Email us if… | |---|---| | **Docs feedback** | You found a typo, an unclear paragraph, a missing detail, or content that doesn't match what you observed | | **Technical questions** | You're integrating against Firmly and the docs don't fully answer your question | | **Bug reports** | You're seeing unexpected API behavior, error messages that don't match the docs, or something that looks broken | | **Integration scoping** | You're evaluating whether Firmly fits your use case and the docs leave you with open questions | | **Sandbox access** | You want a sandbox App ID to try the API — issued on request, typically within one business day | | **Feature requests** | You'd like Firmly to support something it doesn't yet, and you want it on the roadmap discussion | | **Security questions** | You're a security or compliance reviewer with questions about data handling, PII, retention, or audit posture | ## What to include in your email The faster we can help, the better. Including a few details up front saves a round-trip: - **Your name and company** — so we know who's reaching out and can route appropriately - **Your role** — developer, PM, security reviewer, etc. Helps us match you with the right team on our side - **Which Firmly solution** you're working with — Agentic Commerce, Branded Commerce, Firmly Connect, Ad Commerce, Marketplace, or Publisher Commerce - **Which docs page or section** the question is about — copy the URL or the heading - **What you're trying to do** — the goal, not just the symptom - **Whether you're blocked** — and if so, by what specifically (error code, missing info, broken example) - **Request IDs, timestamps, or error codes** if you're reporting a bug — we can correlate against logs You don't need every field. Just whatever's relevant. We'll ask follow-ups if we need more. ## Where to go for other things This inbox is for **docs-side concerns**. For other paths: | You want… | Where to go | |---|---| | **A commercial conversation** (sales, contracts, partnership, pricing) | Email **contact@firmly.ai**, or use the lead-capture form on [firmly.ai](https://www.firmly.ai) — both route to the commercial team | | **Account-team support for a live engagement** | For account matters or a production incident, use the contact you've been working with at Firmly directly — they have full context on your integration. **Docs and API questions are welcome here whether or not you're already live** — you don't need to go through your account team for those. | | **Security disclosure** (responsible disclosure of a vulnerability) | Email **firmlydocs@firmly.ai** with `[SECURITY]` in the subject line so we route it appropriately | | **Press, analyst, or partnership inquiry** | [firmly.ai](https://www.firmly.ai) | ## What we don't do here To set expectations honestly: - **Live support for production incidents** — if you're an existing partner with a live integration that's down right now, reach your account team / on-call contact directly. This inbox is not a 24/7 paging path. - **Contract negotiation** — commercial terms, pricing, and SLAs go through the commercial path (**contact@firmly.ai** or the [firmly.ai](https://www.firmly.ai) form), not this inbox. - **Replies on individual API trace investigations without a request ID** — we can't search for "the order that didn't go through yesterday" without a `cart_id`, request ID, or timestamp window. Help us help you. --- # 1-Step Checkout > **Note** > **The simplest checkout flow possible**: Go from cart to completed order in a single API call. Perfect for destinations that want to maximize conversion with minimal friction. ## Why 1-Step Checkout? Firmly's full Cart API walks through several steps: 1. Add items (the cart is created implicitly) → 2. Set shipping → 3. Get merchant-calculated tax & totals → 4. Process payment → 5. Complete order With Firmly's `place-order` API, you can do all of this in **one single API call**. > **Note** > **`place-order` (one-shot) vs `complete-order` (existing cart).** `place-order` is the one-shot path documented on this page — it creates the cart *and* places the order in a single call, so you pass the full `items[]` array plus `shipping_info` and `billing_info` in the request body. If you've instead built the cart across multiple calls (add line items → set shipping → choose method → consents), finalize it with [`complete-order`](/api-reference/payment/complete-order-v2), which uses the **existing** cart and takes only `encrypted_card` + `billing_info`. Don't call `place-order` on an already-built cart — it flushes and rebuilds the cart from the `items[]` you pass, discarding the shipping method and consents you set. ### Benefits - **Higher Conversion** — Reduce checkout abandonment with fewer steps - **Faster Integration** — Implement in hours, not weeks - **Less Complexity** — One endpoint to maintain instead of six ## How It Works The `place-order` API combines cart creation, item addition, shipping calculation, and payment processing into a single atomic operation: ```mermaid graph LR A[Customer Data] --> B[place-order API] B --> C[Completed Order] ``` > **Note** > **Real-Time Updates**: The `place-order` API supports Server-Sent Events (SSE) for real-time order processing updates. Perfect for showing progress indicators during checkout. ## Quick Implementation ### Collect Customer Information Gather items, shipping address, and credit card details in your checkout form ### Encrypt Credit Card Use Firmly's public key to JWE-encrypt card details for secure transmission ### Call place-order API Submit everything in one API call and handle the response ## Credit Card Encryption > **Warning** > **Security First**: Never send raw credit card data to any API. Always encrypt card details using JWE (JSON Web Encryption) with Firmly's public key. The credit card data must be encrypted as a JWE token containing these fields: | Field | Description | Example | |---|---|---| | `number` | Card number (PAN) | `4111111111111111` | | `name` | Cardholder name | `John Smith` | | `verification_value` | CVV/CVC | `123` | | `month` | Expiry month (2 digits) | `08` | | `year` | Expiry year (4 digits) | `2028` | The plaintext object encrypted into the JWE looks like this: ```json { "number": "4111111111111111", "name": "John Smith", "verification_value": "123", "month": "08", "year": "2028" } ``` ## Complete Example Here's a full implementation of 1-step checkout. > **Note** > **Prerequisite — get an auth token.** The `authToken` used below is the `access_token` returned by the browser-session endpoint. Fetch it first (`POST /api/v1/browser-session` with your `x-firmly-app-id`) and pass it as `x-firmly-authorization`. See [Browser session](/api-reference/authentication/browser-session). **JavaScript** ```javascript // First, install the jose library: npm install jose import * as jose from 'jose'; async function oneStepCheckout(checkoutData, domain, authToken) { // Step 1: Get public key for encryption const publicKeyResponse = await fetch( 'https://cc.firmly.work/api/v1/payment/key', { headers: { 'x-firmly-authorization': authToken } } ); const publicKeyJWK = await publicKeyResponse.json(); // Step 2: Encrypt credit card data using JWE const cardData = { number: checkoutData.cardNumber, name: checkoutData.cardholderName, verification_value: checkoutData.cvv, month: checkoutData.expMonth, // e.g., "08" year: checkoutData.expYear // e.g., "2028" }; // Import the public key const publicKey = await jose.importJWK(publicKeyJWK, 'RSA-OAEP-256'); // Create JWE encrypted card const encryptedCard = await new jose.CompactEncrypt( new TextEncoder().encode(JSON.stringify(cardData)) ) .setProtectedHeader({ alg: 'RSA-OAEP-256', enc: 'A256GCM', kid: publicKeyJWK.kid }) .encrypt(publicKey); // Step 3: Place order in one call const orderResponse = await fetch( `https://cc.firmly.work/api/v2/payment/domains/${domain}/place-order`, { method: 'POST', headers: { 'x-firmly-authorization': authToken, 'Content-Type': 'application/json' }, body: JSON.stringify({ items: [ { add_to_cart_ref: { variant_id: 'WS12-XS-Orange' }, quantity: 2 } ], shipping_info: { first_name: 'John', last_name: 'Doe', address1: '123 Main St', city: 'New York', state_or_province: 'NY', postal_code: '10001', country: 'US', email: 'john@staging.luma.gift', phone: '555-1234' }, billing_info: { // Same structure as shipping_info (billing_info is required) first_name: 'John', last_name: 'Doe', address1: '123 Main St', city: 'New York', state_or_province: 'NY', postal_code: '10001', country: 'US', email: 'john@staging.luma.gift', phone: '555-1234' }, encrypted_card: encryptedCard }) } ); // Handle response const result = await orderResponse.json(); // Success is signalled by cart_status === "submitted", // NOT by the mere presence of cart_id. if (result.cart_status === 'submitted') { // Success! Order completed return { success: true, cartId: result.cart_id, orderNumber: result.platform_order_number }; } else { // Handle error return { success: false, error: result.error }; } } // Example usage: const checkoutData = { cardNumber: '4111111111111111', cardholderName: 'John Doe', cvv: '123', expMonth: '12', expYear: '2028' }; const domain = 'staging.luma.gift'; const authToken = 'YOUR_AUTH_TOKEN'; // Get this from browser session // Call the function oneStepCheckout(checkoutData, domain, authToken) .then(result => { if (result.success) { console.log('Order placed successfully!', result.orderNumber); } else { console.error('Order failed:', result.error); } }); ``` **Python** ```python import requests import json from joserfc.jwe import encrypt_compact from joserfc.jwk import RSAKey def one_step_checkout(checkout_data, domain, auth_token): # Step 1: Get public key in JWK format (default) public_key_response = requests.get( "https://cc.firmly.work/api/v1/payment/key", headers={ 'x-firmly-authorization': auth_token } ) public_key_jwk = public_key_response.json() # Step 2: Prepare card data card_data = { 'number': checkout_data['card_number'], 'name': checkout_data['cardholder_name'], 'verification_value': checkout_data['cvv'], 'month': checkout_data['exp_month'], # e.g., "08" 'year': checkout_data['exp_year'] # e.g., "2028" } # Step 3: Encrypt using JWE with JWK # Import the JWK public_key = RSAKey.import_key(public_key_jwk) # Create JWE encrypted card. joserfc's signature is # encrypt_compact(protected, plaintext, public_key): # protected header first, plaintext second, key third. protected_header = { "alg": "RSA-OAEP-256", "enc": "A256GCM", "kid": public_key_jwk['kid'] # Get kid from JWK response } encrypted_card = encrypt_compact( protected_header, json.dumps(card_data).encode('utf-8'), public_key ) # Step 4: Place order order_data = { 'items': [ { 'add_to_cart_ref': {'variant_id': 'WS12-XS-Orange'}, 'quantity': 2 } ], 'shipping_info': { 'first_name': 'John', 'last_name': 'Doe', 'address1': '123 Main St', 'city': 'New York', 'state_or_province': 'NY', 'postal_code': '10001', 'country': 'US', 'email': 'john@staging.luma.gift', 'phone': '555-1234' }, 'billing_info': { # Same structure as shipping_info 'first_name': 'John', 'last_name': 'Doe', 'address1': '123 Main St', 'city': 'New York', 'state_or_province': 'NY', 'postal_code': '10001', 'country': 'US', 'email': 'john@staging.luma.gift', 'phone': '555-1234' }, 'encrypted_card': encrypted_card } response = requests.post( f"https://cc.firmly.work/api/v2/payment/domains/{domain}/place-order", headers={ 'x-firmly-authorization': auth_token, 'Content-Type': 'application/json' }, json=order_data ) result = response.json() # Success is signalled by cart_status == "submitted", # NOT by the mere presence of cart_id. if result.get('cart_status') == 'submitted': return { 'success': True, 'cart_id': result.get('cart_id'), 'order_number': result.get('platform_order_number') } else: return { 'success': False, 'error': result.get('error') } # Example usage: checkout_data = { 'card_number': '4111111111111111', 'cardholder_name': 'John Doe', 'cvv': '123', 'exp_month': '12', 'exp_year': '2028' } domain = 'staging.luma.gift' auth_token = 'YOUR_AUTH_TOKEN' # Get this from browser session # Call the function result = one_step_checkout(checkout_data, domain, auth_token) if result['success']: print(f"Order placed successfully! Order Number: {result['order_number']}") else: print(f"Order failed: {result['error']}") ``` **Java** ```java // Dependencies: // - com.nimbusds:nimbus-jose-jwt:9.31 // - com.fasterxml.jackson.core:jackson-databind:2.15.2 import com.nimbusds.jose.*; import com.nimbusds.jose.crypto.RSAEncrypter; import com.nimbusds.jose.jwk.RSAKey; import com.fasterxml.jackson.databind.ObjectMapper; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.net.URI; import java.util.Map; import java.util.HashMap; import java.util.List; public class OneStepCheckout { private static final String API_BASE = "https://cc.firmly.work"; private static final ObjectMapper mapper = new ObjectMapper(); public static CheckoutResult performCheckout( CheckoutData checkoutData, String domain, String authToken ) throws Exception { // Step 1: Get public key in JWK format HttpClient client = HttpClient.newHttpClient(); HttpRequest keyRequest = HttpRequest.newBuilder() .uri(URI.create(API_BASE + "/api/v1/payment/key")) .header("x-firmly-authorization", authToken) .GET() .build(); HttpResponse keyResponse = client.send( keyRequest, HttpResponse.BodyHandlers.ofString() ); Map jwkData = mapper.readValue( keyResponse.body(), Map.class ); // Step 2: Prepare card data Map cardData = new HashMap<>(); cardData.put("number", checkoutData.getCardNumber()); cardData.put("name", checkoutData.getCardholderName()); cardData.put("verification_value", checkoutData.getCvv()); cardData.put("month", checkoutData.getExpMonth()); // e.g., "08" cardData.put("year", checkoutData.getExpYear()); // e.g., "2028" // Step 3: Encrypt using JWE RSAKey rsaKey = RSAKey.parse(mapper.writeValueAsString(jwkData)); // Create JWE object JWEHeader header = new JWEHeader.Builder( JWEAlgorithm.RSA_OAEP_256, EncryptionMethod.A256GCM ) .keyID(jwkData.get("kid").toString()) .build(); Payload payload = new Payload(mapper.writeValueAsString(cardData)); JWEObject jweObject = new JWEObject(header, payload); // Encrypt jweObject.encrypt(new RSAEncrypter(rsaKey)); String encryptedCard = jweObject.serialize(); // Step 4: Place order Map orderData = new HashMap<>(); orderData.put("items", List.of( Map.of( "add_to_cart_ref", Map.of("variant_id", "WS12-XS-Orange"), "quantity", 2 ) )); Map shippingInfo = new HashMap<>(); shippingInfo.put("first_name", "John"); shippingInfo.put("last_name", "Doe"); shippingInfo.put("address1", "123 Main St"); shippingInfo.put("city", "New York"); shippingInfo.put("state_or_province", "NY"); shippingInfo.put("postal_code", "10001"); shippingInfo.put("country", "US"); shippingInfo.put("email", "john@staging.luma.gift"); shippingInfo.put("phone", "555-1234"); orderData.put("shipping_info", shippingInfo); orderData.put("billing_info", shippingInfo); // Same as shipping orderData.put("encrypted_card", encryptedCard); HttpRequest orderRequest = HttpRequest.newBuilder() .uri(URI.create(API_BASE + "/api/v2/payment/domains/" + domain + "/place-order")) .header("x-firmly-authorization", authToken) .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofString( mapper.writeValueAsString(orderData) )) .build(); HttpResponse orderResponse = client.send( orderRequest, HttpResponse.BodyHandlers.ofString() ); Map result = mapper.readValue( orderResponse.body(), Map.class ); // Success is signalled by cart_status == "submitted", // NOT by the mere presence of cart_id. if ("submitted".equals(String.valueOf(result.get("cart_status")))) { return new CheckoutResult( true, String.valueOf(result.get("cart_id")), String.valueOf(result.get("platform_order_number")), null ); } else { return new CheckoutResult( false, null, null, result.get("error").toString() ); } } } // Supporting classes class CheckoutData { private String cardNumber; private String cardholderName; private String cvv; private String expMonth; private String expYear; // ... getters and setters } class CheckoutResult { private boolean success; private String cartId; private String orderNumber; private String error; public CheckoutResult(boolean success, String cartId, String orderNumber, String error) { this.success = success; this.cartId = cartId; this.orderNumber = orderNumber; this.error = error; } // ... getters } // Example usage: public class Main { public static void main(String[] args) { CheckoutData checkoutData = new CheckoutData(); checkoutData.setCardNumber("4111111111111111"); checkoutData.setCardholderName("John Doe"); checkoutData.setCvv("123"); checkoutData.setExpMonth("12"); checkoutData.setExpYear("2028"); String domain = "staging.luma.gift"; String authToken = "YOUR_AUTH_TOKEN"; // Get this from browser session try { CheckoutResult result = OneStepCheckout.performCheckout( checkoutData, domain, authToken ); if (result.isSuccess()) { System.out.println("Order placed successfully! Order Number: " + result.getOrderNumber()); } else { System.out.println("Order failed: " + result.getError()); } } catch (Exception e) { System.err.println("Error: " + e.getMessage()); } } } ``` **PHP** ```php $checkoutData['cardNumber'], 'name' => $checkoutData['cardholderName'], 'verification_value' => $checkoutData['cvv'], 'month' => $checkoutData['expMonth'], // e.g., "08" 'year' => $checkoutData['expYear'] // e.g., "2028" ]; // Step 4: Create JWE $algorithmManager = new AlgorithmManager([ new RSAOAEP256(), new A256GCM(), ]); $compressionMethodManager = new CompressionMethodManager([ new Deflate(), ]); $jweBuilder = new JWEBuilder( $algorithmManager, $algorithmManager, $compressionMethodManager ); $payload = json_encode($cardData); $jwe = $jweBuilder ->create() ->withPayload($payload) ->withSharedProtectedHeader([ 'alg' => 'RSA-OAEP-256', 'enc' => 'A256GCM', 'kid' => $publicKeyData['kid'] ]) ->addRecipient($jwk) ->build(); $serializer = new CompactSerializer(); $encryptedCard = $serializer->serialize($jwe, 0); // Step 5: Place order $orderData = [ 'items' => [ [ 'add_to_cart_ref' => ['variant_id' => 'WS12-XS-Orange'], 'quantity' => 2 ] ], 'shipping_info' => [ 'first_name' => 'John', 'last_name' => 'Doe', 'address1' => '123 Main St', 'city' => 'New York', 'state_or_province' => 'NY', 'postal_code' => '10001', 'country' => 'US', 'email' => 'john@staging.luma.gift', 'phone' => '555-1234' ], 'billing_info' => [ // Same structure as shipping_info 'first_name' => 'John', 'last_name' => 'Doe', 'address1' => '123 Main St', 'city' => 'New York', 'state_or_province' => 'NY', 'postal_code' => '10001', 'country' => 'US', 'email' => 'john@staging.luma.gift', 'phone' => '555-1234' ], 'encrypted_card' => $encryptedCard ]; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "https://cc.firmly.work/api/v2/payment/domains/{$domain}/place-order"); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "x-firmly-authorization: {$authToken}", "Content-Type: application/json" ]); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($orderData)); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); $result = json_decode($response, true); curl_close($ch); // Success is signalled by cart_status === "submitted", // NOT by the mere presence of cart_id. if (isset($result['cart_status']) && $result['cart_status'] === 'submitted') { return [ 'success' => true, 'cart_id' => $result['cart_id'] ?? null, 'order_number' => $result['platform_order_number'] ?? null ]; } else { return [ 'success' => false, 'error' => $result['error'] ?? 'Unknown error' ]; } } // Example usage: $checkoutData = [ 'cardNumber' => '4111111111111111', 'cardholderName' => 'John Doe', 'cvv' => '123', 'expMonth' => '12', 'expYear' => '2028' ]; $domain = 'staging.luma.gift'; $authToken = 'YOUR_AUTH_TOKEN'; // Get this from browser session // Call the function $result = oneStepCheckout($checkoutData, $domain, $authToken); if ($result['success']) { echo "Order placed successfully! Order Number: " . $result['order_number']; } else { echo "Order failed: " . $result['error']; } ?> ``` ## Important Security Notes > **Warning** > **Critical Security Requirements:** > > 1. **Never store card data** - Card details should only exist in memory during encryption > 2. **Always use HTTPS** - All API calls must be over secure connections > 3. **PCI Compliance** - Ensure your implementation follows PCI DSS guidelines > 4. **Encrypt with Firmly's public key** - JWE encryption happens client-side using Firmly's public key. The public key is safe to expose; the card plaintext never leaves the client unencrypted, and only Firmly's private key can decrypt it. > 5. **Validate SSL certificates** - Ensure you're connecting to genuine Firmly endpoints ## Real-Time Progress with SSE > **Note** > **Server-Sent Events Support**: Both `place-order` endpoints (v1 and v2) support SSE for live progress during the place-order call itself. This lets you show the user processing state (validation → payment authorization → order placement) instead of a single waiting spinner. ### Using SSE for Live Updates ```javascript // Option 1: Use SSE by setting Accept header const domain = 'staging.luma.gift'; const authToken = 'YOUR_AUTH_TOKEN'; // Get this from browser session const orderData = { items: [{ add_to_cart_ref: { variant_id: 'WS12-XS-Orange' }, quantity: 1 }], shipping_info: { /* ... */ }, billing_info: { /* ... */ }, encrypted_card: encryptedCard }; const response = await fetch( `https://cc.firmly.work/api/v2/payment/domains/${domain}/place-order`, { method: 'POST', headers: { 'x-firmly-authorization': authToken, 'Content-Type': 'application/json', 'Accept': 'text/event-stream' // Enable SSE }, body: JSON.stringify(orderData) } ); // Read the event stream const reader = response.body.getReader(); const decoder = new TextDecoder(); while (true) { const { done, value } = await reader.read(); if (done) break; const chunk = decoder.decode(value); // Parse SSE events from chunk console.log('Event:', chunk); } ``` ### SSE Event Types - **`order_processing`**: Order is being validated and processed - **`payment_processing`**: Payment is being authorized - **`order_completed`**: Order successfully placed with order details - **`error`**: Processing failed with error details ## When to Use 1-Step Checkout **Perfect For** - Single vendor stores - Standard shipping only - High-volume, low-complexity products - Mobile-first experiences **Consider Alternatives If** - Multiple shipments needed - Complex shipping options (scheduled delivery) - B2B with special requirements - Require extensive customization ## Error Handling The `place-order` API provides detailed error responses: ```json { "code": 400, "error": "InvalidShippingInfo", "description": "Shipping address could not be validated" } ``` The error envelope is `{ code, error, description }` — `code` is the numeric HTTP status and `error` is the PascalCase wire name from the [error catalog](/api-reference/errors-and-conventions). Common error scenarios: - **InvalidShippingInfo**: Address validation failed (`InvalidInputBody` for malformed request bodies) - **NotEnoughStockError**: Product not available (409) - **CreditCardDeclined**: Card declined (422) - **CreditCardInvalidNumber / CreditCardInvalidExpiry / CreditCardInvalidSecurityCode**: Card details failed validation (422) ## Next Steps - [API Reference](/api-reference/) — Complete place-order API documentation - [Payment Encryption](/api-reference/payment/get-public-key) — Learn about secure payment handling - [Cart API Guide](/cookbook/full-cart-api-guide) — Multi-step alternative with cart, shipments, and addons - [Testing Guide](/api-reference/authentication/browser-session) — Set up test environment ## Support Need help implementing 1-step checkout? Contact [Firmly](/contact). --- # Advanced Checkout Guide A complete, runnable walkthrough of the **Advanced flow** (`/api/v2`) — the richer cart with split shipments, add-ons, delivery scheduling, and ZIP-coverage gating — end-to-end in Node against the sandbox. It places a **real order** with a **test card** (no real money). > **Note** > This is the **Advanced** flow. Most integrations are simpler — if you need only a single-merchant, one-shipment checkout, use the [Standard Checkout Guide](/cookbook/standard-checkout-guide). **Auth, catalog, and discovery are identical across both flows** — only the cart, checkout, and order calls differ — so starting with one and moving to the other later is cheap. For solution-specific framing (AI agents, ad surfaces, branded checkout, marketplace), see [Solutions](/solutions/) after you've got the flow running. ## Prerequisites - **Node 20 or 22** (LTS) - **An App ID** — your `_appId`. Contact [Firmly](/contact) to provision a sandbox app and a test merchant domain. - **A test merchant domain** — for the examples below we use `staging.luma.gift`. Substitute the domain [Firmly](/contact) gave you. - **One dependency**: `jose` (for JWE card encryption); everything else (`fetch`, `crypto`) is built into Node. ```bash mkdir firmly-quickstart && cd firmly-quickstart npm init -y npm install jose ``` Add `"type": "module"` to your `package.json` so the script can use `import`. ## The full script Save this as `agent.mjs`: ```javascript // agent.mjs — Minimal flow that places a real Firmly order. // Usage: FIRMLY_APP_ID=... node agent.mjs import { CompactEncrypt, importJWK } from 'jose'; import { randomUUID } from 'node:crypto'; const APP_ID = process.env.FIRMLY_APP_ID || 'YOUR_APP_ID'; const DOMAIN = process.env.FIRMLY_DOMAIN || 'staging.luma.gift'; if (APP_ID === 'YOUR_APP_ID') throw new Error('Set FIRMLY_APP_ID to your sandbox App ID first (request one from Firmly): FIRMLY_APP_ID= node agent.mjs'); const API = 'https://api.firmly.work'; const PAY_API = 'https://cc.firmly.work'; // Some HTTP clients' default User-Agent is blocked by sandbox bot-protection (403). // A browser-style UA passes — set one on every call. const UA = 'Mozilla/5.0 (compatible; firmly-quickstart)'; // A test shipping address. Same address is used for billing. const ADDRESS = { first_name: 'Test', last_name: 'Buyer', email: 'test@example.com', phone: '+15551234567', address1: '500 Howard St', city: 'San Francisco', state_or_province: 'CA', country: 'US', postal_code: '94105' }; // A sandbox-safe test card. Only works against test merchants. const TEST_CARD = { number: '4111111111111111', name: 'Test Buyer', verification_value: '123', month: '12', year: '2030' }; // 1. Bootstrap a browser session (returns a JWT) const session = await fetch(`${API}/api/v1/browser-session`, { method: 'POST', headers: { 'x-firmly-app-id': APP_ID, 'User-Agent': UA } }).then(r => r.json()); const TOKEN = session.access_token; const auth = { 'x-firmly-authorization': TOKEN, 'Content-Type': 'application/json', 'User-Agent': UA }; // 2. Discover — search the catalog const search = await fetch( `${API}/api/v1/discovery/search`, { method: 'POST', headers: auth, // discovery/search spans every merchant — scope it to this store with filters.domains body: JSON.stringify({ query: 'bag', filters: { domains: [DOMAIN] }, page_size: 5 }) } ).then(r => r.json()); // Take the first product and its first *available* variant const product = search.products?.find(p => p.domain === DOMAIN); if (!product) throw new Error(`No products matched at ${DOMAIN}`); const variant = product.variants?.find(v => v.available) || product.variants?.[0]; const addRef = variant.add_to_cart_ref; // 3. Add to cart await fetch( `${API}/api/v2/domains/${DOMAIN}/cart/line-items`, { method: 'POST', headers: auth, body: JSON.stringify({ add_to_cart_ref: addRef, quantity: 1 }) } ); // 4. Set shipping address const shipped = await fetch( `${API}/api/v2/domains/${DOMAIN}/cart/shipping-info`, { method: 'POST', headers: auth, body: JSON.stringify(ADDRESS) } ).then(r => r.json()); const shipmentId = shipped.shipments?.[0]?.shipment_id; // 5. Pick the cheapest shipping method. // Methods are populated inline on the shipment by set-shipping-info — // read them from shipping_method_options (get-availability returns // delivery dates / slots, not methods). // See api-reference/shipment-configuration/shipping-and-fulfillment. const methods = shipped.shipments?.[0]?.shipping_method_options || []; const cheapest = methods.slice().sort((a, b) => a.price.value - b.price.value)[0]; // 6. Set the chosen shipping method await fetch( `${API}/api/v2/domains/${DOMAIN}/cart/shipment/methods`, { method: 'POST', headers: auth, body: JSON.stringify({ shipment_id: shipmentId, shipping_method_id: cheapest.id }) } ); // 7. Get the payment public key const jwk = await fetch(`${PAY_API}/api/v1/payment/key?format=JWK`, { headers: { 'User-Agent': UA } }).then(r => r.json()); // 8. JWE-encrypt the card const publicKey = await importJWK(jwk, 'RSA-OAEP-256'); const encryptedCard = await new CompactEncrypt( new TextEncoder().encode(JSON.stringify(TEST_CARD)) ) .setProtectedHeader({ alg: 'RSA-OAEP-256', enc: 'A256GCM', kid: jwk.kid }) .encrypt(publicKey); // 9. Complete the order. // The cart was built over steps 3–6 (line item, shipping address, shipping // method), so complete-order finalizes that EXISTING cart — the body carries // only encrypted_card + billing_info. place-order is the one-shot alternative: // it creates the cart AND places the order in a single call, taking an items[] // array plus shipping_info instead. See the API reference for both. const order = await fetch( `${PAY_API}/api/v2/payment/domains/${DOMAIN}/complete-order`, { method: 'POST', headers: { ...auth, 'Idempotency-Key': randomUUID() }, body: JSON.stringify({ encrypted_card: encryptedCard, billing_info: ADDRESS }) } ).then(r => r.json()); console.log('Status:', order.cart_status); // "submitted" on success console.log('Cart ID:', order.cart_id); // Firmly's internal reference console.log('Confirmation URL:', order.urls?.thank_you_page); // merchant's confirmation page console.log('Merchant ref:', order.platform_order_number); // merchant's order number console.log('Total:', order.total?.symbol + order.total?.value); // value = decimal price; number is smallest-unit (cents) ``` Run it: ```bash FIRMLY_APP_ID=your_sandbox_app_id node agent.mjs ``` > **Note** > **This script doesn't check `response.ok` after each call** — to keep the flow readable it assumes every call succeeds. In real code, check `response.ok` after each `fetch` (or wrap it in a small `assertOk` helper) — a 4xx on add-to-cart or shipping-info otherwise silently produces `undefined` downstream (`shipmentId`, `cheapest`). See [Errors & Conventions](/api-reference/errors-and-conventions) for the error shape. ## What each step is doing ### Session bootstrap (step 1) Every Firmly call needs an authenticated session. `POST /api/v1/browser-session` exchanges your App ID for a short-lived JWT (~1 hour). The JWT goes in the `x-firmly-authorization` header on subsequent calls. See [Authentication](/for-destinations/authentication) for the full auth model. ### Discovery (step 2) `POST /api/v1/discovery/search` runs a search **across every Firmly merchant** — that's the point of discovery. To scope results to one store, pass `filters.domains` in the request body (as above); each product also carries a `domain` field you can check client-side. ### Add to cart (step 3) `POST /cart/line-items` creates a cart implicitly. The response is the full cart object including totals, line items, and an empty `shipments[]` array. ### Shipping address (step 4) `POST /cart/shipping-info` sets the destination. The response includes updated `shipments[]` with `shipment_id`s. See [Shipping & Fulfillment](/api-reference/shipment-configuration/shipping-and-fulfillment) for the shipment model. ### Shipping methods (steps 5–6) For each shipment, read the available methods from its inline `shipping_method_options` (populated by `set-shipping-info`), then record your choice. `get-availability` is a separate, optional call for delivery dates / time slots / pickup locations — not shipping methods — and returns `501 NotImplemented` on merchants whose adapters don't support it. ### Payment key (step 7) `GET /payment/key?format=JWK` returns an RSA public key. JWE-encrypt the card with this key so the unencrypted PAN (the raw card number) never leaves your process. ### JWE encryption (step 8) The card payload is encrypted with `RSA-OAEP-256` + `A256GCM` and serialized as a compact JWE. The result is a single string passed as `encrypted_card`. ### Complete order (step 9) `POST /payment/complete-order` finalizes the cart you built in steps 3–6 — the body is just `encrypted_card` + `billing_info`, because the line items and shipping already live on the cart. (The one-shot alternative, [`place-order`](/api-reference/payment/place-order-v2), instead creates the cart *and* places the order in a single call with an `items[]` array — use it when you have everything up front and haven't built a cart.) Send an `Idempotency-Key` UUID with it — but note the core REST endpoints don't deduplicate on it today, so before any retry, re-read the cart and check `cart_status` first (see [Errors & Conventions](/api-reference/errors-and-conventions#idempotency)). ## Where to go from here - **Build with a specific solution** → [Solutions](/solutions/) — agentic, ad, branded, marketplace, publisher, Firmly Connect - **Multi-product / multi-shipment** → [Shipping & Fulfillment](/api-reference/shipment-configuration/shipping-and-fulfillment) - **Express checkout (Klarna, PayPal)** → [Klarna Express Checkout](/api-reference/payment/express-checkout/klarna/start) or [PayPal Express Checkout](/api-reference/payment/express-checkout/paypal/start) instead of card encryption - **Error handling** → [Errors & Conventions](/api-reference/errors-and-conventions) for the full catalog and recovery patterns - **Hosted checkout instead** → [Hosted Checkout](/solutions/agentic-commerce/integration-patterns/hosted-checkout) — skip steps 4–9 and hand the user off to Firmly's checkout page ## A few things to know - This script uses **browser session** auth. For backend agents, **[server-to-server](/api-reference/authentication/server-to-server)** is simpler — one static secret, no `/browser-session` bootstrap. - The test card `4111111111111111` only works against sandbox / test merchants. Real merchants reject it. - Some HTTP clients' default User-Agent is blocked by the sandbox's bot-protection with a `403` — the script sets a browser-style `User-Agent`; keep one on your own calls. - Order placement is synchronous on Firmly's side — you get the merchant's order identifier back in the `complete-order` response. --- # Cart API Implementation Guide ## Cart API Guide Build a complete checkout flow with Firmly's Cart API. This guide walks through adding items, setting shipping, and completing payment. ### When to Use the Cart API The Cart API is the canonical multi-step path through checkout. Use it for: - Mix of standard shipping and scheduled delivery - Items requiring different fulfillment types - Addon services (warranties, protection plans) - In-store pickup options - Complex shipping scenarios - Any flow where you need to mutate the cart across multiple turns (multi-product agentic flows, cart review, etc.) If your flow is a one-shot purchase with no cart mutation between steps, [1-Step Checkout](/cookbook/one-step-checkout) is a lighter alternative. ### Prerequisites Before starting, ensure you have: - **App ID** — Your App ID from Firmly (contact support if you don't have one) - **Test Merchant Domain** — Work with Firmly to enable your App ID for a specific test store - **API Client** — cURL, Postman, or your preferred HTTP client > **Note** > **Important:** Before you can access a merchant's store, Firmly must configure your App ID to work with that specific domain. Contact our team to set up access to your test merchant. ### Step 1: Authenticate Get an access token for your session: ```bash curl -X POST https://api.firmly.work/api/v1/browser-session \ -H "x-firmly-app-id: YOUR_APP_ID" ``` Use the `access_token` from the response as `x-firmly-authorization` in all API calls. ### Step 2: Browse Products Discover available products from the merchant: ```bash # List products curl -X GET "https://api.firmly.work/api/v1/domains-products/staging.luma.gift?size=100" \ -H "x-firmly-authorization: YOUR_TOKEN" # Get product details curl -X GET "https://api.firmly.work/api/v1/domains-products/staging.luma.gift/radiant-tee" \ -H "x-firmly-authorization: YOUR_TOKEN" ``` ### Step 3: Add to Cart Add a product variant to the cart: ```bash curl -X POST https://api.firmly.work/api/v2/domains/staging.luma.gift/cart/line-items \ -H "x-firmly-authorization: YOUR_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "add_to_cart_ref": { "variant_id": "WS12-XS-Orange" }, "quantity": 1 }' ``` ### Step 4: Set Shipping Address Add shipping information and get available shipping methods: ```bash curl -X POST https://api.firmly.work/api/v2/domains/staging.luma.gift/cart/shipping-info \ -H "x-firmly-authorization: YOUR_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "first_name": "John", "last_name": "Doe", "email": "john.doe@staging.luma.gift", "phone": "555-123-4567", "address1": "123 Main St", "city": "New York", "state_or_province": "NY", "postal_code": "10001", "country": "US" }' ``` The response includes a `shipments[]` array. Each shipment carries the `shipment_id` you need for the next step, along with its shipping-method options: ```json { "cart_status": "active", "shipments": [ { "shipment_id": "0fec2a3d-ef1a-905d-c54b-46caf872356f", "shipping_method_options": [ { "id": "standard", "description": "Standard", "price": { "value": 5.00, "number": 500, "symbol": "$", "currency": "USD" } } ] } ] } ``` > **Note** > **Where shipping options live.** Options are exposed per shipment at `shipment.shipping_method_options[]`, populated inline by set-shipping-info. Some merchants populate a cart-level `cart.shipping_method_options[]` array instead — read that as a fallback. Prefer the per-shipment array when present, since a multi-shipment cart needs an independent selection per shipment. (`get-availability` does not return shipping methods — it returns delivery dates, time slots, and pickup locations.) ### Step 5: Select Shipping Method Choose a shipping method for each shipment, using the `shipment_id` from the previous response: ```bash curl -X POST https://api.firmly.work/api/v2/domains/staging.luma.gift/cart/shipment/methods \ -H "x-firmly-authorization: YOUR_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "shipment_id": "SHIPMENT-ID-FROM-CART", "shipping_method_id": "standard" }' ``` ### Step 6: Complete the Order Get the public key and complete the order with encrypted payment: ```bash # Get public key for encryption curl -X GET https://cc.firmly.work/api/v1/payment/key \ -H "x-firmly-authorization: YOUR_TOKEN" # Complete order with encrypted card data curl -X POST https://cc.firmly.work/api/v2/payment/domains/staging.luma.gift/complete-order \ -H "x-firmly-authorization: YOUR_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "encrypted_card": "eyJhbGciOiJSU0EtT0FFUC0yNTYiLCJlbmMiOiJBMjU2R0NNIiwia2lkIjoidjEifQ...", "billing_info": { "first_name": "John", "last_name": "Doe", "email": "john.doe@staging.luma.gift", "phone": "555-123-4567", "address1": "123 Main St", "city": "New York", "state_or_province": "NY", "postal_code": "10001", "country": "US" } }' ``` ### Complete Example **JavaScript** ```javascript // npm install jose import * as jose from 'jose'; // Encrypt the card object into a JWE using Firmly's public JWK. // The public key is safe to embed client-side; only Firmly's private // key can decrypt. See the Get Public Key / Complete Order references. async function encryptCardData(card, publicKeyJWK) { const publicKey = await jose.importJWK(publicKeyJWK, 'RSA-OAEP-256'); return await new jose.CompactEncrypt( new TextEncoder().encode(JSON.stringify(card)) ) .setProtectedHeader({ alg: 'RSA-OAEP-256', enc: 'A256GCM', kid: publicKeyJWK.kid }) .encrypt(publicKey); } // Full checkout flow async function checkout(domain, productVariantId) { // 1. Authenticate const authResponse = await fetch('https://api.firmly.work/api/v1/browser-session', { method: 'POST', headers: { 'x-firmly-app-id': 'YOUR_APP_ID' } }); const { access_token } = await authResponse.json(); const headers = { 'x-firmly-authorization': access_token, 'Content-Type': 'application/json' }; // 2. Add to cart const cartResponse = await fetch( `https://api.firmly.work/api/v2/domains/${domain}/cart/line-items`, { method: 'POST', headers, body: JSON.stringify({ add_to_cart_ref: { variant_id: productVariantId }, quantity: 1 }) } ); const cart = await cartResponse.json(); // 3. Set shipping const shippingResponse = await fetch( `https://api.firmly.work/api/v2/domains/${domain}/cart/shipping-info`, { method: 'POST', headers, body: JSON.stringify({ first_name: 'John', last_name: 'Doe', email: 'john.doe@staging.luma.gift', phone: '555-123-4567', address1: '123 Main St', city: 'New York', state_or_province: 'NY', postal_code: '10001', country: 'US' }) } ); const cartWithShipping = await shippingResponse.json(); // 4. Select shipping method const shipment = cartWithShipping.shipments[0]; const shippingMethod = shipment.shipping_method_options[0]; await fetch( `https://api.firmly.work/api/v2/domains/${domain}/cart/shipment/methods`, { method: 'POST', headers, body: JSON.stringify({ shipment_id: shipment.shipment_id, shipping_method_id: shippingMethod.id }) } ); // 5. Get public key and encrypt card. // The /payment/key response IS a JWK (import it directly with jose). const publicKeyJWK = await fetch( 'https://cc.firmly.work/api/v1/payment/key', { headers } ).then(r => r.json()); // Encrypt card data into a JWE using the public JWK. The JWE contract // fields are: number, verification_value, month, year, name. const encryptedCard = await encryptCardData( { number: '4111111111111111', verification_value: '123', month: '12', year: '2028', name: 'John Doe' }, publicKeyJWK ); // 6. Complete order const orderResponse = await fetch( `https://cc.firmly.work/api/v2/payment/domains/${domain}/complete-order`, { method: 'POST', headers, body: JSON.stringify({ encrypted_card: encryptedCard, billing_info: { first_name: 'John', last_name: 'Doe', email: 'john.doe@staging.luma.gift', phone: '555-123-4567', address1: '123 Main St', city: 'New York', state_or_province: 'NY', postal_code: '10001', country: 'US' } }) } ); const order = await orderResponse.json(); return order; } ``` **Python** ```python import requests import json from joserfc.jwe import encrypt_compact from joserfc.jwk import RSAKey def encrypt_card_data(card, public_key_jwk): """Encrypt the card object into a JWE using Firmly's public JWK. The public key is safe to use client-side; only Firmly's private key can decrypt. joserfc's signature is encrypt_compact(protected, plaintext, key). """ public_key = RSAKey.import_key(public_key_jwk) protected_header = { 'alg': 'RSA-OAEP-256', 'enc': 'A256GCM', 'kid': public_key_jwk['kid'] } return encrypt_compact( protected_header, json.dumps(card).encode('utf-8'), public_key ) def checkout(domain, product_variant_id): # 1. Authenticate auth_response = requests.post( 'https://api.firmly.work/api/v1/browser-session', headers={'x-firmly-app-id': 'YOUR_APP_ID'} ) access_token = auth_response.json()['access_token'] headers = { 'x-firmly-authorization': access_token, 'Content-Type': 'application/json' } # 2. Add to cart cart_response = requests.post( f'https://api.firmly.work/api/v2/domains/{domain}/cart/line-items', headers=headers, json={ 'add_to_cart_ref': {'variant_id': product_variant_id}, 'quantity': 1 } ) cart = cart_response.json() # 3. Set shipping shipping_response = requests.post( f'https://api.firmly.work/api/v2/domains/{domain}/cart/shipping-info', headers=headers, json={ 'first_name': 'John', 'last_name': 'Doe', 'email': 'john.doe@staging.luma.gift', 'phone': '555-123-4567', 'address1': '123 Main St', 'city': 'New York', 'state_or_province': 'NY', 'postal_code': '10001', 'country': 'US' } ) cart_with_shipping = shipping_response.json() # 4. Select shipping method shipment = cart_with_shipping['shipments'][0] shipping_method = shipment['shipping_method_options'][0] requests.post( f'https://api.firmly.work/api/v2/domains/{domain}/cart/shipment/methods', headers=headers, json={ 'shipment_id': shipment['shipment_id'], 'shipping_method_id': shipping_method['id'] } ) # 5. Get public key (the /payment/key response IS a JWK) key_response = requests.get( 'https://cc.firmly.work/api/v1/payment/key', headers=headers ) public_key_jwk = key_response.json() # 6. Encrypt card and complete order. # The JWE contract fields are: number, verification_value, month, year, name. encrypted_card = encrypt_card_data( { 'number': '4111111111111111', 'verification_value': '123', 'month': '12', 'year': '2028', 'name': 'John Doe' }, public_key_jwk ) order_response = requests.post( f'https://cc.firmly.work/api/v2/payment/domains/{domain}/complete-order', headers=headers, json={ 'encrypted_card': encrypted_card, 'billing_info': { 'first_name': 'John', 'last_name': 'Doe', 'email': 'john.doe@staging.luma.gift', 'phone': '555-123-4567', 'address1': '123 Main St', 'city': 'New York', 'state_or_province': 'NY', 'postal_code': '10001', 'country': 'US' } } ) return order_response.json() ``` ### Error Handling The error envelope is `{ code, error, description }`, where `error` is the PascalCase wire name from the [error catalog](/api-reference/errors-and-conventions). Common errors: - `CartNotFound` — Cart session expired - `ProductNotFound` — Invalid variant ID - `NotEnoughStockError` — Item out of stock - `CountryNotSupported` — Shipping country not available - `CreditCardDeclined` — Payment failed ### Next Steps - Review [Error Codes](/api-reference/errors-and-conventions) for comprehensive error handling - Explore [Addon Management](/api-reference/addon-management/) for warranties and services - Check [Session Management](/api-reference/session/) for managing multiple carts --- # Cookbook > **Note** > These recipes assume you've run a checkout guide first — [Standard](/cookbook/standard-checkout-guide) or [Advanced](/cookbook/advanced-checkout-guide). > **Note** > **Cookbook vs solution Recipes** — both exist, and they're scoped differently: > > - **This Cookbook** (`/cookbook/*`) — the two runnable **checkout guides** (Standard and Advanced), deeper checkout patterns (one-shot vs multi-step carts, multi-shipment), plus **cross-solution** recipes (stacking promotions with card-linked offers). The patterns here are solution-agnostic where possible — they work for any destination. > - **Solution Recipes** (e.g., `/solutions/agentic-commerce/recipes/*`) — **solution-specific** recipes scoped to that solution's surface. Chat-to-checkout, wallet-pass-purchase. Each recipe sits inside one solution's narrative. > > If you're not sure which to read: start with the solution Recipes for your solution; jump here when your problem crosses solution boundaries. The Cookbook is for when you know exactly what you want to do and you want a single page that shows you how. Each recipe is task-focused, code-heavy, and pulls together whichever Firmly APIs are needed regardless of which solution or destination type they sit under. Recipes here complement the [API Reference](/api-reference/) (which documents endpoints in isolation) and the [Use Case pages](/solutions/agentic-commerce/use-cases/) (which document broad pattern flows). The Cookbook is the "give me the pattern as a working snippet" layer. ## Checkout guides The two flows, end to end and runnable. **Start with Standard** — it fits most integrations; move to **Advanced** for richer fulfillment. Auth and catalog are the same for both. - [Standard Checkout Guide](/cookbook/standard-checkout-guide) — The Standard (v1) flow end-to-end — single-merchant, one-shipment checkout — in ~90 lines of Node. Right for most integrations. - [Advanced Checkout Guide](/cookbook/advanced-checkout-guide) — The Advanced (v2) flow end-to-end — split shipments, add-ons, scheduling, coverage — in ~150 lines of Node. ## Deeper checkout patterns Beyond the two end-to-end guides — one-shot ordering, the full multi-step cart, and multi-shipment fulfillment (Advanced). - [1-Step Checkout](/cookbook/one-step-checkout) — The single-call path — place a complete order in one `place-order` request, when the cart needs no multi-step mutation. - [Cart API Implementation Guide](/cookbook/full-cart-api-guide) — The full multi-step cart — line items, shipments, addons, configurable fulfillment, and promotions across multiple turns. - [Handle multi-shipment carts](/cookbook/handle-multi-shipment) — Walking the `shipments[]` array — availability and method selection when one merchant ships from different warehouses. ## Cross-solution recipes - [Stack card-linked offers with promo codes](/cookbook/stack-card-linked-offers-with-promo-codes) — Combining a bank's card-linked rewards with Firmly's Promotions API. Order of operations, what to validate, what conflicts to watch for. ## What goes in the Cookbook - **Task-focused** — each recipe answers a specific *"how do I…"* question - **Code-heavy** — runnable snippets, not narrative - **Cross-cutting** — recipes pull from multiple solutions and APIs as needed - **Honest** — what works today, what's planned, what has gotchas ## Want a recipe added? Common patterns get baked into Cookbook recipes when they come up repeatedly. If your integration is solving something other destinations will hit too, suggest it to [Firmly](/contact). --- # Handle multi-shipment carts When a merchant ships items from multiple warehouses or with different fulfillment timelines, Firmly groups them into separate shipments inside the same cart. Each shipment needs its own shipping-method selection before checkout. This recipe is the canonical pattern for handling multi-shipment. ## When this applies - Apparel merchants where items ship from different warehouses - Furniture merchants with white-glove items separate from accessories - Electronics merchants with main product + accessory bundles from different fulfillment centers - Anytime `cart.shipments[]` has more than one entry ## The pattern After calling [Set shipping info](/api-reference/checkout/set-shipping-info), inspect `cart.shipments[]`. Each shipment already carries its available methods in `shipment.shipping_method_options`. For each `shipment_id`, pick a method and record it independently. The snippets below assume a few things are already set up: ```javascript // Base URL for the cart API, scoped to your merchant domain. const API = `https://api.firmly.work/api/v2/domains/${domain}`; // The access_token from POST /api/v1/browser-session, sent as // x-firmly-authorization on every call. const token = 'YOUR_TOKEN'; // The shipping address you collected from the buyer. const shippingInfo = { /* first_name, last_name, address1, ... */ }; // callFirmly() is a thin fetch wrapper that POSTs JSON to `${API}${path}` // with the auth header and returns the parsed response. ``` > **Note** > **Endpoint paths — the singular/plural split is intentional.** Availability lives at `/cart/shipments/get-availability` (plural `shipments`), while method selection lives at `/cart/shipment/methods` (singular `shipment`). This is correct — don't "normalize" them to match, or you'll hit a 404. ```javascript // After setting shipping info, the cart has a shipments[] array const cart = await fetch(`${API}/cart/shipping-info`, { method: 'POST', headers: { 'x-firmly-authorization': token, 'Content-Type': 'application/json' }, body: JSON.stringify(shippingInfo), }).then(r => r.json()); // One shipment → simple. Many shipments → walk each. for (const shipment of cart.shipments) { // Step 1: Read the methods for THIS shipment — populated inline on the // shipment by set-shipping-info (no separate call needed). const cheapest = shipment.shipping_method_options .sort((a, b) => a.price.value - b.price.value)[0]; // Step 2: Record the choice await fetch(`${API}/cart/shipment/methods`, { method: 'POST', headers: { 'x-firmly-authorization': token, 'Content-Type': 'application/json' }, body: JSON.stringify({ shipment_id: shipment.shipment_id, shipping_method_id: cheapest.id, }), }); } ``` You can also parallelize since each shipment is independent: ```javascript await Promise.all(cart.shipments.map(async (shipment) => { const method = pickMethod(shipment.shipping_method_options); await callFirmly('/cart/shipment/methods', { shipment_id: shipment.shipment_id, shipping_method_id: method.id, }); })); ``` ## How to pick a method for each shipment The simplest defaults: - **Cheapest** — minimize cost; good for replenishment and price-optimized agents - **Fastest** — pick the shipment method with the earliest estimated delivery - **User-specified** — let the user pick per shipment For buyer-facing surfaces, the agent typically picks defaults and surfaces them: *"Two of your items ship from different warehouses — standard for both, $12 total. Want to upgrade either to expedited?"* ## Surface what's happening to the user Multi-shipment can confuse users if they're not warned. A helpful pattern: ```javascript if (cart.shipments.length > 1) { const summary = cart.shipments.map(s => { const items = s.line_item_ids.map(id => { // Guard the lookup — a missing match would otherwise throw. // The documented line-item label field is `description` (per Get Cart). const li = cart.line_items.find(li => li.line_item_id === id); return li?.description ?? id; }).join(', '); return `${items} (shipment ${s.shipment_id})`; }).join('; '); agent.say(`Your order will ship in ${cart.shipments.length} packages: ${summary}.`); } ``` ## Edge cases to handle - **`shipping_method_options` is empty for a shipment** — that shipment cannot ship to the address. Check `cart.notices` for `ITEM_NOT_SHIPPABLE` codes and either remove the item or change the address. - **Get-availability returns 501 NotImplemented** — some merchants don't implement the availability endpoint. This does **not** affect method selection: shipping methods always come from `shipment.shipping_method_options`. `get-availability` is only for delivery dates, time slots, and pickup locations on scheduled-delivery or in-store-pickup shipments, so treat a 501 as "no scheduled-delivery/pickup detail for this merchant" and proceed with the inline methods. - **Methods differ across shipments** — sometimes Shipment A has overnight available but Shipment B only has standard. Surface this so the user understands. --- ## Related - [Shipping & Fulfillment concept](/api-reference/shipment-configuration/shipping-and-fulfillment) — the architectural picture - [Get shipping availability](/api-reference/shipment-configuration/get-availability) — endpoint reference - [Set shipping method](/api-reference/shipment-configuration/set-shipping-method) — endpoint reference - [Multi-product purchase flow](/solutions/agentic-commerce/flows/multi-product-purchase) — the broader flow this recipe sits inside --- # Stack card-linked offers with promo codes Banks and BNPL providers often have card-linked offers (cashback, accelerated rewards, statement credits) that overlay on top of merchant promo codes. Stacking them — or deciding NOT to stack them when the merchant's rules disallow it — is a real integration concern for bank, fintech, and brand-loyalty destinations. This recipe shows the canonical pattern and the conflict checks to put in place. ## The two layers | Layer | Owner | Where it applies | |---|---|---| | **Merchant promo codes** | The merchant — codes apply at the merchant's checkout rules | Inside Firmly's [Promotions API](/api-reference/promotions/) | | **Card-linked offers** | The bank or wallet — applied at the network or PSP layer | Outside Firmly — calculated by the bank when the transaction settles | Because they live at different layers, both can apply simultaneously **if the merchant permits it**. Most merchants do; some explicitly exclude card-linked offers from stacking with codes. ## The recommended sequence 1. **Build the cart** as usual — discovery, add line items 2. **Apply merchant promo code first** via Firmly's `add-promo-codes` (the reference-page name for `POST /cart/promo-codes`) 3. **Re-read the cart** and confirm the discount actually applied (200 doesn't mean applied — see [Common issues](/troubleshooting/common-issues)). Not every promo moves `sub_total` — free-shipping and order-level discounts land on `total` or a discount field instead, so check the field the promo actually affects. 4. **Calculate the card-linked offer separately** on the destination side, against the post-merchant-promo cart total 5. **Surface BOTH to the user** before checkout: *"$5 off with code SAVE5, plus 4% back via your bank card — total saved: $9.20."* 6. **Place the order** with the chosen payment instrument 7. **Reconcile the card-linked offer separately** when the bank's settlement runs (this happens outside Firmly) > **Note** > **This snippet is pseudocode.** `callFirmly` (a fetch wrapper), `bankApi`, `agent`, `user`, and `cartBeforePromo` (the cart you captured before applying the code) are placeholders for your own integration — wire them to your real client and bank SDK. > > **Money units:** amounts use Firmly's money object `{ value, number, symbol, currency }`, where `value` is the decimal amount (e.g., `54.00`) and `number` is the integer smallest-unit (cents, e.g., `5400`). Display uses `value`; do arithmetic on `number` (integer cents) to avoid floating-point rounding, then divide by 100 for display. Note that `number` is optional on cart-level totals — fall back to `value` when it is absent. See the [money object convention](/api-reference/errors-and-conventions). ```javascript // 1-2. Add merchant promo (POST /cart/promo-codes) const cartAfterPromo = await callFirmly('/cart/promo-codes', { promo_codes: ['SAVE5'], }); // 3. Did it apply? Compare totals before and after. // NOTE: sub_total only moves for line-item discounts. Free-shipping and // order-level promos land on `total` (or a discount field) instead — compare // the field the promo actually affects, and/or inspect `coupons` / // `cart_discount` on the cart response. const subTotalBefore = cartBeforePromo.sub_total.value; // decimal dollars const subTotalAfter = cartAfterPromo.sub_total.value; // decimal dollars const totalBefore = cartBeforePromo.total.value; const totalAfter = cartAfterPromo.total.value; const promoApplied = subTotalAfter < subTotalBefore || totalAfter < totalBefore; if (!promoApplied) { // Check notices for the reason const promoNotice = cartAfterPromo.notices?.find( n => n.code === 'PROMO_EXPIRED' || n.code === 'PROMO_NOT_APPLICABLE' ); agent.say(`The code didn't apply — ${promoNotice?.details?.description || 'check the merchant rules'}.`); return; } // 4. Calculate card-linked offer on your side, against the post-promo total const cardLinkedOffer = await bankApi.calculateOffer({ cardId: user.cardId, merchantDomain: cart.shop_id, cartTotal: cartAfterPromo.total.value, }); // 5. Surface both to the user. All math is on `value` (decimal dollars), // so no division is needed. estimatedSavings from the bank is also decimal. const codeSavings = totalBefore - totalAfter; agent.say(` Cart: $${cartBeforePromo.total.value} Code SAVE5: -$${codeSavings.toFixed(2)} Card-linked offer: -$${cardLinkedOffer.estimatedSavings.toFixed(2)} (at settlement) Total to charge today: $${cartAfterPromo.total.value} Estimated savings: $${(codeSavings + cardLinkedOffer.estimatedSavings).toFixed(2)} `); ``` ## Conflict checks Some merchants disallow stacking. Things to validate: | Check | How | |---|---| | Does the merchant allow card-linked offers alongside promo codes? | Merchant-specific; not exposed in the cart response. Talk to [Firmly](/contact) for the merchant's policy | | Does the user's card actually carry the offer for this merchant? | Bank-side check — call your bank's offer API with the merchant domain | | Will the offer settle on the card you're charging? | If the user's chosen payment method isn't the offer-bearing card, no card-linked offer applies — surface this | ## What can go wrong - **User expects card-linked savings on the wrong card**. Make it visually clear which card needs to be charged for the offer to apply. - **Merchant promo code silently rejects the cart**. Always re-read and check `cart.notices` for `PROMO_EXPIRED`, `PROMO_NOT_APPLICABLE`, etc. - **Card-linked offer settles weeks later**. Don't quote it as "savings now" — surface as "estimated, applied at settlement." - **Double-discounting at the merchant side**. Some merchants are sensitive to perceived double-discounting and may reject orders. Confirm with the merchant's terms. ## When NOT to stack - The merchant's terms explicitly forbid stacking - The user has a fixed budget and the agent should pick the SINGLE best offer (often the larger of the two) rather than try both - The merchant's order placement fails when both apply (test in sandbox first) --- ## Related - [Promotions overview](/api-reference/promotions/) - [Add promo codes](/api-reference/promotions/add-promo-codes) - [Smart Payment Selection use case](/solutions/agentic-commerce/use-cases/smart-payment) - [Destinations overview](/solutions/destination-surfaces/) - [Errors & Conventions → recovery patterns](/api-reference/errors-and-conventions) --- # Standard Checkout Guide A complete, runnable walkthrough of the [Standard flow](/api-reference/standard-flow/) (`/api/v1`) — session, catalog, cart, address, and a placed order — in about 90 lines of Node against the shared [sandbox](/for-destinations/try-the-sandbox). It places a **real order** with a **test card** (no real money). > **Note** > This is the **Standard** (single-merchant, one-shipment) flow — right for most integrations. Need split shipments, add-ons, delivery scheduling, or coverage gating? Use the [Advanced Checkout Guide](/cookbook/advanced-checkout-guide) (`/api/v2`). **Auth, catalog, and discovery are identical across both flows**, so switching later is cheap. ## Prerequisites - Node 18+ (uses built-in `fetch`). - One dependency: [`jose`](https://github.com/panva/jose) for JWE card encryption. ```bash mkdir firmly-standard && cd firmly-standard npm init -y npm install jose ``` Add `"type": "module"` to `package.json` so the script can use `import`. ## The full script Save as `standard.mjs` and run with `FIRMLY_APP_ID= node standard.mjs`. ```javascript // standard.mjs — the Standard (v1) flow, end to end. import { CompactEncrypt, importJWK } from 'jose'; const APP_ID = process.env.FIRMLY_APP_ID; const API = 'https://api.firmly.work'; // general API const PAY_API = 'https://cc.firmly.work'; // payment API const DOMAIN = 'staging.luma.gift'; // test merchant const UA = 'Mozilla/5.0 (compatible)'; // avoids sandbox bot-protection 403s const TEST_CARD = { number: '4111111111111111', name: 'Test Buyer', verification_value: '123', month: '12', year: '2030' }; const ADDRESS = { first_name: 'Test', last_name: 'Buyer', email: 'test@example.com', phone: '+15551234567', address1: '500 Howard St', city: 'San Francisco', state_or_province: 'CA', country: 'US', postal_code: '94105' }; const json = r => r.json(); async function ok(r, step) { if (!r.ok) throw new Error(`${step} -> ${r.status}: ${(await r.text()).slice(0, 300)}`); return r; } // 1. Bootstrap a session — App ID in, access_token out. const session = await fetch(`${API}/api/v1/browser-session`, { method: 'POST', headers: { 'x-firmly-app-id': APP_ID, 'User-Agent': UA } }).then(r => ok(r, 'session')).then(json); const H = { 'x-firmly-authorization': session.access_token, 'Content-Type': 'application/json', 'User-Agent': UA }; // 2. Pick a product and add it — the cart is created on the first successful add. // Catalog availability can go stale between browse and add, so a 409 // NotEnoughStockError just means: move on to the next product. const list = await fetch(`${API}/api/v1/domains-products/${DOMAIN}?page=1&size=100`, { headers: H }).then(r => ok(r, 'catalog')).then(json); let cart; for (const item of list.products) { const pdp = await fetch(item.loc, { headers: H }).then(r => ok(r, 'product')).then(json); const v = pdp.variants.find(v => v.available); // add_to_cart_ref e.g. { variant_id: 'MH09-S-Blue' } if (!v) continue; const res = await fetch(`${API}/api/v1/domains/${DOMAIN}/cart/line-items`, { method: 'POST', headers: H, body: JSON.stringify({ add_to_cart_ref: v.add_to_cart_ref, quantity: 1 }) }); if (res.status === 409) continue; // stock drifted since browse — next product cart = await ok(res, 'add').then(json); break; } if (!cart) throw new Error('no in-stock product on the first catalog page'); console.log('cart', cart.cart_id, 'subtotal', cart.sub_total.value); // 4. Set the shipping address. await fetch(`${API}/api/v1/domains/${DOMAIN}/cart/shipping-info`, { method: 'POST', headers: H, body: JSON.stringify(ADDRESS) }).then(r => ok(r, 'shipping-info')); // 5. Read the shipping rates and choose one (methods are keyed by `sku`). const rates = await fetch(`${API}/api/v1/domains/${DOMAIN}/cart/shipping-rates`, { headers: H }).then(r => ok(r, 'rates')).then(json); const method = rates[0].sku; // e.g. 'freeshipping_freeshipping' await fetch(`${API}/api/v1/domains/${DOMAIN}/cart/shipping-method`, { method: 'POST', headers: H, body: JSON.stringify({ shipping_method: method }) }).then(r => ok(r, 'shipping-method')); // 6. Fetch the payment key and JWE-encrypt the card (the raw PAN never leaves your process). const jwk = await fetch(`${PAY_API}/api/v1/payment/key?format=JWK`, { headers: { 'User-Agent': UA } }).then(r => ok(r, 'key')).then(json); const encryptedCard = await new CompactEncrypt(new TextEncoder().encode(JSON.stringify(TEST_CARD))) .setProtectedHeader({ alg: 'RSA-OAEP-256', enc: 'A256GCM', kid: jwk.kid }) .encrypt(await importJWK(jwk, 'RSA-OAEP-256')); // 7. Complete the order on the existing cart. const order = await fetch(`${PAY_API}/api/v1/payment/domains/${DOMAIN}/complete-order`, { method: 'POST', headers: H, body: JSON.stringify({ encrypted_card: encryptedCard, billing_info: ADDRESS }) }).then(r => ok(r, 'complete-order')).then(json); console.log('order', order.platform_order_number, order.cart_status, 'total', order.total.value); ``` ## What it prints ```text cart e7e27aaa-36c1-4196-a334-9c57b0001fd9 subtotal 69 order 56335 submitted total 74.69 ``` ## How it works 1. **Session** — `POST /api/v1/browser-session` exchanges your App ID for a short-lived `access_token`; it rides in `x-firmly-authorization` on every later call. 2. **Catalog** — list products, open one via its `loc` (a ready-made [product-by-URL](/api-reference/catalog/get-product-from-url) request), and take an available variant's `add_to_cart_ref`. Stock can drift between browse and add, so a `409 NotEnoughStockError` on the add means try the next product — not a bug. 3. **Cart** — the first [add](/api-reference/standard-flow/cart) creates the cart; every cart call returns the full cart with merchant-resolved prices. 4. **Address & shipping** — set the [address](/api-reference/standard-flow/checkout), read the rates, and select one by its `sku`. 5. **Payment** — `GET /payment/key?format=JWK` returns an RSA public key; the card is encrypted as a compact JWE (`RSA-OAEP-256` + `A256GCM`) so the unencrypted card number never leaves your process. 6. **Order** — [`complete-order`](/api-reference/standard-flow/place-order) finalizes the existing cart with `encrypted_card` + `billing_info`. (`place-order` is the one-shot alternative — it builds the cart *and* pays in a single call, taking `items[]` + `shipping_info` + `billing_info`.) > **Tip** > For readability this script assumes every call succeeds — the `ok()` helper throws on a non-2xx. In production, handle each error explicitly; see [Errors & Conventions](/api-reference/errors-and-conventions) for the error shape. ## Next - [Standard flow reference](/api-reference/standard-flow/) — Every Standard endpoint, with request and response detail - [API Explorer](/api-explorer/) — Try each call interactively against the sandbox --- # FAQ The cross-cutting questions that come up when someone is **first encountering Firmly**. For deeper questions, use the FAQ closest to what you're working on: - [Technical FAQ](/troubleshooting/faq-technical) — Auth, environments, protocols, idempotency, rate limits — questions developers ask while building. - [Agentic Commerce FAQ](/solutions/agentic-commerce/faq) — Solution-specific — discovery scope, multiple carts, SSO between destination and merchant. - [Branded Commerce FAQ](/solutions/branded-commerce/faq) — Solution-specific — partner setup, multi-merchant landing pages, ROAS tracking, "Powered by Firmly". - [Common issues](/troubleshooting/common-issues) — Symptoms and fixes for known integration issues. ## What Firmly is and isn't ### Is Firmly the agent? No. Firmly is the commerce backend an AI surface integrates with. The destination owns the conversation, the consent layer, and the user-facing experience. See [Agentic Commerce overview](/solutions/agentic-commerce/). ### Is Firmly the merchant of record? No. **The merchant is always the merchant of record.** They are the seller, their PSP charges the card, and their order management system is the source of truth for fulfillment. Firmly is the orchestration layer in between. That is deliberate, and it works in a destination's favor: | You don't take on | Because the merchant is MoR | |---|---| | **Payment licensing and PCI scope** | The merchant's PSP charges the buyer, so you never become a payment facilitator or hold card data | | **Tax registration and remittance** | Sales tax is calculated and remitted by the merchant in their own jurisdictions | | **Chargebacks and disputes** | Raised against the merchant's PSP account and handled in their existing process | | **Returns, refunds, and support** | Run in the merchant's back office, on their own policy — no returns desk for you to staff | | **Inventory and pricing risk** | You never buy or hold stock; price and availability stay the merchant's | What you get instead is reach: you add merchants without adding regulatory surface, so onboarding the tenth merchant costs you no more compliance work than the first. ### Does Firmly process payments? Firmly's vault submits the card to the merchant's PSP, which returns a payment token — the PSP mints the token, Firmly orchestrates the call. The actual payment processing happens at the PSP. Card data passes through Firmly's encrypted vault layer (PCI-scoped) — see [Smart Payment Selection](/solutions/agentic-commerce/use-cases/smart-payment). ### What does Firmly NOT do? Firmly's scope ends at order placement. Everything after that — fulfillment, shipping, returns, refunds, customer service — runs in the merchant's existing back-office workflows. Firmly doesn't run those operations. It does expose a read-only [order status](/api-reference/) lookup so you can show a buyer where their order is, but the work itself happens in the merchant's systems. ## Which solution fits me? ### I'm a… | If you are… | Start with | |---|---| | An AI app, chatbot, AI assistant, or wallet | [Agentic Commerce](/solutions/agentic-commerce/) | | A deal publisher, affiliate network, or retail-media partner driving ad traffic to checkout | [Branded Commerce](/solutions/branded-commerce/) | | An ad platform or DSP | [Ad Commerce](/solutions/ad-commerce/) | | Linking identity / SSO across merchant and destination | [Firmly Connect](/solutions/firmly-connect/) | | A multi-brand or aggregator surface across many merchants | [Marketplace](/solutions/marketplace/) | | A publisher, media, or content platform | [Publisher Commerce](/solutions/publisher-commerce/) | If you're not sure, [Destinations](/solutions/destination-surfaces/) walks through which solution shape fits which kind of company. ### Can I use more than one solution? Yes. The solutions share the same underlying platform (cart, discovery, payment, tax, shipping, order placement). They differ in destination shape and contractual posture. Many destinations use multiple solutions — for example, **Branded Commerce + Agentic Commerce** is common (the destination runs deal-driven hosted checkout AND exposes the same merchants to AI agents). ## Compliance basics ### Does Firmly see the conversation between the user and the agent? Firmly receives only the fields your API calls actually contain — cart contents, address, payment details. The surrounding conversation isn't part of any request. The one exception is Agentic Pay, where you can optionally pass a short `consumer_prompt` string that the card network shows the cardholder during authorization. ### Where does payment card data live? Card data is JWE-encrypted client-side using Firmly's public key. Firmly's payment vault decrypts it **in memory** and submits it over TLS to the merchant's payment processor or platform. The cleartext card is never written to storage. See [Get Payment Public Key](/api-reference/payment/get-public-key) and the [Security model](/foundations/security-model). ### How long does Firmly retain cart and order data? | Data | Retention | |---|---| | Session JWT | 1 hour active; renewable while session state persists (~7 days from last activity) | | Cart state (Firmly's session store) | 7 days | | Card number | Never stored. The order record keeps the last four digits and the card brand | | Order references | Per merchant policy | | Conversation context | Not part of any request — Firmly gets only the fields you send | See [Consent & Disclosure](/solutions/agentic-commerce/consent-and-disclosure). ### Who's responsible for user consent before placing an order? The destination. Firmly does not enforce a "review and confirm" step — that's the destination's responsibility because consent UX varies wildly across surfaces (chat, voice, ambient, autonomous). ## For merchants ### Is my commerce platform supported? **Most likely, yes.** Firmly supports a **wide range of industry-standard commerce platforms** and speaks each store's **native API**, so the large majority of stores connect **without a custom build** — and if yours is less common, we can usually add it. We confirm your specific store during onboarding — to check, reach out at **contact@firmly.ai**. ### How long does it take to go live? It depends on your store and readiness (business verification, catalog, and a go-live review). We confirm a timeline with you during onboarding — start the conversation at **contact@firmly.ai**. ### Who handles payments, chargebacks, and returns? Your existing setup does — you stay the seller of record, your PSP charges the card, and fulfillment, returns, and refunds run in your back-office as they do today (see [What does Firmly NOT do?](#what-does-firmly-not-do)). The specifics for your setup are covered during onboarding — reach out at **contact@firmly.ai**. ## Pricing and getting started ### How does Firmly price? Pricing varies by solution, volume, and merchant set. There's no published price card — reach out at **contact@firmly.ai** for the commercial conversation. ### Is there a free tier? **For destinations:** sandbox access is provisioned for evaluation; production usage is contracted. **For merchants:** there's no separate sandbox or trial mode — onboarding is the path to live, with two Firmly-reviewed gates (KYB and Go-live) along the way. See [Merchant quickstart](/for-merchants/quickstart). ### How do I contact Firmly? | You want… | Where to go | |---|---| | **Docs feedback, technical questions, bug reports, integration scoping** | Email **firmlydocs@firmly.ai** — see [/contact](/contact) for what to include | | **Commercial / sales conversation** | Email **contact@firmly.ai** | | **Account-team support for a live engagement** | Use the contact you've been working with at Firmly directly — see [Contact us](/contact) | --- ## Related - [Technical FAQ](/troubleshooting/faq-technical) — auth, environments, protocols, idempotency, rate limits - [Agentic Commerce FAQ](/solutions/agentic-commerce/faq) — solution-specific - [Branded Commerce FAQ](/solutions/branded-commerce/faq) — solution-specific - [Common issues](/troubleshooting/common-issues) — symptom-and-fix pairs - [Errors & Conventions](/api-reference/errors-and-conventions) — specific error codes - [Contact us](/contact) — how to reach the docs team --- # Authentication Firmly accepts two distinct authentication patterns. Pick the one that matches where your code runs. | Pattern | Where your code runs | What you send | Endpoint reference | |---|---|---|---| | **Browser session** | Client-side (browser, mobile app, embedded widget) | App ID → bootstrap → use returned JWT | [Browser Session](/api-reference/authentication/browser-session) | | **Server-to-server** | Backend (your servers, agent backend, integration tier) | Long-lived S2S secret + device identifier | [Server-to-Server](/api-reference/authentication/server-to-server) | Your **App ID** is the durable destination credential Firmly issues you. Depending on where your code runs, it either bootstraps a short-lived JWT (browser-session pattern) or is paired with an S2S secret and device identifier (server-to-server pattern). Both result in a per-request `x-firmly-authorization` header — only the value differs. ## The two patterns ### Browser session (most common) The browser-session pattern is what client-side applications use: one bootstrap call returns a JWT, which you then send in `x-firmly-authorization` on every subsequent request. The [Sandbox Setup](/for-destinations/sandbox-setup) walks the actual request and response. Token lifetime is ~1 hour (`expires_in: 3600`). To renew, re-post to the same endpoint with the prior (expired) token in the body — this returns a new token with the same `device_id` as long as the session state is still retained (~7 days from last activity). There's no separate server-enforced renewal window. ```bash # Bootstrap curl -X POST https://api.firmly.work/api/v1/browser-session \ -H "x-firmly-app-id: YOUR_APP_ID" ``` The bootstrap returns the token and session identity: ```json { "access_token": "eyJhbGc...", "device_id": "dev_01H2X...", "device_created": true, "expires_in": 3600 } ``` Send `access_token` as `x-firmly-authorization` on every subsequent call: ```bash curl -X GET https://api.firmly.work/api/v2/domains/staging.luma.gift/cart \ -H "x-firmly-authorization: " ``` See [Browser Session reference](/api-reference/authentication/browser-session) for the full field list, renewal pattern, and error cases. ### Server-to-server The S2S pattern is for backend systems that act on behalf of devices/users. The flow: ```mermaid sequenceDiagram participant Server as Your Backend participant Firmly as Firmly API Note over Server: Static S2S_SECRET
+ a device_id you assign per user Server->>Firmly: API calls
x-firmly-authorization: S2S_SECRET
x-firmly-device-id: USER_ID Firmly-->>Server: Response ``` **Firmly issues the S2S secret to you alongside your App ID.** There's no bootstrap call — you put that long-lived secret in `x-firmly-authorization` on every request, plus a `device_id` you assign per user/session so Firmly can isolate carts and orders correctly. ```bash curl -X POST https://api.firmly.work/api/v1/discovery/search \ -H "x-firmly-authorization: YOUR_S2S_SECRET" \ -H "x-firmly-device-id: user-12345" \ -H "Content-Type: application/json" \ -d '{"query": "shoes"}' ``` The `x-firmly-device-id` value is your own user/session identifier — typically your own user ID or a session UUID. It must be ≤ 256 chars and contain only `a-z`, `A-Z`, `0-9`, `-`, `_`. See [Server-to-Server reference](/api-reference/authentication/server-to-server) for the full spec. ## Which to pick | Question | Browser Session | S2S | |---|---|---| | Does your code run client-side? | ✅ | ❌ | | Can the credential safely appear in client code? | App ID (intentional) | No — the S2S secret must stay server-side | | Do you want to manage device identity yourself? | No (Firmly assigns) | Yes (you assign `device_id`) | | Is your code a backend service acting for many users? | Not the fit | ✅ Use S2S | | Is your code an embedded widget or browser app? | ✅ Use Browser Session | Not the fit | Most agentic deployments use **browser session** because the agent is acting client-side or as a per-user session. Backend integrations and batch jobs use **S2S**. ## What's in the JWT The `POST /browser-session` call returns a JSON body with these **bootstrap response fields**: | Field | Meaning | |---|---| | `access_token` | The JWT itself | | `device_id` | Unique session identifier — store it so you can renew the token later | | `device_created` | Boolean — was this device new in this call? | | `expires_in` | Seconds until expiry (typically 3600) | | `expires` | Unix timestamp of expiry | The `access_token` is a standard JWT — not encrypted, just signed. Decode its payload to see the claims inside: - `appid` — your App ID - `deviceid` — same as the `device_id` above - `sub` — partner / destination name bound to your App ID - `env` — environment (`uat`, `prod`, etc.) - `iss` — `identity` (the issuer) - `iat` / `exp` — issued at / expires at (Unix timestamps) ## Idempotency Pass an `Idempotency-Key` header — a UUID your code generates — on mutation requests, and reuse the same key when retrying the same attempt. ```bash curl -X POST .../complete-order \ -H "x-firmly-authorization: $TOKEN" \ -H "Idempotency-Key: $(uuidgen)" \ -d '{...}' ``` > **Warning** > **Scope.** The key is deduplicated only on the UCP protocol bridge today — the core REST endpoints accept but do not act on it, so a REST retry re-runs the operation. Guard retries client-side: after a failed `complete-order`, re-read the cart and check `cart_status` before retrying. See [Errors & Conventions](/api-reference/errors-and-conventions#idempotency). ## Common auth errors All errors use the standard REST envelope: `{ "code": , "error": "", "description": "..." }`. | Status | Error | Fix | |---|---|---| | 400 | `MissingAuthHeader` | Add the `x-firmly-authorization` header | | 400 | `InvalidToken` | Token is malformed (not a valid JWT structure) — re-bootstrap | | 401 | `InvalidJWTToken` | JWT signature failed verification, or the token is expired — bootstrap a new session or renew | See [Errors & Conventions](/api-reference/errors-and-conventions) for the full catalog. ## Endpoint references - **[Browser Session](/api-reference/authentication/browser-session)** — request/response, renewal, all fields - **[Server-to-Server](/api-reference/authentication/server-to-server)** — headers, device-id format, full sample requests --- # Destination Dashboard The **Destination Dashboard** is where a destination runs its integration on Firmly's network day-to-day. It's a single shared surface across all five solution types — agentic, branded, publisher, ad, and marketplace — keyed on your App ID, not on which solution you build. Once Firmly provisions your App ID, it invites your team by email; you accept, sign in, and manage everything below. App ID provisioning and merchant scope are still set by Firmly — the dashboard is where you operate, not where you self-issue credentials. ## What's in the dashboard - **Dashboard** — At-a-glance metrics for your App ID — orders, conversion, and activity across the merchants you reach. - **Funnel** — Conversion-funnel breakdown — where users move and drop off between discovery, cart, and completed order. - **Orders** — Order list and per-order detail for transactions placed through your destination. Read-only — fulfillment stays in the merchant's backend. - **Merchants** — The merchants your App ID is approved to transact against. - **Team** — Invite teammates, assign roles, and manage access. Invitations expire after 7 days. - **Audit logs** — Record of team actions and configuration changes for your destination. - **Settings** — Destination configuration, including API access details for your App ID. ## Role-based access | Role | Can do | |---|---| | **Primary Owner** | Everything, plus ownership transfer (one Primary Owner per destination) | | **Owner** | Everything except ownership transfer | | **Editor** | Edit settings and operational data | | **Viewer** | Read-only | ## What the dashboard does not do - **Issue or rescope App IDs** — provisioning and merchant scope are set by Firmly. See [Onboarding](/for-destinations/onboarding) for the handshake. - **Replace the API** — the dashboard is for visibility and team management; your integration still runs against the [API](/api-reference/). --- ## Related - [Onboarding](/for-destinations/onboarding) — how Firmly provisions your App ID and invites your team - [Going Live](/for-destinations/going-live) — what to watch once production traffic flows - [Authentication](/for-destinations/authentication) — how your App ID authenticates API calls --- # For Destinations > **Tip** > **Want to try the API?** Request a sandbox App ID (email [firmlydocs@firmly.ai](mailto:firmlydocs@firmly.ai) — typically within one business day), then use the [sandbox walkthrough](/for-destinations/try-the-sandbox) to call a test merchant end to end. > **Note** > For your own integration, request access from Firmly. Firmly issues your App ID directly, usually within one business day — paired with a test merchant and scoped to your environment, so you can make a real call as soon as it lands. See [Onboarding](/for-destinations/onboarding) and [Contact](/contact). If you're a destination — an AI agent, publisher, ad platform, marketplace operator, or brand partner — Firmly is the commerce backend that powers discovery, cart, and checkout across merchants — all through a single integration. One App ID, one API collection, and your surface can transact against every Firmly-connected merchant. **The merchant stays the merchant of record.** They are the seller, their payment processor charges the buyer, and their systems own fulfillment. For you that means no payment licensing or PCI scope, no sales-tax registration, no chargeback queue, no returns desk, and no inventory risk — so adding the tenth merchant costs you no more regulatory work than the first. See [Is Firmly the merchant of record?](/faq#is-firmly-the-merchant-of-record) for the full breakdown. ## How it works ![How Firmly works for a destination — your surface calls Firmly's APIs (discovery, cart, checkout, payment, order, attribution); Firmly places the order with the merchant; order confirmation and affiliate attribution flow back to your surface](/images/for-destinations/destination-flow.svg) ## Choose your checkout flow **Start with Standard** — it fits most integrations. Move up to **Advanced** when you need split shipments, delivery scheduling, add-ons, or ZIP coverage. Auth, catalog, and discovery are the same for both — only the cart, checkout, and order calls differ, so switching later is cheap. ## How destinations onboard Destinations onboard through a Firmly-issued **App ID** plus a paired test merchant. Firmly provisions each App ID directly, so your test merchant, environment scope, and per-destination configuration are already correct when you make your first call. The flow is: request a sandbox App ID from Firmly (typically within one business day) → receive your App ID + a test merchant → make your first API call. Sandbox is where you build; production is a separate App ID issued after the integration is verified. Destinations write code. Merchants don't — they sign up on [Firmly Connect](/solutions/firmly-connect/) and walk through a wizard. The two sides are kept clean: destinations build against APIs, merchants configure through forms. For the API reference, see [API Reference](/api-reference/). For solution-specific patterns (Agentic Commerce, Publisher Commerce, Ad Commerce, Marketplace, Branded Commerce), see [Solutions](/solutions/). Once Firmly provisions your App ID, it invites your team to the **Destination Dashboard** — the surface you sign into to track your funnel, review orders, manage your team, and read audit logs. See [Destination Dashboard](/for-destinations/destination-dashboard) for the full reference. ## The 6-step destination journey | # | Step | Who does it | What it is | |---|---|---|---| | 1 | Request an App ID | **You** | Email or contact Firmly with your destination type and intended integration shape | | 2 | Receive App ID + test merchant pairing | **Firmly** | Sandbox App ID and a test merchant domain provisioned for you | | 3 | Sandbox setup | **You** | Verify auth, search, and the test merchant catalog with a few curl calls | | 4 | Build your integration | **You** | Implement against the API reference — discovery, cart, checkout, payment | | 5 | Pre-launch review | **Firmly + You** | Walk through your integration, error handling, rate-limit posture, and observability | | 6 | Production App ID | **Firmly** | Production App ID issued; production merchants enabled | The App ID issuance step (step 2) is manual — there's no auto-provisioning. Most destinations receive their sandbox App ID within one business day of the initial request. ## What you get - **One API, all merchants** — Discovery, cart, checkout, payment, tax, shipping, and order placement — the same API surface against every merchant on Firmly's network. - **Real merchant catalogs** — Live pricing, real-time inventory, and authentic merchant order flows — your users transact against the real store, not a simulation. - **No per-merchant integration** — You integrate Firmly once. Adding a new merchant on Firmly's side doesn't require any change on yours. - **Sandbox parity** — Sandbox uses the same API shapes, flow, and base URLs as production — the only differences are your App ID and the test merchant. - **Payment flexibility** — Card via JWE encryption, Google Pay, PayPal, Klarna, Click to Pay, and Agentic Pay for autonomous agents — pick what fits your surface. - **Affiliate attribution** — Orders are tagged with your destination identifier so commissions and attribution flow correctly without manual reconciliation. ## Read next - [Try the Sandbox](/for-destinations/try-the-sandbox) — Request a sandbox App ID, then call the API against a test merchant - [Find your solution](/solutions/) — Agentic, ad, branded, marketplace, publisher — pick the integration shape that fits before you build - [Standard Checkout Guide](/cookbook/standard-checkout-guide) — The simplest path — the Standard (v1) flow end-to-end in ~90 lines of Node. Right for most integrations - [Advanced Checkout Guide](/cookbook/advanced-checkout-guide) — The richer Advanced (v2) flow — split shipments and add-ons — end-to-end in ~150 lines of Node - [Onboarding](/for-destinations/onboarding) — The App ID handshake — what Firmly issues, what you provide - [Authentication](/for-destinations/authentication) — Browser session vs server-to-server — pick the right auth model - [Sandbox setup](/for-destinations/sandbox-setup) — Verify your sandbox is live with three curl calls - [Going live](/for-destinations/going-live) — Pre-launch checklist and the production App ID handover ## What stays on your side, what's on Firmly's | Layer | Where it lives | |---|---| | Your user-facing surface (chat, search, ad placement, publisher page, marketplace UI) | Yours — Firmly doesn't render anything in your UI | | The shopping experience (discovery, cart, checkout) | Yours — your code calls Firmly's APIs and renders the results in your surface | | Merchant catalogs, inventory, pricing | Firmly — read from each merchant's commerce backend by Firmly's platform adapter | | Payment processing | Firmly — card encryption, network token, alternative payment methods | | Order placement at the merchant | Firmly — orders land in the merchant's existing order management system | | Attribution and reconciliation | Firmly — your destination identifier is tagged on every order | ## What about merchants Merchants don't need to do anything special for your destination to start transacting — they opt into Firmly's network through [Firmly Connect](/solutions/firmly-connect/), and once they're live, every destination on the network can sell their catalog (subject to per-destination opt-ins). When Firmly issues your sandbox App ID, it's paired with a specific test merchant. In production, your App ID is scoped to the merchants your destination is approved to transact against. --- ## Related - [How Firmly Works](/how-firmly-works) — the underlying platform - [Destination Dashboard](/for-destinations/destination-dashboard) — your day-2 home for funnel, orders, team, and audit logs - [Destinations](/solutions/destination-surfaces/) — the five destination categories - [Solutions overview](/solutions/) — all Firmly solutions - [For Merchants](/for-merchants/) — the merchant's side of the integration --- # Going Live Going live for a destination is a clean cutover, not a code rewrite. Your integration uses the same API shapes and follows the same flow. What changes is the App ID you send, the merchants you're transacting against, and that real money starts moving. Production also runs on different hosts than the sandbox, so the base URLs change too — Firmly provides them at go-live. This page covers what you should validate before going live, what Firmly reviews, and what to expect in the first hours and weeks of production traffic. ## What "going live" actually means | Before going live | After going live | |---|---| | Sandbox App ID | Production App ID | | Test merchants only | Real merchants you're approved for | | Test cards (`4111111111111111`, etc.) | Real cards, wallets, real payment methods | | Test orders — no money moves | Real orders, real charges, real fulfillment | | Catalog has sample data | Catalog reflects real merchant inventory and pricing | ## How the cutover works | Stage | What happens | |---|---| | **Pre-launch review** | You schedule a working session with Firmly to walk through the integration. See [Onboarding](/for-destinations/onboarding) Phase 3 | | **Production App ID issued** | Firmly issues a separate production App ID and enables your approved production merchants | | **You swap config** | Your code reads the new App ID **and the production base URLs** from configuration. No SDK change, no protocol change | | **First production order** | Smoke-test with a small order against a known production merchant before scaling traffic | | **Ramp traffic** | Gradually increase live traffic — start with a small percentage of users, watch error rates and order success rates | The cutover is a configuration change on your side — the new App ID. The base URL stays the same; the same Firmly platform serves both environments. **What changes is your configuration and the merchants you're scoped to, not your code.** ## Pre-launch checklist Before requesting your production App ID, confirm you have these working in sandbox: ### Auth and credentials - App ID is read from configuration, not hard-coded in source - Token renewal is implemented — browser sessions expire after ~1 hour; your code handles renewal without dropping user flows - Server-to-server secrets (if used) are stored in your secrets manager, not in source - The App ID is never logged or surfaced in error messages ### Order placement - Duplicate-order safety is handled: the core REST endpoints do **not** deduplicate on `Idempotency-Key` today, so guard client-side (re-read `cart_status` before any retry of a cart mutation or the order-placement call — `complete-order` for a cart built across calls, or `place-order` for the one-shot path). Send `Idempotency-Key` on the endpoints that do accept it (UCP bridge). See [Errors & Conventions](/api-reference/errors-and-conventions) - Idempotency keys are stable for retry windows — same logical operation, same key - Order success is validated against the response's `cart_status` field (`submitted` indicates success) - The merchant's order identifier is captured for reconciliation ### Error handling - 4xx errors are surfaced to the user with appropriate messaging - 5xx errors trigger retry with exponential backoff (cap at ~30 seconds — see [Errors & Conventions](/api-reference/errors-and-conventions)) - Specific error codes — `ucp_disabled`, `DomainNotFound`, decline codes — have specific handling, not generic catch-all - Payment declines distinguish between hard declines (don't retry) and soft declines (offer alternative payment) ### Observability - Request IDs are logged so you can correlate with Firmly's logs during incident review - Order placement attempts are logged with the idempotency key, merchant domain, and outcome - A dashboard or log query exists for "orders attempted vs orders completed" so you can spot regressions ### Cart and checkout flow - Multi-shipment carts are handled — shipping method is set per shipment, not globally - Shipping methods are read from each shipment's inline `shipping_method_options` (populated by `set-shipping-info`), not from `get-availability` - `get-availability` (delivery dates / time slots / pickup) is optional; merchants that don't support it return `501 NotImplemented`, which your code tolerates and skips - The user's chosen shipping address is validated client-side before submission to reduce 4xx on `/shipping-info` ### Production readiness - Your monitoring is wired up — alerts on elevated error rates, failed orders, or auth failures - Your team knows where to find Firmly request IDs in logs for incident triage - Rate limits are documented and your code respects them — see [Rate Limits](/api-reference/rate-limits) - Outbound network allows the sandbox hosts `api.firmly.work` and `cc.firmly.work`. **Production uses different hosts** — allowlist the production base URLs Firmly gives you at go-live before you cut over ## What Firmly reviews The pre-launch review (Onboarding Phase 3) walks the same checklist from Firmly's side. Common items the review surfaces: - Idempotency not being sent on all mutations - Token renewal not implemented (manifests as 401 errors after ~1 hour of activity) - Retry storms on 503 — backoff missing or too aggressive - Test cards still hard-coded — sandbox-only credentials present in code paths that will run in production - Order success determined by HTTP status alone, not by the response body (a payment decline surfaces as a `422 CreditCardDeclined` error, so confirm success against `cart_status: "submitted"` rather than assuming any 2xx means the order was placed) ## After going live ### Day 1 Smoke-test with one real production order. Confirm the merchant's order shows up in their order management system. Watch your error rates for the next hour. ### First week Ramp traffic gradually. Watch order success rates, payment decline rates, and average time-to-order-placement. ### First month Review your funnel and attribution in the [Destination Dashboard](/for-destinations/destination-dashboard) — your destination identifier should be on every order. Reconcile against Firmly's reporting if discrepancies appear. ## When something goes wrong | Symptom | First thing to check | |---|---| | All requests returning 401 | App ID env-var swap missed — production App ID isn't loaded | | Specific merchant returning 404 | That merchant isn't in your production App ID's approved scope. Contact [Firmly](/contact) | | Specific endpoints returning 404 `ucp_disabled` | The merchant hasn't opted into the relevant capability. Firmly can confirm | | Elevated decline rate | Card payments hitting a real-world decline rate (~5–10% is normal). If higher, check your test cards aren't leaking into production paths | | Orders placed but not in merchant OMS | Reconciliation issue. Capture the Firmly request ID and contact Firmly for triage | ## What stays stable after go-live After go-live, your integration is stable. The same App ID continues to work. Firmly may add new merchants to your scope (you get an email; no code change needed) or add capabilities behind feature flags — both are additive. Breaking changes go through advance notice and a deprecation window. --- ## Related - [Onboarding](/for-destinations/onboarding) — the full handshake, especially Phase 3 pre-launch review - [Destination Dashboard](/for-destinations/destination-dashboard) — track your funnel, orders, and attribution post-launch - [Authentication](/for-destinations/authentication) — auth model details - [Errors & Conventions](/api-reference/errors-and-conventions) — error catalog and retry patterns - [Rate Limits](/api-reference/rate-limits) — production rate-limit posture --- # Onboarding Firmly onboards each destination directly. You get an App ID paired with a test merchant, scoped to your environment, so your first call works straight away. The flow is short — most destinations are live in sandbox within one business day of the initial request — but every App ID is issued deliberately so that environment scope, merchant pairing, and per-destination configuration are correct before the first call. This page walks the full path. For the abbreviated version, see [Advanced Checkout Guide](/cookbook/advanced-checkout-guide). ## The 4 phases at a glance | Phase | Who does what | Typical duration | |---|---|---| | 1 — Sandbox provisioning | You request; Firmly provisions App ID + test merchant | ~1 business day | | 2 — Sandbox integration | You build against the API | Days to weeks (your pace) | | 3 — Pre-launch review | You and Firmly walk through the integration | ~1–2 hours | | 4 — Production App ID issuance | Firmly issues production App ID + enables production merchants | ~1 business day after review | ## Phase 1 — Sandbox provisioning You contact [Firmly](/contact) with a short brief. Useful details to include: - **Destination type** — AI agent, publisher, ad platform, marketplace operator, brand partner - **Integration shape** — hosted checkout, embedded checkout, full Cart API, headless SDK - **Target launch surface** — what users will see (a chat assistant, an article page, a creative unit, a marketplace UI) - **Solution** — Agentic Commerce, Publisher Commerce, Ad Commerce, Marketplace, Branded Commerce - **Tech stack** — language, runtime, where the integration code will live Firmly issues: 1. **A sandbox App ID** (`_appId`) — a UUID scoped to a non-production environment 2. **A test merchant domain** — typically something like `staging.luma.gift`, with a non-empty catalog you can search and buy from 3. **Optional: a server-to-server secret** — if you plan to use S2S auth instead of browser sessions The sandbox App ID + test merchant pair is the gate. Until you have both, no API call will return data — `/discovery/search` and `/cart/*` are scoped to the merchants your App ID is approved to transact against. ## Phase 2 — Sandbox integration This is where you write the code. The full surface area is in the [API Reference](/api-reference/). Most integrations follow this rough sequence: 1. **Bootstrap auth** — see [Authentication](/for-destinations/authentication) 2. **Discover products** — `POST /api/v1/discovery/search` 3. **Add to cart** — `POST /api/v2/domains/{domain}/cart/line-items` 4. **Set shipping address** — `POST /api/v2/domains/{domain}/cart/shipping-info` 5. **Set shipping method** — `POST /api/v2/domains/{domain}/cart/shipment/methods` 6. **Encrypt card and complete order** — `POST /api/v2/payment/domains/{domain}/complete-order` (finalizes the cart built in steps 3–5; `place-order` is the one-shot alternative that creates the cart and places the order in a single call) For a runnable end-to-end example, see [Advanced Checkout Guide](/cookbook/advanced-checkout-guide) (~150 lines of Node). The sandbox accepts test cards (`4111111111111111`, etc.) — see [Sandbox setup](/for-destinations/sandbox-setup) for the full list. These cards only work against test merchants; real merchants reject them. ### What you build during sandbox | Capability | Why it matters | |---|---| | Auth bootstrap + token renewal | Browser session tokens expire after ~1 hour; your code needs to handle renewal cleanly | | Duplicate-safe retries | Guard mutations against duplicates: re-read the cart's `cart_status` before retrying a failed `complete-order`. `Idempotency-Key` is honored on the UCP bridge; core REST accepts it but doesn't deduplicate on it today (see [Errors & Conventions](/api-reference/errors-and-conventions#idempotency)) | | Error handling for 4xx/5xx | The 503/412 retry pattern is documented in [Errors & Conventions](/api-reference/errors-and-conventions) | | Multi-shipment cart flow | Carts with items from multiple shipping origins need shipping methods set per-shipment | | Payment flow appropriate to your surface | Card-encrypted, Google Pay, Klarna, PayPal Express, or Agentic Pay for autonomous agents | ## Phase 3 — Pre-launch review Once your sandbox integration is feature-complete, schedule a pre-launch review with Firmly. The review covers: - **Integration walkthrough** — how your code flows from user intent to placed order - **Error handling** — how you handle merchant declines, payment failures, network issues - **Idempotency** — are you guarding against duplicate mutations? Re-read `cart_status` before retrying `complete-order`/`place-order`. (`Idempotency-Key` is honored on the UCP bridge; core REST doesn't deduplicate on it today.) - **Rate-limit posture** — are you throttling appropriately for production traffic - **Observability** — what you'll log for debugging and reconciliation - **Production merchants** — which merchants you'll transact against in production This is not a hard gate — it is a structured review. If items need to be addressed, the destination addresses them and Firmly re-reviews the relevant parts. ## Phase 4 — Production App ID After the review, Firmly issues: 1. **A production App ID** — a separate UUID, distinct from your sandbox App ID 2. **Production merchant scope** — the live merchants your App ID is approved to transact against 3. **Base URLs** — production runs on different hosts from the sandbox. Firmly provides them at go-live, so treat the cutover as a configuration change, not just a new App ID. There's no separate "production SDK" or library swap. Same code, different App ID, real merchants. ## What changes between sandbox and production | | Sandbox | Production | |---|---|---| | App ID | Sandbox `_appId` | Production `_appId` | | Merchants | Test merchants (e.g., `staging.luma.gift`) | Real merchants you're approved for | | Cards accepted | Test cards (`4111...`) | Real cards, wallets, alternative payment methods | | Catalog | Sample data from test merchant | Real merchant catalog and inventory | | Orders | Test orders — no money moves | Real orders, real payment capture, real fulfillment | ## What Firmly does not provide - **No self-serve App ID provisioning** — every App ID is issued manually by Firmly, and scope changes go through Firmly; there's no form that generates or rescopes one yourself. App ID requests come through [Firmly](/contact). - **No SDK in 10 languages** — Firmly publishes endpoint contracts plus examples in cURL and TypeScript; integration happens at the destination's HTTP layer This is intentional. Destination integration is lightweight on Firmly's tooling side — the heavy lifting (merchant adapters, payment routing, order placement) runs on Firmly's servers, not in a client library. ## The Destination Dashboard Once Firmly provisions your App ID, it invites your team by email to the **Destination Dashboard** — the surface you sign into to run your integration day-to-day. It's a single shared surface across all five solution types (agentic, branded, publisher, ad, marketplace), keyed on your App ID. From the dashboard you track your conversion funnel, review orders, see the merchants you can reach, manage your team with role-based access, and read audit logs. App ID provisioning and merchant scope stay with Firmly — the dashboard is for operating and team management, not self-serve credential issuance. See [Destination Dashboard](/for-destinations/destination-dashboard) for the full reference. --- ## Related - [Advanced Checkout Guide](/cookbook/advanced-checkout-guide) — runnable end-to-end example - [Authentication](/for-destinations/authentication) — browser session vs server-to-server - [Sandbox setup](/for-destinations/sandbox-setup) — verify your sandbox is live - [Going live](/for-destinations/going-live) — pre-launch checklist + production cutover - [API Reference](/api-reference/) — full endpoint catalog --- # Sandbox Setup This page is the prerequisite for the [Advanced Checkout Guide](/cookbook/advanced-checkout-guide). It walks you through getting credentials, choosing a test merchant, and validating your environment with a curl call. ## What you need from Firmly Email [firmlydocs@firmly.ai](mailto:firmlydocs@firmly.ai) and ask for: 1. **A sandbox App ID** (`_appId`) — a UUID scoped to a non-production environment 2. **A test merchant domain** — typically something like `staging.luma.gift` 3. **Optional: a server-to-server secret** — if you plan to use S2S auth instead of browser sessions 4. **Optional: an Agentic Pay API token** — if you plan to enroll cards and pay with network tokens. See [Agentic Pay in the sandbox](#agentic-pay-in-the-sandbox) Firmly will provision these and confirm the test merchant has a non-empty catalog you can search and buy from. ## Endpoints | Surface | Host | |---|---| | General API (auth, discovery, cart, checkout, orders) | `https://api.firmly.work` | | Payment (public key, place-order) | `https://cc.firmly.work` | These are the **sandbox** base URLs. Production runs on **different hosts** from the sandbox. Firmly provides your production base URLs at go-live — plan for a configuration change, not just a new App ID. Going live changes your App ID, your merchants, and your base URLs. For the embedded / hosted checkout drop-in URL, [contact Firmly](/contact). ## Test cards Firmly accepts these public sandbox cards against test merchants: | Card number | Brand | What it tests | |---|---|---| | `4111111111111111` | Visa | Successful payment | | `4000000000000002` | Visa | Generic decline | | `4000000000009995` | Visa | Insufficient funds decline | | `4000000000000069` | Visa | Expired card decline | Use any future date (e.g. `12 / 2030`), any 3-digit CVV, and any cardholder name. **These cards only work against sandbox merchants** — real merchants reject them. > **Note** > These cards are for the **JWE card payment** path (Place Order / Complete Order). They are not enrollable with [Agentic Pay](/solutions/agentic-commerce/agentic-pay), which tokenizes the card at the network's own sandbox — see [Agentic Pay in the sandbox](#agentic-pay-in-the-sandbox) for what to use there. ## Verify your setup with curl Once you have your `_appId` and a test merchant domain, run these three calls. If all three succeed, you're ready to run the [Advanced Checkout Guide](/cookbook/advanced-checkout-guide). > **Tip** > Set your App ID once — `export FIRMLY_APP_ID=` — and use `$FIRMLY_APP_ID` in the commands below, or replace `YOUR_APP_ID` inline. The App ID is a UUID like `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx`. ### 1. Bootstrap a session ```bash curl -X POST https://api.firmly.work/api/v1/browser-session \ -H "x-firmly-app-id: YOUR_APP_ID" ``` `YOUR_APP_ID` is the UUID Firmly provisioned for you — it looks like `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx`, not a short slug. Substitute the exact value Firmly sent. Expected: a JSON response with `access_token`, `device_id`, `expires_in`. Save the `access_token` as `$TOKEN`. ### 2. Search the test merchant catalog Scope the search to your paired test merchant with `filters.domains` so you're verifying that specific merchant's catalog: ```bash curl -X POST https://api.firmly.work/api/v1/discovery/search \ -H "x-firmly-authorization: $TOKEN" \ -H "Content-Type: application/json" \ -d '{"query": "gift", "filters": {"domains": ["staging.luma.gift"]}, "page_size": 3}' ``` Expected: a JSON response with a `products` array. Each product carries a `domain` field — it should match the test merchant domain you queried (`staging.luma.gift` above). **Empty `products` array?** Ask [Firmly](/contact) to load sample products for your test merchant. ### 3. Get the payment public key ```bash curl "https://cc.firmly.work/api/v1/payment/key?format=JWK" ``` Expected: an RSA JWK with `kty`, `n`, `e`, and a `kid` (key ID). No auth needed for this endpoint. If all three return 200s with sensible bodies, your sandbox is live. ## Common setup errors | What you see | Why | Fix | |---|---|---| | `401` on browser-session | App ID isn't recognized in this environment | Confirm you're using the sandbox App ID, not production | | `404 ucp_disabled` on search | Merchant hasn't opted into the relevant surface | Ask Firmly to enable it for the test merchant | | `404 DomainNotFound` | Domain typo or wrong environment | Verify the exact domain string from [Firmly](/contact) | | Empty `products` array | Merchant has no products in catalog | Ask Firmly to load sample products into the test merchant | | Network failure on `cc.firmly.work` | Outbound HTTPS to payment domain is blocked | Add `cc.firmly.work` to your allowlist alongside `api.firmly.work` | | `400 InvalidAPIToken` on `/wallets/agentic-pay/*` | You sent the browser-session `access_token` (or a production token) instead of the Agentic Pay API token | Use the Agentic Pay API token Firmly issued for the sandbox in `x-firmly-authorization` | | `409 PaymentMethodNotAvailable` on `/enroll` | The card's network is not enabled for your destination, or the card is not a network sandbox test card | Ask Firmly to enable the network on your token; enroll only the network sandbox test cards Firmly provided | ## Agentic Pay in the sandbox [Agentic Pay](/solutions/agentic-commerce/agentic-pay) — enrolling a cardholder's card and paying with a network token — runs on the sandbox hosts listed above (`api.firmly.work` for enrollment and intent, `cc.firmly.work` for order placement) against the test merchant. It needs one more credential and different test cards. ### What you need 1. **An Agentic Pay API token** — sent as `x-firmly-authorization` on the `/api/v1/wallets/agentic-pay/*` endpoints. This is an app-level token, **not** the browser-session `access_token`. Request it from [firmlydocs@firmly.ai](mailto:firmlydocs@firmly.ai) together with your sandbox App ID, and say which card networks you want enabled (Visa, Mastercard, Discover). Networks are enabled per destination; a card on a network that is not enabled returns `409 PaymentMethodNotAvailable`. 2. **Network sandbox test cards** — enrollment tokenizes the card at the card network's **sandbox**, so the generic test cards above are not enrollable there. Firmly provides network sandbox test cards for each enabled network along with your token. 3. **Your sandbox App ID and a device session** — still required. Order placement (`/wallet-complete-order`) is authenticated with the device session token from [Browser Session](/api-reference/authentication/browser-session), exactly as for card payments. ### Verify your token with curl Enrolling a card is the quickest proof that the token is valid and the network is enabled. Use a network sandbox test card Firmly provided: ```bash curl -s -X POST https://api.firmly.work/api/v1/wallets/agentic-pay/enroll \ -H "x-firmly-authorization: $AGENTIC_PAY_TOKEN" \ -H "Content-Type: application/json" \ -d '{"pan": "", "expiry_month": "12", "expiry_year": "2030", "cvv": "123", "consumer": {"email": "cardholder@example.com", "country_code": "US"}}' ``` Expected: `200` with a `flow_token`, a `virtual_card_id`, and `verification_methods` (empty for Discover). A `400 InvalidAPIToken` means the token is wrong for this environment; a `409 PaymentMethodNotAvailable` means the network is not enabled for your destination or the card is not a sandbox test card. ### Browser pieces in the sandbox Visa and Mastercard verification runs in a network-hosted iframe in the cardholder's browser. In the sandbox those iframes are served from the networks' sandbox hosts, and the result comes back through Firmly's [Iframe Callback](/api-reference/agentic-pay/iframe-callback) bridge on `api.firmly.work`. If you use the [Headless SDK](/api-reference/headless-sdk/), configure it for the sandbox as: - `baseUrl` — `https://api.firmly.work` - `iframeOrigins` — the Firmly bridge origin plus the network sandbox iframe origins. These are the values Firmly's wallet service ships for the sandbox and injects into the hosted SDK bundle (`GET https://api.firmly.work/api/v1/wallets/sdk/js?appId=`, as `window.__FIRMLY_AGENTIC_PAY_CONFIG__.iframeOrigins`); load that bundle, or copy its values, rather than hard-coding hosts — currently `https://api.firmly.work`, `https://sandbox.src.mastercard.com`, `https://sbx.vts.auth.visa.com` - `bridgeUrl` — `https://api.firmly.work/api/v1/wallets/agentic-pay/iframe-callback` - `vaultBaseUrl` — `https://cc.firmly.work` - `merchantDomain` — `staging.luma.gift` Discover has no iframe step, so a Discover enrollment and intent can be exercised entirely with curl. ### Run the full flow The [Agentic Pay Integration](/solutions/agentic-commerce/agentic-pay-integration) guide walks the complete chain — enroll → verify → intent → order — against this sandbox and the test merchant. Create the cart first (session → add line item → set shipping) exactly as in the [Advanced Checkout Guide](/cookbook/advanced-checkout-guide); the Agentic Pay steps replace only the JWE card payment. ## Going from sandbox to production When you're ready to go live: 1. Request a production App ID from [Firmly](/contact) 2. Confirm the live merchants you'll transact against — a production App ID is typically scoped to a specific set of merchants 3. Stop using the test cards above; production requires real cards or wallet-based payments 4. If you use Agentic Pay, request a production Agentic Pay API token and switch the SDK `iframeOrigins` to the networks' production hosts, which Firmly provides at go-live Going live is a configuration change for your application, plus the Firmly-side onboarding of any production merchants. There's no separate "production SDK" to install. ## Next steps - [Advanced Checkout Guide](/cookbook/advanced-checkout-guide) — run the full purchase flow - [Authentication](/for-destinations/authentication) — auth model in depth - [Cart lifecycle](/api-reference/cart-management/cart-lifecycle) — cart states and what's allowed when --- # Try the Sandbox Experiment with the Firmly API against a sandbox — a **test merchant** and **test cards**, no real money. To make live calls you first need a **sandbox App ID**, which Firmly issues on request: email **[firmlydocs@firmly.ai](mailto:firmlydocs@firmly.ai)** and we'll send you one for evaluating the API. Once you have it, the calls below run end to end. > **Note** > This is a **sandbox-only** environment — scoped to test merchants and test cards, never real orders or real money. Your sandbox App ID is **issued by Firmly on request** (email **firmlydocs@firmly.ai**). For a production-scoped App ID, see [Onboarding](/for-destinations/onboarding). ## What you get | | | |---|---| | **Sandbox App ID** | Issued on request — email **firmlydocs@firmly.ai** | | **Test merchant** | `staging.luma.gift` (sample catalog) | | **Test card** | `4111111111111111`, exp `12 / 2030`, CVV `123` | | **Hosts** | `https://api.firmly.work` (general API), `https://cc.firmly.work` (payment) | ## Run your first calls (curl) > **Tip** > Every call below includes a browser-style `User-Agent` header on purpose. Some clients send a default User-Agent (for example Python's `urllib`, or an unlabeled agent) that the sandbox's bot-protection blocks with a `403`. curl, browsers, and mainstream SDKs usually pass as-is — the header is included here so every client works. **1. Export the sandbox App ID Firmly sent you**, then bootstrap a session — it returns an `access_token`: ```bash export FIRMLY_APP_ID= curl -s -X POST https://api.firmly.work/api/v1/browser-session \ -H "x-firmly-app-id: $FIRMLY_APP_ID" \ -H "User-Agent: Mozilla/5.0 (compatible)" ``` Capture that `access_token` in a shell variable in one line (with [`jq`](https://jqlang.github.io/jq/)): ```bash TOKEN=$(curl -s -X POST https://api.firmly.work/api/v1/browser-session \ -H "x-firmly-app-id: $FIRMLY_APP_ID" \ -H "User-Agent: Mozilla/5.0 (compatible)" | jq -r '.access_token') ``` No `jq`? Copy the `access_token` value out of the response above by hand, then run `export TOKEN=`. **2. Search the test merchant's catalog:** ```bash curl -s -X POST https://api.firmly.work/api/v1/discovery/search \ -H "x-firmly-authorization: $TOKEN" -H "Content-Type: application/json" \ -H "User-Agent: Mozilla/5.0 (compatible)" \ -d '{"query":"bag","filters":{"domains":["staging.luma.gift"]},"page_size":5}' ``` **3. Add an item to the cart** — `24-MB05` is a sample `variant_id` from the step-2 search response; swap in any `variant_id` from your own results: ```bash curl -s -X POST https://api.firmly.work/api/v1/domains/staging.luma.gift/cart/line-items \ -H "x-firmly-authorization: $TOKEN" -H "Content-Type: application/json" \ -H "User-Agent: Mozilla/5.0 (compatible)" \ -d '{"add_to_cart_ref":{"variant_id":"24-MB05"},"quantity":1}' ``` From here you set a shipping address and method, encrypt the test card as a **JWE** (a JSON Web Encryption token — the card is encrypted inside your own process before it is sent), and place the order. That payment + order step needs a little code — the [Standard Checkout Guide](/cookbook/standard-checkout-guide) is a complete, runnable Node script that carries this same flow (session → cart → payment → placed order) end-to-end against this sandbox. Need split shipments, add-ons, or delivery scheduling? The [Advanced Checkout Guide](/cookbook/advanced-checkout-guide) does it on the richer `/api/v2` cart. ## Next - [Standard Checkout Guide](/cookbook/standard-checkout-guide) — finish this flow end-to-end (session → cart → payment → placed order) in ~90 lines of Node against this sandbox. Right for most integrations. - [Advanced Checkout Guide](/cookbook/advanced-checkout-guide) — the same flow on the richer `/api/v2` cart: split shipments, add-ons, delivery scheduling - [API Reference](/api-reference/) — every endpoint, with a live [API Explorer](/api-explorer/) - [Onboarding](/for-destinations/onboarding) — request your own scoped App ID for a real integration - [Agentic Pay in the sandbox](/for-destinations/sandbox-setup#agentic-pay-in-the-sandbox) — enroll a card and pay with a network token instead of a JWE card; needs an Agentic Pay API token and network sandbox test cards --- # Catalog & Pricing This page covers how your product catalog and pricing surface across Firmly-connected destinations. The headline: **destinations see your products, your prices, and your rules — accurately**. ## Two-layer model: catalog index + real-time validation Firmly maintains a **catalog index** updated periodically from your platform, plus **real-time validation** at the merchant at key transactional moments. The two layers serve different purposes: | Layer | What it does | Refresh cadence | |---|---|---| | **Catalog index** | Powers fast discovery and search across destinations | Per-merchant; typically every few hours | | **Real-time validation** | Confirms price and stock at the merchant at order-placement time | Every transaction, against your platform's live API | This means destinations can search quickly (against the index) but orders never land on stale price or out-of-stock SKUs (because of real-time validation). ## What lives in the catalog index Firmly's catalog index stores the structured product data needed for discovery. The exact fields per platform vary, but typically include: | Field | Source | |---|---| | Product ID | Your platform's stable identifier | | Variant ID | Per-variant SKU identifier | | Title | Your product title | | Description | Your product description (HTML or plain text per platform convention) | | Images | URLs to your product images (typically your CDN) | | Price | Current price including any active discounts | | Currency | Your store's currency | | Inventory level | Stock indicator (in-stock / out-of-stock or quantity, per your platform) | | Variant attributes | Size, color, etc. per your platform's convention | | Category | Your taxonomy classification | | Custom attributes | Platform-specific fields you flag in the scoping conversation with Firmly's team during onboarding (not a self-serve wizard field) | ## What Firmly does NOT ingest Firmly indexes only what's needed to discover and transact. It never ingests: - Your existing customer database - Your historical order data - Internal admin notes on products (private fields, vendor notes, admin-only metadata) - Pricing intelligence data (cost basis, margin, MSRP comparisons) ## Real-time price and stock validation At critical transaction moments, Firmly re-validates against your platform's live API: | Moment | What's re-validated | |---|---| | Product detail view | Current price (in case the index is stale) | | Add to cart | Variant availability | | Cart re-read | Cart-wide price re-check | | Place order | **Hard validation** — price, stock, eligibility — against your live merchant API | If validation fails at `place-order`, the order doesn't go through — the destination receives an error (e.g., `NotEnoughStockError`) and surfaces it to the user. Your platform never sees an order it can't fulfill. ## Pricing nuances ### Sale price vs regular price Firmly's index stores the **price you display** — typically the sale price if a sale is active. The pre-sale "regular price" is exposed per your platform's convention (the exact field name varies by platform) so destinations can show strikethrough pricing if they want. ### Regional / multi-currency pricing If your store offers different prices per region or currency, Firmly's index respects that. Destinations request a price for a specific market context, and Firmly returns the matching price. ### Member / loyalty pricing If your platform supports member pricing (logged-in customer sees a lower price), Firmly-originated orders default to the public price. Exposing member pricing to a destination is a per-destination contractual decision, and it depends on a mechanism for carrying a member identity through to your platform at price-fetch time. (Note: Firmly Connect SSO is merchant-team portal login, not shopper identity — it does not carry a shopper's membership through to your store. Discuss the member-identity mechanism with Firmly during onboarding.) ### Currency conversion Firmly doesn't convert currencies. If your store sells in USD, destinations transact in USD against your store. Multi-currency support comes from your platform's native multi-currency features. ## Promo codes and promotions Firmly's [Promotions API](/api-reference/promotions/) lets destinations apply promo codes during cart-building. The codes themselves come from **your platform's discount engine** — Firmly is the relay, not the issuer. The flow is simple: a destination calls `add-promo-codes` with a code (e.g. `SAVE10`); Firmly forwards it to your platform; your platform validates it against its own rules (stacking, expiry, minimum-cart, category exclusions, customer eligibility) and decides whether the discount applies; and the cart sub-total updates in the response. If a code doesn't apply, the destination's agent reads `cart.notices` for codes like `PROMO_EXPIRED`, `PROMO_NOT_APPLICABLE` — surfaced from your platform's discount engine. ### Promo-code stacking Whether promo codes stack is your platform's decision and your business rules. Firmly does not enforce or override stacking rules — it forwards each code application to your platform and lets the platform respond. ### Anti-abuse rate limits Firmly's edge applies aggressive rate limits to the `/promo-codes` endpoint to prevent code-stuffing — see [Rate limits](/api-reference/rate-limits). Because destinations are rate-limited when trying codes, your discount engine won't be hammered by code-guessing traffic. ## Excluded products You can exclude specific products from Firmly's catalog index — they won't appear in discovery, can't be added to carts, won't be reachable from any destination. Common exclusions: - Gift cards (some merchants exclude; others include explicitly) - Restricted items (alcohol, tobacco, regulated goods in regions where rules vary) - Region-exclusive products - Bundle SKUs that don't make sense outside your storefront - Test or internal-only products Exclusions aren't a self-serve wizard field — you set them up in the catalog-scoping conversation with Firmly's team during onboarding (the same conversation that scopes the Selected Products subset), and they can be updated later per request. ## Inventory and stock signals Firmly's index reflects stock state per your platform's convention: - **Boolean (in stock / out of stock)** — the simplest signal: no quantity is exposed, only whether the item is available - **Quantity level** — if your platform exposes count, Firmly stores it - **Threshold-based** — some merchants treat anything below N as out of stock for protection If a destination requests an out-of-stock product, discovery still returns the product (so the user can see it exists) but the variant is flagged as unavailable. The destination's agent surfaces this to the user. ## Image hosting Product images are served from **your CDN** in nearly all cases. Firmly's catalog stores the image URLs, and destinations link directly to your images. This means: - Your CDN handles the bandwidth and caching - Image latency depends on your CDN's performance, not Firmly's - You can swap images in your platform; destinations pick up the new URLs on the next catalog sync Firmly never caches or mirrors your images — it stores only the image URL. If you have specific image-hosting needs (e.g., signed URLs, geo-restricted CDN), discuss during onboarding. ## Multi-variant products Products with variants (sizes, colors, options) flow through the catalog as you've structured them on your platform. Each variant has its own ID, price, and inventory. Destinations browse the product, see variants, and add a specific variant to the cart. For variant-heavy verticals (apparel, beauty, supplements) see [Use Cases → Vertical Specialist](/solutions/agentic-commerce/use-cases/vertical-specialist). --- ## Related - [Onboarding](/for-merchants/onboarding) — catalog questions in the onboarding checklist - [Credentials & API Access](/for-merchants/credentials-and-api-access) — what catalog-read scope Firmly needs - [Cart Lifecycle](/api-reference/cart-management/cart-lifecycle) — the destination-side view of the cart state machine --- # Credentials & API Access For most merchants on industry-standard commerce platforms, **you don't provide API credentials yourself**. Firmly's pre-built platform adapter connects to your store the same way your own website's front end does — through the standard public storefront APIs the platform already exposes. The "Complete integration" task in the Onboarding Wizard is Firmly-driven and automated. For headless, composable, or custom platforms, there's a short credential handoff conversation with Firmly's onboarding team — covered in detail below. This page covers the cases where merchant input matters. > **Note** > **Most merchants provide only a store URL — no API keys.** The credential handoff below applies to headless, composable, or custom platforms only. ## What you provide, by platform category | Platform category | What you actually provide | |---|---| | **Industry-standard cloud commerce platforms** | Just the store URL. Firmly's adapter handles the rest | | **Headless or heavily customized deployments** | Storefront API key + deployment-specific details — [Firmly](/contact) confirms during onboarding | | **Composable / API-first platforms** | Project key + minimum scope details may be requested if Firmly's discovery can't determine them | | **Custom or in-house platforms** | [Firmly](/contact) walks you through what's needed — typically endpoint URLs, authentication shape, and example responses | For most merchants on industry-standard commerce platforms, the conversation about credentials is short. You provide the store URL during signup, and Firmly's adapter does the rest. ## What Firmly's adapter does behind the scenes For pre-built platform adapters, the adapter connects to your store through the same public storefront APIs your own website's front end calls — the standard read and cart patterns the platform exposes natively. The same patterns power discovery, cart, checkout, payment, and order placement. You don't issue Firmly an admin token, an app key, or a long-lived secret. The adapter does what any well-behaved client of your platform's standard API would do. ## When merchant input matters There are real cases where Firmly will ask for something: | Case | What Firmly asks for | |---|---| | **Custom platform** | Endpoint URLs, authentication scheme, example responses — [Firmly](/contact) walks you through the spec | | **Headless / heavily customized enterprise deployment** | Storefront API key + deployment-specific details | | **OAuth-only access on certain platform scopes** | A one-time OAuth consent through your platform's standard consent screen — you authorize Firmly's adapter | | **Custom CDN whitelist value** | The `x-ac-auth` header value that your CDN rule uses — see [CDN whitelisting](/solutions/firmly-connect/onboarding/cdn-whitelisting) | For all of these, [Firmly](/contact) will walk you through the specifics. There's no generic API-key handoff form because it varies by platform. > **Note** > When header-based CDN whitelisting applies, the shared secret has to be given back to Firmly so Firmly's outbound requests include it. The channel for that hand-off is confirmed with Firmly during go-live — see [CDN whitelisting](/solutions/firmly-connect/onboarding/cdn-whitelisting) for how the value is generated and used. ## What if my platform requires OAuth instead of long-lived tokens OAuth is fine — Firmly's platform adapter handles the OAuth flow, including refresh-token rotation. You authorize Firmly's adapter through your platform's standard OAuth consent screen. If your platform requires OAuth (some platform-specific scopes or enterprise deployments), [Firmly](/contact) will walk you through the authorization step during onboarding. ## Custom adapter merchants If you're on a fully custom commerce stack, Firmly may provision a **custom adapter** — JavaScript code that Firmly executes against your backend when none of the pre-built platform adapters fit. You'll see a **Custom Adapter Editor** in the **Merchant Portal** (Firmly Connect), where you can review, edit, test, and publish the adapter without leaving the portal. Firmly's solutions team typically pairs with you on the first version before a publish. This is power-user surface — most merchants never need it. ## What gets stored where | Data | Where it lives | |---|---| | Your store URL | Firmly's tenant record | | Your platform credentials (when you do provide any) | Stored encrypted in Firmly's secrets store; accessed only by the platform adapter that needs them | | Your customer database (existing customers) | Stays in your platform — Firmly doesn't ingest it | | Order data on Firmly-originated orders | Both in your platform (primary) and in Firmly's records (for reconciliation) | | Card data | JWE-encrypted, transits through Firmly's vault to your PSP — Firmly never stores cleartext PAN | --- ## Related - [Onboarding walkthrough](/for-merchants/onboarding) — the wizard flow - [Going Live](/for-merchants/going-live) — Firmly's go-live approval step - [Supported platforms](/for-merchants/supported-platforms) — platform-specific notes --- # For Merchants If you're a merchant — selling on any industry-standard commerce platform or a custom platform — Firmly connects your catalog and checkout to where your customers discover: AI agents, publishers, marketplaces, banks, and wallets. One connection on [Firmly Connect](/solutions/firmly-connect/), and your products are reachable across every Firmly-powered destination. - [Sign up at Firmly Connect](https://merchant.firmly.ai) — Create your merchant account at merchant.firmly.ai and start the onboarding wizard. ## How merchant onboarding works > **Tip** > **Most stores onboard without writing code** — through forms and toggles. Some setups need light technical help (a firewall/CDN allow-rule, or read access to your catalog), and custom or headless stacks may need a build. Merchants onboard through a guided wizard at [merchant.firmly.ai](https://merchant.firmly.ai) (Firmly Connect). The wizard has two Firmly-reviewed gates (KYB approval, Go-live approval); everything else is self-serve. Firmly handles the platform integration on its side. Merchants go live through onboarding itself — there's no separate sandbox to set up and no App ID to manage. (App IDs are the destination side: AI agents, publishers, and other surfaces get a try-it path with one; merchants don't need it.) After go-live, the **Merchant Portal** in Firmly Connect is your day-to-day home — orders, catalog scope, destination opt-ins, team, and audit logs. See [Firmly Connect](/solutions/firmly-connect/) for the full Merchant Portal reference. ## The 7-step wizard | # | Task | Who does it | What it is | |---|---|---|---| | 1 | Complete integration | **Firmly** | Firmly's integration systems connect to your commerce backend — automated; you have no "Start" button | | 2 | Know Your Business (KYB) | **You** | Fill out company info, brand identity, terms & privacy — submitted for Firmly review | | 3 | Configure product catalog | **You** | Pick Entire Catalog (recommended) or a curated subset | | 4 | Configure destinations | **You** | Opt into specific channels on Firmly's network | | 5 | Sign merchant agreement | **You** | Review and sign the participation agreement | | 6 | Complete CDN whitelisting | **You** | Whitelist Firmly's traffic at your CDN — *most merchants don't need it* | | 7 | Go-live approval | **Firmly** | Firmly reviews your configuration and approves you to go live | KYB approval gates everything else. Most steps are simple forms, radio buttons, and toggles (the agreement is a form plus a click-through signature), so onboarding is **largely** self-serve — a few things are settled in a short conversation with Firmly's team rather than in the wizard: [catalog scoping and exclusions](/for-merchants/catalog-and-pricing), and, for headless/composable/custom platforms, the [credential handover](/for-merchants/supported-platforms). CDN whitelisting is the main optionally-technical step and most merchants don't need it — it applies only when your CDN/WAF actively blocks Firmly's traffic. Review turnaround for the two Firmly-reviewed gates (KYB and Go-live) is communicated during onboarding and confirmed during KYB — Firmly gives you the expected timeline so you know when to expect a decision. ## What you get - **Reach new surfaces** — Your products available wherever your customers are inspired to buy — AI assistants, search engines, wallets, brand-loyalty apps, publishers — without rebuilding for each surface. - **Keep your checkout** — Firmly routes traffic and order intent into your existing storefront — the checkout your customers complete is still yours. - **No replatforming** — Firmly adapts to a wide range of industry-standard commerce platforms and custom platforms — without code changes on your side. - **Real-time inventory** — Pricing, stock, and availability are read live from your store, and stock is re-checked before an order is placed — so oversells are rare rather than routine. - **Native order flow** — Orders appear in your platform's native admin / order management system with full line items, addresses, and payment captured. - **Affiliate attribution** — Each order is tagged with its originating destination so commissions and origination credit flow correctly without manual reconciliation. ## Checkout capabilities **Most stores are Standard** — the simple checkout works on every connected platform, no extra setup. You need **Advanced** only if you sell items that split into multiple shipments (furniture, appliances, multi-warehouse) or need delivery scheduling, add-ons, or ZIP-coverage gating — and only if your platform supports it. Not sure? Assume Standard — see [which is my store?](/for-merchants/supported-platforms#standard-vs-advanced) or ask Firmly during onboarding. ## Read next - [Quickstart](/for-merchants/quickstart) — Sign up at Firmly Connect and walk through the wizard - [Onboarding walkthrough](/for-merchants/onboarding) — The 7 wizard tasks in detail - [Credentials & API Access](/for-merchants/credentials-and-api-access) — What Firmly needs to connect to your platform — and what you don't have to provide - [Catalog & Pricing](/for-merchants/catalog-and-pricing) — How your catalog and pricing flow through Firmly - [Going Live](/for-merchants/going-live) — Firmly's go-live approval step — what they review and how to satisfy it - [Supported Platforms](/for-merchants/supported-platforms) — What platforms are connected today and how each is handled ## Where Firmly does and doesn't touch your stack | Layer | Firmly involvement | |---|---| | Your catalog (SKUs, prices, images) | Read by Firmly via your platform's standard API | | Your storefront pages | Untouched — Firmly doesn't render anything on your own storefront | | Your cart and checkout | Firmly drives this for orders coming from connected destinations; your own storefront cart and checkout are untouched | | Your order management system | Orders arrive here exactly as native customer orders | | Your payment processor | Firmly routes payment to your existing PSP, in your existing accounts | | Your analytics and reporting | Untouched — orders show up in your normal reports | | Everything after order placement | Untouched — your existing workflows continue exactly as before | **You stay the seller of record.** Firmly never becomes the seller — orders placed through connected destinations land in your own order management system, under your own merchant and payment accounts, exactly as native customer orders. **Security and data handling.** Firmly's data-flow, data-handling, and compliance details are available under NDA on request — [contact Firmly](/contact) to review them with your security team. ## What about API credentials For most industry-standard commerce platforms, **you don't provide API credentials yourself**. Firmly connects via standard discovery patterns against your store. The "Complete integration" step in the wizard is Firmly-driven and automated. For custom platforms, [Firmly](/contact) will walk you through any specific connection your stack requires — see [Credentials & API Access](/for-merchants/credentials-and-api-access) for the full list of cases where merchant input matters. --- ## Related - [Firmly Connect](/solutions/firmly-connect/) — the **Merchant Portal** product (canonical reference) - [How Firmly Works](/how-firmly-works) — the underlying platform - [Destinations](/solutions/destination-surfaces/) — which surfaces use Firmly - [Solutions overview](/solutions/) — all Firmly solutions - [Allow listing](/for-merchants/allow-listing/index.md) - [Configure payment provider](/for-merchants/configure-payment-provider/index.md) --- # Going Live Going live is the **final wizard step** and is Firmly-driven, not merchant-driven. Once you've completed your tasks (KYB, catalog, destinations, agreement, optional CDN) and Firmly has finished the integration on its side, you submit for go-live and Firmly's review team approves or rejects. Throughout, **you remain the seller of record** — Firmly never becomes the seller; once you're live, approved orders land in your own systems under your own merchant and payment accounts. Going live doesn't move, redeploy, or re-credential anything. The same Firmly platform serves your store before and after — going live just switches your tenant from "onboarding" to "live." > **Warning** > You're not live until you press **Submit for Go-Live** and Firmly's review team approves it. Until that approval, no destination traffic flows to your store. ## What "going live" actually means | Before go-live | After go-live | |---|---| | Your tenant is in onboarding state | Your tenant is in live state | | The Merchant Portal shows the onboarding wizard | The Merchant Portal shows the live operations dashboard | | Destinations you've opted into are configured but not yet receiving live traffic | Destinations route real customer traffic to your store via Firmly | | Orders aren't flowing into your OMS via Firmly | Orders flow into your OMS as native customer orders | ## How the go-live wizard step works | Stage | What happens | |---|---| | **You submit** | After completing all merchant-actioned tasks, you press the "Submit for Go-Live" call to action on the wizard. The task transitions to `Awaiting approval`. Firmly is notified | | **Firmly reviews** | The review team verifies your KYB, catalog scope, destination opt-ins, agreement, and any required CDN configuration. They also confirm the platform integration is healthy. The expected review turnaround is communicated during onboarding, so you can tell a normal wait at `Awaiting approval` from a stalled one | | **Outcome — Approved** | Your tenant flips to live. The Merchant Portal switches from the wizard to the live operations dashboard. Orders from connected destinations start flowing into your OMS | | **Outcome — Rejected** | The rejection notes are surfaced inline against the go-live task. You see exactly what to fix, address it, and resubmit | ## What Firmly typically reviews - **KYB completeness** — company info filled in, accurate, and approved - **Catalog scope** — your catalog selection is reasonable for the destinations you've opted into - **Destination opt-ins** — each destination is enabled with the right merchant settings (some destinations have additional per-destination requirements) - **Agreement signed** — for the current agreement version - **CDN configuration** — if needed for your edge setup, the whitelist rule is in place - **Integration health** — Firmly can read your catalog, place test orders, and receive order responses from your backend. These test orders are placed against your store to verify the end-to-end flow; Firmly coordinates them as part of review (e.g., using test payment data and canceling or flagging them so you're not left with real fulfillment obligations) — confirm the specifics with your Firmly contact if your platform needs special handling ## What you should validate before submitting You're not required to do these, but they make for a smoother go-live: - **Confirm the catalog list shows your products** — the read-only Products view under Catalog should reflect what you expect - **Confirm the destinations you've enabled** — opt-ins are accurate; nothing toggled by accident - **Confirm the agreement signer** — your KYB/agreement signer is someone with signing authority - **CDN rule (if applicable)** — header value is in place; check the audit log for the "cdn_whitelisting_completed" event. If your CDN uses a header-based rule, the shared secret must also be given back to Firmly so Firmly's outbound requests carry it — the channel for that hand-off is confirmed with Firmly at go-live (see [CDN whitelisting](/solutions/firmly-connect/onboarding/cdn-whitelisting)) ## What happens after go-live | Day 1 | First week | Ongoing | |---|---|---| | Orders start arriving in your OMS from any connected destination that's already routing live traffic | First Merchant Portal dashboard data populates; KPI cards show period-over-period change | Continuous traffic from every destination as they're added to Firmly's network or as you opt into new ones | You don't have to do anything to "go live" beyond the wizard step. Your platform integration was already established during onboarding. The flag changes; the data flows. ## Common rejection causes (and what to do) | Cause | Fix | |---|---| | KYB rejected | Reviewer notes show what's missing or inaccurate — address them and resubmit KYB | | Destinations require extra per-destination setup | Some destinations (e.g., specific marketplaces) have additional merchant settings — Firmly's review will list what's needed | | CDN whitelisting required but not completed | Complete the CDN step before resubmitting | | Catalog scope misaligned with destination opt-ins | Some destinations expect entire-catalog merchants — narrow your subset or pick Entire Catalog | | Integration health check failed | Firmly's review team or your Firmly account manager will reach out with specifics — usually a platform-side rate limit or auth issue | ## Once you're live The wizard chrome disappears. The Merchant Portal flips from the wizard to the live operations dashboard — see [Merchant Portal](/solutions/firmly-connect/portal/). You can revisit any onboarding task surface as a settings page to adjust catalog scope, opt into new destinations, re-sign new agreement versions, or update CDN rules. --- ## Related - [Onboarding walkthrough](/for-merchants/onboarding) — the wizard steps before go-live - [Firmly Connect → Onboarding wizard](/solutions/firmly-connect/onboarding/) — canonical wizard reference - [Portal](/solutions/firmly-connect/portal/) — what you do once you're live --- # Merchant Quickstart The merchant onboarding flow is a **guided wizard** at `merchant.firmly.ai` — Firmly handles integration on its side; you handle forms and toggles on yours. The wizard has two Firmly-reviewed gates (KYB approval, Go-live approval); the rest is largely self-serve. There's no separate sandbox or trial mode — onboarding IS the path to live. Before real customers transact, Firmly places test orders against your store as part of its go-live review, so your store is verified end-to-end before launch (see [Going Live](/for-merchants/going-live)). ## The path ### Sign up at merchant.firmly.ai Open [merchant.firmly.ai](https://merchant.firmly.ai) and click **Start Onboarding** on the welcome page. The signup form collects: - **Store URL** - **Work email** (must match the store URL domain) - **Full name, job title, company name, location** - Optional phone number Submitting creates both your merchant tenant and your primary-owner user in one round trip. ### Verify your work email A 6-digit code is sent to the work email you submitted. Type the code on the next step. You're now signed in. ### You land in the onboarding task menu Your first stop after signup is the 7-task wizard menu. Two tasks are Firmly-driven (you have no "Start" button); five are yours to complete. Submit them in order — KYB gates everything else. You can start KYB right away; Firmly's integration task (Task 1) runs in parallel in the background. ### Complete Know Your Business (KYB) Fill in Company Info (Company Name, Online Revenue band — both required) and submit for review. Firmly reviews and either approves or rejects with notes. See [KYB](/solutions/firmly-connect/onboarding/know-your-business). ### Configure catalog, destinations, agreement Once KYB is approved, the next three tasks unlock: - **[Catalog configuration](/solutions/firmly-connect/onboarding/catalog-configuration)** — pick Entire Catalog (recommended) or a curated subset - **[Destinations configuration](/solutions/firmly-connect/onboarding/destinations-configuration)** — toggle on the destinations you want to sell through - **[Agreement signing](/solutions/firmly-connect/onboarding/agreement-signing)** — review and sign Firmly's merchant agreement Each is a single form or toggle page; saving advances the wizard. ### (If needed) Complete CDN whitelisting You don't need to diagnose this yourself. Firmly determines whether CDN whitelisting applies during integration. The task appears in your wizard only if you must complete it. Use Web Bot Auth or a merchant-specific header rule when possible. Use IP allowlisting only as a fallback. **Most merchants don't need this step** — CDN whitelisting applies only when your CDN/WAF actively blocks Firmly's traffic. See [CDN whitelisting](/solutions/firmly-connect/onboarding/cdn-whitelisting). ### Submit for Go-Live approval Once your tasks are done and Firmly has finished its side of the integration, **you press "Submit for Go-Live"**. Your tenant moves to `Awaiting approval`, and Firmly's review team then approves (you're live) or rejects with notes. The submission is yours; the review is Firmly's. ## Prerequisites - Store URL (the public storefront URL Firmly connects to; you do not hand over admin credentials) - Privacy policy and terms-of-use URLs - Brand assets — logo, primary brand color - Knowledge of any custom checkout rules or scope restrictions - The geographies you ship to (asked about during the onboarding conversation with Firmly, alongside the wizard, rather than as a wizard step) ## What you do NOT need - API credentials *(for industry-standard platforms; headless / composable / custom platforms have a short credential handoff conversation alongside the wizard)* - Frontend code changes (for most stores) - Customer PII - An App ID (App IDs are for destinations calling Firmly's API, not for merchants) ## What's next After signup, the Merchant Portal flips between **two states**: | Until you're live | After you're live | |---|---| | Shows the onboarding task menu | Shows the dashboard with KPIs, orders breakdowns, recent orders | See [Merchant Portal](/solutions/firmly-connect/portal/) for what comes after go-live. --- ## Related - [Firmly Connect overview](/solutions/firmly-connect/) — the merchant portal product - [Onboarding wizard](/solutions/firmly-connect/onboarding/) — the 7-step walkthrough - [Supported platforms](/for-merchants/supported-platforms) — confirm yours is covered --- # Onboarding walkthrough Merchant onboarding is a 7-step wizard inside Firmly Connect, in the same order for every merchant (the CDN whitelisting task is conditional — it's shown only when it applies; see Task 6). This page walks through the journey from sign-up to go-live: the task table shows who does each step, and the sections that follow cover each one in detail. For the canonical Firmly Connect documentation see [Onboarding wizard](/solutions/firmly-connect/onboarding/). ## Sign up and verify your email Onboarding begins at [`merchant.firmly.ai`](https://merchant.firmly.ai). Enter your store URL and a work email on the same domain, add a few contact details, and continue. Firmly emails a verification code to confirm the address; entering it creates your account and drops you into the task wizard. ![The Firmly Connect sign-up form — store URL, work email, name, job title, company, location, and optional phone, with a Continue button and a note that the work-email domain must match the store domain](/images/for-merchants/onboarding-signup.svg) > **Note** > Your **work email domain must match your store's website domain** — it's the first ownership check. `you@yourstore.example` signing up for `yourstore.example` works; a mailbox on an unrelated domain won't. ## The 7 tasks at a glance ![Merchant onboarding 7-step wizard — Integration and Go-live are Firmly-driven; KYB, Catalog, Destinations, Agreement, and CDN are merchant-actioned; KYB and Go-live are Firmly approval gates; CDN is most skipped; the flow ends at live on the network](/images/for-merchants/onboarding-flow.svg) | # | Task | Who does it | Type | |---|---|---|---| | 1 | Complete integration | Firmly | Automated | | 2 | Know Your Business (KYB) | Merchant | Form submission for Firmly review | | 3 | Configure product catalog | Merchant | Radio button | | 4 | Configure destinations | Merchant | Toggles | | 5 | Sign merchant agreement | Merchant | Form + click-through signature | | 6 | Complete CDN whitelisting | Merchant | CDN dashboard configuration (most merchants don't need it) | | 7 | Go-live approval | Firmly | Firmly review and approve | > **Note** > **KYB approval gates the rest.** Tasks 3–6 unlock only after KYB is approved, and Go-live (Task 7) needs both KYB approval and integration completion. Tasks 1 (integration) and 2 (KYB) run in parallel — you can submit KYB without waiting for integration to finish. ## What the wizard looks like ![The Firmly Connect onboarding task menu — a five-stage progress rail across the top, a seven-task checklist with per-task status, and a background integration-progress panel showing six sub-steps](/images/for-merchants/onboarding-wizard.svg) The task menu is your home base until you go live: a progress rail across the top for the five stages you action (the five merchant-actioned tasks; the two Firmly-driven ones don't appear on the rail), the full seven-task checklist with each task's status, and — while Firmly connects to your store — an **Integration progress** panel tracking the background work. ## Task 1 — Complete integration (Firmly-driven) Firmly's integration systems connect to your commerce backend automatically. This task appears in the wizard list for visibility, but there's no "Start" button for you to click. Firmly handles the platform integration on its side based on the store URL you provided at signup. For most industry-standard platforms this connects through the same public storefront APIs your own website's front end already calls — you don't hand Firmly an admin token, app key, or long-lived secret (see [Credentials & API Access](/for-merchants/credentials-and-api-access)). You don't have to wait for it — integration runs in the background while you complete KYB, and only needs to be finished by go-live. If you're on a custom or in-house stack, [Firmly](/contact) may reach out for the specific connection details it needs. You can follow the connection in the wizard's **Integration progress** panel. It runs through six stages — platform identification, content, cart, shipping, payment, and final setup — marking each done as Firmly completes it. Nothing here needs action from you; it's there so you can see how far along the connection is. ## Task 2 — Know Your Business (KYB) This is your first substantive task. The KYB form is the **Company Info** tab on the general settings page. **Required fields:** - Company Name - Online Revenue band **Recommended:** - Employee count - Headquarters address (Street / City / State / Postal / Country) - Brand identity (Display Name, primary color, action color, logo) - Privacy policy URL - Terms of use URL Once filled in and saved, a **Submit for Review** button appears. Pressing it transitions KYB to `pending`. Firmly reviews and either approves (you're unblocked) or rejects with notes shown inline. Because KYB gates Tasks 3–6, it's on the critical path — the expected review turnaround is communicated during onboarding and confirmed during KYB, so you know when to expect a decision rather than waiting in the dark. **See [KYB](/solutions/firmly-connect/onboarding/know-your-business)** for the full feature documentation. ## Task 3 — Configure product catalog Once KYB is approved, the catalog task unlocks. Pick one mode: | Mode | When to pick | |---|---| | **Entire Catalog** *(Recommended)* | Sell all products. New products auto-sync. Inventory updates in real time. Fastest to launch | | **Selected Products (Subset)** *(Advanced)* | A curated set of categories or individual products. Firmly's team helps scope the selection | The default is Entire Catalog. Save advances the wizard. A separate read-only **Products** view shows what Firmly has ingested from your commerce backend — your confirmation that integration is working. **See [Catalog configuration](/solutions/firmly-connect/onboarding/catalog-configuration)** for details. ## Task 4 — Configure destinations Opt into the destinations on Firmly's network you want to sell through. Each destination is a single toggle in a table grouped by category (AI Shopping Agents & LLMs, Marketplace, Publishers, Social, Other). During onboarding this is just an opt-in step — flip on the destinations you want. Per-destination performance (orders and average order value for your store) shows later in the [Merchant Portal](/solutions/firmly-connect/portal/), once you're live and transacting. There's no per-destination configuration form — Firmly handles every behind-the-scenes integration step with the destination platform. **See [Destinations configuration](/solutions/firmly-connect/onboarding/destinations-configuration)** for details. ## Task 5 — Sign merchant agreement Review the agreement PDF and fill out the participation form: - Company Legal Name - Signer Name, Title, Email, Phone - "I have read and accept the terms" checkbox Most fields are pre-filled from your KYB details, so you just review and confirm. Signing captures audit metadata (signer email, timestamp, client location, agreement version, and signing browser). **See [Agreement signing](/solutions/firmly-connect/onboarding/agreement-signing)** for details. ## Task 6 — Complete CDN whitelisting *(most merchants don't need it)* If your CDN or WAF blocks Firmly traffic, you must configure an allow rule. Use Web Bot Auth when your edge can verify FirmlyAI Bot. Otherwise, use a merchant-specific header rule. Use IP allowlisting only when request-level identity is not available. **Most merchants don't need this step.** Firmly decides whether it applies during setup based on your commerce platform; when it's not needed, it's skipped automatically. If it does apply, it appears as a task in your wizard — you won't have to discover it yourself — and the go-live review double-checks it. **See [CDN whitelisting](/solutions/firmly-connect/onboarding/cdn-whitelisting)** for the methods, setup steps, and current egress addresses. ## Task 7 — Go-live approval (Firmly-driven) Once your tasks are complete and Firmly has finished its side of the integration, **you press "Submit for Go-Live"**. That moves the task to `Awaiting approval`, and Firmly's review team verifies your configuration and either: - **Approves** — you're live; the Merchant Portal flips from the task menu to the dashboard - **Rejects** — the rejection notes are surfaced inline so you know exactly what to fix The expected go-live review turnaround is communicated during onboarding, so a merchant sitting at `Awaiting approval` can tell a normal wait from a stalled one. ![The onboarding checklist near completion — six tasks marked Completed and the final Go-live approval task showing Awaiting approval, at 86% overall](/images/for-merchants/onboarding-golive.svg) ## After go-live After go-live, the wizard disappears and every step becomes a settings page you can reopen anytime — to widen your catalog, re-sign a new agreement, change which destinations you sell through, or update CDN rules. ![The merchant dashboard after go-live — left navigation, a greeting, four metric cards (total revenue, total orders, average order value, active destinations, all at zero for a new store), and panels for cumulative revenue and orders by destination](/images/for-merchants/onboarding-dashboard.svg) Your home base is now the [Merchant Portal](/solutions/firmly-connect/portal/) dashboard: revenue, orders, average order value, and active destinations across the top, with revenue and per-destination breakdowns below. A brand-new store starts at zero — the numbers fill in as agents start transacting. --- ## Related - [Firmly Connect Onboarding Wizard](/solutions/firmly-connect/onboarding/) — canonical reference - [Quickstart](/for-merchants/quickstart) — the abbreviated path - [Going live](/for-merchants/going-live) — Firmly's go-live approval step in depth --- # Supported Platforms This page sets expectations before you sign up — your platform category, what's universal across categories, and what your category typically provides during onboarding. Firmly maintains adapters for a wide range of commerce platforms and speaks each merchant's native API, so most stores connect without a custom build. ## Standard vs Advanced — which is my store? {#standard-vs-advanced} **Most stores are Standard.** The Standard checkout — cart, address, one shipment, order — works on every connected platform with no extra setup. You need **Advanced** only if your products or fulfillment call for it: items that split into **multiple shipments** (furniture, appliances, large or multi-warehouse orders), **delivery scheduling or pickup**, **add-ons and protection plans**, or **ZIP-coverage gating** before checkout. Advanced also requires your commerce platform to support those richer operations. Not sure? **Assume Standard.** If your catalog or fulfillment turns out to need Advanced, Firmly flags it during onboarding and confirms whether your platform can support it — you don't have to decide up front. ## What category is your store in? Answer the questions in order — the first one that matches is your category. Click your category to jump to what you provide for it. | Question | If yes, your category is | |---|---| | Did your team build the storefront platform yourselves (in-house, bespoke)? | [**Custom or in-house**](#custom-or-in-house) | | Is your storefront composable or API-first (separate microservices for cart, checkout, catalog)? | [**Composable / API-first**](#composable) | | Is your storefront headless or heavily customized (decoupled front-end + back-end, custom checkout flow)? | [**Headless or heavily customized**](#headless) | | Is your storefront on a major SaaS or enterprise commerce platform (out-of-the-box, light customization)? | [**Cloud-native**](#cloud-native) | If you're uncertain — for example, between headless and composable — just sign up. The wizard or Firmly's onboarding team will clarify. The distinction usually matters only on Firmly's side. ## What's true for every category Regardless of category, Firmly provides the same capabilities — all driven by your platform's live data: - **Catalog read** — products, variants, pricing, and inventory pulled live from your platform. **The same pricing and inventory your storefront shows** — validated live at transaction time, so there's no stale data at order placement. (Firmly does keep a catalog index for fast discovery; it's always confirmed against your live platform before an order is placed — see [Catalog & Pricing](/for-merchants/catalog-and-pricing).) - **Cart orchestration** — Firmly handles cart state for the transaction; **you don't manage a separate cart system on top of your existing platform.** Line items, addons, promo codes, and shipping methods all flow through your platform's standard APIs. - **Tax and shipping calculation** — using your platform's live rules. - **Payment tokenization** — card, PayPal, Click to Pay, Google Pay, Klarna. - **Order placement** — orders land in your native order management system as if a customer placed them directly. - **Affiliate attribution** — origin attribution flows back to the destination. Your existing PSP, OMS, analytics, reporting, and storefront pages stay untouched. Firmly's scope ends at order placement. > **Note** > **Your store stays the single source of truth.** Firmly reads pricing, inventory, tax rules, and shipping methods live from your platform and validates them at transaction time — no stale data at order placement. Firmly's catalog index (used for fast discovery) is always confirmed against your live platform before an order goes through, so the data your storefront shows and the data a Firmly-driven transaction places against are the same. ## What you provide, by category What you provide depends on your category — usually just one or two things, captured during the Onboarding Wizard. ### Custom or in-house {#custom-or-in-house} If your team built the storefront platform yourselves. **What you provide:** Endpoint URLs, authentication scheme, example responses. ### Composable / API-first {#composable} If your storefront is composable or API-first — separate microservices for cart, checkout, catalog. **What you provide:** Project key + minimum scope details (if Firmly's discovery can't determine them). ### Headless or heavily customized {#headless} If your storefront is headless or heavily customized — decoupled front-end and back-end, custom checkout flow. **What you provide:** Storefront API key + deployment-specific details. ### Cloud-native {#cloud-native} If your storefront is on a major SaaS or enterprise commerce platform, out-of-the-box with light customization. **What you provide:** Just the store URL. Firmly handles the rest. For cloud-native, the specifics are confirmed inside the wizard during onboarding. For headless, composable, and custom platforms, the credential handover happens in a short conversation with Firmly's onboarding team alongside the wizard. ## Custom platforms — the one exception {#custom-platforms-the-one-exception} The categories above cover merchants whose platform exposes a standard storefront API, including most headless and heavily customized deployments (which provide a storefront API key rather than a custom build). The exception is a **truly custom or legacy stack** with no standard API surface Firmly's pre-built adapters can use: for those, Firmly builds a per-merchant adapter. Typical effort is **2–4 weeks**, scoped during onboarding. For these merchants only, it makes sense to [contact Firmly](/contact) before signing up so the adapter scoping conversation can start in parallel with onboarding. For every other category, just sign up. A **Custom Adapter Editor** in your Firmly Connect dashboard lets you review, edit, test, and publish the adapter without leaving the portal — see [Credentials & API Access → Custom adapter merchants](/for-merchants/credentials-and-api-access#custom-adapter-merchants) for how it works. ## Ready to start? Sign up at [merchant.firmly.ai](https://merchant.firmly.ai) and walk through the [7-step wizard](/for-merchants/onboarding). See [Merchant Quickstart](/for-merchants/quickstart) for the abbreviated path. --- ## Related - [For Merchants overview](/for-merchants/) - [Credentials & API Access](/for-merchants/credentials-and-api-access) - [Merchant onboarding](/for-merchants/onboarding) - [Going live](/for-merchants/going-live) --- # Data Flow Firmly sits between the destination (where the user expresses purchase intent) and the merchant (where the order is fulfilled). This page covers what data flows in each direction, where it lives in motion, and what Firmly persists vs passes through. ## The three actors and what each holds | Actor | Holds | Doesn't hold | |---|---|---| | **Destination** | User identity, conversation/page context, App ID, short-lived session JWT, attribution params (UTM, click-IDs) | Cleartext PAN at rest, merchant catalog data persistently, order fulfillment state | | **Firmly** | Cart state during checkout, session identity (device_id), encrypted payment payload (in motion), order placement record | Cleartext PAN at rest, destination's internal user model, the merchant's authoritative catalog and inventory (those stay with the merchant) | | **Merchant** | Full product catalog, inventory, customer order records, payment processing relationship with PSP, post-order fulfillment | Destination's internal user identity, the destination's session data | ## Data in motion — the canonical purchase Trace the data on a single purchase from intent to order placement: | Step | What flows | Path | |---|---|---| | 1. Auth bootstrap | App ID | Destination → Firmly | | 1. Auth bootstrap | JWT (access_token) | Firmly → Destination | | 2. Discovery | Search query | Destination → Firmly | | 2. Discovery | Catalog query | Firmly → Merchant | | 2. Discovery | Product results | Merchant → Firmly → Destination | | 3. Cart create | Product reference, quantity | Destination → Firmly | | 3. Cart create | Cart state | Firmly persists in its session store (~7 days) | | 4. Shipping | Address | Destination → Firmly → Merchant | | 4. Shipping | Shipping methods + prices | Merchant → Firmly → Destination | | 5. Payment key | RSA public key | Firmly → Destination | | 6. Card encryption | Cleartext card payload | Destination's local memory only — never transmitted in cleartext | | 6. Card encryption | JWE payload | Destination → Firmly | | 7. Place order | Encrypted card + cart + shipping | Destination → Firmly | | 7. Place order | A **$0 authorization** against the card to validate it, before the order is placed | Firmly → PSP | | 7. Place order | Decrypted card → PSP (which returns a token) or → merchant's own platform, over TLS | Firmly → PSP / merchant platform | | 7. Place order | Order metadata + line items | Firmly → Merchant's OMS | | 7. Place order | Merchant order ID | Merchant → Firmly → Destination | ## What lives at rest, where, and for how long | Data | Stored where | Retention | |---|---|---| | Session JWT | Destination's session memory | ~1 hour (token lifetime) | | Device identifier | Destination + Firmly | Session-scoped; Firmly retains session state ~7 days from last activity | | Cart state | Firmly's session store | 7 days from last activity | | Idempotency keys (UCP protocol bridge) | Firmly internal | 24 hours | | Order placement record | Firmly internal + Merchant OMS | Per merchant retention policy | | Cleartext card PAN | Nowhere at rest — the vault decrypts in memory and submits the card to the PSP or merchant platform over TLS | Never persisted | | Customer order | Merchant OMS | Per merchant policy (typically years) | ## Attribution flow — separate from purchase data Attribution data (UTM params, click-IDs, publisher identifiers) flows alongside the purchase data but goes to different destinations: | Attribution data | Captured at | Flows to | |---|---|---| | UTM params | Destination on page load / impression | Order metadata → Merchant OMS, Destination's analytics | | Ad-platform click-ID | Destination on click | Order metadata, then ad-platform postback | | Publisher identifier | Destination's session | Firmly affiliate service → Merchant OMS, Publisher's payout system | | Marketplace operator ID | Destination's session | Firmly attribution → Merchant OMS, Operator's reconciliation system | ## What Firmly does NOT see - **Destination's own user identity** — Firmly tracks a session device ID, not the destination's user model - **Cleartext PAN at rest** — see [Security Model](/foundations/security-model) - **Destination's full conversation / page context** — only the intent that arrives at the API (search query, product reference, address, payment) - **The authoritative catalog, inventory, and pricing** — these stay with the merchant. Firmly reads them live from the merchant's commerce backend at request time, and the merchant's store remains the source of truth. **Firmly does maintain a discovery index** so [search](/api-reference/discovery/search) can span the merchant network — so this is not a claim that Firmly holds no catalog data, only that it does not hold the system of record. --- ## Related - [Security Model](/foundations/security-model) — auth, card encryption, PCI scope - [Lifecycle and States](/foundations/lifecycle-and-states) — how data state transitions through the flow - [How Firmly Works](/how-firmly-works) — the higher-level architecture - [API Reference](/api-reference/) — endpoint contracts for each step above --- # Foundations The concepts behind how Firmly moves data and money — read these before building anything non-trivial on top of the API. - [Data Flow](/foundations/data-flow) — start here: how a request travels from your app to the merchant and back - [Lifecycle and States](/foundations/lifecycle-and-states) — the states a cart and an order move through - [Security Model](/foundations/security-model) — how card data, auth, and merchant credentials are protected --- # Lifecycle and States A Firmly purchase moves through several state machines — session, cart, checkout, order — each with its own lifetime and transition rules. This page covers each lifecycle so a destination engineer knows what state exists at any moment and how long it lives. ## Session lifecycle | State | Meaning | Duration | |---|---|---| | Bootstrap requested | `POST /browser-session` made; awaiting response | Sub-second | | Active | Token issued, `device_id` assigned | ~1 hour from issue | | Expired (renewable) | Token past `exp`; prior session state still retained | Renewable while session state persists (~7 days from last activity) | | Expired (state cleared) | Session state garbage-collected | Permanent — must bootstrap fresh | Renewal: re-POST to `/browser-session` with the prior (expired) token in the body. As long as the session state is still retained, Firmly returns a new token with the same `device_id`. There's no separate server-enforced renewal window — renewal works while the session state persists (~7 days from last activity), after which a fresh bootstrap is required. ## Cart lifecycle | State | Meaning | Triggers | |---|---|---| | `active` | Cart exists, items can be added/removed/modified | `POST /cart/line-items` (first item creates the cart implicitly) | | `item_not_shippable` | One or more line items can't ship to the chosen address | Set during `POST /cart/shipping-info` when an item has no valid shipping option | | `checkout_blocked` | Cart has validation errors preventing checkout | Out-of-stock items, expired promotions, shipping unavailable — see [Cart lifecycle](/api-reference/cart-management/cart-lifecycle#4-checkout-blocked-state-cart_status-checkout_blocked) | | `pending` | **Reserved** — no current cart operation produces it | Treat as an unexpected state; don't branch checkout logic on it | | `submitted` | Order successfully placed at merchant | Merchant returned order ID | > **Note** > While a cart is `active` it moves through several milestones — address set (`POST /cart/shipping-info`), shipping method picked (`POST /cart/shipment/methods`), ready for payment — but the cart status stays `active` throughout. A **declined payment is not a cart state**: it surfaces as a `422 CreditCardDeclined` error on `place-order`, and the cart remains `active` so you can retry with a different payment method. Cart persistence: cart state is held in Firmly's session store for ~7 days from the last activity. After 7 days idle, the cart is garbage-collected; the destination must start a fresh cart. ## Order placement lifecycle `POST /payment/place-order` is the moment the cart transitions to `submitted`. The response includes: | Field | What it represents | |---|---| | `cart_status` | `submitted` on success. A payment failure returns a `422 CreditCardDeclined` error rather than a status value | | `cart_id` | Firmly's stable reference for the cart | | `urls.thank_you_page` | Merchant's own confirmation URL (populated post-success) | | `platform_order_number` | Merchant's native order number — capture for reconciliation | Post-`submitted`, Firmly's scope ends. The order is the merchant's responsibility for fulfillment, tracking, returns, and refunds. ## Idempotency window On the **UCP protocol bridge**, `Idempotency-Key` values are cached for **24 hours**: the same key within the window returns the cached response, and the operation runs at most once. The core REST endpoints accept the header but do not deduplicate on it today — a REST retry re-runs the operation. Before retrying a failed `place-order` over REST, re-read the cart and check `cart_status`: if it's already `submitted`, the order went through. See [Errors & Conventions → Idempotency](/api-reference/errors-and-conventions#idempotency). ## State diagram — a typical purchase ```mermaid stateDiagram-v2 [*] --> SessionBootstrap SessionBootstrap --> SessionActive: 200 with JWT SessionActive --> CartActive: POST /cart/line-items CartActive --> Submitted: order placed note right of CartActive Edits and payment retries stay in CartActive end note Submitted --> [*] ``` ## What expires when | Token / state | Expires after | Recovery | |---|---|---| | Session JWT | ~1 hour | Renew via re-POST to `/browser-session` | | Cart state | 7 days idle | Start fresh cart | | Idempotency key | 24 hours | Different key = new call | | Payment public key cache | Rotated periodically; cadence not public | Re-fetch via `GET /payment/key` on invalid-key encryption error | | `submitted` order | Permanent (no Firmly-side TTL) | n/a — merchant's OMS owns post-order | ## Destination-side state to track A destination engineer should hold: | State | Why | |---|---| | Current session JWT + `device_id` | For subsequent API calls and renewal | | Current cart state (last response) | Avoids re-fetching for read-only renders | | Idempotency key per logical operation | Stable for retries within 24h | | Order success indicators (`cart_status`, merchant order ID) | For reconciliation and reporting | | Attribution params (UTM, click-IDs) | Persisted in session for inclusion on `place-order` | --- ## Related - [Security Model](/foundations/security-model) — session lifetime in security terms - [Data Flow](/foundations/data-flow) — what data moves through each state - [Cart Lifecycle (API reference)](/api-reference/cart-management/cart-lifecycle) — endpoint-level detail - [Errors & Conventions](/api-reference/errors-and-conventions) — error states and recovery - [Authentication](/for-destinations/authentication) — session bootstrap and renewal patterns --- # Security Model Firmly is a commerce backend that handles authentication, payment-credential encryption, and data isolation across merchants. This page covers the security boundaries that matter to destinations and merchants integrating Firmly. ## Authentication boundaries Firmly uses two distinct authentication patterns. Both result in a per-request `x-firmly-authorization` value — a short-lived JWT for browser sessions, a long-lived secret for server-to-server. | Pattern | Where the code runs | Credentials | |---|---|---| | **Browser session** | Client-side (browser, mobile app, ad surface, embed) | App ID exchanged for short-lived JWT (~1 hour) | | **Server-to-server (S2S)** | Backend (destination server, integration tier) | Long-lived secret + device identifier per user | See [Authentication](/for-destinations/authentication) for the full request/response shapes and renewal patterns. **Why two patterns:** client-side code can't safely hold a long-lived secret, so it exchanges a relatively safe identifier (App ID) for a short-lived token. Server-side code can hold a long-lived secret, so it skips the bootstrap step. ## Card encryption — JWE Card payment payloads are encrypted client-side before they ever reach Firmly's servers. | Step | What happens | |---|---| | 1. Get public key | `GET /payment/key` returns an RSA JWK | | 2. Encrypt locally | Client encrypts the card with `RSA-OAEP-256 + A256GCM` (JWE) | | 3. Send encrypted payload | `POST /payment/place-order` with the JWE in the request body | | 4. Decrypt server-side | Firmly's vault decrypts the card in memory and submits it over TLS to the payment path for that merchant (see below) | | 5. Discard | The plaintext card never persists on Firmly's servers; the JWE payload is also discarded post-order | This means the destination's environment doesn't hold cleartext card numbers at rest. The encryption happens before the network call. After decryption, the vault routes the card one of two ways, depending on the merchant's payment setup: - **PSP tokenization** — the vault submits the card to the merchant's payment processor (PSP) over TLS; the PSP returns a **token**, and Firmly uses that token to place the order on the merchant's platform. - **Direct to the merchant's platform** — for merchants that process payments themselves (no separate PSP), the vault submits the **card** to the merchant's own platform over TLS. In both cases the card is decrypted only in memory, and the cleartext card is never stored. ## PCI scope boundary PCI DSS scope is determined by where cleartext card data lives. With Firmly's JWE flow: | Location | Holds cleartext PAN? | In PCI scope? | |---|---|---| | Destination's client (browser, app) | Briefly, during the JWE encryption step | Yes — destination's responsibility | | Destination's server | No (JWE payload only) | Reduced scope | | Firmly's API edge | No (JWE only) | Yes — Firmly's responsibility | | Firmly's vault | Briefly, in memory during decryption | Yes — Firmly's responsibility | | Merchant's PSP | Yes, for processing | PSP's responsibility | For destinations using JWE encryption, this reduces PCI scope toward SAQ A-EP — the self-assessment questionnaire for merchants whose payment pages are partially delivered by their own systems but who don't store cardholder data — for the client-side encryption surface. Confirm your exact PCI assessment with your compliance team. ## Audits and certifications Firmly maintains current third-party audits for both data security and payment-card handling: | Certification | Scope | |---|---| | **PCI DSS v4.0.1** | Card data handling — Firmly's vault and the JWE encryption flow are in-scope | | **SOC 2 Type II** | Security, availability, and confidentiality controls across Firmly's commerce platform | Certification artifacts (current reports, attestation letters, scope statements) are available under NDA during commercial onboarding. ## Per-merchant data isolation A destination's App ID is scoped to a specific set of merchants — in sandbox to a paired test merchant, in production to the merchants the destination is approved to transact against. | Boundary | How it's enforced | |---|---| | Discovery results | `POST /discovery/search` returns products only from merchants the App ID can reach | | Cart access | `POST /cart/...` calls with a `{domain}` outside the App ID's scope return `DomainNotFound` | | Order metadata | Orders carry the originating destination's identifier; merchants only see orders from destinations they've opted into | This means one destination cannot accidentally transact against a merchant it's not approved for, even if it knows the merchant's domain. ## Session lifetime and renewal Browser-session tokens expire after ~1 hour (`expires_in: 3600`). After expiry: - The token returns 401 on subsequent calls - The destination calls `POST /browser-session` again with the expired token in the body to renew without losing the `device_id` - Renewal isn't a separate server-enforced window — it works while the session state is still retained (~7 days from last activity in Firmly's session store); once that state is cleared, a fresh session bootstrap is required This is shorter than typical e-commerce session lifetimes, which constrains the blast radius if a token is exposed. ## What Firmly never sees Specifically excluded from Firmly's systems: - **Cleartext PAN at rest** — JWE encryption removes this from storage - **Destination's internal business logic** — Firmly receives the user-facing intent + payment + address; not the destination's pricing models, internal user state, etc. --- ## Related - [Authentication](/for-destinations/authentication) — request/response shapes for browser-session and S2S - [Lifecycle and States](/foundations/lifecycle-and-states) — session, cart, and order states - [Data Flow](/foundations/data-flow) — what data moves where - [Errors & Conventions](/api-reference/errors-and-conventions) — auth and session errors --- # How Firmly Works Firmly is the commerce layer between a **destination** — the surface where a buyer shops (an AI agent, a publisher article, an ad unit, a marketplace) — and a **merchant**, the seller on their existing commerce platform. The destination integrates once; Firmly translates every operation to each merchant's native platform. ![How Firmly fits: the buyer shops on the destination's surface; the destination calls Firmly's APIs for discovery, cart, payment, and order; Firmly places the order on the merchant's platform; the merchant remains the seller of record](/images/how-firmly-works.svg) ## Who owns what - **Destination** — the buyer-facing experience and the buyer relationship. - **Firmly** — discovery across merchants, cart and checkout orchestration, payment, and order placement, plus affiliate attribution. Tax and shipping are calculated by the merchant and relayed through the cart. - **Merchant** — catalog, pricing, inventory, fulfillment, and the seller-of-record relationship. Orders land in the merchant's order management system as if a customer bought directly. Firmly's scope ends at order placement — tracking, returns, and refunds stay with the merchant. ## Next steps - [Find your solution](/solutions/#find-your-fit) — Which solution shape fits your product. - [Standard Checkout Guide](/cookbook/standard-checkout-guide) — A runnable end-to-end purchase script — start here. - [Authentication](/for-destinations/authentication) — Set up API access. - [API Reference](/api-reference/) — Every endpoint. --- # Addon schemas Addons are merchant-offered add-ons attached to a cart or line item — warranties, gift wrap, gift messages, protection plans. The `AddonsContainer` lives on the cart; `AddonOffer` describes what's available; `AddonSelection` records the user's choices. ## AddonsContainer Container for addon offers and customer selections. - `offers` (array, required) — Available addon services for the cart. Each is an [AddonOffer](#addonoffer). - `selections` (array, required) — Customer's selected addons. Each is an [AddonSelection](#addonselection). ## AddonOffer Available addon service that can be selected. - `addon_id` (string, required) — Unique addon identifier. - `display` (AddonDisplay, required) — Display information for the addon. See [AddonDisplay](#addondisplay). - `scope` (string, required) — Where the addon applies. **Enum values:** - `ITEM` — Applies to specific items - `GROUP` — Applies to item groups - `CART` — Applies to the entire order - `INHERIT` — Inherits scope from the parent offer (used by child offers) - `coverage_mode` (string, required) — How items are covered by the addon. **Enum values:** - `PER_ITEM` — Price per individual item - `PREDEFINED_GROUP` — Fixed groups - `FREE_GROUPING` — Customer chooses grouping - `price` (Amount, required) — Base price for the addon. - `platform_addon_id` (string) — Identifier for the addon in the merchant's underlying commerce platform. - `hide_price` (boolean) — When `true`, the price is not shown to the buyer. - `eligible_line_item_ids` (array) — Line item IDs eligible for this addon. - `line_item_pricing` (object) — Per-item pricing overrides, keyed by `line_item_id`. **properties** - `[line_item_id]` (object) — An object with `price` (Amount) and optional `hide_price` (boolean) for that line item. - `constraints` (AddonConstraints) — Rules and limitations. See [AddonConstraints](#addonconstraints). - `child_offers` (array) — Hierarchical sub-options. Each child offer has the same shape as an `AddonOffer` (without further nesting): `addon_id`, `display`, `scope`, `coverage_mode`, `price`, and the optional `platform_addon_id`, `hide_price`, `eligible_line_item_ids`, `line_item_pricing`, and `constraints`. **Example - Cart-Level Protection** ```json { "addon_id": "shipping_protection", "display": { "name": "Shipping Protection", "description": "Covers lost or damaged shipments", "image_url": "https://staging.luma.gift/addons/protection.png" }, "scope": "CART", "coverage_mode": "PREDEFINED_GROUP", "price": { "value": 4.99, "currency": "USD" } } ``` **Example - Item-Level Warranty** ```json { "addon_id": "extended_warranty", "display": { "name": "Extended Warranty", "description": "2-year extended warranty" }, "scope": "ITEM", "coverage_mode": "PER_ITEM", "eligible_line_item_ids": [ "8f3a2b1c-1d2e-4a5b-9c8d-1a2b3c4d5e6f", "b2c3d4e5-6f70-4a1b-8c9d-0e1f2a3b4c5d" ], "price": { "value": 29.99, "currency": "USD" }, "line_item_pricing": { "8f3a2b1c-1d2e-4a5b-9c8d-1a2b3c4d5e6f": { "price": { "value": 29.99, "currency": "USD" } }, "b2c3d4e5-6f70-4a1b-8c9d-0e1f2a3b4c5d": { "price": { "value": 19.99, "currency": "USD" } } } } ``` ## AddonDisplay Display information for an addon offer. - `name` (string, required) — Addon display name. - `description` (string) — Short description. - `long_description` (string) — Extended description. - `image_url` (string) — Image URL (absolute `http(s)` URL). - `links` (array) — Related links (for example, terms or coverage details). ## AddonConstraints Rules that govern how an addon can be combined with others. - `exclusive_group_id` (string) — Addons sharing the same exclusive group ID are mutually exclusive — only one can be selected. - `requires_addon_ids` (array) — Addon IDs that must also be selected for this addon to be valid. ## AddonSelection Customer's selected addon configuration. - `addon_id` (string, required) — References `AddonOffer.addon_id`. - `selected_line_item_ids` (array) — Line item IDs this addon applies to (for `ITEM` scope). - `selected_child_ids` (array) — Selected child addon IDs. - `hide_price` (boolean) — When `true`, the price is not shown to the buyer. - `price` (Amount) — Total price for this selection (calculated server-side). - `line_item_pricing` (object) — Per-item price breakdown, keyed by `line_item_id`. - `metadata` (object) — Addon-specific attributes. ```json { "addon_id": "extended_warranty", "selected_line_item_ids": ["8f3a2b1c-1d2e-4a5b-9c8d-1a2b3c4d5e6f"], "price": { "value": 29.99, "currency": "USD" }, "line_item_pricing": { "8f3a2b1c-1d2e-4a5b-9c8d-1a2b3c4d5e6f": { "price": { "value": 29.99, "currency": "USD" } } } } ``` --- ## Related - [Schemas overview](/resources/schemas/) - [API Reference](/api-reference/) - [Errors & Conventions](/api-reference/errors-and-conventions) --- # Changelog What's shipped in the API and these docs, most recent first. Non-breaking additions ship continuously; breaking changes are announced ahead of time through [Firmly](/contact) — none ships without notice. ## Recent changes - **September 22, 2026 — 3-D Secure payment challenges documented; merchant-access guides restored behind sign-in.** [Complete Order](/api-reference/payment/complete-order-v2) and [Place Order](/api-reference/payment/place-order-v2) can return `409 payment_challenge_required` when the issuer requires card verification — not a failure, but a step the shopper completes before you call [Resume After Challenge](/api-reference/payment/complete-order-v2-resume). `openapi.json` carries the envelope on every route that emits it, so generated clients no longer treat a challenge as a dead end. Available to App IDs opted in via `supports_payment_challenge`; others keep the previous `422 PaymentChallengeRequired`. Separately, the merchant allow-listing and payment-provider guides are published again under [For Merchants](/for-merchants/), behind the same sign-in they had before — [contact Firmly](/contact) for access. [Search Products](/api-reference/discovery/search) is the canonical discovery search endpoint. - **September 15, 2026 — PayPal Express Checkout documented, express checkout grouped by provider.** PayPal's three-call sequence now has reference pages — [Start](/api-reference/payment/express-checkout/paypal/start), [Authorize](/api-reference/payment/express-checkout/paypal/authorize) and [Complete Order](/api-reference/payment/express-checkout/paypal/complete-order) — verified against the API. Express checkout is now grouped per provider, so the Klarna and Google Pay pages moved to `/express-checkout/klarna/…` and `/express-checkout/google-pay/…`; the previous URLs redirect. Each provider page carries the availability check and host note for its gateway; the endpoint pages stay self-contained. Note for PayPal integrators: a declined PayPal payment returns `422 CreditCardDeclined` despite the name — see [Complete Order](/api-reference/payment/express-checkout/paypal/complete-order#error-responses). - **September 2, 2026 — Merchant fees itemized on the cart.** Cart responses now carry an optional `fees` array plus a `fee_total`, so merchant-imposed charges (recycle, regulatory, environmental) are itemized with their own descriptions instead of being folded into `tax`. Both fields are optional and absent when a cart has no fees, and `total` is unchanged. See [Get Cart](/api-reference/cart-management/get-cart), the [ShoppingCartV2 schema](/resources/schemas/shopping-cart), and [Common types → Fee](/resources/schemas/common-types#fee). - **August 21, 2026 — Reference accuracy pass.** Corrected the documented shapes for [place-order / complete-order](/api-reference/standard-flow/place-order) (the response carries `submitted_at` alongside `platform_order_number`), [Get Product from URL](/api-reference/catalog/get-product-from-url) (full product detail, and it can return `412 ProductNotSupported`), [Discovery search](/api-reference/discovery/search) (paginate with `cursor`; `query` is optional when you send `filters`), [Add Line Item](/api-reference/cart-management/add-line-item) (`flush_cart`/`fast_mode` are the strings `"true"`/`"false"`, and unknown query parameters are rejected), and [Set Fulfillment Type](/api-reference/shipment-configuration/set-fulfillment-type) (`fulfillment_type` enum plus `location_id`). Cart responses now document the `session` object and the `tax` / `tax_total` pairing. Example identifiers are UUIDs throughout, matching what the API returns, and every example card is the documented sandbox card. - **August 19, 2026 — Clearer Standard vs Advanced.** Both checkout flows now have a runnable, end-to-end guide — the [Standard Checkout Guide](/cookbook/standard-checkout-guide) (`/api/v1`) and the [Advanced Checkout Guide](/cookbook/advanced-checkout-guide) (`/api/v2`) — plus a chooser on the [For Destinations](/for-destinations/) and [For Merchants](/for-merchants/) pages, and a [which-is-my-store heuristic](/for-merchants/supported-platforms#standard-vs-advanced) for merchants. The [API Explorer](/api-explorer/) is now grouped by flow: **Shared setup**, **Standard (v1)**, **Advanced (v2)**. - **August 18, 2026 — Standard (v1) checkout documented end-to-end.** New [Standard flow reference](/api-reference/standard-flow/) (catalog, cart, checkout, order) and the runnable Standard Checkout Guide, verified against the sandbox. The Advanced (v2) endpoint set — cart, shipments, orders, sessions, and ZIP-coverage — is now complete in the reference and the Explorer. ## How updates are communicated - **Breaking changes** are announced ahead of time through [Firmly](/contact); no breaking change ships without notice. - **Non-breaking additions** (new endpoints, optional fields, new guides) ship continuously. - **Internal refactors** that don't change the public contract are not announced. ## Versioning - Two flows share the same auth and catalog: **Standard** (`/api/v1`) — single-merchant, one-shipment checkout, right for most integrations — and **Advanced** (`/api/v2`) — split shipments, add-ons, delivery scheduling, and coverage. See [Choose your checkout flow](/for-destinations/) for how to pick. - Endpoint-level detail is in the [API Reference](/api-reference/) and the live [API Explorer](/api-explorer/). --- ## Related - [API Reference](/api-reference/) - [API Explorer](/api-explorer/) - [Contact](/contact) --- # Common types These primitive types appear throughout other schemas — `Amount` for any money value, `Fee` for a labeled merchant-imposed charge, `Address` for any shipping or billing address, `TimeSlot` for scheduled-delivery and pickup windows. ## Amount Monetary value with currency information. - `value` (number, required) — Decimal value (e.g., 99.99). - `currency` (string, required) — ISO 4217 currency code, exactly three characters (e.g., "USD"). - `number` (integer) — Value in smallest currency unit (e.g., 9999 for $99.99). - `symbol` (string) — Currency symbol (e.g., "$"). ```json { "value": 99.99, "currency": "USD", "number": 9999, "symbol": "$" } ``` ## Fee A merchant-imposed fee. Same fields as `Amount`, plus a `description` that labels the fee for the shopper. - `description` (string, required) — Human-readable label for the fee (e.g., "Recycle fee"). - `value` (number, required) — Decimal value (e.g., 16.00). - `currency` (string, required) — ISO 4217 currency code, exactly three characters (e.g., "USD"). - `number` (integer) — Value in smallest currency unit (e.g., 1600 for $16.00). - `symbol` (string) — Currency symbol (e.g., "$"). ```json { "description": "Recycle fee", "value": 16.00, "currency": "USD", "number": 1600, "symbol": "$" } ``` ## Address > **Note** > **`state_or_province` and `phone` can be relaxed per merchant.** Both are required by default. A merchant whose buyers are in countries with no state/province in the address format — most of continental Europe — can have Firmly relax them, in which case the field may be absent or an empty string. The cart tells you which relaxations are active: check `shop_properties.optional_fields` (`shipping_state`, `shipping_phone`) on [Get Cart](/api-reference/cart-management/get-cart). Don't hard-require these client-side without checking. There are two address shapes. `ShippingInfo` is used for the buyer's shipping address and requires contact details; the looser `AddressInfo` is used for billing addresses and for store (pickup-location) addresses, where the contact fields are optional. ### ShippingInfo Buyer shipping address. This is the wire shape used by [Set Shipping Info](/api-reference/checkout/set-shipping-info) and returned on the cart as `shipping_info`. - `first_name` (string, required) — Buyer first name. - `last_name` (string, required) — Buyer last name. - `address1` (string, required) — Primary address line. - `city` (string, required) — City name. - `state_or_province` (string, required) — State or province. - `postal_code` (string, required) — Postal code. - `country` (string, required) — Country. - `phone` (string, required) — Contact phone number. - `email` (string, required) — Contact email. - `address2` (string) — Secondary address line (apt, suite, etc.). - `company` (string) — Company name. - `state_name` (string) — Full state or province name, when the merchant provides it in addition to `state_or_province`. ```json { "first_name": "Ada", "last_name": "Lovelace", "address1": "123 Main St", "address2": "Apt 4", "city": "San Francisco", "state_or_province": "CA", "postal_code": "94105", "country": "US", "phone": "(415) 555-0123", "email": "ada@example.com" } ``` ### AddressInfo (billing and location addresses) Used for the cart's `billing_info` and for store `address` fields on a [PickupLocation](/resources/schemas/fulfillment#pickuplocation). Same fields as `ShippingInfo`, but `first_name`, `last_name`, `phone`, and `email` are optional. - `address1` (string, required) — Primary address line. - `city` (string, required) — City name. - `state_or_province` (string, required) — State or province. - `postal_code` (string, required) — Postal code. - `country` (string, required) — Country. - `first_name` (string) — First name. - `last_name` (string) — Last name. - `company` (string) — Company name. - `address2` (string) — Secondary address line. - `state_name` (string) — Full state or province name. - `phone` (string) — Contact phone number. - `email` (string) — Contact email. ## TimeSlot Available time window for scheduled delivery or in-store pickup. - `start_time` (Time, required) — Window start time. - `end_time` (Time, required) — Window end time. - `slot_id` (string) — Unique slot identifier. - `description` (string) — Human-readable time range. - `price` (Amount) — Additional cost for this time slot. ### Time object - `utc` (string, required) — UTC timestamp (ISO 8601). - `local` (string, required) — Local time representation. - `local_timezone` (string, required) — IANA timezone identifier. - `display` (string) — Display-ready time string. ```json { "slot_id": "morning_9_12", "start_time": { "utc": "2024-02-15T17:00:00Z", "local": "2024-02-15T09:00:00", "local_timezone": "America/Los_Angeles" }, "end_time": { "utc": "2024-02-15T20:00:00Z", "local": "2024-02-15T12:00:00", "local_timezone": "America/Los_Angeles" }, "description": "9:00 AM - 12:00 PM", "price": { "value": 0, "currency": "USD" } } ``` --- ## Related - [Schemas overview](/resources/schemas/) - [API Reference](/api-reference/) - [Errors & Conventions](/api-reference/errors-and-conventions) --- # Error response schema The error response schema is also documented in [Errors & Conventions](/api-reference/errors-and-conventions) with the full error code catalog. This page is the schema reference. ## Error Response ### ErrorResponse Standard error response format. Every `FirmlyError` serializes to this envelope — there is no `message` or `details` field. - `code` (integer, required) — Numeric HTTP status code (for example, `404`, `422`). - `error` (string, required) — The PascalCase error identifier (for example, `ProductNotFound`, `CartNotFound`, `CreditCardDeclined`). See [Errors & Conventions](/api-reference/errors-and-conventions) for the full catalog. - `description` (string, required) — Human-readable description of the error. Every `FirmlyError` carries exactly these three fields — no additional or domain-specific fields. > **Note** > **One exception.** [Get All Products](/api-reference/catalog/get-all-products) returns a bare `{"error": "Size is not valid: ..."}` (400, invalid `size`) — it carries no `code` or `description`. The [UCP protocol bridge](/solutions/agentic-commerce/protocols/ucp/) uses a different `messages[]` envelope entirely. See [Errors & Conventions](/api-reference/errors-and-conventions#error-response-shape). ```json { "code": 404, "error": "ProductNotFound", "description": "Product variant was not found" } ``` ## Schema Evolution > **Note** > The `schema_version` field in ShoppingCartV2 indicates the API version. Current version is "2.0". Future versions will maintain backward compatibility where possible. --- ## Related - [Errors & Conventions](/api-reference/errors-and-conventions) — full error code catalog with recovery patterns - [Schemas overview](/resources/schemas/) --- # Fulfillment schemas These three schemas describe how a cart is fulfilled: shipping to an address, BOPIS (buy online, pick up in store), or scheduled delivery. The `FulfillmentType` schema captures the high-level choice; `ShippingMethod` and `PickupLocation` describe the specific selection. ## FulfillmentType Defines how items will be delivered to the customer. - `id` (string, required) — Fulfillment type identifier. **Enum values:** - `SHIP_TO_ADDRESS` — Standard shipping to address - `SCHEDULED_DELIVERY` — Delivery with date/time selection - `PICKUP_IN_STORE` — Customer pickup at store location - `name` (string, required) — Human-readable name for display. - `description` (string, required) — Detailed description of the fulfillment method. ```json { "id": "SHIP_TO_ADDRESS", "name": "Standard Delivery", "description": "Items will be shipped to your address" } ``` ```json { "id": "SCHEDULED_DELIVERY", "name": "White Glove Delivery", "description": "Schedule delivery date and time window"} ``` ```json {"id": "PICKUP_IN_STORE", "name": "Store Pickup", "description": "Pick up at selected store location" } ``` ## ShippingMethod A shipping option returned on the cart (in `shipping_method_options[]` and, once selected, `shipping_method`). See [ShoppingCartV2](/resources/schemas/shopping-cart). - `id` (string, required) — Unique shipping method identifier. - `description` (string, required) — Display name for the shipping option. - `price` (Amount) — Shipping cost. Required unless `hide_price` is `true`. - `hide_price` (boolean) — When `true`, the price is not shown to the buyer (and `price` may be omitted). - `message` (string) — Optional message shown alongside the option (for example, a free-shipping threshold note). - `estimated_delivery` (string) — Estimated delivery timeframe. ```json { "id": "express", "description": "Express Shipping", "price": { "value": 19.99, "currency": "USD" }, "estimated_delivery": "1-2 business days" } ``` ## PickupLocation Store location for in-store pickup. - `location_id` (string, required) — Unique location identifier. - `name` (string, required) — Store name. - `address` (AddressInfo, required) — Store address. See [Common types → Address](/resources/schemas/common-types#address). - `pickup_options` (array, required) — Available pickup dates and their time slots. **properties** - `date` (string, required) — Pickup date. - `time_slots` (array, required) — Time slots available on the date. Each is a [TimeSlot](/resources/schemas/common-types#timeslot). - `phone` (string) — Store contact phone number. - `operating_hours` (array) — Store operating hours, one entry per day. **properties** - `day` (string, required) — Day of the week. - `open_time` (string, required) — Opening time. - `close_time` (string, required) — Closing time. - `is_closed` (boolean) — Whether the store is closed on this day. - `distance` (object) — Distance from the buyer to the store. **properties** - `value` (number, required) — Distance value. - `unit` (string, required) — Distance unit. One of `miles`, `kilometers`. - `formatted` (string, required) — Display-ready distance string. ```json { "location_id": "store_123", "name": "Downtown Store", "address": { "address1": "123 Main St", "city": "San Francisco", "state_or_province": "CA", "postal_code": "94105", "country": "US" }, "phone": "(415) 555-0123", "operating_hours": [ { "day": "Monday", "open_time": "09:00", "close_time": "18:00" }, { "day": "Sunday", "open_time": "", "close_time": "", "is_closed": true } ], "distance": { "value": 2.4, "unit": "miles", "formatted": "2.4 mi" }, "pickup_options": [ { "date": "2024-02-15", "time_slots": [ { "start_time": { "utc": "2024-02-15T17:00:00Z", "local": "2024-02-15T09:00:00", "local_timezone": "America/Los_Angeles" }, "end_time": { "utc": "2024-02-15T20:00:00Z", "local": "2024-02-15T12:00:00", "local_timezone": "America/Los_Angeles" }, "description": "9:00 AM - 12:00 PM" } ] } ] } ``` --- ## Related - [Schemas overview](/resources/schemas/) - [API Reference](/api-reference/) - [Errors & Conventions](/api-reference/errors-and-conventions) --- # Glossary If you're seeing a term in the docs and want a quick definition, this page collects them in one place. Each entry has a short definition and a link to the page where it's used in depth. ## Core platform terms ### Adapter Firmly's pre-built connector for a merchant's store — either a shared platform adapter (config-only, for industry-standard commerce platforms) or a purpose-built one for custom or in-house stacks. It translates Firmly's unified cart, checkout, payment, and order APIs into the merchant's native calls, and the responses back. Each adapter implements only the operations its platform supports, so some endpoints may return `OperationNotSupported` or `NotImplemented` for a given merchant. Used in: [Errors & Conventions](/api-reference/errors-and-conventions) · [Supported platforms](/for-merchants/supported-platforms) ### App ID (`_appId`) A UUID identifying a destination's application. The App ID determines which merchants the destination can call, which environment (sandbox vs production) the calls run against, and which authentication scope applies. Contact [Firmly](/contact) to provision one. Used in: [Authentication](/for-destinations/authentication) · [Sandbox setup](/for-destinations/sandbox-setup) ### Device ID The identifier Firmly issues for a buyer's session, returned in the [browser-session](/api-reference/authentication/) response and carried in the session JWT. It may or may not be reused across carts, depending on the destination's integration — use it to follow a single buyer's session and interactions. ### Ray ID Cloudflare's per-request identifier, returned in the `CF-RAY` response header on every call to Firmly. Include it when [reporting an issue](/troubleshooting/reporting-an-issue) — it lets Firmly trace the exact request. Used in: [Errors & Conventions](/api-reference/errors-and-conventions) ### Buyer The party shopping and purchasing through a destination's surface — the default term for the person or party buying via Firmly. The buyer buys from the merchant; the destination hosts the experience; Firmly runs the commerce underneath. ### Destination The surface where a buyer encounters Firmly-powered commerce — an AI chat product, a wallet, a banking app, a publisher, a brand-loyalty app. Destinations integrate with Firmly's APIs to reach merchants. Used in: [Destinations overview](/solutions/destination-surfaces/) ### Merchant The seller of record. Orders placed via Firmly land in the merchant's native order management system. The merchant owns everything that happens after the order is placed. Used in: [For Merchants](/for-merchants/) · [Supported platforms](/for-merchants/supported-platforms) ### Merchant domain (`domain`) The string identifying a merchant in API calls — e.g., `staging.luma.gift`. Most Firmly endpoints take `domain` as a path parameter or query argument so each call is scoped to a specific merchant. Used in: [API Reference overview](/api-reference/) ### Solution Firmly's product packaging — one of six: Agentic Commerce, Ad Commerce, Branded Commerce, Firmly Connect, Marketplace, Publisher Commerce. Solutions share the underlying platform; they differ in destination shape and contractual posture. Used in: [Solutions overview](/solutions/) ### Use case A common pattern destinations build on top of Firmly — e.g. shopping copilot, deal & coupon hunting, smart payment, smart gifting, scheduled buying. Use cases compose Firmly's underlying APIs (discovery, cart, checkout, payment) into a recognizable buyer behavior. The list is not exhaustive; destinations combine these patterns as their product shape requires. Used in: [Use Cases overview](/solutions/agentic-commerce/use-cases/) ## Authentication terms ### JWT JSON Web Token — the signed, self-contained token format Firmly issues for browser sessions. The `access_token` returned by `POST /api/v1/browser-session` is a JWT; pass it on subsequent calls in the `x-firmly-authorization` header. Used in: [Browser session reference](/api-reference/authentication/browser-session) ### Browser session A per-buyer session bootstrapped via `POST /api/v1/browser-session`. Returns a JWT `access_token` valid for 1 hour active (renewable while session state persists, ~7 days from last activity). Used when the destination acts on behalf of a specific buyer. Used in: [Browser session reference](/api-reference/authentication/browser-session) ### Server-to-server (S2S) Backend authentication using a Firmly-issued secret instead of a per-buyer JWT. Used when the destination is a backend service with its own service identity — banks, wallets, scheduled-buying agents. Used in: [Server-to-server reference](/api-reference/authentication/server-to-server) ### `device_id` A stable identifier for the buyer's device or session, used in S2S contexts so Firmly can scope cart and order state to the right buyer. The destination generates and tracks this. Used in: [Server-to-server reference](/api-reference/authentication/server-to-server) ### `x-firmly-authorization` The header carrying either the browser-session JWT or the S2S secret. Required on most authenticated endpoints. ## Cart and checkout terms ### `cart_status` The high-level state of a cart: `active` (in progress), `submitted` (order placed), `item_not_shippable` (blocking issue), or `checkout_blocked` (validation error). See the lifecycle for state transitions. Used in: [Cart Lifecycle](/api-reference/cart-management/cart-lifecycle) ### `line_item_id` A stable identifier for an item in a cart. Returned by `add-line-item`; used to update or remove that specific item later. Distinct from the product's variant ID. Used in: [Cart Management](/api-reference/cart-management/) ### `shipment_id` When a cart contains items that ship separately (different warehouses, different fulfillment timelines), Firmly groups them into shipments. Each shipment has its own `shipment_id` for availability and method selection. Used in: [Shipping & Fulfillment](/api-reference/shipment-configuration/shipping-and-fulfillment) ### `add_to_cart_ref` A structured reference object that identifies what to add to the cart. Its fields come from discovery + catalog responses: `variant_id` (required — a single clean variant identifier), plus optional `product_id` and `variant_handles`. Pass the object to `add-line-item` or `place-order`'s `items` array. It's distinct from a raw variant ID because it carries the additional attributes some merchants need to resolve an add-to-cart. See [Request schemas](/resources/schemas/request-schemas) for the full field list. Used in: [Add line item](/api-reference/cart-management/add-line-item) ### `custom_properties` Free-form merchant- and platform-specific properties attached to a cart or order. Contents vary by adapter — treat it as an opaque bag and don't rely on any particular key. The merchant's order number is **not** here; it's the top-level `platform_order_number`. Used in: [Cart Lifecycle](/api-reference/cart-management/cart-lifecycle) · [Place order](/api-reference/payment/place-order-v2) ### Fulfillment How an order's items reach the buyer — shipped to an address, picked up in store, or delivered on a schedule. The fulfillment type is set per cart or shipment before a shipping method is chosen. Used in: [Shipping & Fulfillment](/api-reference/shipment-configuration/shipping-and-fulfillment) ### Shipping method A specific delivery option for a shipment (e.g. standard or expedited) with its own price. Available methods appear in `cart.shipments[].shipping_method_options` after shipping info is set, and the destination records the chosen one. Methods are address-specific — changing the address clears the selection. Used in: [Shipping & Fulfillment](/api-reference/shipment-configuration/shipping-and-fulfillment) ### Promo code A merchant discount code applied to a cart through the Promotions API. A `200` response does not guarantee the code was accepted — re-read the cart afterward and compare the field the promo actually moves. Used in: [Promotions](/api-reference/promotions/) ### Express checkout Payment paths that skip manual card entry using a wallet or buy-now-pay-later provider — [Google Pay](/api-reference/payment/express-checkout/google-pay/complete-order), [PayPal Express](/api-reference/payment/express-checkout/paypal/start), Click to Pay, and [Klarna](/api-reference/payment/express-checkout/klarna/start). Each has its own endpoint under the payment surface. Used in: [Express checkout](/api-reference/payment/express-checkout/) ### Consent A merchant-required agreement (terms of sale, warranty, delivery acknowledgment) the buyer must accept before an order is placed. Fetch required consents with Get Consents and record acceptance with Set Consents; unsigned required-explicit consents are rejected at order completion. Used in: [Get Consents](/api-reference/checkout/get-consents) · [Set Consents](/api-reference/checkout/set-consents) ## Payment terms ### Encrypted card Card data after JWE encryption with Firmly's public key. The encrypted blob travels through the destination's servers but the cleartext PAN never does. Passed as `encrypted_card` in `place-order`. Used in: [Get Payment Public Key](/api-reference/payment/get-public-key) ### JWE JSON Web Encryption — the format used for encrypting card data. Firmly uses `RSA-OAEP-256` for key wrapping and `A256GCM` for content encryption. Implementations exist in every major language. Used in: [Get Payment Public Key](/api-reference/payment/get-public-key) ### JWK JSON Web Key — the RSA public-key format returned by `GET /payment/key`. It carries `kty`, `n`, `e`, `use`, and a `kid`; use it to JWE-encrypt the card before placing an order. Used in: [Get Payment Public Key](/api-reference/payment/get-public-key) ### `kid` (key ID) An identifier for which Firmly public key was used to encrypt a card. Returned in the public-key response. Firmly rotates keys; always re-fetch before placing an order rather than caching long-term. Used in: [Get Payment Public Key](/api-reference/payment/get-public-key) ### Idempotency key A UUID generated by the destination, passed in the `Idempotency-Key` header on mutation calls. On the UCP protocol bridge, retrying with the same key returns the same result instead of duplicating the effect; the core REST endpoints accept the header but do not deduplicate on it today, so guard REST retries by re-reading state first. Use the same key on retries of the same logical attempt; new key only for a genuinely new attempt. Used in: [Errors & Conventions → Idempotency](/api-reference/errors-and-conventions) ### Vault token A long-lived reference to a saved card stored in Firmly's vault service. Used for repeat purchases without re-asking the buyer for card data. Used in: [Smart payment selection](/solutions/agentic-commerce/use-cases/smart-payment) ### Agentic Pay Firmly's payment path for agent-driven checkout, where Firmly acts as a network-token router: it enrolls the cardholder's card once, then routes tokenization and authorization to the right card network. Supports both a human-in-the-loop model (the cardholder approves each payment) and an autonomous, cardholder-not-present model (the agent transacts within a cardholder-authorized mandate). Used in: [Agentic Pay](/solutions/agentic-commerce/agentic-pay) ### PAN Primary Account Number — the full card number. With Firmly's JWE flow the cleartext PAN is encrypted client-side and never travels through the destination's servers in the clear. Used in: [Security Model](/foundations/security-model) ### Network token A card-network-issued token that stands in for the underlying card during a transaction. Agentic Pay retrieves network token credentials (token, expiry, cryptogram) at order completion; the token's last four can differ from the funding card's last four. Used in: [Agentic Pay](/solutions/agentic-commerce/agentic-pay) ### Cardholder-not-present A payment made when the cardholder is not actively present to approve it — for example, an autonomous agent transacting within a pre-authorized mandate. Agentic Pay supports this alongside cardholder-present (human-in-the-loop) checkout. Used in: [Agentic Pay](/solutions/agentic-commerce/agentic-pay) ## Protocol terms ### UCP Universal Commerce Protocol — Google's open standard for AI search surfaces to talk to commerce providers. Firmly's UCP bridge translates UCP calls into Firmly's underlying cart and checkout APIs. Used in: [Protocols](/solutions/agentic-commerce/protocols/) ### MCP Model Context Protocol — Anthropic's open standard for AI agents to invoke tools. Firmly's MCP server exposes commerce tools (search, cart, shipping, payment) the LLM can call iteratively. Used in: [Protocols](/solutions/agentic-commerce/protocols/) ### ACP Agentic Commerce Protocol — OpenAI's spec for agentic commerce in ChatGPT and Operator surfaces. Used in: [Protocols](/solutions/agentic-commerce/protocols/) ### MCP-Apps An extension of MCP that allows hosts (like ChatGPT or Claude) to render a widget UI alongside the conversation. Firmly's MCP server can act as an MCP-Apps host's commerce backend. Used in: [Protocols](/solutions/agentic-commerce/protocols/) ## Surface and UI terms ### Dropin Firmly's pre-built checkout widget — a Svelte-based UI hosted at a Firmly URL. Can be loaded as a top-level page (hosted checkout), embedded in an iframe (embedded checkout), or wrapped via the SDK. Renders cart, shipping, payment, and order confirmation. Used in: [Hosted checkout](/solutions/agentic-commerce/integration-patterns/hosted-checkout) · [Embedded checkout](/solutions/agentic-commerce/integration-patterns/embedded-checkout) ### Hosted checkout The pattern where Firmly hosts the entire checkout UI on a Firmly-owned page. The destination redirects the buyer to the dropin URL; after order placement the buyer lands on the merchant's confirmation page. Used in: [Hosted checkout](/solutions/agentic-commerce/integration-patterns/hosted-checkout) ### Embedded checkout The pattern where the dropin is rendered inside the destination's surface as an iframe. The two communicate via `window.postMessage`. Used in: [Embedded checkout](/solutions/agentic-commerce/integration-patterns/embedded-checkout) ### Headless / Deep link The pattern where the destination calls Firmly's REST API directly without any Firmly-rendered UI. The destination is the checkout UI, or the checkout has no UI at all. Used in: [Deep link / Headless](/solutions/agentic-commerce/integration-patterns/deep-link) ## Other ### `place-order` The atomic operation that submits a cart to the merchant as a real order. After success, `cart_status` becomes `submitted` and the merchant's order number appears in `platform_order_number`. Used in: [Place order (v2)](/api-reference/payment/place-order-v2) ### `thank_you_page` The merchant-side confirmation URL returned in the `place-order` response. This is where the buyer lands after a hosted-checkout flow. Distinct from any destination-side confirmation page. Used in: [Hosted checkout](/solutions/agentic-commerce/integration-patterns/hosted-checkout) ### Affiliate attribution The mechanism by which Firmly relays the originating destination to the merchant, so affiliate commissions and origination credit flow back to the destination — without manual reconciliation. Used in: [How Firmly Works](/how-firmly-works) ### Attribution The general practice of tagging each order with the originating destination's identifier so origination credit flows back to the right destination. See **Affiliate attribution** for the commission-relay case. Used in: [How Firmly Works](/how-firmly-works) ### TTL Time to live — how long a piece of state persists before it expires. Firmly's edge cart state has a 7-day TTL; browser-session tokens carry their own, shorter lifetime. Used in: [Cart Lifecycle](/api-reference/cart-management/cart-lifecycle) --- ### VCC (Virtual Card) A network-tokenized, purpose-scoped card credential provisioned for an autonomous purchase (used by Agentic Pay) so a merchant or PSP never receives a real cardholder PAN. ### V1 adapters Older (version 1) merchant-platform adapters. Some operations available on v2 adapters are not exposed by v1 adapters; pages note where behavior differs by adapter version. ### PCI scope The set of systems subject to PCI DSS controls because they handle cardholder data. Firmly's client-side JWE encryption keeps the destination's servers out of scope for the card number — no cleartext PAN passes through them. ## Related - [Concepts overview](/how-firmly-works) — for the architectural picture - [API Reference overview](/api-reference/) — for endpoint-level specifics - [Errors & Conventions](/api-reference/errors-and-conventions) — for envelope, idempotency, error codes --- # LineItem schema Each item in a cart is represented as a `LineItem`. Line items have a stable `line_item_id` (a UUID) that you use for subsequent update or remove calls. ## LineItem Individual product item in the cart. - `line_item_id` (string, required) — Unique item identifier within the cart (UUID). Use this value for subsequent update and remove calls. - `sku` (string, required) — Stock keeping unit for the selected variant. - `quantity` (integer, required) — Item quantity. - `price` (Amount, required) — Unit price of the item. See [Common types → Amount](/resources/schemas/common-types#amount). - `msrp` (Amount, required) — Manufacturer's suggested retail price (unit). - `line_price` (Amount, required) — Extended price for the line (unit price times quantity). - `image` (ImageObject, required) — Primary product image for the line. **properties** - `url` (string, required) — Image URL (absolute `http(s)` URL). - `alt` (string) — Alternative text. - `type` (string) — Image size hint. One of `preview`, `small`, `medium`, `large`, `default`, `video`. Defaults to `default`. - `aspect_ratio` (number) — Width-to-height ratio. - `width` (integer) — Intrinsic width in pixels. - `height` (integer) — Intrinsic height in pixels. - `position` (integer) — Ordering position when multiple images exist. - `srcset` (array) — Additional image renditions (each the same shape as the base image). - `base_sku` (string) — SKU of the parent product the variant belongs to. - `description` (string) — Human-readable product description. - `variant_description` (string) — Human-readable variant description (for example, "XS / Orange"). - `variant_handles` (array) — Selected variant option handles. - `universal_product_id` (string) — Universal product identifier (for example, a GTIN/UPC), when the merchant provides one. - `discount` (Amount) — Discount applied to the unit price. - `line_discount` (Amount) — Discount applied to the line (unit times quantity). - `discounts` (array) — Named discounts applied to the line. **properties** - `code` (string, required) — Discount code. - `description` (string, required) — Human-readable discount description. - `line_item_tax` (Amount) — Tax attributed to the line. - `requires_shipping` (boolean) — Whether the item requires shipping. Defaults to `true`. - `requires_scheduled_delivery` (boolean) — Whether the item requires a scheduled-delivery selection. - `taxable` (boolean) — Whether the item is taxable. - `fixed_quantity` (boolean) — When `true`, the quantity cannot be changed. - `parent_line_item_id` (string) — Line item ID (UUID) of the parent line, for nested/bundled items. - `platform_line_item_id` (string) — Identifier for the line item in the merchant's underlying commerce platform. - `extended_attributes` (object) — Additional merchant-specific attributes for the line. - `properties` (object) — Free-form line-level properties (for example, personalization inputs). - `messages` (array) — Display messages attached to the line. **properties** - `text` (string, required) — Message text. - `type` (string) — Message category. One of `promotion`, `stock`, `badge`, `banner`, `shipping`, `urgency`, `info`. ```json { "line_item_id": "8f3a2b1c-1d2e-4a5b-9c8d-1a2b3c4d5e6f", "sku": "WS12-XS-Orange", "base_sku": "WS12", "description": "Radiant Tee", "variant_description": "XS / Orange", "quantity": 2, "price": { "value": 29.99, "currency": "USD", "number": 2999, "symbol": "$" }, "msrp": { "value": 34.00, "currency": "USD", "number": 3400 }, "line_price": { "value": 59.98, "currency": "USD", "number": 5998 }, "line_discount": { "value": 8.02, "currency": "USD", "number": 802 }, "image": { "url": "https://staging.luma.gift/products/radiant-tee.jpg", "alt": "Radiant Tee", "type": "default" }, "requires_shipping": true, "platform_line_item_id": "1452" } ``` --- ## Related - [Schemas overview](/resources/schemas/) - [API Reference](/api-reference/) - [Errors & Conventions](/api-reference/errors-and-conventions) --- # Migrating from another commerce vendor If you're moving from another commerce orchestration vendor or rolling off a homegrown integration, this guide is the rough translation layer. It's not platform-specific — every commerce vendor has its own quirks — but it covers the shape of the migration. > **Note** > **Written for destinations.** This page addresses the party that *calls* the API (a destination, platform, or agent) — it talks about App IDs, sandbox credentials, and swapping endpoints. If you're a **merchant** connecting your store, start at [For Merchants](/for-merchants/) instead; there's no code for you to migrate. For platform-specific guidance, see [Supported platforms](/for-merchants/supported-platforms). ## Conceptual mapping | You probably have today | Firmly equivalent | |---|---| | A way to authenticate as a client app | [Browser session](/api-reference/authentication/browser-session) or [server-to-server](/api-reference/authentication/server-to-server) | | A product / catalog search API | [Discovery search](/api-reference/discovery/search) and [Catalog](/api-reference/catalog/) | | A cart object with line items | [Cart management](/api-reference/cart-management/) | | Shipping address + method selection | [Set shipping info](/api-reference/checkout/set-shipping-info) + [Set shipping method](/api-reference/shipment-configuration/set-shipping-method) | | A payment tokenization step | [Get payment public key](/api-reference/payment/get-public-key) + JWE encryption client-side | | A "place order" / "submit order" call | [Place order (v2)](/api-reference/payment/place-order-v2) | | Per-merchant API integrations | Single integration → access all Firmly-connected merchants | | Tax + shipping calculation on your side | Merchant-driven calculation via Firmly (you don't compute) | ## What changes structurally ### 1. One integration, many merchants If your previous vendor required per-merchant authentication or per-merchant API setup, that goes away. With Firmly, the destination has a single `_appId`. The merchant is identified by the `domain` parameter in each call. Adding a new merchant is a Firmly-side configuration change — no code on the destination side. ### 2. Cart state lives at Firmly's edge Cart state is stored in Firmly's edge session store. Your previous vendor may have required you to maintain cart state on your side; with Firmly you can — but you don't have to. The cart can be retrieved at any time via [Get Cart](/api-reference/cart-management/get-cart). ### 3. Payment data flow is JWE-encrypted, not PCI-on-your-side Card data is encrypted client-side using Firmly's RSA public key before transit. Your code handles JWE encryption with a Firmly-provided public key; the encrypted blob travels through your servers but you never see (or have to PCI-scope) the plaintext PAN. If your previous integration used a hosted-checkout pattern (the user filled card data on the vendor's page), the equivalent on Firmly is [Hosted checkout](/solutions/agentic-commerce/integration-patterns/hosted-checkout). ### 4. Carts are scoped to one merchant Firmly carts hold multi-product items **from a single merchant**. To reach several merchants, place one order per merchant. ### 5. Firmly's scope ends at order placement Once `place-order` returns success, Firmly's role is done. Anything beyond that lives entirely on the merchant's side. ## What stays the same - HTTPS REST patterns - JSON request and response bodies - Standard HTTP status codes - Authentication via header - Idempotency keys for safety on mutations - Multi-step cart and checkout flow If your previous vendor was REST-based, the call patterns and conventions will feel familiar. The data shapes differ; the protocol shape doesn't. ## Migration sequence A typical migration goes through these phases: 1. **Sandbox setup** — get your sandbox App ID and a test merchant. Run [Sandbox setup](/for-destinations/sandbox-setup) end-to-end to confirm connectivity 2. **Catalog translation** — map your existing product references to Firmly's discovery + catalog APIs 3. **Cart translation** — map your cart object to Firmly's [cart shape](/api-reference/cart-management/cart-lifecycle) 4. **Payment translation** — implement JWE encryption client-side. See [Get Payment Public Key](/api-reference/payment/get-public-key) 5. **Place-order translation** — replace your "submit order" call with [Place order (v2)](/api-reference/payment/place-order-v2). Send `Idempotency-Key` on every attempt, and guard retries by re-reading `cart_status` first (see [Idempotency](/api-reference/errors-and-conventions#idempotency)) 6. **Cutover** — when sandbox runs cleanly, swap sandbox `_appId` for production `_appId` and swap test merchant domains for live merchant domains. No deployment of a "production SDK" — it's the same API, different credentials ## Things to watch for during migration - **Currency formatting**: money values come as a decimal in `value` (e.g. `99.99`) and integer cents in `number` (e.g. `9999`), plus a `symbol` and `currency`. Display uses `value`; do arithmetic on `number` to avoid floating-point rounding - **Multi-shipment**: Even single-product carts can have multiple `shipment_id`s if the merchant ships from different warehouses. Walk each shipment for availability and method - **Promo behavior**: A 200 response on `add-promo-codes` doesn't mean the code applied — re-read the cart and check the field the promo moves (`sub_total` for line-item discounts, `total` / `cart_discount` for order-level and free-shipping promos) - **Idempotency keys**: Use the same key on retries of the same attempt; new key only on a genuinely new attempt. Note the key is deduplicated only on the UCP protocol bridge today — on the core REST endpoints, re-read the cart before retrying - **Order placement is atomic**: Once `place-order` returns 200 with `cart_status: "submitted"`, the order is at the merchant — never retry after a `submitted` response ## When you might NOT want to migrate - Your previous integration involves a single merchant on a stable in-house platform — direct integration may stay simpler than going through a layer - You need features Firmly doesn't have (subscriptions, B2B procurement workflows) - Your destination is a category Firmly doesn't serve today (travel bookings, ticketing, healthcare prescriptions) In those cases, the migration cost outweighs the benefit. Talk to [Firmly](/contact) if you're not sure. --- ## Related - [How Firmly Works](/how-firmly-works) — the conceptual map - [Sandbox setup](/for-destinations/sandbox-setup) — first stop in any migration - [Cart API guide](/cookbook/full-cart-api-guide) — the multi-step cart flow in detail - [Errors & Conventions](/api-reference/errors-and-conventions) — recovery patterns --- # Request schemas Schemas for the request bodies sent to Firmly's mutation endpoints. For the response shape, see the [response schemas](/resources/schemas/shopping-cart) — all cart-mutation endpoints return a cart object. ## Cart Operations ### AddLineItemRequest - `add_to_cart_ref` (object, required) — Product reference **properties** - `variant_id` (string, required) — Product variant ID - `product_id` (string) — Product ID - `variant_handles` (array) — Variant handle identifiers - `quantity` (integer, required) — Quantity to add (minimum: 1) ### UpdateLineItemRequest - `quantity` (integer, required) — New quantity (0 to remove) ## Fulfillment ### SetFulfillmentTypeRequest - `shipment_id` (string, required) — Target shipment ID - `fulfillment_type` (string, required) — New fulfillment type enum - `location_id` (string) — Required for PICKUP_IN_STORE ### SetShippingMethodRequest - `shipment_id` (string, required) — Target shipment ID - `shipping_method_id` (string, required) — Selected method ID ## Addons ### SetAddonSelectionsRequest - `selections` (array, required) — Array of addon selections **properties** - `addon_id` (string, required) — Addon to select - `selected_line_item_ids` (array) — Items to apply to - `selected_child_ids` (array) — Child addon selections ## Promotions ### AddPromoCodesRequest - `promo_codes` (array, required) — Array of 1–10 promotional codes to apply --- ## Related - [Schemas overview](/resources/schemas/) - [API Reference](/api-reference/) - [Errors & Conventions](/api-reference/errors-and-conventions) --- # Resources Reference material that supports the guides rather than describing a single endpoint: the object [schemas](/resources/schemas/) the API returns, a [glossary](/resources/glossary) of Firmly terms, the [changelog](/resources/changelog), and notes on [migrating from another commerce vendor](/resources/migrating-from-another-commerce-vendor). - [Schemas](/resources/schemas/) - [Changelog](/resources/changelog) - [Glossary](/resources/glossary) - [Migrating from another commerce vendor](/resources/migrating-from-another-commerce-vendor) --- # Schemas This section is the canonical reference for every object Firmly's API returns or accepts. Each schema is on its own page so you can link to it directly. If you're looking for the **endpoints that return these schemas**, see the [API Reference](/api-reference/). If you're looking for **how the API behaves** (errors, idempotency, pagination), see [Concepts](/how-firmly-works) and [Errors & Conventions](/api-reference/errors-and-conventions). ## Core objects - [ShoppingCartV2](/resources/schemas/shopping-cart) — The main cart object returned by most cart-mutation endpoints. - [LineItem](/resources/schemas/line-item) — An individual item within a cart. - [Shipment](/resources/schemas/shipment) — Groups line items by fulfillment when items ship separately. ## Fulfillment - [Fulfillment schemas](/resources/schemas/fulfillment) — FulfillmentType, ShippingMethod, and PickupLocation — how an order is delivered, shipped, or picked up in store. ## Add-ons - [Addon schemas](/resources/schemas/addons) — AddonsContainer, AddonOffer, AddonSelection — warranties, gift wrap, gift messages, protection plans. ## Primitive types - [Common types](/resources/schemas/common-types) — Amount, Address, TimeSlot — primitive types referenced throughout the other schemas. ## Requests and errors - [Request schemas](/resources/schemas/request-schemas) — Request bodies for cart, fulfillment, addon, and promotion operations. - [Error response](/resources/schemas/error-response) — The shape of error responses. For the full error code catalog and recovery patterns, see [Errors & Conventions](/api-reference/errors-and-conventions). ## Schema conventions - **Field names are `snake_case`** across the cart schemas (e.g., `line_item_id`, `cart_status`, `add_to_cart_ref`) — see each schema page for the exact fields - **Money values** carry a decimal amount in `value` (e.g. `54.00`), integer cents in `number` (e.g. `5400`), plus `symbol` and `currency`. Display uses `value`; do arithmetic on `number` — see [Common types → Amount](/resources/schemas/common-types) - **Required vs optional fields** are marked on each schema page - **Field-level descriptions** match what the API actually returns (validated against QA traffic) ## Where each schema is returned | Schema | Endpoints that return it | |---|---| | ShoppingCartV2 | Every cart-mutation endpoint, `GET /cart` | | LineItem | Nested inside `ShoppingCartV2.line_items[]` | | Shipment | Nested inside `ShoppingCartV2.shipments[]` | | FulfillmentType | Nested inside `Shipment.fulfillment_type` | | ShippingMethod | Returned on the cart in `ShoppingCartV2.shipping_method_options[]` and `shipping_method`; also per-shipment in `Shipment.shipping_method_options[]` | | PickupLocation | Returned by [get-availability](/api-reference/shipment-configuration/get-availability) when BOPIS is supported | | CartNotice | Nested inside `ShoppingCartV2.notices[]` | | AddonsContainer | Nested inside `ShoppingCartV2.addons` | | AddonOffer | Returned by addon-related endpoints | | AddonSelection | Nested inside `AddonsContainer.selections[]`; also sent as the request body to [addon selection endpoints](/resources/schemas/request-schemas#addons) | | Amount | Used throughout for all monetary values | | Address | Used in shipping and billing info | | TimeSlot | Used in scheduled-delivery contexts | | Error response | Returned on any non-2xx HTTP response | --- # Shipment schema When a cart contains items that ship from different warehouses or have different fulfillment timelines, Firmly groups them into shipments. Each shipment has its own `shipment_id` for availability and method selection. See [Shipping & Fulfillment](/api-reference/shipment-configuration/shipping-and-fulfillment). ## Shipment Represents a group of items with the same fulfillment method. - `shipment_id` (string, required) — Unique shipment identifier (UUID). Echo it back exactly as returned when calling [Set Fulfillment Type](/api-reference/shipment-configuration/set-fulfillment-type), [Set Shipping Method](/api-reference/shipment-configuration/set-shipping-method), or [Get Availability](/api-reference/shipment-configuration/get-availability). The request side accepts any non-empty string, so treat the value as opaque rather than parsing it. - `fulfillment_type` (FulfillmentType, required) — Current fulfillment method for this shipment - `fulfillment_type_options` (array) — Available fulfillment options for these items **properties** - `FulfillmentType` (object) — See FulfillmentType schema - `line_item_ids` (array, required) — Array of line item IDs in this shipment - `shipping_method_options` (array) — Available shipping methods (for SHIP_TO_ADDRESS) **properties** - `ShippingMethod` (object) — See ShippingMethod schema - `shipping_method` (ShippingMethod) — Selected shipping method - `selected_location` (PickupLocation) — Selected store for pickup (PICKUP_IN_STORE) - `selected_date` (string) — Selected delivery/pickup date (YYYY-MM-DD) - `selected_time_slot` (TimeSlot) — Selected time window for delivery/pickup - `notes` (string) — Delivery instructions or special requests **Example - Standard Shipping** ```json { "shipment_id": "f05a8032-9bc5-8e50-d672-9bfa7253485e", "fulfillment_type": { "id": "SHIP_TO_ADDRESS", "name": "Standard Delivery", "description": "Ship to customer address" }, "line_item_ids": ["cfc9f563-f860-237d-9a0c-d8970ee710f6", "bb00bef1-df27-b9a2-fed9-3bac13b1893f"], "shipping_method_options": [ { "id": "standard", "description": "Standard Shipping (5-7 days)", "price": { "value": 5.99, "currency": "USD" } } ], "shipping_method": { "id": "standard", "description": "Standard Shipping (5-7 days)", "price": { "value": 5.99, "currency": "USD" } } } ``` **Example - Scheduled Delivery** ```json { "shipment_id": "ee74829d-e8b1-a875-38be-5e70b1b5a9f1", "fulfillment_type": { "id": "SCHEDULED_DELIVERY", "name": "Scheduled Delivery", "description": "Choose delivery date and time" }, "line_item_ids": ["5fa6a3db-b4a7-c9da-fa93-562f13c27e6e"], "selected_date": "2024-02-15", "selected_time_slot": { "slot_id": "morning", "start_time": { "utc": "2024-02-15T17:00:00Z", "local": "2024-02-15T09:00:00", "local_timezone": "America/Los_Angeles" }, "end_time": { "utc": "2024-02-15T20:00:00Z", "local": "2024-02-15T12:00:00", "local_timezone": "America/Los_Angeles" }, "description": "9:00 AM - 12:00 PM" } } ``` --- ## Related - [Schemas overview](/resources/schemas/) - [API Reference](/api-reference/) - [Errors & Conventions](/api-reference/errors-and-conventions) --- # ShoppingCartV2 schema The `ShoppingCartV2` object is the canonical cart payload returned by most cart-mutation endpoints. It contains line items, shipments, addons, pricing, and metadata. ## ShoppingCartV2 The main cart object containing all cart information. - `cart_id` (string, required) — Unique cart identifier (UUID). - `platform_id` (string, required) — Identifier of the merchant's underlying commerce platform. The literal value varies by merchant. - `shop_id` (string, required) — Shop identifier (merchant domain). - `schema_version` (string, required) — The schema version ("2.0"). - `line_items` (array, required) — Array of cart items. See [LineItem](/resources/schemas/line-item). - `total` (Amount, required) — Final total including all costs. - `urls` (object, required) — Post-order redirect URLs. The object is always present; its members are optional. **properties** - `thank_you_page` (string) — Order confirmation ("thank you") page URL. - `order_status_page` (string) — Order status page URL. - `display_name` (string) — Merchant display name. - `cart_status` (string) — Current cart status. One of `active`, `pending`, `submitted`, `item_not_shippable`, `checkout_blocked`. - `shipments` (array) — Multi-shipment array for grouped fulfillment. See [Shipment](/resources/schemas/shipment). - `shipping_method_options` (array) — Cart-level shipping options the buyer can choose from. Each is a [ShippingMethod](/resources/schemas/fulfillment#shippingmethod). - `shipping_method` (object) — The selected cart-level shipping method. See [ShippingMethod](/resources/schemas/fulfillment#shippingmethod). - `addons` (object) — Container for addon offers and selections. See [Addon schemas](/resources/schemas/addons). **properties** - `offers` (array) — Available addon services. - `selections` (array) — Currently applied addons. - `sub_total` (Amount) — Subtotal before discounts, shipping, and taxes. - `cart_discount` (Amount) — Total discount amount from promotions. - `shipping_total` (Amount) — Total shipping costs across all shipments. - `addon_total` (Amount) — Total cost of selected addons. - `tax_total` (Amount) — Total tax amount. - `fees` (array) — Merchant-imposed fees (e.g. recycle, regulatory), if any. See [Fee](/resources/schemas/common-types#fee). - `fee_total` (Amount) — Total of all fees. - `shipping_info` (ShippingInfo) — Buyer shipping address — see [Common types → ShippingInfo](/resources/schemas/common-types#shippinginfo). - `billing_info` (AddressInfo) — Buyer billing address — see [Common types → Address](/resources/schemas/common-types#address). - `coupons` (array) — Applied promotional codes. - `notices` (array) — Refresh-related notices about items, promotions, shipping, or prices. See [CartNotice](#cartnotice). - `payment_summary` (object) — Summary of the payment method associated with the cart (for example, masked card or wallet details). - `platform_order_number` (string) — Order number assigned by the merchant's underlying commerce platform once the cart is submitted. - `custom_properties` (object) — Free-form merchant- or integration-specific properties. ```json { "cart_id": "550e8400-e29b-41d4-a716-446655440000", "platform_id": "example_commerce", "shop_id": "staging.luma.gift", "schema_version": "2.0", "display_name": "Luma Gift Store", "cart_status": "active", "line_items": [], "shipments": [], "shipping_method_options": [ { "id": "standard", "description": "Standard Shipping", "price": { "value": 5.99, "currency": "USD", "number": 599 }, "estimated_delivery": "3-5 business days" } ], "addons": { "offers": [], "selections": [] }, "sub_total": { "value": 99.99, "currency": "USD", "number": 9999 }, "cart_discount": { "value": 10.00, "currency": "USD", "number": 1000 }, "shipping_total": { "value": 5.99, "currency": "USD", "number": 599 }, "addon_total": { "value": 4.99, "currency": "USD", "number": 499 }, "tax_total": { "value": 8.25, "currency": "USD", "number": 825 }, "fees": [{ "description": "Recycle fee", "value": 2.00, "currency": "USD", "number": 200 }], "fee_total": { "value": 2.00, "currency": "USD", "number": 200 }, "total": { "value": 111.22, "currency": "USD", "number": 11122 }, "coupons": ["SAVE10"], "notices": [ { "code": "PRICE_INCREASED", "severity": "warning", "item_id": "8f3a2b1c-1d2e-4a5b-9c8d-1a2b3c4d5e6f", "details": { "description": "Price changed since the item was added", "old_value": { "value": 24.99, "currency": "USD" }, "new_value": { "value": 29.99, "currency": "USD" } } } ], "urls": { "thank_you_page": "https://staging.luma.gift/checkout/thank-you", "order_status_page": "https://staging.luma.gift/orders/status" } } ``` ## CartNotice A refresh-related notice surfaced on `ShoppingCartV2.notices[]` when an item, promotion, shipping option, or price changes after the cart was built. - `code` (string, required) — Notice code. **Enum values:** - `ITEM_NOT_SHIPPABLE` - `ITEM_OUT_OF_STOCK` - `PROMO_EXPIRED` - `PROMO_NOT_APPLICABLE` - `SHIPPING_NOT_AVAILABLE` - `PRICE_INCREASED` - `PRICE_DECREASED` - `severity` (string, required) — Notice severity. One of `warning`, `info`, `error`. - `item_id` (string) — Identifier of the line item the notice relates to, when applicable. - `details` (object) — Additional context for the notice. **properties** - `description` (string) — Human-readable description. - `promo_code` (string) — Related promotion code, for promo notices. - `old_value` (Amount) — Previous value, for price-change notices. - `new_value` (Amount) — New value, for price-change notices. - `reason` (string) — Machine-readable reason, when provided. --- ## Related - [Schemas overview](/resources/schemas/) - [API Reference](/api-reference/) - [Errors & Conventions](/api-reference/errors-and-conventions) --- # AI Deal & Coupon Hunting > **Note** > This is one common pattern customers build with Firmly. Many other shapes are possible — adapt or combine use cases to fit your specific build. The user gives the agent a target ("running shoes under $80, with any coupons applied"). The agent searches the connected merchants, finds candidates that match the price target, applies any available promo codes during cart-building, and completes checkout. This scenario exercises Firmly's [Promotions API](/api-reference/promotions/). It's a strong fit when the agent is positioned as a "savings agent" or when the destination wants to differentiate on price optimization. ## Recommended setup | Choice | Default | Why | |---|---|---| | **Integration pattern** | [Deep Link / Headless](/solutions/agentic-commerce/integration-patterns/deep-link) | Agent needs to inspect cart totals before/after promo application | | **Protocol** | [MCP](/solutions/agentic-commerce/protocols/) or direct REST | MCP tools include `apply_coupon` natively | | **Flow shape** | Single- or multi-product | Either works — apply promos at the cart level | ## API sequence | # | Endpoint | Purpose | |---|---|---| | 1 | [Browser session](/api-reference/authentication/browser-session) | Auth | | 2 | [Discovery search](/api-reference/discovery/search) | Find candidates within the price target | | 3 | [Add line item](/api-reference/cart-management/add-line-item) | Add the selected item | | 4 | [Add promo codes](/api-reference/promotions/add-promo-codes) | Apply one or more codes to the cart | | 5 | [Get cart](/api-reference/cart-management/get-cart) | Re-inspect totals — confirm the discount applied | | 6 (conditional) | [Clear promo codes](/api-reference/promotions/clear-promo-codes) | Only if the code didn't qualify — remove and try another, then re-read the cart | | 7 | [Set shipping info](/api-reference/checkout/set-shipping-info) | Address; populates the `shipments` array with `shipping_method_options` | | 8 | [Get shipping availability](/api-reference/shipment-configuration/get-availability) | *(Optional)* Delivery dates / time slots / pickup locations | | 9 | [Set shipping method](/api-reference/shipment-configuration/set-shipping-method) | Pick a method from the shipment's `shipping_method_options` | | 10 | … then the standard checkout tail | Get/set consents → set billing info → get payment public key → complete order (v2, with `encrypted_card`). Because the cart was built above, finalize it with [`complete-order`](/api-reference/payment/complete-order-v2), not the one-shot `place-order`. See the [single-product flow](/solutions/agentic-commerce/flows/single-product-purchase#the-implementation-steps-phase-4-broken-out) | ## Agent logic to consider - **Validate the discount applied.** Some codes look valid but fail merchant-side rules (minimum cart value, category exclusions). Always re-read the cart after applying and compare the totals before and after. Depending on how the merchant models the promotion, the change can appear in `sub_total`, `total`, or a discount line rather than only in `sub_total` — compare `total` to be sure the discount actually landed. - **Stack carefully.** Most merchants disallow stacking. If applying code B silently removes code A, the destination's agent should detect and surface that. - **Surface the actual savings to the user.** "I found this for $69.99 with code SAVE10" is a stronger UX than just placing the order. --- ## Related - [Promotions overview](/api-reference/promotions/) — full endpoint catalog - [Cart lifecycle](/api-reference/cart-management/cart-lifecycle) — cart state and the notices surfaced when a promo expires or doesn't apply - [AI Shopping Copilot](/solutions/agentic-commerce/use-cases/shopping-copilot) — base flow without promo logic - [Errors & conventions](/api-reference/errors-and-conventions) — handling failed promo applications --- # AI Shopping Copilot > **Note** > This is one common pattern customers build with Firmly. Many other shapes are possible — adapt or combine use cases to fit your specific build. A user describes what they want in natural language. The AI agent searches across connected merchant catalogs, picks a product (or asks the user to choose), assembles the cart, and places the order against the merchant's native platform. This is the default agentic commerce scenario. If you're not sure which scenario fits, start here — every other scenario on this site is a specialization of this one. ## Recommended setup | Choice | Default | Why | |---|---|---| | **Integration pattern** | [Deep Link / Headless](/solutions/agentic-commerce/integration-patterns/deep-link) | Agent has full control of the conversational flow | | **Protocol** | [MCP](/solutions/agentic-commerce/protocols/) or direct REST | MCP lets the agent expose Firmly as tools; REST is universal | | **Auth** | [Browser session](/api-reference/authentication/browser-session) for per-user; [S2S](/api-reference/authentication/server-to-server) for backend | Pick based on where the agent runs | | **Flow shape** | [Single-product](/solutions/agentic-commerce/flows/single-product-purchase) | Multi-product is just steps 3–4 repeated per item | ## API sequence Every call below is a link to the canonical reference. Payload examples live in the API Reference — this page is the order of operations. | # | Endpoint | Purpose | |---|---|---| | 1 | [Browser session](/api-reference/authentication/browser-session) | Bootstrap auth, get a JWT | | 2 | [Discovery search](/api-reference/discovery/search) | Find candidate products across merchants | | 3 | [Get product](/api-reference/catalog/get-product) | Fetch detail + variants for the chosen item | | 4 | [Add line item](/api-reference/cart-management/add-line-item) | Create the cart (implicit) and add the item | | 5 | [Set shipping info](/api-reference/checkout/set-shipping-info) | Address; populates `shipments` array with `shipping_method_options` | | 6 | [Get shipping availability](/api-reference/shipment-configuration/get-availability) | *(Optional)* Delivery dates / time slots / pickup locations | | 7 | [Set shipping method](/api-reference/shipment-configuration/set-shipping-method) | Pick a method from the shipment's `shipping_method_options` | | 8 | [Set consents](/api-reference/checkout/set-consents) | Merchant-required consents (terms, warranty acknowledgments) | | 9 | [Set billing info](/api-reference/checkout/set-billing-info) | Billing address | | 10 | [Get payment public key](/api-reference/payment/get-public-key) | RSA key for card encryption | | 11 | [Complete order (v2)](/api-reference/payment/complete-order-v2) | Finalize the cart built in steps 4–9 (body: `encrypted_card` + `billing_info`) | For multi-product, repeat steps 3–4 per item (fetch the product, then add the line item). For multi-shipment (same merchant, different shipments), repeat steps 6–7 per `shipment_id`. Because this sequence builds the cart across steps 4–9, step 11 finalizes it with [`complete-order`](/api-reference/payment/complete-order-v2) (existing cart). Reach for [`place-order`](/api-reference/payment/place-order-v2) only on the one-shot path — it creates the cart and places the order in a single call with an `items[]` array, replacing steps 4–11. ## Runnable example The [Advanced Checkout Guide](/cookbook/advanced-checkout-guide) is this sequence as a complete Node script — start there for working code. --- ## Related - [Flows → Single-product purchase](/solutions/agentic-commerce/flows/single-product-purchase) — annotated walkthrough - [Flows → Multi-product purchase](/solutions/agentic-commerce/flows/multi-product-purchase) — iterative cart-building - [Integration patterns](/solutions/agentic-commerce/integration-patterns/) — pick where the checkout UI lives - [Errors & conventions](/api-reference/errors-and-conventions) — recovery patterns for every call above --- # AI surfaces AI surfaces — conversational AI products, AI-driven search and answer engines, AI assistants embedded in apps — are where users increasingly ask to buy things. The destination is the AI surface itself: a chat thread, a generative search result, an in-app assistant. The agent responds to a purchase intent by calling commerce APIs in the background and presenting the result back inside the conversation. The Firmly platform turns any AI surface into a transactional one without per-merchant integration on the AI surface's side. ## What this category covers AI surfaces as a destination category includes: | Surface type | What it does | |---|---| | **Conversational AI products** | Chat-based AI products where commerce shows up alongside other interaction types | | **AI answer engines and generative search** | Search surfaces where results need to become transactable, not just informational | | **In-app AI assistants** | AI integrated inside another product (workplace, productivity, lifestyle) that needs commerce as one capability | | **Autonomous agents** | AI that completes purchases on the user's behalf with explicit consent and constraints — see [Agentic Pay](/solutions/agentic-commerce/agentic-pay) | ## Why AI surfaces are a Firmly destination Conversational commerce introduces challenges an AI surface usually doesn't want to solve in-house: - **Multi-merchant discovery** — a single conversation might span products from many merchants; one Firmly integration reaches all of them, with no per-merchant build on the AI surface's side. - **Conversation-aware error handling** — when the cart is blocked (out of stock, address invalid, payment declined), the agent needs to recover gracefully inside the conversation, not break the user back to a form. - **Consent and disclosure** — the user has to know what they're authorizing, especially for autonomous purchases. See [Consent & Disclosure](/solutions/agentic-commerce/consent-and-disclosure). - **Protocol heterogeneity** — different agent stacks speak different protocols. Firmly speaks UCP, MCP, ACP, and direct REST. - **Payment for cardholder-not-present** — when an autonomous agent purchases on the user's behalf, network-token-based mandate payment is essential. See [Agentic Pay](/solutions/agentic-commerce/agentic-pay). ## Which Firmly solutions apply | Solution | When to use it | |---|---| | **[Agentic Commerce](/solutions/agentic-commerce/)** | The primary solution for AI-surface destinations. Designed end-to-end for AI-agent-driven commerce — protocols, errors, consent, payments. | | **[Branded Commerce](/solutions/branded-commerce/)** | When the AI surface routes the user to a partner-branded checkout (e.g., for a guided purchase flow). | ## Recommended starting points When you integrate (see [Status today](#status-today) for current availability), these are the defaults to reach for: | Choice | Default | Why | |---|---|---| | **Auth** | [Browser session](/api-reference/authentication/browser-session) | Per-conversation authentication; user-scoped session token | | **Protocol** | [MCP](/solutions/agentic-commerce/protocols/) for chat / agent-call surfaces; **direct REST** for backend agents | MCP exposes Firmly tools the LLM can call iteratively; REST is the canonical fallback | | **Integration pattern** | [Embedded checkout](/solutions/agentic-commerce/integration-patterns/embedded-checkout) or [deep link / headless](/solutions/agentic-commerce/integration-patterns/deep-link) | Embedded for visual rendering; deep link / headless for chat-only | | **Payment** | Card via JWE; Agentic Pay for autonomous flows | Standard for user-present; mandate-based for user-absent | ## Status today As a destination category, AI surfaces are a roadmap buildout. The underlying agentic-commerce platform — protocols, payment, error handling, consent — is production-ready and documented at [Agentic Commerce](/solutions/agentic-commerce/). Surface-specific buildout (per-AI-surface integration patterns, MCP server templates, agent-stack guidance) is scoped per engagement. ## What to think about - **Discovery scope.** AI surfaces typically curate the merchant set rather than expose every merchant on Firmly. Discuss the scope during onboarding. - **Error patterns.** Conversational commerce has unique error states (stock changed mid-conversation, payment declined, address invalid). See [Errors & Recovery](/solutions/agentic-commerce/operations/errors) for the patterns. - **Going live readiness.** Before flipping production traffic, work through the [Going Live](/solutions/agentic-commerce/operations/going-live) checklist. --- ## Related - [Agentic Commerce overview](/solutions/agentic-commerce/) - [Agentic Pay](/solutions/agentic-commerce/agentic-pay) — mandate-based payment for autonomous purchases - [Consent & Disclosure](/solutions/agentic-commerce/consent-and-disclosure) - [Protocols overview](/solutions/agentic-commerce/protocols/) — UCP, MCP, ACP, REST --- # Ad Commerce > **Note** > **What's in this section:** Use Cases (which scenario you're building), Flows (the API sequence in detail), Integration Patterns (in-ad checkout vs post-click landing), and Operations (sandbox + going live). ## What this solution enables Ad Commerce turns advertising surfaces — display ads, video, social posts, and sponsored placements — into a complete purchase experience: the buyer buys the moment they're interested, without being redirected away. ![How Ad Commerce fits — the ad surface hosts checkout in place, Firmly runs the commerce backend, and the merchant stays the seller of record](/images/ad-commerce/how-ad-commerce-fits.svg) ## How Ad Commerce fits within Firmly The Firmly platform is shared across all solutions — the cart, discovery, payment, tax, shipping, and order-placement APIs are the same. Ad Commerce is the solution-level packaging of those features for a specific kind of integration shape and destination type. The Ad Commerce section follows the same structure as Agentic Commerce; see [Agentic Commerce](/solutions/agentic-commerce/) for the most fully worked example. ## What's documented - [Why Firmly for Ad Commerce](/solutions/ad-commerce/why-firmly) — Positioning, scope, and what's specific to Ad Commerce versus the shared platform. - [Use Cases](/solutions/ad-commerce/use-cases/) — The feature menu — what destinations and merchants can use. - [Flows](/solutions/ad-commerce/flows/single-product-purchase) — End-to-end user flows annotated with the canonical API sequence. - [Integration Patterns](/solutions/ad-commerce/integration-patterns/) — In-ad checkout or post-click landing — pick the surface that fits. - [Operations](/solutions/ad-commerce/operations/) — Sandbox setup and operational guidance. --- ## Related - [Solutions overview](/solutions/) — all Firmly solutions - [Destinations](/solutions/destination-surfaces/) — which destination types use which solution - [How Firmly Works](/how-firmly-works) — the underlying platform - [API Reference](/api-reference/) — every endpoint --- # Ads Unlike publisher sites — where editorial content sits next to commerce links — ad networks sell *placement* across third-party properties: an in-feed card on a news app, a sponsored result on an app store, a video pre-roll on a streaming service, a sidebar unit on a social feed. The buyer doesn't arrive on the ad network's property; they arrive on whichever app or site the ad network filled inventory for. When commerce can complete *inside* the ad placement (or in a partner-branded surface the ad routes to), the entire ad-to-purchase friction disappears. ## What this category covers Ads as a destination category includes: | Type | What it does | |---|---| | **Shoppable ad units** | In-feed and sponsored cards that allow product selection and checkout without leaving the ad host | | **Transactable ad-driven landing pages** | Ad clicks route to a partner-branded checkout flow rather than the merchant's storefront | | **Sponsored search and discovery** | Sponsored results on app stores, marketplaces, or search platforms where purchase happens inline | | **Video and CTV ad commerce** | Pre-roll, mid-roll, and overlay ad formats with embedded purchase paths | ## Why ads are a Firmly destination Ad-driven commerce is where the friction is highest and the addressable value is largest: - **Ad-to-purchase drop-off** — every click between ad and order placement reduces conversion. In-ad or partner-branded checkout removes the redirect cost. - **Brand and attribution continuity** — keeping the buyer in the advertiser's brand (or the ad host's surface) preserves ad-platform attribution and conversion event quality. - **PCI scope offload** — advertisers running shoppable ad campaigns don't want to own PCI, fraud, tokenization, or PSP relationships. - **Multi-merchant ad inventory** — an ad placement can promote any merchant on Firmly without per-merchant integration. ## Which Firmly solutions apply | Solution | When to use it | |---|---| | **[Ad Commerce](/solutions/ad-commerce/)** | The primary solution for ad-driven destinations. Designed for shoppable ad placements and ad-to-checkout flows. | | **[Branded Commerce](/solutions/branded-commerce/)** | When the ad routes to a partner-branded checkout under the advertiser's or ad host's domain. | ## Status today The Firmly platform supports ad-driven commerce destinations today, with first ad-network integrations in production. Broader coverage across additional ad networks is on the roadmap. Specific ad-network compatibility — including ad-platform conversion signals, click-ID preservation, and attribution — is scoped during the onboarding conversation. ## What to think about - **Click-ID preservation.** Ad-platform click identifiers need to be carried server-side through the checkout session so conversion postbacks attribute correctly. - **Conversion signal delivery.** Each ad platform expects its own conversion-event format. Firmly fires events to the ad networks the partner has credentials for. See [Branded Commerce → Integration Patterns](/solutions/branded-commerce/integration-patterns/) for the pixel-channel matrix. - **Compliance and disclosure.** Ad placements have platform-specific disclosure requirements. Pre-purchase consent UX is documented under [Consent & Disclosure](/solutions/agentic-commerce/consent-and-disclosure). --- ## Related - [Ad Commerce overview](/solutions/ad-commerce/) - [Branded Commerce overview](/solutions/branded-commerce/) - [How Firmly Works](/how-firmly-works) — attribution and conversion-signal infrastructure --- # Agentic Commerce FAQ For cross-cutting questions, see the [General FAQ](/faq) and [Technical FAQ](/troubleshooting/faq-technical). ## Multiple carts ### Can the destination chain multiple single-merchant carts together? Yes. Each cart is independent. The destination can place several orders in sequence — one per merchant — within a single conversation. ### Can I have multiple carts open simultaneously? Yes. Carts are scoped by `domain` (merchant) and session. The session API ([Get active carts](/api-reference/session/get-active-carts)) lets you list and switch between them. ## Discovery and catalog ### Does Firmly's discovery search across all merchants? Yes, by default. The destination can scope discovery to specific merchants by App ID configuration (banks and brand-loyalty destinations often do this — see [Destinations](/solutions/destination-surfaces/)). ### Is the catalog real-time? The catalog index is refreshed regularly per merchant. Price and stock are validated in real time against the merchant at order-placement time — even if the catalog index is slightly stale, the order placement uses fresh data. ## Identity and sessions ### Does Firmly handle SSO between the destination and the merchant? That's what [Firmly Connect](/solutions/firmly-connect/) is for. Firmly Connect lets a user signed into the destination appear signed into the merchant at order time, so the order goes under the user's existing merchant account rather than as a guest order. ### Does Firmly see the conversation between the user and the agent? No. Only structured commerce data (cart contents, address, payment token) crosses the boundary. Conversational context stays on the destination's side. ## Payment choices ### What's the difference between Smart Payment Selection and Agentic Pay? - **[Smart Payment Selection](/solutions/agentic-commerce/use-cases/smart-payment)** is the pattern of *choosing* the right payment path per transaction — card, Klarna BNPL, express wallets (Google Pay / PayPal / Click to Pay), saved cards, or Agentic Pay. It's the broader picker. - **[Agentic Pay](/solutions/agentic-commerce/agentic-pay)** is one of those paths — a Network Token Router specifically designed for autonomous-agent purchasing (cardholder pre-authorizes a mandate; agent transacts within it without a live human at checkout). It's a specific payment mode, not the picker. In a Smart Payment Selection flow, Agentic Pay is Path E. See [Smart Payment Selection → Path E](/solutions/agentic-commerce/use-cases/smart-payment). ### When should an agent use Agentic Pay vs a normal card flow? Use Agentic Pay when the cardholder is **not present at checkout** — autonomous purchasing (the agent decides when to buy within a pre-authorized mandate), recurring buys, or biometric / passkey-confirmed purchases. For an interactive flow where the user confirms each purchase, a normal saved card or fresh JWE-encrypted card is simpler. See [Autonomous Agent Purchasing](/solutions/agentic-commerce/use-cases/autonomous-agent-purchasing) for the use case framing. --- ## Related - [Agentic Commerce overview](/solutions/agentic-commerce/) - [Why Firmly for Agentic Commerce](/solutions/agentic-commerce/why-firmly) - [General FAQ](/faq) - [Technical FAQ](/troubleshooting/faq-technical) - [Branded Commerce FAQ](/solutions/branded-commerce/faq) - [Use Cases](/solutions/agentic-commerce/use-cases/) --- # Agentic Commerce > **Note** > **What's in this section:** Use Cases (which scenario you're building), Flows (the API sequence in detail), Integration Patterns (where the checkout UI lives), Recipes (copy-pasteable code for specific scenarios), Operations (sandbox + going live), and Protocols (UCP, MCP, ACP standards). ## Firmly handles the commerce A single integration with Firmly reaches every connected merchant — no per-destination work for the merchant, no per-merchant work for the destination. ## How it fits together ![How Firmly fits between AI surfaces and merchants — the destination owns the experience, Firmly owns the commerce, the merchant remains the seller](/images/agentic-commerce/how-firmly-fits.svg) The destination owns the user-facing experience (chat, voice, wallet UI, app surface). Firmly owns discovery across merchants, cart orchestration, payment, order placement to the merchant's native platform, and affiliate attribution. Tax and shipping are calculated by the merchant's platform and returned through the cart — Firmly relays them, it doesn't compute them. ## Use cases at a glance These are common patterns destinations build on Firmly — recognizable shapes, not an exhaustive list. Every destination type can use any combination of them. - [AI Shopping Copilot](/solutions/agentic-commerce/use-cases/shopping-copilot) — General-purpose discovery → cart → checkout. Start here if you're not sure. - [Deal & Coupon Hunting](/solutions/agentic-commerce/use-cases/deal-coupon-hunting) — Find deal-eligible items and apply promo codes at checkout. - [Smart Payment Selection](/solutions/agentic-commerce/use-cases/smart-payment) — Pick the best payment per transaction — express wallet, BNPL, saved card, or fresh card. - [Vertical Specialist](/solutions/agentic-commerce/use-cases/vertical-specialist) — Variant-rich multi-product cart for fashion, beauty, supplements. - [Smart Gifting & Occasion](/solutions/agentic-commerce/use-cases/smart-gifting) — Find a gift, add gift wrap, optionally a gift card, express checkout. - [Scheduled / Triggered Buying](/solutions/agentic-commerce/use-cases/scheduled-buying) — Replenishment, restock, price-drop auto-buy. Destination schedules; Firmly executes. - [Autonomous Agent Purchasing](/solutions/agentic-commerce/use-cases/autonomous-agent-purchasing) — Mandate-based payment when the cardholder isn't present — Agentic Pay with network-enforced spending limits. See [Use Cases](/solutions/agentic-commerce/use-cases/) for the full menu with a comparison table mapping each use case to its closest flow, integration pattern, and recipe. ## Three layers of the platform - **Discovery** — Search across connected merchant catalogs and return rich product detail — with live price and stock validation at the merchant. - **Cart & Checkout** — Build the cart, then set shipping address and method. The cart returns merchant-calculated tax and totals. Collect payment via card, PayPal, Klarna, Click to Pay, or [Agentic Pay](/solutions/agentic-commerce/agentic-pay) (Network Token Router for autonomous agents). - **Order Placement** — Submit the order to the merchant's native platform, across industry-standard and custom commerce platforms alike. Firmly's scope ends here — the merchant's existing back-office workflows pick up from there. ## Start here - [Advanced Checkout Guide](/cookbook/advanced-checkout-guide) — A complete working Node script from intent to placed order — the fastest way to see end-to-end. - [Integration Patterns](/solutions/agentic-commerce/integration-patterns/) — The hub for scoping the build — hosted, embedded, or headless — with links to every API you'll need. - [Sandbox Setup](/solutions/agentic-commerce/operations/sandbox-setup) — Get credentials, pick a test merchant, run your first verified call. - [Errors & Recovery](/solutions/agentic-commerce/operations/errors) — UCP error catalog with recovery patterns for each. ## For your PM, legal, and compliance reviewers - [Consent & Disclosure](/solutions/agentic-commerce/consent-and-disclosure) — Where the user's review and consent sits in an agentic flow — what Firmly expects from the destination, and how to surface it. ## What Firmly handles (so the destination doesn't have to) - **Affiliate attribution** — Firmly relays the originating destination to the merchant so affiliate commissions and attribution flow back without manual reconciliation. - **Tax and shipping** — the merchant's platform calculates these from its live rules; Firmly relays the results in the cart, and neither Firmly nor the destination computes them. - **Inventory and price validation** — every quote is re-validated against the merchant's current state before order placement. - **Payment tokenization and PCI handling** — handled at the payment layer. - **Order placement format** — orders land in the merchant's order management system as if a customer placed them directly, so the destination doesn't fight per-merchant integration formats. ## Which protocol fits your stack Firmly speaks UCP, MCP, and ACP, plus direct REST. See [Protocols](/solutions/agentic-commerce/protocols/) for the comparison. The flows and integration patterns on this page apply regardless of which protocol you pick. --- ## Related - [Agentic Commerce FAQ](/solutions/agentic-commerce/faq) — multi-merchant, discovery scope, SSO, payment-mode choice - [How Firmly Works](/how-firmly-works) — the platform underneath every solution - [Cart Lifecycle](/api-reference/cart-management/cart-lifecycle) — the lifecycle that all flows follow - [Cart API Implementation Guide](/cookbook/full-cart-api-guide) — multi-step cart, shipments, addons - [API Reference](/api-reference/) — every endpoint you'll call - [For Merchants](/for-merchants/) — the merchant's side of the integration - [Why Firmly for Agentic Commerce](/solutions/agentic-commerce/why-firmly/index.md) - [Flows](/solutions/agentic-commerce/flows/index.md) - [Recipes](/solutions/agentic-commerce/recipes/index.md) - [Agentic Pay Integration](/solutions/agentic-commerce/agentic-pay-integration/index.md) --- # Agentic Pay Integration This guide walks you through integrating Agentic Pay — Firmly's Network Token Router for agentic commerce. Firmly handles the network-specific mechanics behind one abstract API. > **Note** > **Prerequisites**: > - An API token (`x-firmly-authorization`) provisioned by Firmly with Agentic Pay access — used for the enrollment and intent endpoints. In the sandbox this is a separate credential from the App ID, and enrollment needs network sandbox test cards — see [Agentic Pay in the sandbox](/for-destinations/sandbox-setup#agentic-pay-in-the-sandbox). The card numbers in the samples below are placeholders; substitute the network sandbox test card Firmly provided > - A **device session token** for placing the order (`/wallet-complete-order`). This can come from **either** a browser-session JWT (browser-present checkout) **or** server-to-server auth (backend / autonomous-agent contexts with no browser) > - **An existing cart** for the merchant domain, with line items and shipping info already set. The enrollment/intent steps below are independent of the cart, but [Step 8](#step-8-place-the-order) completes an existing cart — create it first via [Browser Session](/api-reference/authentication/browser-session) → [Add Line Item](/api-reference/cart-management/add-line-item) → [Set Shipping Info](/api-reference/checkout/set-shipping-info). > **Tip** > Prefer not to wire the auth iframes by hand? The [Headless SDK](/api-reference/headless-sdk/) (`@firmly/agentic-pay-sdk`) wraps every step in this guide — including the Visa/Mastercard authentication iframes and the order hand-off — behind a small JavaScript API. ## Overview There are two entry points — both converge on the same intent → order chain: ### New card: Enroll Send the cardholder's PAN to Firmly. Firmly detects the network, enrolls the card, and returns verification challenges. Persist `virtual_card_id`, `card_art`, and `masked` for returning buyers. ### Saved card: Select Card For returning buyers, call `/select-card` with the stored `virtual_card_id` — no PAN re-entry. Returns the same shape as `/enroll`, so the rest of the flow is identical. ### Create a payment intent Create an intent with the transaction amount. A FIDO assertion proves cardholder presence. ### Place the order Send the `flow_token` and `intent_id` to the wallet-complete-order endpoint. Firmly retrieves network token credentials and completes the payment. ## Step 1: Enroll a Card (New Card Only) Send the cardholder's PAN to Firmly. Firmly inspects the BIN and routes to the correct network automatically. For returning buyers with a stored card, skip to [Select Card](#saved-card-select-card-alternative-to-step-1) instead. **JavaScript** ```javascript const enrollResponse = await fetch( 'https://api.firmly.work/api/v1/wallets/agentic-pay/enroll', { method: 'POST', headers: { 'x-firmly-authorization': apiToken, 'Content-Type': 'application/json' }, body: JSON.stringify({ pan: '4111111111111111', expiry_month: '12', expiry_year: '2030', cvv: '123', consumer: { email: 'cardholder@example.com', country_code: 'US' } }) } ); const { flow_token, virtual_card_id, verification_methods } = await enrollResponse.json(); ``` **Python** ```python import requests response = requests.post( 'https://api.firmly.work/api/v1/wallets/agentic-pay/enroll', headers={ 'x-firmly-authorization': api_token, 'Content-Type': 'application/json' }, json={ 'pan': '4111111111111111', 'expiry_month': '12', 'expiry_year': '2030', 'cvv': '123', 'consumer': { 'email': 'cardholder@example.com', 'country_code': 'US' } } ) data = response.json() flow_token = data['flow_token'] verification_methods = data['verification_methods'] ``` **cURL** ```bash curl -X POST https://api.firmly.work/api/v1/wallets/agentic-pay/enroll \ -H "x-firmly-authorization: YOUR_API_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "pan": "4111111111111111", "expiry_month": "12", "expiry_year": "2030", "cvv": "123", "consumer": { "email": "cardholder@example.com", "country_code": "US" } }' ``` The response includes `verification_methods`, `card_art`, and `masked` (last4, expiry, brand). > **Note** > **Persist for returning buyers:** Save `virtual_card_id`, `card_art`, and `masked` from this response. These are only returned on the first enrollment — `/select-card` returns `null` for `card_art` and `masked`. Check `verification_methods` for `embed_iframe_handshake` or `embed_iframe` to determine the next step. ## Step 2: Iframe Handshake (If Required) If the response includes a verification method of type `embed_iframe_handshake`, load the iframe URI in the cardholder's browser and capture the `secure_token` via postMessage. Skip this step if no handshake method is returned. ```javascript const iframe = document.createElement('iframe'); iframe.src = verification_methods[0].attributes.uri; document.body.appendChild(iframe); window.addEventListener('message', (event) => { // Always verify the sender's origin if (event.origin !== new URL(iframe.src).origin) return; const data = event.data; if (data.type === 'AUTH_READY') { iframe.contentWindow.postMessage({ requestID: data.requestID, type: 'CREATE_AUTH_SESSION', version: '1', client: { id: '__from-server__' }, contentType: 'application/json' }, new URL(iframe.src).origin); } if (data.sessionContext?.secureToken) { const secureToken = data.sessionContext.secureToken; sendToServer({ secure_token: secureToken }); } }); ``` > **Note** > **Visa vs Mastercard.** The `embed_iframe_handshake` + `secure_token` postMessage flow above is the **Visa** path. **Mastercard** does not return a handshake method — instead, pass a `callback_uri` on the trigger/intent call and load the network iframe; the iframe posts its result back through Firmly's [Iframe Callback](/api-reference/agentic-pay/iframe-callback) bridge (an `agentic_pay_callback` message). For saved Mastercard cards, `/select-card` returns an empty `verification_methods` array (skip straight to Step 6). **Discover** has no cardholder-verification step at all: `/enroll` and `/select-card` both return an empty `verification_methods` array, and `/intent` returns the `intent_id` directly (skip Step 7). ## Step 3: Trigger Enrollment Verification Call the trigger endpoint with the selected verification method. Include `secure_token` if captured from an iframe handshake, or `callback_uri` for iframe-based challenges without a handshake. **JavaScript** ```javascript const triggerResponse = await fetch( 'https://api.firmly.work/api/v1/wallets/agentic-pay/enroll/trigger', { method: 'POST', headers: { 'x-firmly-authorization': apiToken, 'Content-Type': 'application/json' }, body: JSON.stringify({ flow_token: flowToken, method_id: 'OTP_SMS', secure_token: secureToken // omit if not applicable }) } ); const { flow_token: updatedToken, challenge } = await triggerResponse.json(); // challenge.type === 'otp' means an OTP was sent to the cardholder ``` **cURL** ```bash curl -X POST https://api.firmly.work/api/v1/wallets/agentic-pay/enroll/trigger \ -H "x-firmly-authorization: YOUR_API_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "flow_token": "eyJhbGci...", "method_id": "OTP_SMS", "secure_token": "ezAwMX06..." }' ``` ## Step 4: Verify Enrollment Submit the OTP or iframe result. This step may need to be called more than once — for example, an OTP verification may be followed by a FIDO registration step. **JavaScript** ```javascript const verifyResponse = await fetch( 'https://api.firmly.work/api/v1/wallets/agentic-pay/enroll/verify', { method: 'POST', headers: { 'x-firmly-authorization': apiToken, 'Content-Type': 'application/json' }, body: JSON.stringify({ flow_token: updatedToken, type: 'otp', value: '456789' }) } ); const verifyResult = await verifyResponse.json(); // If verifyResult.verification_methods exists, another verification step is needed // If verifyResult.virtual_card_id exists, enrollment is complete ``` **cURL** ```bash curl -X POST https://api.firmly.work/api/v1/wallets/agentic-pay/enroll/verify \ -H "x-firmly-authorization: YOUR_API_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "flow_token": "eyJhbGci...", "type": "otp", "value": "456789" }' ``` > **Note** > If the response contains `verification_methods` with type `embed_iframe`, a FIDO registration is needed. Load the iframe, complete the ceremony, and call `/enroll/verify` again with `type: "embed_iframe"` and the `iframe_result`. ## Step 5: Complete FIDO Registration Load the FIDO iframe from the verification method's `uri`, complete the ceremony, and submit the result. ```javascript const fidoVerifyResponse = await fetch( 'https://api.firmly.work/api/v1/wallets/agentic-pay/enroll/verify', { method: 'POST', headers: { 'x-firmly-authorization': apiToken, 'Content-Type': 'application/json' }, body: JSON.stringify({ flow_token: latestFlowToken, type: 'embed_iframe', iframe_result: { fidoBlob: capturedFidoBlob, assuranceData: capturedAssuranceData } }) } ); const { flow_token: enrolledToken, virtual_card_id } = await fidoVerifyResponse.json(); // virtual_card_id confirms the card is enrolled ``` ## Step 6: Create Payment Intent With the card enrolled (via Step 1 or [Select Card](#saved-card-select-card-alternative-to-step-1)), create a payment intent when the cardholder is ready to pay. **JavaScript** ```javascript const intentResponse = await fetch( 'https://api.firmly.work/api/v1/wallets/agentic-pay/intent', { method: 'POST', headers: { 'x-firmly-authorization': apiToken, 'Content-Type': 'application/json' }, body: JSON.stringify({ flow_token: enrolledToken, mandate: { amount: '585.49', currency_code: 'USD', merchant_name: 'My Store' } }) } ); const { flow_token: intentToken, challenge, intent_id } = await intentResponse.json(); // challenge.type === 'embed_iframe' — load the FIDO assertion iframe (Step 7) // intent_id present instead of challenge — no challenge needed, go straight to Step 8 ``` **cURL** ```bash curl -X POST https://api.firmly.work/api/v1/wallets/agentic-pay/intent \ -H "x-firmly-authorization: YOUR_API_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "flow_token": "eyJhbGci...", "mandate": { "amount": "585.49", "currency_code": "USD", "merchant_name": "My Store" } }' ``` ## Step 7: Complete Intent Challenge Only when Step 6 returned a `challenge`. Discover — and Mastercard when the cardholder authenticated at enrollment moments earlier — return `intent_id` directly from `/intent`; in that case skip to [Step 8](#step-8-place-the-order). Load the FIDO assertion iframe, capture the result, and submit it. ```javascript const challengeResponse = await fetch( 'https://api.firmly.work/api/v1/wallets/agentic-pay/intent/challenge', { method: 'POST', headers: { 'x-firmly-authorization': apiToken, 'Content-Type': 'application/json' }, body: JSON.stringify({ flow_token: intentToken, type: 'embed_iframe', iframe_result: { fidoBlob: capturedFidoBlob, assuranceData: capturedAssuranceData } }) } ); const { flow_token: finalToken, intent_id } = await challengeResponse.json(); ``` ## Step 8: Place the Order With the `flow_token` and `intent_id`, call the wallet-complete-order endpoint using the cardholder's device JWT. **JavaScript** ```javascript const orderResponse = await fetch( 'https://cc.firmly.work/api/v2/payment/domains/staging.luma.gift/wallet-complete-order', { method: 'POST', headers: { 'x-firmly-authorization': deviceJwt, 'Content-Type': 'application/json' }, body: JSON.stringify({ wallet: 'agentic-pay', additional_data: { flow_token: finalToken, intent_id: intentId, transaction: { amount: '585.49', currency_code: 'USD', merchant_name: 'My Store' } }, billing_info: { first_name: 'John', last_name: 'Smith', address1: '123 Main St', city: 'San Francisco', state_or_province: 'CA', country: 'US', postal_code: '94105', email: 'john@example.com', phone: '4155551212' } }) } ); const order = await orderResponse.json(); ``` **cURL** ```bash curl -X POST https://cc.firmly.work/api/v2/payment/domains/staging.luma.gift/wallet-complete-order \ -H "x-firmly-authorization: DEVICE_JWT" \ -H "Content-Type: application/json" \ -d '{ "wallet": "agentic-pay", "additional_data": { "flow_token": "eyJhbGci...", "intent_id": "1-5C90F150...", "transaction": { "amount": "585.49", "currency_code": "USD" } }, "billing_info": { "first_name": "John", "last_name": "Smith", "address1": "123 Main St", "city": "San Francisco", "state_or_province": "CA", "country": "US", "postal_code": "94105", "email": "john@example.com", "phone": "4155551212" } }' ``` ## Saved Card: Select Card (Alternative to Step 1) For returning buyers with a stored `virtual_card_id`, use `/select-card` instead of `/enroll`. No PAN re-entry needed. It returns the same shape as `/enroll`, so the rest of the flow (handshake → intent → order) is identical. **JavaScript** ```javascript const { flow_token, verification_methods } = await fetch( 'https://api.firmly.work/api/v1/wallets/agentic-pay/select-card', { method: 'POST', headers: { 'x-firmly-authorization': apiToken, 'Content-Type': 'application/json' }, body: JSON.stringify({ network: savedCard.brand, virtual_card_id: savedCard.virtual_card_id, consumer: { email: savedCard.email } }) } ).then(r => r.json()); if (verification_methods.length > 0) { // Iframe handshake needed (Visa) — continue from Step 2 } else { // No handshake (Mastercard) — skip to Step 6 (Create Payment Intent) } ``` **cURL** ```bash curl -X POST https://api.firmly.work/api/v1/wallets/agentic-pay/select-card \ -H "x-firmly-authorization: YOUR_API_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "network": "visa", "virtual_card_id": "cf90be5c86363de702ed19beec46e102", "consumer": { "email": "jane@example.com" } }' ``` Key differences from `/enroll`: - `consumer.email` is required for Visa (device binding); optional for Mastercard - `card_art` and `masked` are `null` — use the values persisted from the original `/enroll` - Visa returns `verification_methods` with an iframe handshake; Mastercard and Discover return an empty array (skip to Step 6) - If the card is revoked or unknown, the API returns `PaymentMethodNotAvailable` — fall back to `/enroll` ## Error Handling **PaymentMethodNotAvailable (409)** The card network is not supported or not enabled for your account. **BadRequest (400) — secure_token required** An iframe handshake is required before triggering. Load the iframe URI from `verification_methods`, capture the `secure_token` via postMessage, and include it in the trigger request. **BadRequest (400) — Invalid flow_token format** The `flow_token` is malformed or expired. Flow tokens must be used promptly and in sequence — each API call returns a fresh token for the next step. **BadRequest (400)** The OTP value was incorrect. A rejected OTP surfaces as `BadRequest` (400), not `InvalidOtp` — do not branch on `InvalidOtp` here. Prompt the cardholder to re-enter or request a new OTP via `/enroll/trigger`. **CheckoutError (412)** Payment info or billing address invalid. Verify the billing address and ensure the cart has a valid payment handle. --- ## Related - [Agentic Pay Concepts](/solutions/agentic-commerce/agentic-pay) — Architecture and flow overview - [Headless SDK](/api-reference/headless-sdk/) — Browser SDK that wraps this entire flow - [Enroll API Reference](/api-reference/agentic-pay/enroll) — Full endpoint documentation - [Wallet Complete Order](/api-reference/payment/wallet-complete-order) — Order placement endpoint --- # Agentic Pay Firmly acts as a **Network Token Router** for agentic commerce. Destinations integrate once with Firmly's APIs and the Firmly iFrame — Firmly routes tokenization, cardholder authentication, and payment instructions to the appropriate card network. Adding a new network is a Firmly-side change with no destination code impact. > **Note** > Agentic Pay uses **App Authentication** (API token via `x-firmly-authorization`) for the enrollment and intent endpoints. Browsers participate only for iframe-mediated cardholder verification. Order completion is authenticated separately — see [Order completion auth](#order-completion-auth). ## Two Ways to Pay **Enrollment happens once per cardholder.** After a card is enrolled and verified, the destination stores the resulting `virtual_card_id` and reuses it for every future payment — no PAN re-entry and no repeat verification. That single enrolled card powers both payment models below; the difference is only *who approves the payment at transaction time*. - **Human in the loop** — The cardholder is present and approves **each** payment in real time — a FIDO/passkey assertion (or OTP) at the intent step proves presence. Best for interactive checkout where the buyer confirms the purchase. - **Autonomous agent** — **No human is present** at transaction time. The agent transacts within a **mandate** the cardholder pre-authorized — bounded by a maximum amount, an expiration time, and the purchase intent. Best for delegated or recurring agent-driven purchases. ### The mandate: a cardholder's delegated authority Every payment intent carries a **mandate** — the cardholder's authorization describing what the agent may charge. In the human-in-the-loop model the cardholder also approves it live; in the autonomous model the mandate **is** the guardrail that lets the agent act without a human present: | Limit | Mandate field | What it bounds | |---|---|---| | **Maximum amount** | `amount` (+ `currency_code`) | The order-completion capture amount **must not exceed** this. Firmly rejects a higher capture before the network is called. | | **Expiration** | `ttl_seconds` | How long the authorization stays valid. Once it lapses, a fresh intent is required. | | **Purchase intent / scope** | `merchant_name`, `merchant_category_code`, `quantity`, `consumer_prompt` | What the agent is authorized to buy, from whom, and the prompt the cardholder approved. | > **Warning** > The capture amount sent at [order completion](/api-reference/payment/wallet-complete-order) must be **≤ the mandate `amount`** authorized at intent. Firmly compares the cart total against the mandate before contacting the network — a higher amount is rejected with `BadRequest` (HTTP 400) at [Wallet Complete Order](/api-reference/payment/wallet-complete-order), and no authorization is attempted. ## How It Works Agentic Pay breaks the payment flow into three phases: **Enrollment**, **Intent**, and **Order Completion**. ### Phase 1: Card Enrollment The destination sends the cardholder's PAN. Firmly inspects the BIN, routes to the correct network, and returns abstract verification challenges. The destination drives the cardholder through the challenges without needing to know which network is involved. ```mermaid sequenceDiagram participant Destination participant Firmly participant Network as Card Network participant Browser as Cardholder Browser Destination->>Firmly: Enroll card (PAN, expiry, consumer) Firmly->>Network: Register card Firmly-->>Destination: flow_token + verification_methods Note over Destination,Browser: Destination loads iframe if needed,
captures tokens via postMessage Destination->>Firmly: Trigger verification (flow_token, method_id) Firmly->>Network: Trigger challenge Firmly-->>Destination: flow_token + challenge (otp or embed_iframe) Note over Destination,Browser: Cardholder completes challenge
(OTP entry or FIDO ceremony) Destination->>Firmly: Verify (flow_token, type, value/iframe_result) Firmly->>Network: Validate response Firmly-->>Destination: flow_token + virtual_card_id ``` After enrollment, the destination receives a `virtual_card_id` and `masked` card details (last4, expiry, brand). The `flow_token` carries all state between steps — no server-side session storage is needed. Destinations should persist `virtual_card_id`, `card_art`, and `masked` for returning buyers. A stored card can start a new payment via `/select-card` without re-entering card details — it returns the same shape as `/enroll`, so the intent and order chain is reused unchanged. ### Phase 2: Payment Intent When it's time to pay, the destination creates a payment intent carrying the **mandate** (amount, expiry, merchant scope — see [The mandate](#the-mandate-a-cardholders-delegated-authority)). The mandate is the cardholder's authorization for the agent to act on their behalf. In the human-in-the-loop model a FIDO assertion in the cardholder's browser proves presence; in the autonomous model the agent transacts within the previously authorized mandate limits. ```mermaid sequenceDiagram participant Destination participant Firmly participant Network as Card Network participant Browser as Cardholder Browser Destination->>Firmly: Create intent (flow_token, mandate) Firmly->>Network: Initiate payment authorization Firmly-->>Destination: flow_token + challenge Note over Destination,Browser: Cardholder completes
FIDO assertion in iframe Destination->>Firmly: Submit challenge (flow_token, iframe_result) Firmly->>Network: Complete authorization Firmly-->>Destination: flow_token + intent_id ``` ### Phase 3: Order Completion The destination sends the `flow_token` and `intent_id` to place the order. Firmly retrieves network token credentials and completes the payment. ```mermaid sequenceDiagram participant Destination participant Firmly participant Network as Card Network participant PSP Destination->>Firmly: Place order (flow_token, intent_id, billing_info) Firmly->>Network: Get credentials Network-->>Firmly: Network token + cryptogram Firmly->>PSP: Tokenize + place order PSP-->>Firmly: Order confirmation Firmly-->>Destination: Submitted cart ``` ## Key Concepts ### Flow Token The `flow_token` is an encrypted token that carries the entire enrollment and payment state. It is: - **Stateless** — no server-side session; all state lives in the token - **Refreshed** on every API call — each response returns a new `flow_token` that must be used for the next call - **Tamper-proof** — encrypted and integrity-checked; any modification invalidates it - **Scoped** — contains destination ID, network, enrollment status, and expiry - **Short-lived** — expires **30 minutes** after issue. An expired or out-of-sequence token returns `BadRequest` (`flow_token expired` / `Invalid flow_token format`) — restart the flow from `/enroll` or `/select-card`. ### BIN Routing Firmly automatically detects the card network from the PAN's BIN (Bank Identification Number): | Network | BIN Range | Status | |---|---|---| | Visa | 4xxx | Supported | | Mastercard | 5xxx, 222100–272099 | Supported | | Discover | 6011, 65xx, 644000–649999 | Supported — no cardholder verification step (see below) | | Amex | 34xx, 37xx | Planned | If a network is not supported or not enabled for the destination, the API returns `PaymentMethodNotAvailable`. Networks are enabled per destination — confirm with Firmly which networks your API token can transact on. **Discover has no cardholder-verification ceremony.** `/enroll` returns an empty `verification_methods` array and the card is immediately enrolled, and `/intent` returns the `intent_id` directly instead of a `challenge` — there is no `/intent/challenge` call. Mastercard can also skip the intent challenge when the cardholder authenticated moments earlier at enrollment (see [Create Intent](/api-reference/agentic-pay/create-intent#response)). ### Verification Methods The API returns `verification_methods` — an abstract challenge contract. Destinations see only the challenge type; network-specific details are encapsulated by Firmly: | Type | Description | |---|---| | `embed_iframe_handshake` | Iframe that captures a `secure_token` via postMessage | | `otp` | One-time passcode sent via SMS or email | | `embed_iframe` | FIDO2 registration or assertion via network-hosted iframe | New networks can plug in without destinations changing code — Firmly maps each network's auth flow into one of the abstract challenge types. ### Card Art Every network returns `card_art` metadata for rendering the card visually, but the exact fields differ by network. Firmly proxies the image through a signed URL so destinations can render card images without CORS issues. | Field | Visa | Mastercard | Discover | |---|---|---|---| | `network` | ✅ | ✅ | ✅ | | `url` | ✅ | ✅ | ✅ | | `background_color` | ✅ | — | ✅ | | `foreground_color` | ✅ | — | ✅ | | `descriptor` (issuer name) | — | ✅ | — | ```json { "card_art": { "network": "mastercard", "url": "https://api.firmly.work/api/v1/wallets/agentic-pay/card-art/", "descriptor": "Test Bank 2" } } ``` The example above is a Mastercard card, so it carries `descriptor` and no color fields. A Visa or Discover `card_art` carries `background_color` and `foreground_color` instead of `descriptor`. The `url` is HMAC-signed — no authentication header is needed. Drop it directly into `![](...)`. ### Masked Card Alongside card art, enrollment returns `masked` — display-only **funding-card** details for rendering a saved-card chip (e.g. "Test Bank 2 •••• 4595 · DEBIT"). It is a sibling of `card_art` (different source). Like `card_art`, its fields are network-dependent: **Mastercard** returns the full set (`last4`, `exp_month`, `exp_year`, `brand`, `card_type`, `issuer_name`); **Visa** returns `last4`, `exp_month`, `exp_year`, `brand` only (no `card_type`/`issuer_name`); **Discover** returns `last4` and `brand` only. ```json { "masked": { "last4": "4595", "exp_month": "12", "exp_year": "2030", "brand": "mastercard", "card_type": "DEBIT", "issuer_name": "Test Bank 2" } } ``` ### Card Metadata Availability **Capture `card_art` and `masked` at enrollment.** They are returned **only** on `/enroll`, never on `/select-card` — persist them with the `virtual_card_id` and reuse them on every later payment and in the order UI. | Source | `card_art` | `masked` | Notes | |---|---|---|---| | **`/enroll`** (new card) | ✅ returned | ✅ returned | Persist both for reuse | | **`/select-card`** (saved card) | `null` | `null` | Reuse the values persisted at enroll | | **Order `payment_summary`** | ✅ when enrolled this session | ✅ when enrolled this session | Carried through from `/enroll` → Vault → order; absent on the select-card path | ### Order Completion Auth The enrollment and intent endpoints use App Authentication (the destination API token). **Order completion** (`/wallet-complete-order`) is authenticated with a **device session token**, which can be obtained either way: - **Browser-session JWT** — for browser-present checkout (human-in-the-loop). - **Server-to-server auth** — for backend or autonomous-agent contexts where no browser is involved. ## Next Steps - [Agentic Pay Integration Guide](/solutions/agentic-commerce/agentic-pay-integration) — Step-by-step implementation - [Headless SDK](/api-reference/headless-sdk/) — Browser SDK that wraps enrollment, the auth iframes, and order completion - [Enroll Endpoint](/api-reference/agentic-pay/enroll) — Start card enrollment - [Wallet Complete Order](/api-reference/payment/wallet-complete-order) — Place the final order --- # Agreement signing The merchant reviews Firmly's merchant agreement, fills in the participation details, and signs. The signature is captured with **audit metadata** (signer email, timestamp, client location, agreement version, and signing browser) so Firmly always has a verifiable record of which agreement version was in effect at any moment. The same surface is reused after onboarding whenever there is a new agreement version to acknowledge. ## Two states on the same surface ### Not yet signed The page renders the agreement PDF for review plus a participation form. The form collects the following; all except Company Address are required to enable the **Sign** button: - Company Legal Name - Company Address *(optional)* - Signer Name - Signer Title - Signer Email - Signer Phone - "I have read and accept the terms" checkbox **Prefill from KYB.** When the merchant has already filled in company / contact info on the [Know Your Business](/solutions/firmly-connect/onboarding/know-your-business) page, those values are prefilled into the participation form so the merchant only has to confirm them. ### Already signed The page shows a "Signed" confirmation card with: - Signer's email - Signing timestamp - Client location ## Audit metadata captured on submit Every signature is recorded with a **tamper-evident audit trail** so Firmly can always show which agreement version a merchant accepted, and when. Captured with each signature: - Signer email - Signing timestamp - Client location (IP-derived) - Agreement version - The signing browser (from the browser's user-agent string) ## First-time signing advances onboarding A successful sign invalidates cached dashboard data and redirects back to the merchant home. During onboarding, that lands the merchant back in the task menu with the agreement step marked complete. ## Re-signing for new versions When Firmly publishes a new agreement version, the page automatically flips back to its "needs signature" state on the merchant's next visit, with the new version's PDF and a fresh participation form. The previous signed record stays in the audit log; the merchant just has to acknowledge the new terms. ## Externally-signed merchants Some merchants sign the agreement out-of-band (e.g. via a paper contract). For those, the page surfaces an "externally signed" state with the relevant prefill information instead of asking for a click-through signature. ## Gating - **KYB-gated during onboarding.** The agreement task stays locked until KYB is approved. See [Onboarding wizard](/solutions/firmly-connect/onboarding/). --- ## Related - [Onboarding wizard](/solutions/firmly-connect/onboarding/) — the 7-step sequence - [Know Your Business](/solutions/firmly-connect/onboarding/know-your-business) — KYB info prefills this form - [CDN whitelisting](/solutions/firmly-connect/onboarding/cdn-whitelisting) — next step - [Audit logs](/solutions/firmly-connect/portal/audit-logs) — where signature events are recorded --- # Audit logs The merchant's record of who did what on the dashboard — team membership changes, destination toggles, configuration updates, signatures, onboarding milestones. It exists for compliance and for answering "who turned this on?" questions without paging through chat history. Access is restricted to Owners, the Primary Owner, and Firmly admins (see [Role gating](#role-gating) below). ## Event feed structure Tabular event feed, ordered newest-first. Each row has four columns: | Column | What it shows | |---|---| | **Event** | Color-coded badge by category | | **Description** | Short human-readable summary | | **By** | The actor's email | | **When** | Relative timestamp (e.g. "16m ago", "1h ago") | ## Event categories The badges are typed; the icon and color reflect the category. Registered event types: | Category | Event types | |---|---| | **Team** | `team_member_invited`, `invite_accepted`, `invite_cancelled`, `member_removed`, `role_changed`, `ownership_transferred` | | **Configuration** | `settings_updated`, `catalog_configured`, `destinations_configured`, `domain_added`, `domain_verified`, `domain_removed`, `sso_configured`, `ucp_verified` | | **Destinations** | `destination_enabled`, `destination_disabled` | | **Integration / Lifecycle** | `integration_completed`, `integration_reset`, `kyb_submitted`, `agreement_signed`, `cdn_whitelisting_completed`, `go_live_submitted` | ## Firmly-admin actions are attributable When the actor is a Firmly admin acting on the merchant's behalf, the row is marked as such — so the merchant can tell the difference between their own team's actions and Firmly's. ## Pagination, not search - **25 events per page** by default - Previous / next navigation - Total count There's no full-text search or date filter on this surface — for incident investigation the merchant pages through the feed. If you need deeper analysis or an export the portal doesn't offer today, ask your Firmly contact. ## Role gating Only **Owners**, the **Primary Owner**, and **Firmly admins** see the Audit Logs entry in the sidebar. Editors and Viewers don't see the link, and the server-side guard rejects direct navigation as well. --- ## Related - [Team management](/solutions/firmly-connect/portal/team-management) — team actions logged here - [Domains and SSO](/solutions/firmly-connect/portal/domains-and-sso) — config changes logged here - [Agreement signing](/solutions/firmly-connect/onboarding/agreement-signing) — signatures logged here --- # Autonomous Agent Purchasing > **Note** > This is one common pattern customers build with Firmly. Many other shapes are possible — adapt or combine use cases to fit your specific build. The user is **not present** at the moment of purchase. They authorized the agent earlier — *"buy a refill when I run out", "book the flight if it drops below $400", "restock my dog's food"* — and now the agent acts on that authorization without an interactive confirmation. For card payments, this requires more than just a saved token. The card network needs **proof that the cardholder authorized this specific transaction** — bounded by an amount cap, an expiration, and a purchase scope. Without that proof, banks decline autonomous-agent transactions as if they were unauthorized. Firmly's **[Agentic Pay](/solutions/agentic-commerce/agentic-pay)** is the Network Token Router that makes this safe. The cardholder enrolls **once** via wallet-style biometric confirmation; each subsequent purchase then runs `select-card → intent → complete` against the user's `virtual_card_id`. The **mandate** — amount cap, expiry, merchant scope — is carried in the intent and enforced by the network. ## The mandate model Every autonomous payment carries a mandate the cardholder pre-authorized: | Mandate field | What it bounds | |---|---| | `amount` | Maximum the agent may charge this transaction. The capture amount at order completion must be ≤ this. | | `currency_code` | Mandate currency — protects against FX surprises | | `ttl_seconds` | The validity window, as seconds-to-live from issuance. After it elapses the intent is no longer usable — create a fresh one | | `merchant_name`, `merchant_category_code` | The scope — what the agent is authorized to buy and from whom | | `quantity`, `consumer_prompt` | What and how many; the prompt the cardholder approved | **The destination doesn't enforce the mandate — Firmly and the card network do.** The amount ceiling is checked by Firmly at order placement: a cart total above `mandate.amount` (or a currency mismatch) is rejected with `400 BadRequest` before the network is ever called. The remaining fields travel to the network with the intent. The destination's job is to build the mandate honestly from the user's standing authorization. ## What Firmly does (and doesn't) for this scenario | Layer | Owner | |---|---| | The user's standing authorization (the "buy if X" or "restock when Y" rule) | **Destination** stores and triggers it | | The mandate construction (amount cap, expiry, merchant scope) | **Destination** builds it; Firmly forwards it to the network | | One-time card enrollment via biometric / OTP / FIDO | **Firmly** runs the Network Token Router | | Virtual card token storage | **Firmly** holds the `virtual_card_id` | | Network-level mandate enforcement | **Card network** (Visa, Mastercard) | | Each individual transaction (intent → complete) | **Firmly** routes through the network | ## Recommended setup | Choice | Default | Why | |---|---|---| | **Payment** | [Agentic Pay](/solutions/agentic-commerce/agentic-pay) | The only Firmly payment path designed for non-present cardholders | | **Integration pattern** | [Deep Link / Headless](/solutions/agentic-commerce/integration-patterns/deep-link) for autonomous-only; [Embedded](/solutions/agentic-commerce/integration-patterns/embedded-checkout) if you also enroll cards interactively | Autonomous runs server-side; enrollment usually needs a browser iframe | | **Auth** | [Server-to-server](/api-reference/authentication/server-to-server) for the autonomous side; [Browser session](/api-reference/authentication/browser-session) for the enrollment step | Two-phase: enroll in-browser once, transact from server forever after | | **Client library** | [Headless SDK](/api-reference/headless-sdk/) for the browser enrollment step | Wraps the iframe handshake and verification methods so you don't write that code yourself | ## API sequence ### One-time enrollment (cardholder is present) | # | Endpoint | Purpose | |---|---|---| | 1 | [Enroll](/api-reference/agentic-pay/enroll) | Submit the card; Firmly routes to Visa, Mastercard, or Discover by BIN | | 2 | [Trigger Enrollment](/api-reference/agentic-pay/trigger-enrollment) | Start the verification challenge (OTP, FIDO, or iframe handshake depending on the network) | | 3 | [Verify Enrollment](/api-reference/agentic-pay/verify-enrollment) | Complete the verification — biometric / passkey / OTP code | | 4 | (destination stores) | Persist the returned `virtual_card_id` for this user | The Headless SDK's [`enrollCard()`](/api-reference/headless-sdk/enroll-card) wraps steps 1–3 behind a single browser call. ### Per autonomous transaction (cardholder is NOT present) | # | Endpoint | Purpose | |---|---|---| | 1 | [Select Card](/api-reference/agentic-pay/select-card) | Resolve the user's stored `virtual_card_id` — no PAN re-entry | | 2 | [Create Intent](/api-reference/agentic-pay/create-intent) | Build the mandate (amount, currency, expiry, scope) and submit | | 3 | [Wallet Complete Order](/api-reference/payment/wallet-complete-order) | Capture the payment against the merchant — capture amount ≤ mandate amount | The destination's scheduler / trigger fires step 1. ## Agent considerations - **Build mandates honestly.** The mandate is the cardholder's authority over the agent. Setting the amount higher "just in case" defeats the protection. Match the mandate to the actual intent — the user agreed to "up to $80 for groceries this week", not "$80 anywhere". - **Re-authorize on scope changes.** A standing rule for "groceries from Merchant X" can't extend to Merchant Y. If the trigger pivots to a different merchant or product category, generate a fresh mandate (which the cardholder must approve interactively if you don't have an outstanding multi-merchant authorization). - **Handle the decline path.** Mandate violations are explicit and user-visible — a `400 BadRequest` from Firmly for an over-ceiling amount, or a decline from the network. Don't retry blindly — surface the decline to the user (in the destination's own conversation surface) and ask whether they want to update the rule or re-authorize. - **Mandate expiration.** Mandates are time-bounded. Track expiry on the destination side and prompt the user to re-authorize before they lapse — don't wait for the agent to try a payment and discover it failed. - **Audit per transaction.** Each autonomous purchase should write to the destination's audit log: which rule fired, what mandate was sent, what the network returned. This is the user's evidence in any dispute. ## When this fits - Wallets with replenishment / auto-buy features - Banks with delegated-purchase rules in their app - Brand-loyalty apps with subscription-like behavior - Connected devices (smart fridges, in-car AI) that buy on the user's behalf without prompting - AI chat products with persistent standing rules ("buy this when…") ## When this doesn't fit - The user is at a screen confirming each transaction → use [Smart Payment Selection](/solutions/agentic-commerce/use-cases/smart-payment) Path A–D instead - The destination doesn't have an existing scheduler / trigger mechanism → [Scheduled/Triggered Buying](/solutions/agentic-commerce/use-cases/scheduled-buying) describes **what the destination must build** (the scheduler and trigger) before autonomous purchasing works — it's a prerequisite to build, not an alternative that runs without one - The card network doesn't support the user's card for Agentic Pay → fall back to interactive Smart Payment paths --- ## Related - [Agentic Pay concept](/solutions/agentic-commerce/agentic-pay) — Network Token Router, two payment models, mandate model in detail - [Agentic Pay Integration Guide](/solutions/agentic-commerce/agentic-pay-integration) — 8-step partner walkthrough - [Headless SDK](/api-reference/headless-sdk/) — browser SDK wrapping the enrollment + intent flow - [Smart Payment Selection](/solutions/agentic-commerce/use-cases/smart-payment) — the broader payment path picker (Agentic Pay is Path E) - [Scheduled / Triggered Buying](/solutions/agentic-commerce/use-cases/scheduled-buying) — destination-side scheduler/trigger patterns - [Consent & Disclosure](/solutions/agentic-commerce/consent-and-disclosure) — how to record and govern the standing authorization --- # Branded Commerce FAQ For cross-cutting questions, see the [General FAQ](/faq) and [Technical FAQ](/troubleshooting/faq-technical). ## Setup and scope ### Do I need to write any code for Branded Commerce? No. Branded Commerce pages are Firmly-hosted under the partner's own domain via DNS — the partner adds two CNAME records (production + staging), provides brand assets and ad-platform credentials, and that's it. Firmly's edge serves the pages; the partner doesn't ship code. See [Integration Patterns](/solutions/branded-commerce/integration-patterns/). ### What environments do I get? Both production and staging, from day one. Each is an independent enrollment in Cloudflare for SaaS with its own CNAME and its own TLS certificate. Staging stays in place permanently for pre-production testing of new themes and campaigns — there's no "promote staging to production" path. See [Partner onboarding](/solutions/branded-commerce/operations/partner-onboarding). ### Who does what during onboarding? The partner provides DNS records, brand assets, ad-platform credentials, and legal copy. Firmly applies theming, provisions TLS, configures the merchant adapters, sets up affiliate routing, and stands up the staging environment. The full split is documented in [Branded Commerce → Who does what](/solutions/branded-commerce/#who-does-what). ### Do I take on PCI scope? No. Payment data is captured by Firmly's checkout component and tokenized via the merchant's PSP. The partner doesn't see card data, store it, or transmit it. PCI scope is entirely on Firmly's side. ## Theming and brand identity ### What is "Powered by Firmly" and is it required? A small attribution mark Firmly places on every partner-branded page (PDP, landing page, checkout, thank-you). It acknowledges Firmly as the commerce engine behind the experience while the partner's brand remains the dominant identity. The buyer sees the partner's logo, colors, fonts, and domain throughout — the "Powered by Firmly" mark is small and unobtrusive. The mark is part of the standard Branded Commerce arrangement and is enabled by default. Whether it can be removed or customized is a commercial matter — discuss it with [Firmly](/contact) during onboarding. ### Can I A/B test the theme? Partner-side A/B testing of themes is handled today by Firmly ops (manual configuration of two theme variants and traffic splitting). Self-service A/B testing is on the roadmap. Discuss your specific A/B needs with [Firmly](/contact) during onboarding. ### Can I run multiple brand properties under one Firmly account? Yes. Per-property theming is supported — one onboarding can produce multiple theme variants (e.g., several deal sites under one parent organization). Each property gets its own theme; the same merchant set can be reachable across all of them. See [Partner onboarding → Per-property theming](/solutions/branded-commerce/operations/partner-onboarding#per-property-theming). ## Multi-merchant landing pages ### Can a landing page span multiple merchants? Yes — a [curated landing page](/solutions/branded-commerce/use-cases/curated-landing-page) can feature products from multiple merchants in the same grid. Each card shows live pricing from its respective merchant. When the buyer clicks a product, they enter the single-product PDP → checkout flow for **that merchant only**. ## Performance tracking and attribution ### What's the ROAS tracking story when the buyer clicks "Visit Merchant"? There's a known limitation: | | Buy on Firmly | Visit Merchant | |---|---|---| | **Affiliate commission** | Tracked | Tracked (affiliate redirect) | | **Ad ROAS** | Tracked (Firmly fires pixel) | **Not tracked** — Firmly does not control the merchant's pages | ROAS tracking covers Firmly-hosted conversions only. Affiliate commission is tracked regardless of path. See [Operations → Performance tracking](/solutions/branded-commerce/operations/#performance-tracking). --- ## Related - [Branded Commerce overview](/solutions/branded-commerce/) - [Why Firmly for Branded Commerce](/solutions/branded-commerce/why-firmly) - [General FAQ](/faq) - [Technical FAQ](/troubleshooting/faq-technical) - [Agentic Commerce FAQ](/solutions/agentic-commerce/faq) - [Use Cases](/solutions/branded-commerce/use-cases/) --- # Branded Commerce > **Note** > **What's in this section:** Use Cases (which scenario you're building), Flows (the API sequence in detail), Integration Patterns (where the checkout UI lives), and Operations (partner onboarding, dashboard, operational workflow). Branded Commerce is a **white-labeled commerce solution**: pages are **Firmly-hosted under the partner's own domain**. The partner provides brand assets, DNS, ad credentials, and legal text; Firmly does the rest — pages, cart, checkout, payment, attribution. When a buyer clicks an ad promoting a product deal, they land on a Firmly-hosted, partner-branded site and complete checkout without ever leaving the partner's domain. The merchant's order management system receives the order as if a customer had placed it on the merchant's own storefront. The buyer never leaves the partner's domain. The merchant remains the seller and the order lands in their existing platform — Firmly's role is the cart, checkout, payment, and attribution plumbing in between. ## Who this is for Branded Commerce is built for partners whose business is **driving deal traffic to checkout** — without owning the commerce stack: - Affiliate networks and deal publishers - Retail-media networks running sponsored-product ads - Ad networks placing product-deal creative - Social commerce platforms surfacing influencer deals - Editorial / content sites with embedded product links The partner shapes the buyer-facing identity. Firmly powers everything underneath — catalog, cart, checkout, payment, attribution. ## How it fits together ![How Branded Commerce fits — partner brand owns the surface, Firmly powers the commerce engine under the partner's domain, merchant remains the seller of record](/images/branded-commerce/how-branded-commerce-fits.svg) ## Who does what The broad split. For the full responsibility matrix see [Why Firmly → Who owns what](/solutions/branded-commerce/why-firmly#who-owns-what). | Area | Partner | Firmly | Merchant | |---|---|---|---| | Brand, design, and buyer experience | ✓ | — | — | | Catalog, cart, checkout, payment | — | ✓ | Catalog source + receives the order | | Affiliate + ad-platform attribution | Credentials (BYO or delegated) | Executes | — | | Legal text (T&C, privacy, disclaimers) | ✓ | Renders | Merchant T&C displayed alongside | | Everything after order placement | — | — | ✓ | ## What the buyer experiences A distraction-free ad-to-checkout path: from ad click to order in a few taps, without leaving the partner's domain. - Ad creative messaging carries forward through every step — PDP, checkout, thank-you page — so the deal context is never lost - No merchant site navigation, no account creation - Express wallets (Click to Pay, PayPal) alongside standard card entry - Promo code from the ad is auto-applied and visible on every screen - A clear merchant identity callout (*"Shopping with [Merchant]"*) so the buyer knows who they're buying from - A small *"Powered by Firmly"* attribution mark acknowledges the commerce engine behind the experience — the partner's brand stays dominant ## What the partner gets - A fully white-labeled commerce experience under their domain, logo, colors, and fonts — buyers never see Firmly's brand (apart from the "Powered by Firmly" attribution) - Automatic affiliate attribution (BYO or Firmly-managed) - Engagement analytics - PCI scope handled entirely on Firmly's side - Editorial content layered on top of merchant product data — promoting a specific product, a new product line, or a curated collection tailored to a campaign ## What the merchant gets Incremental sales from deal-driven ad traffic. Orders are placed on the merchant platform as if they happened on the merchant's own website. Existing affiliate commissions flow unchanged. No merchant-side integration required beyond being onboarded to Firmly. ## Three layers of the platform - **Discovery & PDP** — Fetch live product data — title, images, variants, pricing, inventory — from the merchant's platform via Firmly's adapters. Render the PDP under the partner's theme with the promo applied. - **Cart & Checkout** — Build the cart and set shipping (the cart returns merchant-calculated tax and totals), then collect payment via card, PayPal, or Click to Pay. Apply the promo code from the ad. All under the partner's theme. - **Order Placement** — Submit the order to the merchant's native platform. Fire affiliate conversion + ad-platform signals. Firmly's scope ends here. ## Use cases at a glance - [Single-product deal](/solutions/branded-commerce/use-cases/single-product-deal) — Ad → partner-branded PDP → checkout. The simplest ad-to-checkout path; ad creative promotes one specific product. - [Curated landing page](/solutions/branded-commerce/use-cases/curated-landing-page) — Ad → partner-branded occasion page with a product grid → PDP → checkout. For gift guides, seasonal events, themed deal roundups. - [Retail-media placement](/solutions/branded-commerce/use-cases/retail-media-placement) — Sponsored-product ads on retail-media networks routed to partner-branded checkout. ## Where to start - [Why Firmly](/solutions/branded-commerce/why-firmly) — What Firmly brings, what Firmly is not, the ownership boundary between partner and Firmly. - [Flows](/solutions/branded-commerce/flows/single-product-purchase) — The API sequence behind the buyer experience — annotated call by call. - [Integration Patterns](/solutions/branded-commerce/integration-patterns/) — Partner-hosted under partner's domain, white-label theming, attribution model choice. - [Operations](/solutions/branded-commerce/operations/) — Partner onboarding, ongoing per-product workflow, performance tracking. --- ## Related - [Branded Commerce FAQ](/solutions/branded-commerce/faq) — common partner questions, ROAS limits, multi-merchant rules - [Cart Lifecycle](/api-reference/cart-management/cart-lifecycle) — how the cart progresses to a placed order - [Consent & Disclosure](/solutions/agentic-commerce/consent-and-disclosure) — pre-purchase disclosure responsibilities - [For Merchants](/for-merchants/) — the merchant's side of the integration - [Solutions overview](/solutions/) — Branded Commerce alongside Firmly's other solutions --- # Branded Marketplace A marketplace operator builds a branded shopping destination with a curated set of merchants. The buyer searches across the operator's merchants, selects products, and checks out — each cart scoped to one source merchant. The marketplace identity belongs to the operator; the merchant is the seller of record. ## Recommended setup | Choice | Default | Why | |---|---|---| | **Integration pattern** | [Operator-Hosted](/solutions/marketplace/integration-patterns/operator-hosted) or [Embedded Marketplace](/solutions/marketplace/integration-patterns/embedded-marketplace) | Operator owns the branded UI either fully or embedded in another product | | **Auth** | [Browser session](/api-reference/authentication/browser-session) | Per-user marketplace browsing session | | **Payment** | Card (JWE-encrypted) as primary; PayPal, Google Pay, or Klarna per operator preference | A single-merchant cart supports the full payment menu | | **Attribution** | Marketplace operator ID + source merchant | Operator's identity tagged on every order | ## API sequence Follows the [Single Product Purchase](/solutions/marketplace/flows/single-product-purchase) flow. | Step | Endpoint | |---|---| | 1. Search the marketplace | [`POST /api/v1/discovery/search`](/api-reference/discovery/search) | | 2. Add to cart | [`POST /api/v2/domains/{domain}/cart/line-items`](/api-reference/cart-management/add-line-item) | | 3. Set shipping address | [`POST /api/v2/domains/{domain}/cart/shipping-info`](/api-reference/checkout/set-shipping-info) | | 4. Pick shipping method | [`POST /api/v2/domains/{domain}/cart/shipment/methods`](/api-reference/shipment-configuration/set-shipping-method) | | 5. (Optional) Get delivery availability | [`POST /api/v2/domains/{domain}/cart/shipments/get-availability`](/api-reference/shipment-configuration/get-availability) | | 6. (If required) Get + set merchant consents | [`GET /api/v2/domains/{domain}/cart/consents`](/api-reference/checkout/get-consents) → [`PUT /api/v2/domains/{domain}/cart/consents`](/api-reference/checkout/set-consents) | | 7. Get payment public key | [`GET /api/v1/payment/key`](/api-reference/payment/get-public-key) | | 8. Complete order | [`POST /api/v2/payment/domains/{domain}/complete-order`](/api-reference/payment/complete-order-v2) | The valid `shipping_method_id`s for step 4 come from the cart itself — `cart.shipments[].shipping_method_options`, populated by step 3 (`set-shipping-info`). `get-availability` (step 5) is optional and returns delivery dates, time slots, or pickup locations for scheduled-delivery or in-store-pickup shipments — not shipping methods. Steps 2–6 build the cart, so step 8 finalizes it with [`complete-order`](/api-reference/payment/complete-order-v2) (body: `encrypted_card` + `billing_info`); use [`place-order`](/api-reference/payment/place-order-v2) only for the one-shot create-cart-and-order call. ## Considerations the operator owns - **Curated merchant selection.** The operator decides which merchants are visible. Typically there's an admin process to approve merchants before they appear in marketplace search results. - **Brand consistency.** Marketplace UI carries the operator's brand, not the source merchant's. When the buyer reaches the merchant's order confirmation, the marketplace UI re-wraps it in operator branding (a link to the merchant's real confirmation is still surfaced). - **Trust signals.** Product-level ratings and review counts come through the catalog; surface them on search results and product pages. Any merchant-level reputation presentation is the operator's own layer. - **Marketplace-specific commission.** If the operator charges a commission, reconcile it from the operator ID carried on each order's metadata — the operator's own commission-tracking system matches orders by that identifier. --- ## Related - [Single Product Purchase Flow](/solutions/marketplace/flows/single-product-purchase) - [Operator-Hosted pattern](/solutions/marketplace/integration-patterns/operator-hosted) - [Embedded Marketplace pattern](/solutions/marketplace/integration-patterns/embedded-marketplace) --- # Buyer Purchase Flow This page covers the **end-to-end buyer experience** for Branded Commerce. The flow happens entirely on the partner's domain, under the partner's theme — the buyer never visits the merchant's website (unless they choose to via the *Visit Merchant* link on the PDP). There are **two entry-point variations** of the same flow: | Variation | Entry phase | Where the ad routes to | |---|---|---| | **Single-product** | Ad → PDP | A specific product the partner is promoting | | **Curated landing page** | Ad → Landing page → PDP | An occasion page with a product grid (gift guides, seasonal events, themed roundups) | The PDP, checkout, and thank-you phases are identical across both variations. Everything below applies to both unless flagged. > **Note** > The **phases** on this page describe the buyer's experience (ad click, landing, PDP, checkout, thank-you). They are a different taxonomy from the five **API phases** on [Single Product Purchase](/solutions/branded-commerce/flows/single-product-purchase) (Hosting, Authentication, Discovery, Checkout, Order placement), which describe the integration surface. One buyer-experience phase can span several API phases. ## Phase 1 — Ad click The buyer sees a paid ad. The ad creative carries the deal message and a CTA that links to the partner's Firmly-hosted domain. | Source | Mechanism | Example | |---|---|---| | Social ads | Tap / click | Facebook, Instagram, TikTok with "Shop Now" CTA | | Search ads | Click on sponsored result | Google Shopping, Bing product ad | | Display / TV ads | QR-code scan | Connected-TV ad showing a QR code | | Retail-media | Click on sponsored placement | Walmart Connect, Target Roundel | | Direct | Click on link | Email, SMS, influencer post, deal roundup | The ad links to a URL on the partner's domain. The promo code from the ad is embedded in the URL and **auto-applied** — the buyer does not need to enter it manually. Single-product variation: ```text https://deals.partner.example/buy/?promo=SAVE20 ``` Curated landing-page variation: ```text https://deals.partner.example/event/?promo=MOM20 ``` ## Phase 2 — Landing page *(curated variation only)* A full-page, partner-branded occasion page. The buyer browses curated products before selecting one. **Header (two-part):** 1. Partner branding (logo, name) plus *"Powered by Firmly"* attribution; back arrow to the referring page 2. Promo banner — *"Exclusive offer: Save 20% with code MOM20"* **Merchant identity** — *"Shopping with [Merchant]"*. For multi-merchant landing pages, the per-product cards each show their own merchant. **Occasion title** — large heading identifying the event ("Mother's Day Gift Guide", "Summer Skincare Essentials"). **Product grid** — two-column grid; each card has product image with discount-badge overlay, product name, brief description, pricing (strikethrough + discounted + promo reference), and a **Shop Now** button that taps through to the PDP. **Footer** — *"Discount automatically applied at checkout"* notice; *"Powered by Firmly"*. For curated landing pages, the buyer can browse products from **multiple merchants** in the same grid — each product card links to a single-merchant PDP. See [Curated landing page → Multi-merchant landing pages](/solutions/branded-commerce/use-cases/curated-landing-page#multi-merchant-landing-pages) for details. ## Phase 3 — PDP A full-page, partner-branded product detail page on the partner's domain. **Header (two-part):** 1. Partner branding + *"Powered by Firmly"* + back arrow 2. Merchant identity — *"You are shopping with [Merchant]"* + the merchant's domain **Product content:** - Product images with thumbnail navigation - Product name - Promotional pricing — discounted price prominent, original strikethrough, savings callout, promo reference - Product description (from the merchant's catalog) - Variant selectors — size, color, or others with per-variant prices - Quantity selector - Key benefits — bullet list **Two CTAs at the bottom:** | CTA | Action | |---|---| | **BUY NOW FROM [MERCHANT]** *(primary, solid)* | Proceeds to the partner-branded checkout | | **VISIT [MERCHANT].COM** *(secondary, outlined)* | Redirects to the merchant's own product page with affiliate parameters preserved — the partner still earns commission | The promo code is visible throughout the PDP — in the pricing section, and as a banner below the header. ## Phase 4 — Checkout A full-page, partner-branded checkout. Replaces the PDP — not a slide-out. **Header** — same two-part structure: partner branding plus *"You are checking out with [Merchant]"*. **Order summary** — collapsible section. Collapsed: product name + total. Expanded: full product details, promo confirmation, subtotal, shipping, tax, discount, total due today. **Express checkout** — wallet options alongside standard card entry: | Wallet | Status | |---|---| | Click to Pay (Visa / Mastercard) | Live | | PayPal | Live | | Google Pay | Planned | Clicking an express option skips address and payment entry — the wallet returns both a shipping address and payment authorization. **Standard form** (when not using an express wallet): 1. **Email** — email field, with a Click to Pay consent notice below it 2. **Shipping address** — name, address fields, city, ZIP, state, phone with country-code selector 3. **Shipping method** — available options with prices; *Change* link to select alternatives 4. **Payment** — card number, MM/YY, CVV; billing-address-same-as-shipping checkbox defaults to checked 5. **Order summary** — full breakdown at the bottom **Place order** — the buyer taps **PLACE ORDER**. A legal footer sits below the button linking to the partner's and merchant's terms and to Firmly's privacy policy. The exact documents surfaced are described under [Pre-purchase disclosure](#pre-purchase-disclosure) below, which is the authoritative list — the partner's T&C and privacy policy plus the merchant's T&C are all shown at checkout. **Payment failure (inline)** — if payment fails (e.g., card declined), the error displays inline on the same page: - Error banner with the failure reason - Card field highlighted red with inline error text - **TRY AGAIN** *(primary)* — buyer corrects and retries - **VISIT [MERCHANT].COM** *(secondary)* — redirects to the merchant's site with affiliate parameters preserved ## Phase 5 — Thank-you page After order placement, the checkout transitions to a partner-branded confirmation. - **Success indicator** — confirmation heading - **Merchant confirmation notice** — *"[Merchant] will send the order confirmation"* - **Savings callout** — *"You just saved $[amount] with [Partner]! Coupon SAVE20 was applied to your order"* — reinforces the value of the partner's deal - **Order details** — merchant name, order number from the merchant, order total, payment (card type + last 4), email, shipping-to address, shipping method + estimated delivery - **Merchant links** — Contact, Returns, Terms — pointing to the merchant's own pages so the buyer can reach the merchant directly for anything after the order - **Footer** — *"Powered by Firmly"* with Terms and Privacy links ## What happens behind the scenes Each phase corresponds to operations Firmly performs against the merchant's platform. The buyer-facing experience is unified; the under-the-hood sequence is: 1. **Ad click** — the partner's custom domain routes to Firmly's edge service under first-party TLS 2. **Affiliate URL expansion** — Resolve the affiliate URL, extract the attribution key, identify the network 3. **Session attribution storage** — Persist the attribution key server-side through the checkout session (replaces browser cookies) 4. **Catalog fetch** — Fetch real-time merchant product data via the platform adapter (price, images, variants, stock) 5. **PDP or landing-page render** — Render under the partner's theme with the promo applied 6. **Session + cart on the merchant** — Create an anonymous guest session and a cart on the merchant's backend 7. **Promo application** — Apply the promo code from the ad URL to the merchant's cart 8. **Shipping resolution** — Submit address; fetch available methods + rates; submit chosen method 9. **Tax + billing** — Trigger merchant tax calculation; submit billing address 10. **Payment tokenization** — Tokenize payment data via the merchant's PSP; submit token 11. **Order placement** — Submit the finalized checkout to the merchant for order creation; capture the merchant's order number + confirmation 12. **Affiliate conversion posting** — Fire the conversion to the affiliate network using the stored attribution key 13. **Ad conversion signals** — Fire conversion events to the partner's ad platforms (Meta CAPI, Google Ads Enhanced Conversions, TikTok / Pinterest / Snap / Reddit Conversions APIs) using the partner's pixel IDs and the click context captured at entry Steps 12–13 fire automatically after order placement — the partner doesn't trigger them. ## Pre-purchase disclosure The partner's T&C and privacy policy plus the merchant's T&C are both displayed at checkout. See [Consent & Disclosure](/solutions/agentic-commerce/consent-and-disclosure) for the broader pattern of what to surface before order placement. --- ## Related - [Use Cases](/solutions/branded-commerce/use-cases/) — entry-point variations - [Single-product deal](/solutions/branded-commerce/use-cases/single-product-deal) — phase-by-phase walkthrough scoped to the single-product variation - [Curated landing page](/solutions/branded-commerce/use-cases/curated-landing-page) — the landing-page variation - [Integration Patterns](/solutions/branded-commerce/integration-patterns/) — how partner-hosted setup works - [Cart Lifecycle](/api-reference/cart-management/cart-lifecycle) — how the cart progresses through to a placed order - [Consent & Disclosure](/solutions/agentic-commerce/consent-and-disclosure) --- # CDN whitelisting Allow Firmly traffic through your CDN, WAF, bot-management system, or rate limiter. Configure an allow rule only when these controls block Firmly requests. Apply the rule to each staging and production hostname that Firmly will access. > **Note** > **Whitelisting** is the label in the Firmly Connect wizard. The audit log records this task as `cdn_whitelisting_completed`. **Allowlisting** means the same action. > **Note** > **Most merchants do not need this task.** Firmly shows it in the onboarding wizard only when the merchant's security controls require an allow rule. ## Firmly Connect guidance Firmly Connect detects the CDN or WAF that protects the merchant domain. The merchant can change the detected provider when the result is not correct. The wizard includes provider-specific instructions for: - Cloudflare - Akamai - Fastly - Google reCAPTCHA Enterprise - CloudFront with AWS WAF - Other CDN and WAF products Each guide provides numbered steps and copy controls for rule values. The task remains locked until KYB approval. It is the final merchant action before the Firmly go-live review. ## Choose an allowlisting method Use the first method that your security product supports. - **1. Web Bot Auth** — Verify Firmly's signed requests. This method does not require a shared secret or fixed source IP address. - **2. Header-based** — Match a merchant-specific `x-ac-auth` value. This method works with most CDNs and WAFs. - **3. IP-based** — Allow Firmly's fixed egress addresses. Use this method only when request-level identity is not available. | Method | Use when | Request path | Identity | |---|---|---|---| | Web Bot Auth | Your edge can verify FirmlyAI Bot or HTTP message signatures | Distributed edge | Cryptographic signature | | Header-based | Your security product can match an exact header value | Distributed edge | Merchant-specific shared secret | | IP-based | Your security product cannot use either request-level method | Fixed egress | Source IP address | ## Why request identity is preferred Firmly runs on distributed edge infrastructure. Web Bot Auth and header-based allowlisting attach identity to each request. Firmly can then use a direct path to your CDN or WAF. IP allowlisting requires Firmly to route traffic through fixed egress gateways. This adds a network hop and can add latency. ```mermaid flowchart LR subgraph Identity["Request identity"] FE["Firmly distributed edge"] -->|"Signature or shared header"| MW["Merchant CDN or WAF"] MW --> MA["Merchant API"] end subgraph Fixed["IP allowlisting"] DE["Firmly distributed edge"] --> EG["Fixed egress gateway"] EG -->|"Allowlisted source IP"| FW["Merchant CDN or WAF"] FW --> API["Merchant API"] end ``` Request-level identity has these benefits: - It preserves direct routing from Firmly's edge to your edge. - It continues to work when a reverse proxy changes the source IP address. - It keeps access control independent of Firmly's network topology. - It avoids routing all merchant traffic through fixed egress gateways. > **Warning** > IP allowlisting is a compatibility fallback. Use Web Bot Auth or header-based allowlisting when your security product supports either method. ## Web Bot Auth Firmly signs outbound requests with HTTP message signatures. Your edge verifies the signature with Firmly's published public key. This method does not use a shared secret. Cloudflare lists [FirmlyAI Bot](https://radar.cloudflare.com/bots/directory/firmlyai-bot) in its verified bot directory. Cloudflare can verify the signed request and classify it as FirmlyAI Bot. ### Cloudflare setup 1. Confirm that your Cloudflare plan can create a rule for the FirmlyAI Bot identity. 2. Create an allow or skip policy for verified FirmlyAI Bot requests on the required hosts and routes. 3. Keep your normal security policy for unsigned requests and requests with an invalid signature. 4. Do not remove or rewrite the `Signature-Agent`, `Signature-Input`, or `Signature` headers before Cloudflare verifies the request. 5. Tell Firmly which domains and environments use this policy. Firmly will send a signed request and verify access. If your Cloudflare plan cannot select the FirmlyAI Bot identity, use header-based allowlisting. See [Cloudflare Web Bot Auth](https://developers.cloudflare.com/bots/reference/bot-verification/web-bot-auth/) for plan and verification details. ### Other edge providers Your CDN, WAF, API gateway, or origin must support Web Bot Auth or RFC 9421 HTTP message signatures. It must use the public key identified by `Signature-Agent` to verify `Signature-Input` and `Signature`. Keep your normal security policy for unsigned requests and requests that fail verification. ## Header-based allowlisting Firmly and the merchant agree on a unique shared-secret value. Firmly sends the value in the `x-ac-auth` request header. The exact header name and value shown in Firmly Connect are authoritative for your integration. Do not use an example value from documentation. Some Firmly Connect guides generate a new example secret when the page loads. If you use this value, copy it once. Use the same value in the merchant rule and in the secure handoff to Firmly. A page reload creates a different example and does not change the value already configured at either side. 1. Get the merchant-specific value from Firmly through the agreed secure channel. 2. Create a rule that matches the complete `x-ac-auth` value. The value is case-sensitive. 3. Configure the matching request to skip only the controls that block Firmly. These controls can include managed WAF rules, bot checks, and rate limits. 4. Put the allow rule before conflicting block and rate-limit rules. 5. Limit the rule to the required hostnames and routes when your security product supports this restriction. 6. Tell Firmly that the rule is ready. Firmly will send a request with the same value and verify access. Do not publish the shared secret in documentation, source code, or a support ticket. > **Tip** > To rotate the secret without downtime, allow the old and new values for a short time. Remove the old value after Firmly verifies the new value. ## IP allowlisting Use IP allowlisting only when Web Bot Auth and header matching are not available. | IP address or CIDR | Address family | |---|---| | `104.28.1.121/32` | IPv4 | | `24.199.70.88/32` | IPv4 | | `24.144.66.39/32` | IPv4 | | `161.35.254.19/32` | IPv4 | | `2a09:bac5:fff0:54::/64` | IPv6 | | `2a09:bac6:fff0:54::/64` | IPv6 | 1. Add all four IPv4 addresses to the allowlist. 2. Add both IPv6 ranges when your endpoint and security product support IPv6. 3. Apply the rule at the layer that receives Firmly's source address. 4. Do not trust an arbitrary forwarded-IP header when a CDN replaces the source address. 5. Limit the rule to the required hostnames and routes when possible. 6. Tell Firmly which domains and environments use the rule. Firmly will route a test through fixed egress and verify access. Always check this page for the current IP list before you configure a new environment or production release. ## Complete the Firmly Connect task After you configure the selected method: 1. Ask Firmly to run an access test. 2. Confirm that the request reaches the merchant endpoint without a WAF block, bot challenge, or rate-limit response. 3. Confirm that requests without valid identity continue through the normal security policy. 4. Select **I've completed the configuration** in Firmly Connect. 5. Mark the task complete. Firmly Connect records the action in the audit log and unlocks the next onboarding task. ## Verification criteria Firmly checks these results before integration testing continues: - The selected method identifies Firmly traffic. - Invalid or unidentified traffic does not use the allow rule. - Catalog and cart tests run without intermittent access failures. - The rule covers each required staging and production hostname. --- ## Related - [Onboarding wizard](/solutions/firmly-connect/onboarding/) — the complete merchant onboarding sequence - [Going Live](/for-merchants/going-live) — the final review and approval task - [Audit logs](/solutions/firmly-connect/portal/audit-logs) — the recorded completion event --- # Catalog configuration The merchant chooses how much of their store to expose to Firmly's network of agents, publishers, and marketplaces — either the entire catalog (auto-synced, new products added as they appear in the merchant's commerce backend) or a curated subset that Firmly's team helps scope. The same surface is used during onboarding and as a post-onboarding configuration page. ## Two modes (radio cards) | Mode | What it does | Marked as | |---|---|---| | **Entire Catalog** | Sell all products across enabled destinations. New products auto-sync, inventory updates in real time. | **Recommended** — fastest to launch, maximum exposure, simplified management | | **Selected Products (Subset)** | A curated set of product categories or individual products. Allows destination-specific catalogs and testing with limited inventory. | **Advanced** — after you save this mode, Firmly's team reaches out to scope the specific selection with you; you can also flag it in the onboarding conversation with your Firmly contact | ## How the save flow works - **Default is Entire Catalog.** If the merchant has no existing catalog configuration on first visit, the page pre-selects Entire Catalog. - **Save is required even if accepting the default.** On first visit there is no saved value yet, so Save is enabled and the merchant clicks it once to record the default. After a value is saved, the Save button is disabled until the selection differs from the saved value. - **First save during onboarding advances the wizard.** When the merchant saves this task during onboarding, the page returns them to the task menu so they can pick up the next task. ## The product list (read-only) A separate "Products" view under the Catalog section in the sidebar shows what Firmly has ingested from the merchant's commerce backend. - Search by name - Paginated (24 per page, with "Load more") - **Read-only** — no edit / delete. The merchant's commerce backend remains the source of truth - **Empty state until sync completes.** Until Firmly's integration has finished syncing, the list shows "Products will appear here once they are synced from your store" — the merchant uses this as a sanity check that integration is working. Sync typically completes by the time KYB is approved; if the list is still empty well after that, check with your Firmly contact ## Gating - **KYB-gated during onboarding.** The catalog task stays locked behind KYB approval. See [Onboarding wizard](/solutions/firmly-connect/onboarding/). - **Post-onboarding, always reachable.** The merchant can broaden or narrow what's shared as their store changes. --- ## Related - [Onboarding wizard](/solutions/firmly-connect/onboarding/) — the 7-step sequence - [Know Your Business](/solutions/firmly-connect/onboarding/know-your-business) — KYB must be approved first - [Destinations configuration](/solutions/firmly-connect/onboarding/destinations-configuration) — next step --- # Chat to Checkout The [Advanced Checkout Guide](/cookbook/advanced-checkout-guide) shows the happy path: clear intent, one matching product, no errors. This page covers the messy reality of conversational checkout — ambiguous intent, multiple matches, mid-flow corrections, errors recovered through dialogue. ## The pattern Every conversational purchase moves through five micro-phases that are different from the API-level phases: 1. **Intent** — user expresses what they want, in natural language 2. **Disambiguation** — agent narrows it down to one product, variant, quantity 3. **Confirmation** — agent surfaces what's about to happen and gets explicit consent 4. **Execution** — agent calls Firmly APIs to place the order 5. **Result** — agent surfaces outcome (success, error, partial recovery) The first three happen on your side. Firmly only sees phase 4. ## Worked example — a real chat sequence The dialogue below is annotated with the API calls your agent makes at each step. ```text User: Hey, can you order me a black hoodie? Agent: One sec, let me look. → POST /api/v1/discovery/search { query: "black hoodie" } Response: 4 products from the target merchant, varying prices Agent: Here's what I found: 1. Luma Classic Hoodie — Black — $45 2. Luma Tech Hoodie — Black — $89 3. Luma Premium Heavy Hoodie — Black — $120 4. Luma Hoodie — Black/Gray — $55 Which one — or want me to read more details? User: The classic one. Medium. Agent: One Luma Classic Hoodie, Black, size Medium for $45 — shipping to your usual address (123 Main St, Brooklyn NY). Total with shipping and tax will be around $52. Want me to place the order? [Internally, agent has already done the cart preview:] → POST /cart/line-items { add_to_cart_ref: {…size:M, color:black}, quantity: 1 } → POST /cart/shipping-info { …saved address } (response carries shipping_method_options per shipment) → POST /cart/shipment/methods { shipment_id, shipping_method_id } Response: total = $52.13, shipping_method = "Standard $5", tax = "$2.13" User: Yes go ahead Agent: Placing the order now... → GET /cart/consents (fetch any merchant-required consents) → PUT /cart/consents (record the buyer's acceptance if the merchant requires it) → GET /payment/key (cached) → POST /payment/complete-order { encrypted_card, billing_info } (finalizes the cart built above) Response: { cart_status: "submitted", cart_id: "03798510-b778-4742-ba25-5812a552507f", platform_order_number: "29185", urls: { order_status_page: "https://merchant.example/orders/..." }, custom_properties: { order_token: "..." }, total: { value: 52.13, symbol: "$", currency: "USD" } } Agent: Done! Your order is in for $52.13. It'll ship in 2–3 business days — I'll send you the merchant's order page link if you want. ``` This is the pattern your agent should reach for. Six user-visible turns, eight API calls, full consent, recoverable at every step. ## The four hard parts ### 1. Disambiguation When `discovery/search` returns multiple products, the user has to pick one. There's no winning shortcut here — your agent's job is to present options in a way the user can scan and choose. **Pattern**: cap the visible list at 3–5 items, sorted by relevance or popularity. Offer to read details on any of them. Avoid auto-picking the top result unless the user explicitly delegates (*"just get me whatever you think"*). ```javascript const search = await callFirmly('/api/v1/discovery/search', { query: userIntent.query, page_size: 5 }); if (!search.products?.length) { return reply(`I couldn't find anything matching "${userIntent.query}".`); } if (search.products.length === 1) { return confirmSingle(search.products[0]); } return reply(formatProductList(search.products.slice(0, 5))); ``` ### 2. Variant resolution A single product may have many variants (sizes, colors, materials). The user may have specified some (*"medium"*, *"in black"*) and not others. Walk the variant axes: ```javascript function resolveVariant(product, userHints) { // Variants carry `variant_option_list`: a flat array of option strings // (e.g. ["Black", "Medium"]) with no axis labels. Match each hint value // against any entry in that array. const hintValues = Object.values(userHints); const candidates = product.variants.filter(v => hintValues.every(value => (v.variant_option_list || []).some(opt => opt?.toLowerCase().includes(value.toLowerCase()) ) ) ); if (candidates.length === 1) return candidates[0]; if (candidates.length === 0) return null; // Multiple still match — ask for the missing axis return { needsMoreInfo: true, candidates }; } ``` If `needsMoreInfo`, ask the user the discriminating question (*"Which color — black or charcoal?"*). ### 3. Confirmation that's real A confirmation message that just says *"OK, ordering"* and proceeds is not consent — it's an announcement. A confirmation that names the **item, total, and destination** and waits for an explicit *"yes"* is consent. **Required content** (per [Consent & Disclosure](/solutions/agentic-commerce/consent-and-disclosure)): - What (product, variant, quantity) - From whom (merchant brand) - Total cost including tax and shipping - Where it's going **Optional but recommended**: - Estimated delivery - Payment method (*"on the Visa ending in 4242"*) - Return policy link After the confirmation, **record the user's response with a timestamp**. This is your evidence in any dispute. ### 4. Recovery from errors The most common failure modes in conversational checkout: | Error | Conversational response | |---|---| | `NotEnoughStockError` (409, between confirm and complete-order) | *"Looks like the medium just sold out — they still have a small or a large. Want one of those?"* | | `CreditCardDeclined` (422) | *"The card was declined. Want to try a different one, or use PayPal?"* (Do NOT say the issuer's reason verbatim — it leaks information.) | | No saved address (client-side check before `set-shipping-info`) | *"What address should this ship to?"* | | `StoreUnavailable` (503) | *"The merchant's having a hiccup. Try again in a minute?"* (Don't reveal which merchant or technical detail.) | | Timeout / network error | Retry with the same `Idempotency-Key`. The user shouldn't see this. | See [Errors](/solutions/agentic-commerce/operations/errors) for the full catalog and recovery strategies. ## Pre-fetching for responsiveness To keep the conversation snappy, start the cart preview as soon as the user identifies the product — before they confirm — so you can quote a total without stalling. **Don't** parallelize these calls: `add-line-item` and `set-shipping-info` both mutate the same cart, and concurrent cart mutations race (last one wins). Chain them serially and let the network round-trips overlap the user's reading time instead: ```javascript // As soon as the user identifies the product, build the cart preview serially — // discard the work if they back out. Both calls mutate the same cart, so they run in order. const cartResp = await callFirmly('/cart/line-items', { add_to_cart_ref, quantity }); const addressResp = await callFirmly('/cart/shipping-info', savedAddress); // Now you can quote the user a total in the confirmation message without stalling. ``` When the user confirms, only `complete-order` remains — it finalizes the cart the preview built (body: `encrypted_card` + `billing_info`), so nothing needs to be re-sent. See [Complete Order](/api-reference/payment/complete-order-v2). ## Mid-flow corrections Users change their minds. Common patterns: | User says | Your agent does | |---|---| | *"Make it 2 instead of 1"* | `PUT /cart/line-items/:id { quantity: 2 }` | | *"Actually use the black one"* | `DELETE /cart/line-items` then `POST /cart/line-items` with the new variant | | *"Add a hat too"* | `POST /cart/line-items { add_to_cart_ref: , quantity: 1 }` | | *"Ship it to my office instead"* | `POST /cart/shipping-info { …office_address }` (and re-do shipping method) | | *"Cancel that"* (before complete-order) | `DELETE /cart/line-items`, acknowledge to user | ## When to bail to a screen Some moments in conversational checkout are unpleasant in pure text: - Long address entry (5 fields × possible validation back-and-forth) - Payment method change (especially adding a new card) For these, consider **handing off to hosted checkout** at the awkward moment — text the user a Firmly checkout URL, let them finish on a screen, then re-engage when done. See [Hosted Checkout](/solutions/agentic-commerce/integration-patterns/hosted-checkout) for the handoff pattern. A hybrid agent (conversational by default, hosted for friction moments) is often the best UX. --- # Connected TV Connected TV (CTV) covers commerce on the living-room screen — CTV apps, OTT services, streaming surfaces, and shoppable TV content. The constraints are different from web or mobile: input is a remote control, the screen is shared across multiple household viewers, and the commerce surface has to work without a keyboard. ## What this category covers CTV destinations include: | Type | What it does | |---|---| | **Shoppable streaming content** | Products embedded in shows, ads, or sports broadcasts; viewers can buy without leaving the stream | | **CTV ad-driven commerce** | Shoppable pre-roll and mid-roll ads on CTV inventory | | **CTV-native commerce apps** | Standalone commerce experiences designed for the TV screen and remote | | **Remote-driven checkout** | Purchase flows optimized for D-pad input (not keyboard or touch) | ## Why CTV is a Firmly destination The challenges that map onto Firmly's platform: - **Input constraints** — remote-control purchase flows need fewer steps and larger UI elements; per-step friction is amplified - **Cross-device handoff** — many CTV commerce flows hand off to a mobile device for the final purchase step; the handoff has to preserve cart state and attribution - **Express wallets** — saved-payment wallets are critical because the buyer can't easily type card details on a TV - **Per-screen-format adaptation** — the same commerce flow needs to render correctly across CTV form factors ## Which Firmly solutions apply | Solution | When to use it | |---|---| | **[Branded Commerce](/solutions/branded-commerce/)** | When the CTV surface routes buyers to a partner-branded mobile or web purchase flow. | | **[Ad Commerce](/solutions/ad-commerce/)** | When commerce is driven from CTV ad placements. | ## Status today CTV destinations are on the Firmly roadmap. The underlying platform infrastructure (cart, checkout, attribution, payment) is in production and used by other destination categories. CTV-specific buildout — particularly cross-device handoff, remote-friendly UI, and per-CTV-platform integration — depends on partner demand and is scoped during onboarding. --- ## Related - [Branded Commerce overview](/solutions/branded-commerce/) - [Ad Commerce overview](/solutions/ad-commerce/) - [How Firmly Works](/how-firmly-works) --- # Consent & Disclosure When an agent buys on behalf of a user, the user has surrendered part of the purchase journey. Two questions follow immediately: 1. **Did the user actually authorize this specific purchase?** 2. **Does the user understand what they're getting, from whom, and at what price?** This page is the answer the destination engineer needs to read before going live. The substance is product-and-UX work, not legal language — it tells you what to build into your destination so the user is informed before the order is placed. ## How Firmly divides responsibility | Concern | Firmly handles | Destination handles | |---|---|---| | Payment tokenization, PCI scope | ✓ | — | | Tax & shipping totals — merchant calculates, Firmly relays them in the cart | ✓ | — | | Order placement into the merchant's system | ✓ | — | | Fraud and risk scoring at the payment layer | ✓ | — | | Affiliate attribution to the destination | ✓ | — | | Live inventory and price validation pre-order | ✓ | — | | **Pre-purchase disclosure to the user** | **—** | **✓** | | **Explicit user consent for the specific order** | **—** | **✓** | | **Recording of consent for audit / disputes** | **—** | **✓** | | **Post-purchase communication with the user** | **—** | **✓** | | Post-purchase support (returns, modifications) | Routes to merchant | Communicates outcome to user | The short version: **Firmly is the commerce backend. The destination owns the consent layer.** Firmly will not block an order placement because the user wasn't shown a confirmation — that is the destination's job. ## What Firmly does NOT mandate Firmly's checkout APIs and embedded checkout UI **do not enforce**: - A "review and confirm" step before order placement - Disclosure of merchant name, item, total, or return policy to the user - Consent capture or audit logging on the user side - A cooling-off period - Identity verification of the user This is intentional. Agentic surfaces vary too widely — voice, chat, ambient, autonomous — for one consent model to fit all. Firmly leaves the surface-appropriate consent UX to the destination. ## What the destination should do (recommended model) These are recommendations, not enforced rules. They reflect what we've seen work across early agentic deployments. ### Before placing the order Surface at least these four facts to the user, in whatever form the destination's surface allows: 1. **What** they're buying (product name, variant, quantity) 2. **From whom** (the merchant brand — not "Firmly") 3. **Total cost** including tax and shipping 4. **Where it's going** (shipping address) For text and conversational AI surfaces, this is a structured message before a "yes / confirm" reply. For voice surfaces, a clear spoken summary before *"Should I place the order?"* For ambient or autonomous flows, this still applies but the confirmation may be implicit (a pre-authorized spending limit, a recurring purchase rule the user previously set). ### Capture the confirmation Record: - A timestamp - The exact text shown to the user (or audio for voice) - The user's response - The session ID and any merchant references Keep this for at least as long as the merchant's return window — typically 30 to 90 days. This is the destination's evidence in any chargeback or dispute. ### After placing the order Surface to the user: - The order reference — Firmly's `cart_id` plus the merchant's native order number, returned as the first-class `platform_order_number` field on the [`complete-order`](/api-reference/payment/complete-order-v2) response (some merchants also echo platform-specific identifiers in `custom_properties`) - The merchant's `thank_you_page` URL from the `complete-order` response — that's where the user's relationship with the merchant continues Do not impersonate the merchant in conversations about the placed order. Anything the user wants to do beyond placement lives on the merchant's side. ## Spending controls If the destination's agent operates without explicit per-purchase confirmation (autonomous flows, recurring purchases, parental-allowance flows), implement spending controls on the destination side: - A per-transaction cap - A per-period cap - An allowlist of merchants - A category blocklist (alcohol, age-restricted goods, etc.) - A revocation path the user can trigger in conversation These are the destination's responsibility. Firmly enforces no caps by default. ## Identity and "on whose behalf" A user who is signed into the destination's surface (the destination's account, the destination's auth) is the buyer of record from Firmly's perspective. If the surface supports household accounts, child accounts, or shared sessions, the destination — not Firmly — is responsible for routing the purchase to the right person. For SSO between the destination's surface and the merchant — so the order appears under the user's existing merchant account rather than as a guest order — see [Firmly Connect](/solutions/firmly-connect/sso/). ## A checklist for the launch reviewer When the destination's legal, compliance, or trust team reviews the integration, they'll typically ask: - [ ] What does the user see before the order is placed? - [ ] How is consent recorded and for how long? - [ ] What spending controls are in place? - [ ] If the merchant disputes a charge, what's the evidence? This page answers Firmly's side of consent and disclosure. The destination's application policy fills in the rest. --- ## Related - [Agentic Commerce overview](/solutions/agentic-commerce/) — the broader solution - [Firmly Connect SSO](/solutions/firmly-connect/sso/) — signing the user into the merchant at order time - [Place Order](/api-reference/payment/place-order-v2) — where `custom_properties` and `thank_you_page` are returned --- # Curated Landing Page > **Note** > This is one common pattern partners build with Branded Commerce. Many other shapes are possible — adapt or combine use cases to fit your specific campaign. The partner runs an ad promoting an **occasion or theme** rather than a single product — e.g., *"Mother's Day Gift Guide"*, *"Summer Essentials"*, *"Black Friday Deals"*. The buyer taps the ad and lands on a partner-branded occasion page with a curated product grid, browses, picks a product, and completes checkout. The key difference from a [single-product deal](/solutions/branded-commerce/use-cases/single-product-deal) is the **landing-page browsing step** — the buyer sees multiple products before choosing one. ## What the buyer sees ### 1. Ad click The ad creative highlights the occasion (not a single product) with a CTA like *"Shop Deals"* or *"Shop Gift Guide"*. The ad links to a landing-page URL on the partner's domain: ```text https://deals.partner.example/event/?promo=MOM20 ``` The promo code is auto-applied to any product the buyer eventually selects. ### 2. Landing page — full page A full-page, partner-branded occasion page with the curated grid. **Header (two-part):** 1. **Partner header** — partner branding plus "Powered by Firmly" attribution. A back arrow returns to the referring page. 2. **Promo banner** — a prominent banner below the header showing the deal ("Exclusive offer: Save 20% with code MOM20"). **Merchant identity** — *"Shopping with [Merchant]"* with the merchant's domain (or, for multi-merchant pages, per-product merchant identity on each card — see below). **Occasion title** — a large heading identifying the event ("Mother's Day Gift Guide", "Summer Skincare Essentials"). **Product grid** — products displayed in a two-column grid. Each product card contains: - Product image with a discount badge overlay ("20% OFF") - Product name - Brief description (1–2 lines, truncated) - Promotional pricing — original strikethrough + discounted price - Promo reference ("with code MOM20") - **Shop Now** button — taps through to the PDP for that product **Footer** — *"Discount automatically applied at checkout"* notice and *"Powered by Firmly"* attribution. ### 3. PDP — full page After the buyer taps **Shop Now** on a product card, the experience is identical to the [single-product deal PDP](/solutions/branded-commerce/use-cases/single-product-deal#2-pdp--full-page) — full product detail with variant selectors, quantity, key benefits, and dual CTAs. The header back arrow returns to the **landing page** (not all the way to the ad source). ### 4. Checkout — full page Same checkout experience as the single-product flow — express wallets, Click to Pay, standard card entry, promo auto-applied, place order. See [Single-product deal → Checkout](/solutions/branded-commerce/use-cases/single-product-deal#3-checkout--full-page). ### 5. Thank-you page Same thank-you experience — savings callout, order details, merchant links. See [Single-product deal → Thank-you page](/solutions/branded-commerce/use-cases/single-product-deal#4-thank-you-page). ## Multi-merchant landing pages A landing page can feature products from **multiple merchants**. A "Black Friday Deals" or "Mother's Day Gifts" page is not limited to a single merchant — the partner curates across their merchant portfolio. **How it works:** - Each product on the landing page has its own product configuration (merchant URL, affiliate link, offer details) - The grid shows products from different merchants side by side, each with live pricing fetched from its respective merchant - When the buyer taps a product, they enter the single-product PDP → checkout flow for **that merchant only** **Constraint — single-merchant checkout.** Each purchase is against one merchant. After the thank-you page, the buyer can return to the landing page to browse more products (potentially from a different merchant). Each purchase triggers its own affiliate conversion signal and ad conversion signal — independently per merchant. Why: each merchant has its own cart, shipping, payment, and order system. Affiliate attribution is per-merchant by definition — each network credits per merchant, not per cart. ## Differences from the single-product flow | Aspect | Curated landing page | Single-product deal | |---|---|---| | **Ad CTA** | "Shop Deals" / "Shop Gift Guide" | "Shop Now" / "Buy Now" | | **Landing page** | Occasion page with curated grid | PDP directly | | **Phases** | 5 (landing-page browsing added) | 4 | | **Buyer intent** | Browsing / exploring a themed deal | Ready to buy a specific product | | **Back navigation** | PDP → Landing page → Ad source | PDP → Ad source | | **Multi-merchant possible** | ✓ (one grid, multiple merchants) | ✗ (one product, one merchant) | ## What the partner owns vs. what Firmly handles Same ownership model as the single-product flow, with these additions for the landing page: | | Partner | Firmly | |---|---|---| | Occasion/theme selection + page design direction | ✓ | — | | Product list curation (across one or more merchants) | ✓ | — | | Per-product offer details (promo code, discount amount, copy) | ✓ | — | | Landing-page hero image + editorial copy | ✓ | — | | Building the landing page from the partner's theme | — | ✓ | | Live merchant data fetch per product card | — | ✓ | | Click-tracking from product card to PDP | — | ✓ | ## Performance tracking Tracking is **per purchase, not per landing-page view**. Each completed order triggers: - **Affiliate attribution** to the specific merchant of the purchased product - **Ad conversion signals** to the partner's ad platforms — Meta CAPI, Google Ads, TikTok / Pinterest / Snap / Reddit Conversions APIs Engagement events (page views, card clicks, PDP views, add-to-cart, checkout-start, purchase) are tracked across the entire flow and surfaced in the partner's analytics view. ## Pre-purchase disclosure Same as the single-product flow — partner T&C + privacy and merchant T&C are displayed at checkout. See [Consent & Disclosure](/solutions/agentic-commerce/consent-and-disclosure). --- ## Related - [Single-product deal](/solutions/branded-commerce/use-cases/single-product-deal) — the simpler one-product variant - [Buyer purchase flow](/solutions/branded-commerce/flows/buyer-purchase-flow) — full sequence - [Operations → Operational workflow](/solutions/branded-commerce/operations/operational-workflow) — per-product setup repeats for each landing-page product - [Marketplace](/solutions/marketplace/) — for an operator aggregating many merchants in one surface --- # Curated Product Roundup A reader is on a curated article — "Best Headphones Under $200", "Holiday Gift Guide", "10 Kitchen Gadgets We Love". The article features several products, each with a Buy Now button. The reader can add multiple items to one cart across the article and check out once. This is the multi-product Publisher Commerce shape. Roundups drive higher average order value because the editorial framing already does the cross-sell work — readers arrive in browsing mode and convert on multiple items. ## Recommended setup | Choice | Default | Why | |---|---|---| | **Integration pattern** | [Embedded Buy Button](/solutions/publisher-commerce/integration-patterns/embedded-buy-button) | Same buttons as Shoppable Article, with cart accumulation across multiple Buy Now clicks in the article | | **Auth** | [Browser session](/api-reference/authentication/browser-session) | Per-reader article session | | **Payment** | Google Pay, PayPal Express, Card via JWE, Klarna BNPL | Higher cart values warrant offering BNPL | | **Attribution** | UTM + publisher identifier + article identifier + per-line-item product identifier | Publisher knows which items in the roundup drove orders | ## API sequence The flow follows the [Multi-Product Purchase](/solutions/publisher-commerce/flows/multi-product-purchase) shape — multiple `POST /cart/line-items` calls as the reader clicks Buy on different products in the article. | Step | Endpoint | |---|---| | 1. Bootstrap session | [`POST /api/v1/browser-session`](/api-reference/authentication/browser-session) | | 2. Add to cart (per click) | [`POST /cart/line-items`](/api-reference/cart-management/add-line-item) | | 3. Read cart for review | [`GET /cart`](/api-reference/cart-management/get-cart) | | 4. Set shipping address | [`POST /cart/shipping-info`](/api-reference/checkout/set-shipping-info) | | 5. Pick shipping method | [`POST /cart/shipment/methods`](/api-reference/shipment-configuration/set-shipping-method) | | 6. (Optional) Get delivery availability | [`POST /cart/shipments/get-availability`](/api-reference/shipment-configuration/get-availability) | | 7. (If required) Get + set merchant consents | [`GET /cart/consents`](/api-reference/checkout/get-consents) → [`PUT /cart/consents`](/api-reference/checkout/set-consents) | | 8. Get payment public key | [`GET /payment/key`](/api-reference/payment/get-public-key) | | 9. Complete order | [`POST /payment/complete-order`](/api-reference/payment/complete-order-v2) | The valid `shipping_method_id`s for step 5 come from the cart itself — `cart.shipments[].shipping_method_options`, populated by step 4 (`set-shipping-info`). `get-availability` (step 6) is optional and returns delivery dates, time slots, or pickup locations for scheduled-delivery or in-store-pickup shipments — not shipping methods. Steps 2–7 build the cart, so step 9 finalizes it with [`complete-order`](/api-reference/payment/complete-order-v2) (body: `encrypted_card` + `billing_info`); use [`place-order`](/api-reference/payment/place-order-v2) only for the one-shot create-cart-and-order call. ## Considerations the article surface owns - **Cart accumulation across multiple Buy Now clicks.** Make sure the cart session persists across each Add — don't bootstrap a new session per click. - **Visible cart count.** A persistent cart badge (top of article, sticky on scroll) shows "3 items added" so the reader knows they've been building a cart. - **Cart panel before checkout.** Opening the cart panel surfaces all items with adjust/remove controls. The reader can drop items before paying. - **Single-merchant constraint.** All items in a Publisher Commerce roundup cart must come from the same source merchant. If the roundup features products from different merchants, each Buy Now click is a separate cart (or you need [Marketplace](/solutions/marketplace/) instead). - **Affiliate attribution per line.** The publisher's commission may differ per product or category. Attribution metadata flows per line item so reconciliation is accurate. --- ## Related - [Multi-Product Purchase Flow](/solutions/publisher-commerce/flows/multi-product-purchase) — full API walkthrough - [Embedded Buy Button pattern](/solutions/publisher-commerce/integration-patterns/embedded-buy-button) - [Shoppable Article](/solutions/publisher-commerce/use-cases/shoppable-article) — single-product variant - [Marketplace](/solutions/marketplace/) — for an operator aggregating many merchants in one surface --- # Dashboard The Branded Commerce dashboard is the partner's view of the **Destination Dashboard** — the surface where partners run their Branded Commerce account day-to-day. It's a logged-in web app; partners are invited by Firmly during onboarding. Branded Commerce is one of the five solution types that share this destination-side surface — see [Destination Dashboard](/for-destinations/destination-dashboard) for the generic reference. > **Note** > **What the dashboard is for, what it isn't.** The dashboard is for **operational reporting and account administration** — funnel data, orders, merchant performance, team management, audit logs. It is not currently a self-service product-submission surface; per-product publishing is still manual coordination with Firmly ops (see [Operational workflow](/solutions/branded-commerce/operations/operational-workflow)). Self-service submission is on the roadmap. ## Access and roles Access is per-destination — each partner organization (the "destination") has its own dashboard scoped to its data. Access is role-based — see [Destination Dashboard → Team](/for-destinations/destination-dashboard) for the canonical role table, shared across all five destination-side solution types: | Role | What they can do | |---|---| | **Primary Owner** | Everything, plus ownership transfer (one Primary Owner per destination) | | **Owner** | Everything except ownership transfer | | **Editor** | Edit settings and operational data | | **Viewer** | Read-only | Partners log in with their Firmly credentials. Multiple teammates can share access at different role levels — see [Team management](#team-management) below. ## Dashboard surfaces The dashboard has these surfaces, accessible from the left navigation once you're logged in (Settings, Team management, and Audit logs are grouped into one admin section below): ### Landing dashboard The default view when you log in. Gives a personalized greeting and an at-a-glance summary of the destination's performance: | Section | What it shows | |---|---| | **Metrics grid** | Headline KPIs across the selected period | | **Top merchants** | Merchants ranked by performance contribution | | **Revenue chart** | Revenue trend over time | | **Merchant filter** | Scope all charts to a single merchant or the full set | A refresh button re-fetches the latest data on demand. ### Funnel report The most detailed analytics surface. Three tabs: | Tab | Content | |---|---| | **Raw Data** | The underlying funnel metrics — sessions, buy-now clicks, orders — with a date range picker | | **Funnel Report** | Conversion funnel chart, per-domain breakdowns, payment-path flow (PayPal / Click to Pay / Manual card), orders-by-payment-method donut, and merchant-level funnel comparisons. Filters by domain, path, and payment method | | **Drop-off Analysis** | Waterfall chart showing where buyers drop out, friction signals (form errors, payment retries), and field-by-field checkout progression | This is where partners diagnose performance — *"why is conversion lower on this product?"* — by walking the funnel from session start through to order placement. ### Orders List of orders placed through Branded Commerce, with per-order detail pages. Use this to: - Confirm a specific order landed correctly - Look up the affiliate attribution key applied - See the merchant the order was placed against - Cross-reference with the partner's own ad-platform reporting Order data is read-only — fulfillment and post-order operations live with the merchant. ### Merchants The list of merchants the partner is enabled for, with per-merchant performance breakdowns. Useful for: - Confirming the merchant set the partner is routing to - Identifying which merchants drive the most volume - Spotting under-performing merchants for campaign review ### Settings, Team, and Audit logs | Surface | Purpose | |---|---| | **Settings** | Destination-level configuration controls | | **Team management** | Invite teammates, change their roles, remove access. Pending invitations are listed alongside active members | | **Audit logs** | Record of who did what on the dashboard — team membership changes, settings updates, configuration changes. For compliance and "who turned this on?" questions | ## Team management Owners can invite teammates by email and assign a role at invitation time. Invitations show as pending until the teammate accepts. Owners can: - Change a teammate's role (Owner, Editor, or Viewer) - Remove a teammate's access - Transfer primary ownership to another Owner (Primary Owner only) There are constraints to prevent locking the destination out of owner-level operations — Firmly's team management logic guarantees at least one Owner always exists. ## What's in the dashboard today — and what isn't To be explicit about boundaries: | Feature | Status | |---|---| | Funnel reporting | **Available** | | Orders list + detail | **Available** | | Merchant performance | **Available** | | Team management + audit logs | **Available** | | Self-service product submission | **Not yet** — manual coordination with Firmly ops (see [Operational workflow](/solutions/branded-commerce/operations/operational-workflow)) | | Commission tracking | **Not yet** — affiliate attribution is configured per-network and fires through Firmly's adapters, but in-dashboard commission display is not implemented | | Programmatic API | **Not yet** — bulk product submission and CI/CD-style campaign management are a later phase | If you need data the dashboard doesn't surface yet (e.g., bulk export, custom reporting), reach out to [Firmly](/contact). ## Engagement funnel — what's tracked The funnel surfaces three primary steps with drop-off analysis between them: | # | Step | What it represents | |---|---|---| | 1 | **Sessions** | Buyer arrives on a Branded Commerce page (landing page or PDP) | | 2 | **Buy Now Clicks** | Buyer taps the primary CTA to enter checkout | | 3 | **Orders** | Order successfully placed with the merchant — counted only when the order carries a non-zero total (`total > 0`), so zero-total test or placeholder carts are excluded from the funnel | Plus per-step drop-off waterfall, friction signals (form errors, retries), and a field-by-field progression view through checkout. These are richer than a simple 3-step funnel — drop-offs and friction signals are the actionable layer above the headline numbers. --- ## Related - [Operations overview](/solutions/branded-commerce/operations/) — how onboarding, per-product workflow, and dashboard fit together - [Operational workflow](/solutions/branded-commerce/operations/operational-workflow) — the per-product rhythm (manual today) - [Partner onboarding](/solutions/branded-commerce/operations/partner-onboarding) — one-time setup before any of this - [Integration Patterns](/solutions/branded-commerce/integration-patterns/) — the technical setup - [Branded Commerce FAQ](/solutions/branded-commerce/faq) --- # Dedicated Landing The Buy Now link in the article routes the reader to a dedicated landing — a separate page outside the article — where the product detail, address, and payment all render. The publisher chooses this pattern when a richer shopping experience matters more than reading-flow continuity. ## When this fits | Condition | Does this pattern fit? | |---|---| | Publisher prefers a dedicated shopping page (separate branding or full PDP) | ✅ Yes | | Single product needs rich presentation (long-form review with detailed gallery) | ✅ Yes | | Reader expects to leave the article to shop | ✅ Yes | | Reading-flow continuity is the priority | ❌ Use [Embedded Buy Button](/solutions/publisher-commerce/integration-patterns/embedded-buy-button) instead | | Curated roundup with multiple products | ⚠️ Possible but cart accumulation is harder across separate landings | ## How the click-through flows | Stage | What happens | |---|---| | **Article** | Reader sees Buy Now link inline with the article | | **Click** | Reader navigates to the dedicated landing URL with article ID and product ID encoded | | **Landing renders** | Landing captures article/product context, starts a Firmly browser session | | **Checkout** | Reader fills address + payment on the landing | | **Order placement** | `POST /payment/complete-order` (finalizes the cart built on the landing) with publisher and article identifiers in metadata | | **Confirmation** | Landing shows confirmation; back-link to the article for the reader to return | ## What the publisher owns | Layer | Owner | |---|---| | Article CMS and content management | Publisher | | Buy Now link/component | Publisher | | Dedicated landing page UI | Publisher (or Firmly's [hosted checkout](/solutions/agentic-commerce/integration-patterns/hosted-checkout)) | | Click-through context capture (article ID, product ID) | Publisher | | Cart / order orchestration | Firmly APIs | | Payment + order placement | Firmly APIs | ## Trade-offs vs Embedded Buy Button | Dimension | Embedded | Dedicated Landing | |---|---|---| | Reading-flow continuity | ✅ Preserved | ❌ Reader leaves article | | Product presentation depth | Limited by panel size | Full page available | | Cart accumulation across multiple products | ✅ Natural | ❌ Harder (each landing is its own cart) | | Conversion rate | Typically higher (no extra navigation) | Typically lower, due to the extra navigation step | | Brand control for the shopping experience | Article surface owns | Dedicated landing owns | For most publishers, Embedded Buy Button is the default. Dedicated Landing is the right call when product presentation requirements (long-form merchandising, video, configurators) can't fit in a slide-in panel. ## Constraints to plan for - **Click-through context.** The landing URL must carry the article ID, product ID (SKU), and attribution params. Plan a URL scheme that's stable and shareable — for example, `https://.com/shop/{article-id}/{sku}?utm_source=...`. Once the buyer is on the landing page and the cart exists, pass that context to Firmly with [Set Cart Attribution](/api-reference/cart-management/set-attribution) using `utm`, `referrer_url`, `referral_code`, and `landing_page` (see the [flow attribution note](/solutions/publisher-commerce/flows/single-product-purchase#attribution--article-to-conversion)); the article ID and SKU are yours to define. - **Back-link to article.** Always offer a way back to the article — both on the landing and on the post-purchase confirmation. - **Mobile-first.** Most clicks come from mobile. Landing must work on a narrow viewport without horizontal scroll. - **Cart isolation.** Each landing is its own cart session — readers who want multiple items must do separate purchases or return to a roundup article that aggregates. --- ## Related - [Single Product Purchase Flow](/solutions/publisher-commerce/flows/single-product-purchase) - [Embedded Buy Button](/solutions/publisher-commerce/integration-patterns/embedded-buy-button) — the alternative pattern - [Shoppable Article use case](/solutions/publisher-commerce/use-cases/shoppable-article) — typically pairs with Embedded --- # Deep Link / Headless Headless is the pattern where the destination calls Firmly's REST API for every step of the purchase. There's no iframe, no hosted page, no redirect — the destination's code is the checkout UI, or the checkout has no UI at all. This is the most flexible pattern and the most code to write on the destination side. Use it when you need conversational, voice, or autonomous flows that can't fit a visual checkout. ## When to use it - Conversational and voice surfaces where checkout happens through dialogue - Fully autonomous flows that complete purchases without per-step human confirmation - Custom surfaces where neither hosted nor embedded fits (AR/VR, in-car systems, IoT, smart speakers) - The destination wants total control over UX and accepts the corresponding compliance work (see [Consent & Disclosure](/solutions/agentic-commerce/consent-and-disclosure)) **Don't use this** when [Hosted](/solutions/agentic-commerce/integration-patterns/hosted-checkout) or [Embedded](/solutions/agentic-commerce/integration-patterns/embedded-checkout) fits — they reduce both code and PCI scope on the destination side. ## The full API sequence A complete single-product purchase via headless is the sequence below. Each row links to the canonical API reference — payloads are documented there, not duplicated here. For a runnable end-to-end script, see the [Advanced Checkout Guide](/cookbook/advanced-checkout-guide). | # | Call | Purpose | |---|---|---| | 1 | [Browser session](/api-reference/authentication/browser-session) | Bootstrap auth — get a JWT | | 2 | [Discovery search](/api-reference/discovery/search) | Find products (results carry a `domain` per product) | | 3 | [Add line item](/api-reference/cart-management/add-line-item) | Add an item (cart created implicitly) | | 4 | [Set shipping info](/api-reference/checkout/set-shipping-info) | Set shipping address — response carries `shipping_method_options` per shipment | | 5 | [Get shipping availability](/api-reference/shipment-configuration/get-availability) | *(Optional)* Delivery dates / time slots / pickup locations | | 6 | [Set shipping method](/api-reference/shipment-configuration/set-shipping-method) | Pick a method from the shipment's `shipping_method_options` | | 7 | [Get consents](/api-reference/checkout/get-consents) → [Set consents](/api-reference/checkout/set-consents) | *(If the merchant requires consents)* Fetch required consents, surface each to the buyer, capture acceptance. Skipping required consents makes `complete-order` return `RequiredConsentsNotSigned` (412) | | 8 | [Get payment public key](/api-reference/payment/get-public-key) | Fetch the public key for card encryption | | 9 | *(client-side)* JWE-encrypt the card | No network call — see [Get payment public key](/api-reference/payment/get-public-key) for the encryption requirements | | 10 | [Complete order (v2)](/api-reference/payment/complete-order-v2) | Finalize the cart built in steps 3–8 (body: `encrypted_card` + `billing_info`) | For multi-product, repeat step 3 per item. For multi-shipment, repeat step 6 per shipment. For Klarna express, swap steps 8–10 for the [Klarna express sequence](/api-reference/payment/express-checkout/klarna/start). > **Note** > **`complete-order` vs `place-order`.** This sequence **builds the cart** across steps 3–8, so it finalizes with [`complete-order`](/api-reference/payment/complete-order-v2) (existing cart) — the request body is only `encrypted_card` + `billing_info`, because the line items, shipping, and consents already live on the cart. If instead you have everything up front and want to **create the cart and place the order in a single call**, use [`place-order`](/api-reference/payment/place-order-v2) — the one-shot path takes an `items[]` array plus `shipping_info` in the body and collapses steps 3–10. Don't mix them: calling `place-order` after building a cart flushes and rebuilds it from the `items[]` you pass, discarding the shipping method and consents set above. ## Authentication choice Headless integrations have two auth patterns: | Pattern | Best for | Reference | |---|---|---| | **Browser session** | Client-side or ambient surfaces that act on behalf of a session | [Browser session](/api-reference/authentication/browser-session) | | **Server-to-server** | Backend services acting with a service identity | [Server-to-server](/api-reference/authentication/server-to-server) | S2S is simpler for backend deployments. See the [Authentication overview](/for-destinations/authentication) for picking between them. ## Payment options when going headless | Method | How | |---|---| | **Card** | JWE-encrypt with the payment public key, pass `encrypted_card` in `complete-order` | | **Klarna BNPL** | Use the [Klarna Express Checkout](/api-reference/payment/express-checkout/klarna/start) sequence — `start` → `authorize` → `complete-order` | | **PayPal Express** | Use the [PayPal Express Checkout](/api-reference/payment/express-checkout/paypal/) sequence — `start` → `authorize` → `complete-order` | | **Click to Pay** | When the user has a saved Visa/Mastercard via Click to Pay, the flow short-circuits payment — coordinate with [Firmly](/contact) | ## Retries and idempotency Headless flows are exposed to all the failure modes of distributed systems — network blips, retries, mid-flight cancellations. How you dedupe depends on the path: - **UCP protocol bridge** — pass an `Idempotency-Key` (a UUID generated once per logical attempt) on each mutation. The bridge caches the first response per key for 24 hours and returns it on retry, so the underlying operation runs at most once. Reuse the same key when retrying the same attempt; generate a fresh key for a genuinely new attempt. - **Core REST** — the path this page describes (`add-line-item`, `set-shipping-info`, `complete-order`, etc.) does **not** deduplicate on the `Idempotency-Key` header today. A retry re-runs the operation. Guard against double-placement client-side: on a failed or timed-out `complete-order`, re-read `cart_status` before retrying — if it's already `submitted`, the order landed, so don't resubmit. ```javascript // Core REST complete-order has no server-side dedup — guard by re-reading cart state. async function placeOrderSafely(order) { try { return await callFirmly(placeOrderUrl, { method: 'POST', headers: { ...auth }, body: JSON.stringify(order), }); } catch (e) { const cart = await callFirmly(getCartUrl, { headers: { ...auth } }); if (cart.cart_status === 'submitted') return cart; // already placed — do not retry throw e; // safe to retry } } ``` See [Idempotency](/solutions/agentic-commerce/protocols/ucp/idempotency) for the canonical guidance on the UCP bridge, and the [scope note in Errors & Conventions](/api-reference/errors-and-conventions#idempotency) for why core REST isn't deduplicated. ## Error handling shape ```javascript // A real Error subclass so stack traces and `instanceof Error` keep working. class FirmlyError extends Error { constructor({ status, code, error, description }) { super(description || error); this.name = 'FirmlyError'; this.status = status; // HTTP status this.code = code; // numeric HTTP status from the envelope this.error = error; // PascalCase error name, e.g. CreditCardDeclined this.description = description; } } async function callFirmly(url, options) { const resp = await fetch(url, options); const body = await resp.json(); if (!resp.ok) { // Core REST envelope: { code, error, description } throw new FirmlyError({ status: resp.status, ...body }); } return body; } try { await callFirmly(placeOrderUrl, { ... }); } catch (e) { switch (e.error) { case 'NotEnoughStockError': // re-fetch product, ask user to confirm new quantity break; case 'CreditCardDeclined': // ask user for different payment method break; case 'StoreUnavailable': // exponential backoff retry break; default: // surface to user } } ``` See [Errors](/solutions/agentic-commerce/operations/errors) for the full catalog. ## Concurrency patterns Headless flows often have opportunities to parallelize: - **Catalog lookup + cart fetch** (when resuming a conversation) — parallel - **Shipping availability for multiple shipments** — parallel, one call per `shipment_id` - **Payment key fetch + JWE encryption** — sequential, but key fetch can be cached briefly Don't parallelize: - Calls that mutate the same cart — they'll race and the last one wins - Duplicate `complete-order` calls for the same cart — core REST doesn't dedupe them, so concurrent submits can double-place; serialize and re-read `cart_status` between attempts ## What the destination takes on by going headless - The destination's UI is the checkout UI — address forms, error messages, retry flows - The destination's PCI scope includes any handling of the encrypted card payload (transit, logging) - The destination is responsible for [pre-purchase consent and disclosure](/solutions/agentic-commerce/consent-and-disclosure) - The destination owns retries, idempotency, and error recovery In exchange the destination gets the most natural conversational flow and the most surface flexibility. --- # Destination surfaces A **destination** is where the buyer encounters Firmly-powered commerce — a publisher's deal page, an AI agent's response, a social feed's product card, a shoppable ad, a connected-TV overlay. Firmly is the commerce backend that turns any of these into a working purchase surface. If you're a merchant rather than a destination — making your products reachable to buyers — see [For Merchants](/for-merchants/). ## Destination categories Five categories, organized by the buyer surface where commerce happens. - [Publisher sites](/solutions/destination-surfaces/publisher-sites) — Editorial media, deal and coupon sites, reviews, buying guides, vertical communities. The highest-intent destination category — audiences arrive with purchase intent. - [Ads](/solutions/destination-surfaces/ads) — Shoppable and transactable ad placements across ad networks — in-feed cards, sponsored results, video pre-roll, sidebar units. Commerce moves to where the ad renders. - [AI surfaces](/solutions/destination-surfaces/ai-surfaces) — AI chat products, answer engines, and assistants where users ask to buy. Commerce becomes a turn in the conversation. - [Social platforms](/solutions/destination-surfaces/social-platforms) — Social feeds, messaging surfaces, and creator-driven commerce. Buyers arrive through social discovery. - [Connected TV](/solutions/destination-surfaces/ctv) — CTV apps and OTT surfaces — shoppable content, overlay purchasing, and remote-driven commerce on the living-room screen. ## Status by category Firmly's destination buildout is staged. Each category's page details what's available today and what's on the roadmap. | Category | Status today | |---|---| | **Publisher sites** | Available — Firmly platform supports publisher-driven commerce; partner integrations active | | **Ads** | Emerging — first ad-network integrations in production; broader coverage on roadmap | | **AI surfaces** | Agentic-commerce platform is production-ready today — AI agents transact through Firmly now; the destination-category buildout (packaged per-surface integrations) is on the roadmap | | **Social platforms** | Roadmap | | **Connected TV** | Roadmap | For status on a specific category, see its destination page. ## How destinations relate to solutions A destination is *where* the buyer is. A [solution](/solutions/) is *what* Firmly assembles for that destination shape. Most destinations use more than one solution. For example, a publisher running deal pages typically uses **Publisher Commerce** for editorial commerce and **Branded Commerce** for white-labeled ad-driven checkout. --- ## Related - [Solutions overview](/solutions/) — the products built on top of the destination categories - [How Firmly Works](/how-firmly-works) — the platform underneath every destination - [For Merchants](/for-merchants/) — the merchant side of the integration --- # Destinations configuration The merchant chooses which channels on Firmly's network they want to sell through — AI shopping agents and LLMs, marketplaces, publishers, and social surfaces. **The merchant only opts in; Firmly handles the actual enablement work behind each destination on the merchant's behalf.** ## How it's organized ### Grouped by category Destinations are organized under collapsible category sections: - **AI Shopping Agents & LLMs** - **Marketplace** - **Publishers** - **Social** - **Other** (catch-all) The category header shows a count of destinations in that group; all categories are expanded by default. ### Per-destination row Each row shows: | Column | What it shows | |---|---| | Destination | Name + a short description | | Orders | Recent orders the merchant has received from this destination (populated once live and transacting) | | Avg. Order Value | Mean across orders from this destination | | Toggle | Enable / disable selling through that destination | ### Summary tiles A header strip at the top of the page summarizes: - **Active Destinations** — count of destinations the merchant has opted into - **Total Orders** — across all enabled destinations - **Average Order Value** — across all enabled destinations ## Opt-in is just a toggle The merchant flips destinations on or off — there's no per-destination configuration form here, by design. Firmly handles every behind-the-scenes integration step with the destination platform. **Coming-soon destinations** are listed in the table with their toggle disabled and a `Coming Soon` marker, so the merchant can see what's on the roadmap. ### Which destinations to enable A practical default: enable the destinations you actively want to sell through now, rather than everything. Keep your catalog scope aligned with your destination opt-ins — go-live review flags a catalog scope that's misaligned with the destinations you've enabled (see [Going Live → common rejection causes](/for-merchants/going-live#common-rejection-causes-and-what-to-do)). Destinations can be added later from this same page without re-running the full onboarding review, so there's no need to opt into everything up front. ## Save semantics - **Save Configuration button** is enabled when there are unsaved changes, or on the merchant's first save. - **First-time save advances onboarding.** Same pattern as [catalog configuration](/solutions/firmly-connect/onboarding/catalog-configuration#how-the-save-flow-works): the first save during onboarding returns the merchant to the task menu; subsequent saves stay on the page with a "Destinations updated successfully!" confirmation. ## Gating - **KYB-gated during onboarding.** The destinations task stays locked until KYB is approved. See [Onboarding wizard](/solutions/firmly-connect/onboarding/). - **Post-onboarding, always reachable.** The merchant can opt into new destinations as they become available. --- ## Related - [Onboarding wizard](/solutions/firmly-connect/onboarding/) — the 7-step sequence - [Catalog configuration](/solutions/firmly-connect/onboarding/catalog-configuration) — previous step - [Agreement signing](/solutions/firmly-connect/onboarding/agreement-signing) — next step - [Destinations](/solutions/destination-surfaces/) — destination-side documentation for AI surfaces integrating with Firmly --- # Domains and SSO Register your domains, then choose whether to require single sign-on (SSO) for each one. SSO is set **per verified domain** — so if you run several storefronts, you can require SSO on some and not others. Everything for domains and SSO lives on this one page. ## Domain registration ### Three-action workflow | Step | What happens | |---|---| | 1. Add domain | You type the domain into the **Add domain** dialog and submit | | 2. Publish TXT record | The setup dialog opens automatically, showing the required DNS TXT record (name + value) with copy buttons. You publish the record at your DNS provider | | 3. Verify | Back on Firmly Connect, you click **Verify now**. Firmly looks up the TXT record live | If the record isn't found yet, the page surfaces a friendly "DNS changes can take a few minutes to propagate — try again shortly" message rather than a hard error. ### Status column | Status | Meaning | |---|---| | `Pending` | TXT record not yet found | | `Verified` | Record matched and recorded | ### Removing a domain is deliberate A confirmation dialog explicitly states that removing a verified domain **releases anything bound to it** — SSO enforcement, branded hosting — and disables the related functionality immediately for that domain. ## Per-domain SSO enforcement switch Each verified domain has an **SSO Enforced** switch in the table: | State | What happens at login | |---|---| | **OFF** | Users on that domain can sign in with any method — OTP, magic link, or SSO | | **ON** | The login page blocks OTP and magic link for that domain and only allows the bound Identity Provider. There is no self-service bypass — if the IdP breaks and locks the team out, contact Firmly to recover access | The switch is disabled with a tooltip ("Verify the domain before enforcing SSO") until the domain is verified. Enforcement also requires at least one enabled IdP bound to the domain. ## SSO configuration ### Your SSO providers Each registered IdP row shows: - Display name - Underlying template (e.g. "SAML 2.0") - Domains it's bound to (or "No domains bound") - Enabled / disabled status - Action menu: Edit, Enable / Disable, Delete ### Adding a provider When you add an SSO provider, a picker offers a fixed set of templates: | Template | Status | |---|---| | **Generic OIDC** | Available now — configurable issuer URL, client ID, client secret | | **SAML 2.0** | Available now — displays the SP Entity ID and ACS URL (Firmly provides these); configurable IdP metadata (file upload or pasted XML), IdP entity ID, SSO URL, X.509 certificate | | **Okta** | Coming Soon | | **Microsoft Entra ID** | Coming Soon | | **Google Workspace** | Coming Soon | | **Auth0** | Coming Soon | | **OneLogin** | Coming Soon | ### Configuring a provider Each provider's settings include: - Protocol-specific credentials (issuer, client ID/secret for OIDC; metadata XML, certificates for SAML) - Attribute mapping (e.g. which incoming SAML attribute maps to email) - List of verified domains this IdP is authorized for - **Enabled** switch that flips the IdP on for SSO authentication ## Role gating | Action | Who can do it | |---|---| | Add / verify domain | Owner, Primary Owner, Firmly admin | | Toggle SSO enforcement | Owner, Primary Owner, Firmly admin | | Remove domain | Owner, Primary Owner, Firmly admin | | Configure SSO IdPs | Owner, Primary Owner, Firmly admin | Viewers / Editors see read-only tables. --- ## Related - [Firmly Connect SSO setup guides](/solutions/firmly-connect/sso/) — per-IdP configuration (Generic OIDC, Generic SAML, domain verification details) - [Audit logs](/solutions/firmly-connect/portal/audit-logs) — domain and SSO actions logged here - [Team management](/solutions/firmly-connect/portal/team-management) --- # Embedded Buy Button Buy Now buttons live inline with the article content, next to the product mentions. When the reader clicks, the checkout opens as a slide-in panel, modal, or sticky bottom-sheet — the article stays visible behind it. After purchase, the reader closes the panel and continues reading. ## When this fits | Condition | Does this pattern fit? | |---|---| | Reading-flow continuity matters (don't lose the reader) | ✅ Yes — primary advantage | | Article references multiple products | ✅ Yes — cart accumulates across the article | | Mobile reading audience | ✅ Yes — slide-in panel works well on mobile | | Single product needs full PDP-style presentation | ⚠️ Consider [Dedicated Landing](/solutions/publisher-commerce/integration-patterns/dedicated-landing) instead | ## What the publisher owns | Layer | Owner | |---|---| | Article CMS and content management | Publisher | | Buy Now button component (embedded in article rendering) | Publisher (using Firmly's embed format) | | Inline checkout panel UI | Publisher (or Firmly's [hosted checkout](/solutions/agentic-commerce/integration-patterns/hosted-checkout)) | | Cart badge / sticky indicator | Publisher | | Cart / order orchestration | Firmly APIs | | Payment + order placement | Firmly APIs | ## How the embed works The embed is **HTML data attributes on the publisher's own elements** plus one Firmly **loader script** on the page — there is no Firmly-specific shortcode syntax. The publisher marks up each product mention (a link or button) as a Firmly Buy Now element; Firmly's loader script resolves the product and wires the click to the checkout drop-in. At minimum, the publisher-authored element opts in with `data-firmly-enabled` and points at the product (via its `href`). When the loader script runs, it resolves the product and sets the remaining attributes it needs on that element at runtime: - `data-firmly-product-url` — canonical product URL - `data-firmly-merchant-domain` — the merchant the product belongs to - `data-firmly-affiliate-url` — the affiliate link (expanded if shortened) - `data-firmly-buy-now-url` — the resolved buy target the drop-in acts on ```html Buy Now ``` When the reader clicks a tagged element, the loader checks that the resolved `data-firmly-buy-now-url` and `data-firmly-merchant-domain` are present, prevents the default navigation, and opens the Firmly checkout drop-in as a slide-in panel over the article — the reader never leaves the page. ### Fitting it into a CMS The markup above is what the page renders; how the publisher produces it depends on the CMS. Whatever the authoring surface, the output is the same tagged element plus the site-wide loader script. | CMS type | How the attributes get onto the element | |---|---| | Block-based CMS | Custom block or shortcode that outputs the `data-firmly-*` attributes | | Structured-content CMS | Portable-text / rich-text custom mark or block | | Headless CMS | Custom entry type rendered by the front end | | Custom CMS | Component in the article-render template | The publisher's editorial workflow stays the same — writers pick a product, the CMS renders the tagged element, and the loader script (added once, site-wide) does the rest. > **Note** > The attribute names and loader path above illustrate the **real** embed mechanism — HTML `data-firmly-*` attributes handled by a loader script — not a finalized, self-serve reference. The exact loader host, the customized loader script for your domain, and the minimal set of attributes your pages must author are provided by Firmly during onboarding. Coordinate the concrete embed format with your Firmly contact before building the CMS integration. ## Cart persistence across multiple Buy Now clicks For roundup articles where the reader adds multiple items: - **Same cart session** — every Buy Now click on the same article session adds to the same cart - **Cross-article carts** — if the reader navigates to a different article on the same publisher, the cart persists according to publisher policy. Firmly supports both per-article scoping and cross-article persistence. - **Cart badge updates** — increment the badge after each successful Add ## Constraints to plan for - **Panel responsiveness.** Slide-in panel must work on narrow mobile viewports; design for thumb-reachable controls and a clear close button. - **Article layout interaction.** When the panel is open, the article content behind should be inert (no accidental scroll-through). Restore scroll position when the panel closes. - **Cart abandonment.** Some readers will add items then close the panel without checking out. Decide whether the publisher offers email capture or other recovery options. - **Multiple Buy Now clicks → confused readers.** Clear feedback after each Add ("Added to cart — click cart icon to review") prevents readers from double-tapping. --- ## Related - [Shoppable Article use case](/solutions/publisher-commerce/use-cases/shoppable-article) - [Curated Product Roundup use case](/solutions/publisher-commerce/use-cases/curated-product-roundup) - [Single Product Purchase Flow](/solutions/publisher-commerce/flows/single-product-purchase) - [Dedicated Landing](/solutions/publisher-commerce/integration-patterns/dedicated-landing) — alternative pattern --- # Embedded Checkout Embedded checkout puts Firmly's checkout UI inside the destination's surface as an iframe. The destination owns the surrounding chrome, branding, and conversation context; Firmly handles the secure parts — addresses, payment, order submission — inside the iframe. The two communicate via `window.postMessage`. ## When to use this pattern - The destination has a screen and wants checkout to feel native to it - The destination wants a reduced PCI scope without going fully headless (payment never touches destination code) - The destination wants Firmly's checkout UX (saved cards, address validation, Click to Pay, PayPal) without rebuilding it **Don't use this** for conversational, voice, or fully autonomous surfaces — there's no screen to embed into. Use [Hosted Checkout](/solutions/agentic-commerce/integration-patterns/hosted-checkout) (redirect) or [Deep Link / Headless](/solutions/agentic-commerce/integration-patterns/deep-link) (no UI) instead. ## The iframe URL Point the iframe at the Firmly dropin URL — provided by [Firmly](/contact) — with the parameters below. ### Required parameters | Parameter | What it is | |---|---| | `_appId` | The destination's App ID (UUID) | | `domain` | The merchant domain — e.g. `staging.luma.gift` | ### Optional parameters | Parameter | Default | Purpose | |---|---|---| | `url` | — | Product URL to load directly into a product-detail view | | `variant_id` | — | Skip product selection and pre-fill the variant | | `quantity` | `1` | Initial quantity | | `ui_mode` | `fullscreen` | Layout mode: `fullscreen`, `minimal-pdp`, `full-pdp` | | `force_pdp` | `false` | Force the product-detail view to render | | `skip_pdp` | `false` | Skip product detail and jump straight to checkout | | `flush_cart` | `true` | Clear any existing cart before adding the item | | `affiliate_url` | — | Affiliate-attribution URL for the order | | `custom_properties` | — | JSON-encoded object of merchant-specific properties | ### Example URL ```text /buy ?_appId=YOUR_APP_ID &domain=staging.luma.gift &url=https://staging.luma.gift/products/gift-card-25 &ui_mode=fullscreen ``` ## Minimal HTML embed `FIRMLY_DROPIN_URL` and `FIRMLY_DROPIN_ORIGIN` in the sample below are provided by [Firmly](/contact). ```html ``` ## Communication diagram ```mermaid sequenceDiagram participant P as Destination Page participant I as Firmly Iframe participant F as Firmly API P->>I: Load iframe (src = dropin-url/buy?_appId=...) I->>F: POST /browser-session F-->>I: access_token I->>F: GET /cart (or cart bootstrap) F-->>I: cart state I->>P: postMessage(firmly::CartUpdated) Note over P,I: User interacts in iframe
(address, shipping, payment) I->>F: POST /payment/complete-order F-->>I: order placed I->>P: postMessage(firmly::OrderPlaced) Note over P: Destination reads event,
shows confirmation, fires analytics P->>I: postMessage(firmly::addToCart) [optional follow-on] I->>F: POST /cart/line-items F-->>I: cart updated I->>P: postMessage(firmly::CartUpdated) ``` ## postMessage events The iframe and the destination page communicate using `window.postMessage`. All Firmly messages are JSON with an `action` field as the discriminator. ### Events from Firmly → destination page | `action` | Payload fields | When it fires | |---|---|---| | `firmly::CheckoutClosed` | `domain` | User closed the checkout view (back button, X, or tap-out) | | `firmly::OrderPlaced` | `url`, `session` | Order was successfully placed | | `firmly::QuantityUpdated` | `totalQuantity` | Cart item count changed | | `firmly::CartUpdated` | `cart` | Cart contents changed — full cart object included | | `firmly::Error` | `error`, `context` | An error occurred (validation, payment, network, etc.) | ### Events from destination page → Firmly | `action` | Payload fields | Purpose | |---|---|---| | `firmly::addToCart` | `store_id`, `custom_properties`, `transfer` | Add a product to the cart without user interaction | | `firmly::adjustSize` | `data: { height }` | Tell the iframe to resize itself (rarely needed — the iframe self-sizes) | ## Listening pattern (full example) `FIRMLY_DROPIN_ORIGIN` below is the dropin origin that [Firmly](/contact) provides. Always use it as the target origin when posting into the iframe — never `'*'`, which can leak payload data if the frame navigates. ```javascript const iframe = document.getElementById('firmly-checkout'); window.addEventListener('message', (event) => { // SECURITY: verify the origin matches the Firmly dropin origin. if (event.origin !== FIRMLY_DROPIN_ORIGIN) return; switch (event.data?.action) { case 'firmly::OrderPlaced': { const { session } = event.data; // Destination's own confirmation, analytics, conversation handoff. window.parent.postMessage( { action: 'app::firmly-order', cartId: session?.cart_id, statusUrl: session?.urls?.order_status_page }, '*' ); break; } case 'firmly::CartUpdated': updateCartBadge(event.data.cart); break; case 'firmly::CheckoutClosed': iframe.style.display = 'none'; break; case 'firmly::Error': reportError(event.data.error, event.data.context); break; } }); // Send a command into the iframe (e.g. after product disambiguation). // Target the Firmly dropin origin explicitly — never '*'. iframe.contentWindow.postMessage( { action: 'firmly::addToCart', store_id: 'staging.luma.gift', custom_properties: { ref: 'chat-session-abc' }, transfer: false }, FIRMLY_DROPIN_ORIGIN ); ``` ## Theming The iframe inherits the merchant's brand by default (logo, color, header style as configured in Firmly). For destination-level overrides, pass `custom_properties` as a URL-encoded JSON blob — [Firmly](/contact) will tell you which keys are configurable for the destination's account. ## Security Two rules: 1. **Validate `event.origin`** in the message listener. Only accept messages from the dropin origin that [Firmly](/contact) provided, and when posting into the iframe, always target that origin — never `'*'`. 2. **Never include card data or credentials** in `postMessage` payloads. The iframe is the trust boundary — the destination page never sees the card. ## Versioning Two versions of the embed exist in production: - **v4** — the generation the URL pattern, parameters, and events documented above apply to. - **v5** — a newer rewrite. URL is the same `/buy` path; some routes accept an optional language prefix (e.g. `/pt-br/buy`). For a new integration, [Firmly](/contact) will confirm which version to target for your account — start there rather than assuming a default. ## SDK shortcut Firmly also publishes a small JavaScript SDK that wraps the iframe and event handling. `FIRMLY_DROPIN_URL` in the snippet below is provided by [Firmly](/contact): ```html ``` The SDK exposes `window.firmly` with three documented methods: - `init(config)` — one-time setup (App ID, merchant domain, dropin URL) before the first `buyNow` call; [Firmly](/contact) provides the exact config shape for your account - `buyNow(...)` — launch the dropin (accepts `productUrl`, `affiliateUrl`, `layout`) - `on(event, handler)` — subscribe to events (e.g. `orderPlaced`) Use the SDK for a one-liner; use the raw iframe for full control of the surrounding UX. --- # Embedded Marketplace The marketplace is a feature inside a larger product — a banking app's rewards shopping section, a loyalty program's redemption catalog, a publisher's shop subsection. The host product owns the surrounding UI; the marketplace is embedded as a shopping-capable sub-experience. ## When this fits | Condition | Does this pattern fit? | |---|---| | Shopping is augmenting an existing product, not the primary product | ✅ Yes | | Host product has its own user identity (banking app, loyalty program, publisher account) | ✅ Yes — auth context flows from the host | | A slim, embedded shopping section (not a full standalone site) is sufficient | ✅ Yes | | Full standalone marketplace with own homepage / navigation | ❌ Use [Operator-Hosted](/solutions/marketplace/integration-patterns/operator-hosted) instead | ## What the host product owns | Layer | Owner | |---|---| | Host product surrounding UI (navigation, auth, account, etc.) | Host product | | Embedded marketplace section UI | Host product (using Firmly APIs underneath) | | Catalog presentation and search | Host product | | Checkout — build inline, or use Firmly's [hosted checkout](/solutions/agentic-commerce/integration-patterns/hosted-checkout) | Host product or Firmly | | Cart / order orchestration | Firmly APIs | | Payment + order placement | Firmly APIs | ## Auth and identity passthrough The host product typically has its own user identity (the banking app user, the loyalty program member). When the user enters the marketplace section: - Host product's session identifies the user - Host product calls `POST /browser-session` to start a Firmly session for that user - Subsequent Firmly API calls use the resulting token - A Firmly session is scoped to one host user for the life of that host session — when the host session ends or the token expires, start a fresh Firmly session on the next host login This keeps the marketplace's commerce identity scoped within the host product's user identity. ## Common host-product scenarios | Host product | Marketplace role | |---|---| | Banking app | Rewards shopping — redeem points for products from partner merchants | | Loyalty program | Member-exclusive product catalog | | Publisher's shop section | Editorial-curated products available for purchase | | Brand-loyalty app | Brand-partner exclusive products (alternative to [Branded Commerce](/solutions/branded-commerce/) when the brand wants more aggregation control) | ## Limits to keep in mind - **Real estate.** Embedded marketplace UI is constrained by the host product's layout. Design for a slimmer experience than operator-hosted. - **Auth lifecycle.** When the host product session expires, the embedded marketplace session must expire too. Plan for graceful re-auth or session expiry handling. - **Keep the cart shape simple.** Embedded contexts benefit from a lean, focused checkout — don't over-build the cart UI for the host product's constrained real estate. --- ## Related - [Branded Marketplace use case](/solutions/marketplace/use-cases/branded-marketplace) - [Single Product Purchase Flow](/solutions/marketplace/flows/single-product-purchase) - [Operator-Hosted](/solutions/marketplace/integration-patterns/operator-hosted) — the alternative pattern --- # Errors For the **full error catalog, envelope shape, idempotency, rate limits, and known limitations**, see the canonical page: > 📘 **[API Reference → Errors & Conventions](/api-reference/errors-and-conventions)** That page covers everything — the REST envelope, all error names with HTTP codes + recovery strategies, the UCP envelope for protocol-layer consumers, retry patterns with idempotency, and the `?sse=true` known limitation. This page lists patterns that are specifically relevant to **agentic** flows — extra context for agent builders on top of the canonical reference. ## Patterns specific to agentic flows ### Stock changed mid-conversation The classic agentic race. Your agent showed the user a product, the user confirmed, by the time you call `complete-order` someone else has bought it: ```text discovery/search → OK add-line-item → OK set-shipping → OK complete-order → 409 NotEnoughStockError ``` **Conversational recovery**: re-fetch the product to see current stock, then surface the change as a question: > "Looks like the medium just sold out — they still have a small or large. Want one of those?" Update the cart with the new variant/quantity, retry `complete-order` with a **new** idempotency key (this is a genuinely new attempt with new parameters). ### Payment declined mid-conversation ```text complete-order → 422 CreditCardDeclined ``` Do **not** silently retry the same card. Tell the user the card was declined — without leaking the issuer's reason verbatim (it can signal valid card numbers). Offer a different payment method. If your agent supports PayPal or Klarna, route to express checkout at this point. ### Validation error → conversational ask ```text set-shipping-info → 400 InvalidInputBody "At path: phone — Expected a string with a length between 10 and 13" ``` The `description` includes the failing field path. Map it to a natural-language question rather than echoing the technical error: > "What's the phone number with country code? (10–13 digits)" ### Cart became stale (session TTL expired) Sessions auto-expire after ~1 hour. If your agent has been holding a cart for >1 hour and the session token is rejected: 1. Bootstrap a new session 2. Rebuild the cart (re-call `add-line-item` for each item) 3. Continue **Carts are not portable across sessions** — there's no "transfer cart" operation. The user-visible cart state needs to be re-built from your agent's memory. ### `get-availability` not supported by this merchant Some merchants return `501 NotImplemented` on `cart/shipments/get-availability`. This does **not** block checkout: `get-availability` only returns delivery dates, time slots, and pickup locations for scheduled-delivery or in-store-pickup shipments — it never returns shipping methods. Shipping methods always come from `cart.shipments[].shipping_method_options`, which Firmly populates inline after `set-shipping-info`. Treat a `501` as "no scheduled-delivery/pickup detail for this merchant" and proceed with the inline methods. See [Shipping & Fulfillment](/api-reference/shipment-configuration/shipping-and-fulfillment). ## Agent-specific anti-patterns to avoid | Don't | Do | |---|---| | Retry a declined card silently | Ask user for a different payment method | | Show raw error `description` to user | Translate to natural-language ask | | Keep retrying on `503 StoreUnavailable` indefinitely | Exponential backoff, cap at ~30s, then surface to user | | Generate a new idempotency key per retry | Reuse the same key for genuine retries; new key only for new attempts | ## Where to go next - **[Errors & Conventions](/api-reference/errors-and-conventions)** — canonical catalog and recovery patterns - **[Consent & Disclosure](/solutions/agentic-commerce/consent-and-disclosure)** — what to surface to the user before placing an order --- # Firmly Card UCP Handler > **Note** > **Status: Preview (feature-flagged).** The handler routes (spec, schema, and public-key endpoints) are live, but the handler is advertised in discovery and usable only when the destination, merchant, UCP mode, Vault card path, and merchant PSP path are all enabled. It is not yet generally available — coordinate with [Firmly](/contact) for the current state. The Firmly Card handler exposes normal card payment through UCP by accepting an encrypted card payload and completing the order through Firmly Vault. - **Handler namespace**: `ai.firmly.card` - **Handler id**: `firmly_card` ## Contract - Discovery stays on the merchant domain: `https:///.well-known/ucp` - UCP callers fetch the public key from a UCP route, not Vault directly - Vault remains the key source of truth and the only service that decrypts card data - Public request fields follow UCP schemas; Firmly / Vault internal names stay internal - The JWE plaintext carries only card fields; the checkout it applies to is resolved from the UCP request, not from a field inside the payload - Merchant binding comes from the UCP route domain and checkout session, not from a duplicated payload field ## UCP schema alignment The public handler uses UCP names, not Firmly internal names: | Layer | Shape | |---|---| | Payment handler namespace | `ai.firmly.card` | | Payment handler id | `firmly_card` | | Payment instrument | UCP card payment instrument | | Payment credential wrapper | UCP encrypted credential: `credential.type = "encrypted"`, `credential.encrypted_data = ""` | | JWE plaintext | Simplified Firmly card payload using UCP-style field names: `number`, `expiry_month`, `expiry_year`, `name`, `cvc` | Internal Vault field names such as `encrypted_card`, `billing_info`, `verification_value`, `month`, or `year` are **not exposed** in the UCP-facing contract. They are only used after the UCP service maps the request to Vault. ## Discovery snippet This handler is advertised only when the destination, merchant, UCP mode, Vault card path, and merchant PSP path are all enabled. > **Note** > This snippet is the `payment_handlers` fragment of the modern manifest shape, where `payment_handlers` is a namespace-keyed map nested inside `ucp`. That shape was introduced in manifest version `2026-01-23` and is used by every version from `2026-01-23` onward. The `ai.firmly.card` handler is itself versioned `2026-04-08`. The earlier `2026-01-11` [base UCP manifest](/solutions/agentic-commerce/protocols/ucp/implementation#well-known-manifest) declares payment under a top-level `payment.handlers` array instead. ```json { "payment_handlers": { "ai.firmly.card": [ { "id": "firmly_card", "version": "2026-04-08", "spec": "https://api.firmly.work/api/2026-04-08/ucp/payment-handlers/ai.firmly.card", "schema": "https://api.firmly.work/api/2026-04-08/ucp/payment-handlers/ai.firmly.card/schema.json", "available_instruments": [ { "type": "card", "constraints": { "brands": ["visa", "mastercard", "amex", "discover"] } } ], "config": { "environment": "sandbox", "provider_id": "ai.firmly", "public_key_url": "https://api.firmly.work/api/2026-04-08/ucp/rest/domain//payment-handlers/ai.firmly.card/key", "encryption_algorithm": "RSA-OAEP-256" } } ] } } ``` ## Handler schema The `schema` URL in the handler declaration tells the caller how to construct the handler-specific config and credential payload: ```text https://api.firmly.work/api/2026-04-08/ucp/payment-handlers/ai.firmly.card/schema.json ``` ```json { "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://api.firmly.work/api/2026-04-08/ucp/payment-handlers/ai.firmly.card/schema.json", "title": "Firmly Card UCP Payment Handler", "description": "Schema for submitting a Firmly-encrypted card credential through UCP complete checkout.", "type": "object", "additionalProperties": false, "required": ["payment"], "properties": { "payment": { "type": "object", "additionalProperties": false, "required": ["instruments"], "properties": { "instruments": { "type": "array", "minItems": 1, "items": { "$ref": "#/$defs/paymentInstrument" } } } } }, "$defs": { "paymentInstrument": { "type": "object", "additionalProperties": true, "required": ["id", "handler_id", "type", "credential"], "properties": { "id": { "type": "string" }, "handler_id": { "const": "firmly_card" }, "type": { "const": "card" }, "selected": { "type": "boolean" }, "billing_address": { "$ref": "https://ucp.dev/2026-04-08/schemas/shopping/types/postal_address.json" }, "credential": { "$ref": "#/$defs/encryptedCredential" } } }, "encryptedCredential": { "type": "object", "additionalProperties": false, "required": ["type", "encrypted_data"], "properties": { "type": { "const": "encrypted" }, "encrypted_data": { "type": "string" } } }, "encryptedCardPlaintext": { "type": "object", "additionalProperties": false, "required": ["number", "expiry_month", "expiry_year", "name", "cvc"], "properties": { "number": { "type": "string", "minLength": 12, "maxLength": 19 }, "expiry_month": { "type": "integer", "minimum": 1, "maximum": 12 }, "expiry_year": { "type": "integer", "minimum": 2000 }, "name": { "type": "string", "minLength": 1 }, "cvc": { "type": "string", "minLength": 3, "maxLength": 4 } } }, "handlerConfig": { "type": "object", "additionalProperties": false, "required": ["environment", "provider_id", "public_key_url", "encryption_algorithm"], "properties": { "environment": { "enum": ["sandbox", "production"] }, "provider_id": { "const": "ai.firmly" }, "public_key_url": { "type": "string", "format": "uri" }, "encryption_algorithm": { "const": "RSA-OAEP-256" } } } } } ``` This illustration abbreviates the live schema for readability. Two `$defs` are worth calling out: `encryptedCardPlaintext` is the JWE plaintext the caller encrypts (`number`, `expiry_month`, `expiry_year`, `name`, `cvc` — nothing more), and `handlerConfig` mirrors the `config` block from the discovery snippet above. The caller encrypts an `encryptedCardPlaintext` object and sends the compact JWE as `credential.encrypted_data` on the card instrument. ## Public key route ```http GET /api/:ucpVersion/ucp/rest/domain/:domain/payment-handlers/ai.firmly.card/key ``` The UCP service validates merchant / destination eligibility, fetches the active public key from Vault internally, and returns the JWK. The key is bound to the merchant domain and checkout session. ## Why this matters Today, UCP's primary payment path on Google's surfaces is Google Pay. The Firmly Card handler adds a card-payment path through Firmly's existing Vault infrastructure — opening UCP to flows that need card payment without Google Pay. --- ## Related - [UCP overview](/solutions/agentic-commerce/protocols/ucp/) - [UCP implementation](/solutions/agentic-commerce/protocols/ucp/implementation) — service architecture, manifest - [Get Payment Public Key](/api-reference/payment/get-public-key) — Firmly Vault's existing card encryption flow - [UCP roadmap](/solutions/agentic-commerce/protocols/ucp/roadmap) --- # Firmly Connect Firmly Connect is Firmly's merchant control panel — the dashboard at [merchant.firmly.ai](https://merchant.firmly.ai) where a merchant signs up, walks through onboarding, and then runs their store on Firmly's network of AI shopping agents, publishers, and marketplaces. It's the surface that lets merchants become **agentic-commerce-ready without writing code**: connect the store once on Firmly Connect, and distribute to every channel Firmly supports without a separate integration per destination. ![How Firmly Connect fits — the merchant connects their store once through Firmly Connect, Firmly runs the shared commerce platform, and one connection fans out to every destination the merchant opts into (AI shopping agents, marketplaces, publishers, social)](/images/firmly-connect/how-firmly-connect-fits.svg) - [Sign up at Firmly Connect](https://merchant.firmly.ai) — Create your merchant account at merchant.firmly.ai and start the onboarding wizard. ## What Firmly Connect does For a merchant, Firmly Connect covers everything from "I have a store and I want my products reachable inside AI shopping" through to operating that distribution day-to-day: | Phase | What it covers | |---|---| | **Sign-up & login** | A welcome page and signup form that creates the merchant tenant and primary-owner user. Returning users sign in with OTP, magic link, or corporate SSO | | **Onboarding** | A 7-step wizard that takes the merchant from "account created" to "live on the network" | | **Daily operations** | The Merchant Portal — KPIs, an orders list, an append-only audit log, team management, and per-feature configuration pages | ## Two entry points - [Onboarding wizard](/solutions/firmly-connect/onboarding/) — The 7-step sequence that takes a new merchant from account creation to "live on the Firmly network." Most steps are simple forms, radio buttons, and toggles — only one (CDN whitelisting) involves any technical work, and for most merchants Firmly determines it isn't needed and skips it automatically. - [Merchant Portal](/solutions/firmly-connect/portal/) — The daily-use side of Firmly Connect — live dashboard, orders, audit logs, team management, and per-feature settings. ## What's distinctive about this product - **Merchant-of-record stays with the merchant.** Firmly never becomes the seller. Orders land in the merchant's native order management system as if a customer placed them directly. - **One connection, every destination.** Connect the store once on Firmly Connect; from there Firmly handles the integration with every destination the merchant opts into (AI shopping agents, marketplaces, publishers, social). - **Little or no engineering effort to deploy for most stores.** Most onboarding is simple forms, radio buttons, and toggles — not code. Firmly handles the platform integration on its side, across all industry-standard commerce platforms and custom platforms. - **Per-domain SSO and identity management.** Owners can register multiple storefront domains, enforce SSO per-domain, and bind any verified domain to any Identity Provider cataloged on the dashboard. ## Firmly Connect and the destination side Firmly Connect is the merchant-side counterpart to the destinations on Firmly's network. Destinations (AI chat products, wallets, banks, publishers, etc.) integrate with Firmly's APIs to reach merchants. Merchants use Firmly Connect to make their store reachable. See [Destinations](/solutions/destination-surfaces/) for the other side. --- ## Related - [Onboarding overview](/solutions/firmly-connect/onboarding/) — the 7-step wizard - [Portal overview](/solutions/firmly-connect/portal/) — daily operations - [Why Firmly Connect](/solutions/firmly-connect/why-firmly) — what's already built - [For Merchants](/for-merchants/) — merchant-facing onboarding documentation - [Single Sign-On (SSO)](/solutions/firmly-connect/sso/) — IdP configuration setup guides --- # Flows End-to-end purchase walkthroughs for Ad Commerce — each one follows a single buyer from discovery through to a placed order, showing the exact calls in order. Read these after the solution overview and before the API reference: they show how the endpoints fit together, not what each field means. - [Multi-Product Purchase](/solutions/ad-commerce/flows/multi-product-purchase) - [Single Product Purchase](/solutions/ad-commerce/flows/single-product-purchase) --- # Flows End-to-end purchase walkthroughs for Agentic Commerce — each one follows a single buyer from discovery through to a placed order, showing the exact calls in order. Read these after the solution overview and before the API reference: they show how the endpoints fit together, not what each field means. - [Multi-Product Purchase](/solutions/agentic-commerce/flows/multi-product-purchase) - [Single Product Purchase](/solutions/agentic-commerce/flows/single-product-purchase) --- # Flows End-to-end purchase walkthroughs for Branded Commerce — each one follows a single buyer from discovery through to a placed order, showing the exact calls in order. Read these after the solution overview and before the API reference: they show how the endpoints fit together, not what each field means. - [Buyer Purchase Flow](/solutions/branded-commerce/flows/buyer-purchase-flow) - [Multi-Product Purchase](/solutions/branded-commerce/flows/multi-product-purchase) - [Single Product Purchase](/solutions/branded-commerce/flows/single-product-purchase) --- # Flows End-to-end purchase walkthroughs for Marketplace — each one follows a single buyer from discovery through to a placed order, showing the exact calls in order. Read these after the solution overview and before the API reference: they show how the endpoints fit together, not what each field means. - [Multi-Product Purchase](/solutions/marketplace/flows/multi-product-purchase) - [Single Product Purchase](/solutions/marketplace/flows/single-product-purchase) --- # Flows End-to-end purchase walkthroughs for Publisher Commerce — each one follows a single buyer from discovery through to a placed order, showing the exact calls in order. Read these after the solution overview and before the API reference: they show how the endpoints fit together, not what each field means. - [Multi-Product Purchase](/solutions/publisher-commerce/flows/multi-product-purchase) - [Single Product Purchase](/solutions/publisher-commerce/flows/single-product-purchase) --- # Generic OIDC > **Note** > **Generic OIDC works with any OpenID Connect 1.0–compliant Identity Provider** — Okta, Microsoft Entra ID, Google, Auth0, Keycloak, JumpCloud, OneLogin, and others. This guide covers what you fill in on the Firmly Connect side. For provider-specific application setup steps (creating the OIDC application, granting scopes, mapping claims), refer to your IdP's own integration documentation. ## Prerequisites Before you start, make sure you have: - **At least one verified domain** in Firmly Connect — see [Verify a Domain](/solutions/firmly-connect/sso/domain-verification). - **An OIDC application registered in your IdP** that issues an ID token containing the user's email. You will need its **Client ID**, **Client Secret**, and **Issuer URL**. - **Permission to configure the redirect (callback) URI** on your IdP application. Firmly will give you the exact URL to register. ## Get the Firmly Callback URL When you open the OIDC configuration form in Firmly Connect, the page displays a read-only **Callback URL** with a copy button. This URL is the OAuth2 / OIDC redirect URI that your IdP will send the user back to after authentication. You must register this exact URL as a permitted redirect URI in your IdP's OIDC application before the integration will work. > **Note** > The Callback URL is **deployment-specific** — copy it directly from the Merchant Portal rather than guessing or hand-typing it. A single character mismatch will cause your IdP to reject the redirect with a `redirect_uri` error. ![Callback URL panel with copy button](/images/firmly-connect/sso/oidc-callback-url.png) ## Add an OIDC Identity Provider ### Open Settings → Single Sign-On Navigate to the **Single Sign-On** page in your Merchant Portal settings. ### Click Add Identity Provider The IdP picker dialog opens with all available protocols. ### Select OpenID Connect Click the **OpenID Connect** tile to open the configuration form. ### Fill in the form fields See the [Field reference](#field-reference) below for every field. ### Click Save The IdP is created in **disabled** state. You can now test it, bind it to verified domains, and enable it. ![IdP picker with OpenID Connect tile](/images/firmly-connect/sso/oidc-picker.png) ## Field reference | Field | Required | What to enter | | ----------------- | :------: | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | **Issuer URL** | Yes | The OIDC issuer URL of your IdP — must use `https://` (for example, `https://accounts.google.com`). The form accepts either the bare issuer URL or the full `…/.well-known/openid-configuration` discovery URL; Firmly canonicalizes it on save. | | **Client ID** | Yes | The Client ID for the OIDC application you registered in your IdP. | | **Client Secret** | Yes | The Client Secret for that application. Stored encrypted; the field is masked with a show / hide toggle. | | **Email Claim** | No | The JWT claim name that contains the user's email address. Leave empty to use the standard `email` claim — change only if your IdP exposes the email under a non-standard claim name. | ![OpenID Fields](/images/firmly-connect/sso/oidc-fields.png) > **Note** > Firmly automatically requests the `openid profile email` scopes when initiating the OIDC flow — you do not configure scopes on the form. Make sure your IdP application allows these scopes. ## Bind the IdP to verified domains The IdP configuration form includes an **Authorized Domains** section listing every domain you have verified. Each verified domain appears as a toggle. - Turn on the toggle for each domain you want this IdP to handle. - A single IdP can be bound to multiple domains. - A single domain can be bound to multiple IdPs (users will be presented with a choice at sign-in). - **At least one domain must be bound** before the IdP can be enabled. Unverified domains do not appear in this list. To bind a new domain to this IdP, [verify the domain](/solutions/firmly-connect/sso/domain-verification) first — it will then show up here automatically. ## Enable the IdP The **Enabled** toggle at the top of the form becomes available once: - All required fields are filled and pass validation, **and** - At least one verified domain is bound under **Authorized Domains**. Toggle **Enabled** on to make the IdP usable for sign-in. A disabled IdP keeps all its configuration but cannot complete authentication for any user. ## Test the connection The **Test Connection** button appears on the IdP form in **edit** mode (after the initial save), provided there are no unsaved changes and all required fields are filled. Clicking **Test Connection** performs a real OIDC round trip against your IdP: 1. Firmly redirects you to your IdP's authorization endpoint. 2. You authenticate with a real account at your IdP. 3. Your IdP redirects back to Firmly with an authorization code. 4. Firmly exchanges the code for an ID token, validates the signature against your IdP's JWKS, and extracts the configured claims. On success, the form displays the extracted claims (email, name, sub). On failure, it displays a formatted error explaining where the round trip broke down (for example, `invalid_client`, `redirect_uri_mismatch`, signature verification failure, missing email claim). > **Warning** > Always run **Test Connection** successfully *before* enabling the IdP for a domain that you plan to enforce SSO on. A misconfigured IdP combined with enforcement will lock users out of the dashboard until the configuration is fixed. ![Test Connection button and success result](/images/firmly-connect/sso/oidc-test-connection.png) ## Rotate the Client Secret If you rotate the Client Secret in your IdP (or it leaks and you need to invalidate it): 1. Generate a new Client Secret in your IdP application. 2. Open the IdP configuration in Firmly Connect, paste the new value into **Client Secret**, and click **Save**. 3. Run **Test Connection** to confirm the new secret works. There is no separate "rotate" workflow — updating the field and saving is the rotation. ## Disable or delete the IdP - **Disable** — turn the **Enabled** toggle off on the form. The configuration is preserved, the IdP is removed from sign-in, and any domain enforcement that depended solely on this IdP becomes unavailable. - **Delete** — from the IdP row's actions menu on the SSO page, choose **Delete**. This is a hard delete, recorded in the audit log, and will unbind the IdP from any domains that referenced it. ## Troubleshooting **Invalid issuer** The discovery document at `/.well-known/openid-configuration` must be reachable from Firmly, and its `issuer` field must match the configured **Issuer URL** exactly (per OpenID Connect Discovery 1.0 §4.3). If you used a discovery URL in the form, Firmly stores the bare issuer URL after canonicalization — reopen the form to see the stored value. **Email claim missing** Your IdP's ID token doesn't contain a usable email value. Confirm the OIDC application has the `email` scope granted, that the user has an email attribute populated in the IdP, and (if the IdP uses a non-standard claim name) set the **Email Claim** field to the actual claim name. **Redirect URI mismatch** Your IdP rejects the redirect with `redirect_uri_mismatch` (or similar). Copy the **Callback URL** from the Firmly Connect form *verbatim* and paste it into your IdP application's list of allowed redirect URIs. Trailing slashes, scheme (`http` vs `https`), and host casing all matter. **Test Connection hidden after a change** The **Test Connection** button is hidden while there are unsaved changes on the form. Save first, then click **Test Connection**. ## Next steps - [Verify a Domain](/solutions/firmly-connect/sso/domain-verification) — Add and verify the domains you want this IdP to handle, and enable enforcement when you're ready. - [SSO Overview](/solutions/firmly-connect/sso/) — Recap the full setup flow and per-domain enforcement model. --- # Generic SAML 2.0 > **Note** > **Generic SAML 2.0 works with any SAML-compliant Identity Provider** — Okta, Microsoft Entra ID, ADFS, OneLogin, JumpCloud, Ping Identity, Shibboleth, and others. This guide covers what you fill in on the Firmly Connect side. For provider-specific application setup steps (creating the SAML application, configuring assertions, mapping attributes), refer to your IdP's own integration documentation. ## Prerequisites Before you start, make sure you have: - **At least one verified domain** in Firmly Connect — see [Verify a Domain](/solutions/firmly-connect/sso/domain-verification). - **A SAML 2.0 application registered in your IdP** that signs assertions and accepts the Service Provider's (SP's) Audience / Entity ID and Assertion Consumer Service URL. - **From your IdP**, either: - A **metadata XML file** describing the IdP, **or** - The three values manually: **Entity ID / Issuer**, **SSO URL**, and the **X.509 signing certificate** in PEM format. ## Firmly's Service Provider details The IdP configuration form displays three Service Provider (SP) values that you provide to your IdP. Copy them from the Merchant Portal rather than guessing — they are deployment-specific. | Firmly field | Where to use it in your IdP | | ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | | **SP Entity ID** | Enter as the **Audience** / **Entity ID** / **SP Identifier** in your IdP application. Read-only on the Firmly form, with a copy button. | | **ACS URL** | Enter as the **Assertion Consumer Service (ACS) URL** / **Reply URL** / **Single Sign-On URL** in your IdP application. | | **SP Metadata XML** | Click **Download SP Metadata** to download an XML file. If your IdP supports importing SP metadata, upload this file instead of copying the SP Entity ID and ACS URL fields manually. | ![SP Entity ID, ACS URL, and SP Metadata download panel](/images/firmly-connect/sso/saml-sp-fields.png) ## Add a SAML Identity Provider ### Open Settings → Single Sign-On Navigate to the **Single Sign-On** page in your Merchant Portal settings. ### Click Add Identity Provider The IdP picker dialog opens with all available protocols. ### Select SAML 2.0 Click the **SAML 2.0** tile to open the configuration form. ### Provide IdP configuration Either upload your IdP's metadata XML for one-click setup, or fill in the three required fields manually. See [Field reference](#field-reference) below. ### Click Save The IdP is created in **disabled** state. You can now test it, bind it to verified domains, and enable it. ![IdP picker with SAML tile](/images/firmly-connect/sso/saml-picker.png) ## Fast path: upload IdP metadata XML **With metadata XML (recommended)** Most modern IdPs offer a downloadable metadata XML file describing the SAML endpoints and signing certificate. 1. Download the metadata XML from your IdP. 2. On the Firmly SAML form, click the **IdP Metadata XML (optional)** upload control and select the file. 3. Firmly parses the file in your browser and auto-fills **IdP Entity ID**, **SSO URL**, and **X.509 Certificate**. 4. Review the auto-filled values, edit anything if needed, and click **Save**. The metadata XML itself is **not** stored — only the three extracted fields are persisted. **Without metadata XML** If your IdP does not provide a metadata XML, fill in **IdP Entity ID**, **SSO URL**, and **X.509 Certificate** manually using the values from your IdP's SAML application configuration. ## Field reference | Field | Required | What to enter | | --------------------------- | :------: | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **IdP Metadata XML** | No | Optional metadata XML file from your IdP. Auto-fills the three fields below. UI-only — the file itself is not stored. | | **IdP Entity ID** | Yes | The unique identifier of your IdP, sometimes called *Issuer*. Example: `http://www.okta.com/exk1234567890`. | | **SSO URL** | Yes | Your IdP's Single Sign-On endpoint — the URL Firmly redirects users to in order to authenticate. Must use `https://`. | | **X.509 Certificate** | Yes | Your IdP's public signing certificate in PEM format, including the `-----BEGIN CERTIFICATE-----` and `-----END CERTIFICATE-----` lines. Firmly validates the PEM wrapper and base64 body, and uses this certificate to verify the signatures on SAML responses. | | **Email Attribute** | No | The SAML attribute *Name* containing the user's email address. Leave empty to try the common defaults automatically (`email`, `mail`, `urn:oid:0.9.2342.19200300.100.1.3`, and the ADFS `…/claims/emailaddress` claim). Set this if your IdP emits the email under a different attribute name. | ![SAML Fields](/images/firmly-connect/sso/saml-fields.png) > **Warning** > **SAML signing certificates expire.** Track the expiry date of the certificate you upload here, and update the **X.509 Certificate** field with a fresh certificate before the old one expires — once the certificate expires, every SAML sign-in for this IdP will fail until you update it. ## NameID and user matching Firmly Connect uses the email returned by your IdP to look up the user. Configure your IdP to: - Send a `NameID` in any stable format — Firmly matches users by the email *attribute*, not by NameID, so the NameID format doesn't affect matching (a `urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress` NameID is fine but not required). - Include an **email attribute** in the SAML assertion. By default Firmly checks the common email attribute names — `email`, `mail`, the SAML2 email URN `urn:oid:0.9.2342.19200300.100.1.3`, and the Microsoft/ADFS claim `http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress`. If your IdP uses a different name, set the **Email Attribute** field to that exact name. The email's domain portion must match a verified domain that is bound to this IdP. Sign-in for users whose email domain is not bound to this IdP will be rejected. ## Bind the IdP to verified domains The IdP configuration form includes an **Authorized Domains** section listing every domain you have verified. Each verified domain appears as a toggle. - Turn on the toggle for each domain you want this IdP to handle. - A single IdP can be bound to multiple domains. - A single domain can be bound to multiple IdPs (users will be presented with a choice at sign-in). - **At least one domain must be bound** before the IdP can be enabled. ## Enable the IdP The **Enabled** toggle at the top of the form becomes available once: - All required fields are filled and pass validation (including a well-formed PEM certificate), **and** - At least one verified domain is bound under **Authorized Domains**. Toggle **Enabled** on to make the IdP usable for sign-in. A disabled IdP keeps all its configuration but cannot complete authentication for any user. ## Test the connection The **Test Connection** button appears on the IdP form in **edit** mode (after the initial save), provided there are no unsaved changes and all required fields are filled. Clicking **Test Connection** performs a real SAML round trip against your IdP: 1. Firmly redirects you to your IdP's SSO URL with a SAML AuthnRequest. 2. You authenticate with a real account at your IdP. 3. Your IdP posts a signed SAML response back to Firmly's ACS URL. 4. Firmly verifies the response signature against the configured X.509 certificate, validates the audience matches the configured SP Entity ID, and extracts the email attribute. On success, the form displays the extracted attributes. On failure, it displays a formatted error pointing to where the round trip broke down (for example, signature verification failure, audience mismatch, missing email attribute). > **Warning** > Always run **Test Connection** successfully *before* enabling the IdP for a domain that you plan to enforce SSO on. A misconfigured IdP combined with enforcement will lock users out of the dashboard until the configuration is fixed. ![Test Connection button and success result](/images/firmly-connect/sso/saml-test-connection.png) ## Update the certificate When your IdP rotates the SAML signing certificate (typically annually): 1. Obtain the new certificate from your IdP — either as a fresh metadata XML, or as a PEM-formatted certificate. 2. Open the IdP configuration in Firmly Connect. 3. Either re-upload the new metadata XML (which refreshes all three fields), or paste the new PEM into **X.509 Certificate** directly. 4. Click **Save**, then run **Test Connection** to confirm the new certificate works. There is no separate "rotate" workflow — updating the field and saving is the rotation. ## Disable or delete the IdP - **Disable** — turn the **Enabled** toggle off on the form. The configuration is preserved, the IdP is removed from sign-in, and any domain enforcement that depended solely on this IdP becomes unavailable. - **Delete** — from the IdP row's actions menu on the SSO page, choose **Delete**. This is a hard delete, recorded in the audit log, and will unbind the IdP from any domains that referenced it. ## Troubleshooting **Signature validation failed** The X.509 certificate stored in Firmly does not match the certificate your IdP signed the response with. Re-download the current certificate (or metadata XML) from your IdP and update the **X.509 Certificate** field. Make sure the PEM is pasted with the `-----BEGIN CERTIFICATE-----` and `-----END CERTIFICATE-----` lines intact and no extra whitespace. **No email returned** The SAML assertion did not include a recognizable email attribute. Confirm your IdP application is configured to release an email attribute, and set the **Email Attribute** field to the exact attribute *Name* your IdP emits. ADFS and some Microsoft directories use long URI- or URN-style attribute names (e.g. `http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress` or `urn:oid:0.9.2342.19200300.100.1.3`) — paste that exact string. **Audience / Entity ID mismatch** Your IdP is sending an Audience that does not match Firmly's **SP Entity ID**. Copy the **SP Entity ID** value from the Firmly form *verbatim* and paste it into your IdP application's Audience / Entity ID field. Trailing slashes and scheme matter. **ACS URL not accepted** Your IdP is refusing to redirect to Firmly's ACS URL. Copy the **ACS URL** from the Firmly form *verbatim* and add it to your IdP's allowed reply / ACS URL list. **Test Connection hidden after a change** The **Test Connection** button is hidden while there are unsaved changes on the form. Save first, then click **Test Connection**. ## Next steps - [Verify a Domain](/solutions/firmly-connect/sso/domain-verification) — Add and verify the domains you want this IdP to handle, and enable enforcement when you're ready. - [SSO Overview](/solutions/firmly-connect/sso/) — Recap the full setup flow and per-domain enforcement model. --- # Going Live Moving an Agentic Commerce integration from sandbox to production. The universal launch checklist lives at [For Destinations → Going Live](/for-destinations/going-live); the list below adds the agentic-specific requirements — consent, protocol wiring, and autonomous-purchase checks. Review both end-to-end before pointing real buyer traffic at Firmly. > **Note** > Production access is granted by Firmly, not self-serve. Reach out to [Firmly](/contact) when you're ready to flip — they'll provision the production App ID and confirm the merchant set you're routing to. Sandbox-to-production is a configuration change on Firmly's side, not a separate platform. ## Before you ask for production access Run through each of these against your sandbox build. Anything you can't check off is a launch blocker. ### Credentials & authentication - [ ] You can swap the sandbox App ID for the production ID without code changes — the ID is config, not hardcoded - [ ] Authentication strategy chosen ([browser session](/api-reference/authentication/browser-session) or [server-to-server](/api-reference/authentication/server-to-server)) and your client correctly handles **token expiry** (browser sessions ~1 hour) - [ ] Session tokens are stored server-side, never in client JavaScript or URLs - [ ] No sandbox card numbers (`4111111111111111`, etc.) hardcoded — production rejects these ### Cart lifecycle handling - [ ] Your code reads `cart_status` on every cart response and branches on `active`, `checkout_blocked`, `item_not_shippable`, `submitted` — see [Cart Lifecycle](/api-reference/cart-management/cart-lifecycle) - [ ] You renew the session token when it expires (~1 hour) and re-bootstrap cleanly; idle carts are garbage-collected after ~7 days of inactivity, so your code rebuilds the cart if it's gone - [ ] You handle the case where stock changes between `discovery/search` and `complete-order` — see [Errors → Stock changed mid-conversation](/solutions/agentic-commerce/operations/errors#stock-changed-mid-conversation) ### Error handling & recovery - [ ] You've integrated against the full [Errors & Conventions](/api-reference/errors-and-conventions) catalog — not just happy-path responses - [ ] **You do not silently retry** `CreditCardDeclined` (payment declines) with the same card — surface the failure to the user and offer alternatives - [ ] You map technical errors to natural language for the user — *"the medium is sold out — small or large?"* not *"NotEnoughStockError"* - [ ] You send [idempotency keys](/solutions/agentic-commerce/protocols/ucp/idempotency) on `complete-order` and other mutating writes — and on the core REST endpoints (which don't deduplicate on the key today) you re-read `cart_status` before any retry - [ ] Retries use **exponential backoff**, respect `Retry-After` headers, and have a maximum attempt count ### Rate limits & throughput - [ ] You understand the [rate limits](/api-reference/rate-limits) for each endpoint you call - [ ] Your destination handles `429` responses gracefully — back off, don't hammer - [ ] If you're doing large-scale discovery (e.g. price-monitoring), coordinate throughput with [Firmly](/contact) ahead of launch ### Consent & disclosure - [ ] [Consent & Disclosure](/solutions/agentic-commerce/consent-and-disclosure) requirements are wired into your agent's flow — the user reviews and confirms order details (item, price, total, shipping, payment) before you call `complete-order` - [ ] The merchant's identity is surfaced to the user before checkout — they know **who** they're buying from - [ ] Your privacy policy and terms reference Firmly as the commerce backend where applicable ### Production data hygiene - [ ] No customer or partner names appear in your logs, prompts, or telemetry without their consent - [ ] PII (names, addresses, card data) handled per your jurisdiction's rules — Firmly tokenizes card data; your destination should never see raw card numbers - [ ] Sandbox test data (test merchant domain, test cards, test addresses) doesn't leak into your production prompts or test fixtures ### Protocol-specific If you're using a structured protocol rather than direct REST: - [ ] [UCP](/solutions/agentic-commerce/protocols/ucp/), [MCP](/solutions/agentic-commerce/protocols/), or [ACP](/solutions/agentic-commerce/protocols/) wired against the sandbox host `api.firmly.work` — repoint to the production base URL Firmly provides at go-live - [ ] Your agent stack's tool definitions reference the current schema — see [Schemas](/resources/schemas/) ### Autonomous agent purchases (if applicable) If you're using [Agentic Pay](/solutions/agentic-commerce/agentic-pay) for autonomous (cardholder-not-present) purchases: - [ ] Mandate scope is per-merchant, per-amount, with an expiry — not unbounded - [ ] Network-token enrollment is sandbox-verified for each card you intend to use in production - [ ] You have a recovery path for [`intent-challenge`](/api-reference/agentic-pay/intent-challenge) responses — a network step-up (additional cardholder verification) the card network can require before authorizing an autonomous purchase ## What changes between sandbox and production | | Sandbox | Production | |---|---|---| | **App ID** | Sandbox `_appId` from Firmly | Production `_appId` from Firmly | | **Base URL** | `api.firmly.work` / `cc.firmly.work` | Different hosts — Firmly provides the production base URLs at go-live | | **Test cards** | `4111111111111111` etc. accepted | Rejected — must be real cards | | **Test merchants** | `staging.luma.gift` and similar | Production merchant domains | | **Order placement** | Test orders against sandbox merchants | Real orders, real payment authorization, real fulfillment by the merchant | | **Rate limits** | Identical in both environments | Identical in both environments | The host and SDK don't change. **The only operational change is your App ID** — your code paths against the API surface should already work identically. ## Your first production call 1. Swap the sandbox `_appId` for the production `_appId` in your config 2. Run a single end-to-end test against a real merchant with a real card (your own, not the user's). For a physical-goods SKU, run the full sequence: `browser-session` → `discovery/search` → `add-line-item` → `set-shipping-info` → `set-shipping-method` (picking from the shipment's `shipping_method_options`; optionally call `get-availability` first for scheduled-delivery dates / time slots) → `get-consents` / `set-consents` (if the merchant requires them — skipping required consents makes `complete-order` return `RequiredConsentsNotSigned` (412)) → `get-payment-public-key` → `complete-order` (this sequence builds the cart, so it finalizes with `complete-order`; use `place-order` only for the one-shot create-cart-and-order call). For a digital SKU with no shipping, the shipping steps can be omitted — see the [single-product flow](/solutions/agentic-commerce/flows/single-product-purchase) for the canonical tail 3. Verify the order lands in the merchant's system ([Firmly](/contact) will help confirm) 4. Roll out to buyer traffic incrementally — canary first, then full ramp If anything fails the first end-to-end test, fall back to sandbox immediately and reach out to [Firmly](/contact) before retrying production. ## When to talk to Firmly You don't have to wait until everything's checked off to engage. Reach out for: - Production App ID provisioning - Merchant set scoping (which merchants you're routing to) - Throughput planning if you expect bursty traffic - Custom protocol behavior or non-standard error handling needs - A pre-launch review walkthrough — Firmly's team can sanity-check your integration before you flip See [Contact](/contact) for the support email. --- ## Related - [Sandbox setup](/solutions/agentic-commerce/operations/sandbox-setup) — the prerequisite before any of this - [Errors & Recovery](/solutions/agentic-commerce/operations/errors) — agentic-specific patterns - [Errors & Conventions](/api-reference/errors-and-conventions) — full error catalog - [Cart Lifecycle](/api-reference/cart-management/cart-lifecycle) — `cart_status` state machine - [Idempotency](/solutions/agentic-commerce/protocols/ucp/idempotency) — required for production-grade writes - [Rate Limits](/api-reference/rate-limits) — what to expect under load - [Consent & Disclosure](/solutions/agentic-commerce/consent-and-disclosure) — user-facing requirements - [Agentic Pay](/solutions/agentic-commerce/agentic-pay) — for autonomous (cardholder-not-present) purchases --- # Hosted Checkout Hosted checkout is the pattern where Firmly hosts the entire checkout UI. The destination prepares the cart (or just the intent), generates a Firmly checkout URL, and sends the user to it. Firmly renders the entire checkout — addresses, payment, review, confirm. After the order is placed, the user lands on the merchant's order-confirmation page. "Hosted" means Firmly hosts the page **and owns the UX**. Both the infrastructure and the design are Firmly's. The destination owns the conversation around it. > **Note** > **There is no `return_url` parameter.** After the order, the user lands on the merchant's `thank_you_page` URL (the merchant's native order confirmation page) — not a destination-controlled URL. To detect that the order was placed, embed the dropin in an iframe and listen for the `firmly::OrderPlaced` postMessage event. See [How the destination learns the order was placed](#how-the-destination-learns-the-order-was-placed) below. ## When to use it - The destination wants Firmly's checkout UX rather than building its own - Voice or conversational surfaces that hand off to a phone screen for the final step - Compliance-conscious destinations that want PCI scope entirely on Firmly's side **Don't use this** for surfaces with no human at a screen (use [Deep Link / Headless](/solutions/agentic-commerce/integration-patterns/deep-link)), or when the surrounding UX must match the destination's brand (use [Embedded Checkout](/solutions/agentic-commerce/integration-patterns/embedded-checkout) — same URL, used as iframe `src`). ## The checkout URL The destination redirects the user to the Firmly dropin URL with the parameters below. The dropin URL is provided by [Firmly](/contact) — it is the same URL used for [Embedded Checkout](/solutions/agentic-commerce/integration-patterns/embedded-checkout), just used as a top-level navigation target instead of an iframe `src`. ### Required parameters | Parameter | What it is | |---|---| | `_appId` | Your App ID (UUID) | | `domain` | The merchant domain (e.g. `staging.luma.gift`) | ### Useful optional parameters | Parameter | Default | Purpose | |---|---|---| | `url` | — | Product URL to pre-load into a PDP view | | `variant_id` | — | Pre-select a variant | | `quantity` | `1` | Pre-set quantity | | `ui_mode` | `fullscreen` | Layout: `fullscreen`, `minimal-pdp`, `full-pdp` | | `skip_pdp` | `false` | Skip product detail, jump straight to checkout | | `force_pdp` | `false` | Force the product detail view | | `flush_cart` | `true` | Clear any existing cart before adding the item | | `affiliate_url` | — | Affiliate attribution URL | | `custom_properties` | — | JSON-encoded merchant-specific properties | ### Example URL ```text /buy ?_appId=YOUR_APP_ID &domain=staging.luma.gift &url=https://staging.luma.gift/products/gift-card-25 &skip_pdp=true ``` ## The handoff pattern ### Agent assembles intent The destination resolves the user's request to a product (via [Catalog Search](/api-reference/discovery/search) or [Get Product](/api-reference/catalog/get-product)), then constructs the checkout URL with the appropriate parameters above. ### Agent issues the URL Depending on the surface: - **Chat** — send the link inline - **Voice** — text the URL via SMS or push it to a connected screen - **Web app** — `window.location.href = checkoutUrl` or open in a new tab - **Mobile** — open in an in-app browser or system browser ### User completes checkout on Firmly's page Firmly handles product detail, address, shipping, payment, review, confirm. The destination is not involved during this window. ### After the order: user lands on the merchant's thank-you page The dropin redirects the user to `data.urls.thank_you_page` from the `complete-order` response — that's the **merchant's** confirmation page (e.g. `.com/.../account/orders/...`). Today the user does **not** return to a destination-controlled URL automatically. ### Agent re-engages on next user contact See the next section for how the destination knows the order was placed. ## How the destination learns the order was placed This is the most important section of this page. Read it before scoping the integration. There is **no `return_url` parameter** that redirects the user back to your domain with order details. That option doesn't exist today. Here are the three patterns that actually work: ### Pattern A — Iframe + postMessage (recommended for web surfaces) If your surface can render an iframe, embed the dropin URL in a full-screen iframe and listen for `firmly::OrderPlaced`. This is technically [Embedded Checkout](/solutions/agentic-commerce/integration-patterns/embedded-checkout) — the only difference from "hosted" is the iframe takes the full viewport. You get the order details via postMessage immediately. `FIRMLY_DROPIN_ORIGIN` in the sample below is the dropin origin that [Firmly](/contact) provides. ```javascript window.addEventListener('message', (event) => { if (event.origin !== FIRMLY_DROPIN_ORIGIN) return; if (event.data?.action === 'firmly::OrderPlaced') { const { url, session } = event.data; // url = merchant's thank-you page URL // session = full cart object including cart_id, custom_properties, urls handleOrderPlaced(session); } }); ``` See [Embedded Checkout — postMessage events](/solutions/agentic-commerce/integration-patterns/embedded-checkout#postmessage-events) for the full event catalog. ### Pattern B — Polling cart status (for non-iframe surfaces) If you can't iframe (voice, SMS handoff, AMP, certain in-app browsers), you need to detect order placement by polling the cart endpoint until its `cart_status` transitions to `submitted`. This requires you to correlate the checkout with a session you control. Bootstrap a browser session server-side **before** sending the user to checkout, hold onto its `access_token`, and poll the cart with that same token — the cart the user acts on in the dropin is the one bound to your session. Pass the token into the poller (not a bare `device_id`, which is not a checkout-URL parameter): ```javascript // Before sending the user to checkout, you bootstrapped a browser session server-side // and kept its access_token. Poll the cart with that token until it becomes submitted. async function pollForOrder(accessToken, domain) { for (let i = 0; i < 60; i++) { // 60 attempts = ~10 minutes at 10s interval const cart = await fetch( `https://api.firmly.work/api/v2/domains/${domain}/cart`, { headers: { 'x-firmly-authorization': accessToken } } ).then(r => r.json()); if (cart.cart_status === 'submitted') { return cart; // contains cart_id and custom_properties } await new Promise(r => setTimeout(r, 10000)); } throw new Error('Order not detected within timeout'); } ``` ### Pattern C — Out-of-band confirmation For voice agents that don't have a screen at all, the simplest pattern is: text the user the checkout URL, accept that the destination loses real-time visibility, and re-engage when the user mentions the order in the next conversation turn. Combine with Pattern B (polling) if you want proactive notification. ## Sample agent flow ```text Agent: "I'll send you a link to complete the purchase." [Agent constructs URL: /buy?_appId=...&domain=...] [Agent texts URL via SMS, OR redirects user via window.location, OR opens iframe] [User completes checkout on Firmly's page] Option A (iframe): Agent immediately receives firmly::OrderPlaced postMessage Option B (no iframe): Agent polls cart status every 10s; sees cart_status: "submitted" Option C (voice + out-of-band): Agent waits for user to come back to the conversation Agent: "Great — your order is placed." ``` ## Theming The hosted page inherits the merchant's brand by default. Destination-level overrides (logo, accent color, copy) are configured per App ID — talk to [Firmly](/contact). There's no per-call theming via URL parameters at this layer. ## What you don't have to build When you use hosted checkout, you skip: - Address entry forms and validation - Payment field rendering and PCI compliance - Shipping method selection UI - Order review and confirm screens - Refund/dispute UI (handled by merchant) This is why hosted is the fastest first integration — you're not building any of the above. The trade-off is the user ends up on the **merchant's** thank-you page, not yours, and you need one of the three patterns above to detect order completion programmatically. --- # How JavaScript injection works Firmly Social Commerce Checkout requires a JavaScript file, supplied by Firmly, to be injected into the in-app webview (IAW) of the social media platform. The script is injected at several points during the shopping experience, as described in [Shopping workflow](#shopping-workflow) below. ## Receiving your JS from Firmly The Firmly JS is the key component of Firmly Social Commerce Checkout. Once you receive it, inject it into your social commerce process. To request your file, [contact Firmly](/contact). A Firmly representative will follow up. ## Shopping workflow 1. **The customer begins the shopping experience.** From the social media site, the customer clicks a merchant ad (for example, `merchant.example`) intending to make a purchase. 2. **The merchant website opens.** The site opens in an in-app webview (IAW) within the social media application. The social media backend fetches metadata for the merchant website and returns the JS injection script with that metadata attached. 3. **The customer shops.** Until the customer clicks Checkout, the entire experience takes place on the merchant site — they select one or more items and add them to the cart. The social media app requests a health check from Firmly services and receives a health status. As the customer browses to different pages on the merchant's domain, the JS must be injected into each new page. 4. **The customer navigates to the Cart page.** The JS enhances the Checkout button so that it initiates the native social media checkout rather than the merchant checkout. 5. **The customer clicks Checkout.** Firmly Social Commerce Checkout launches and the customer leaves the merchant website. The injected JavaScript collects the required information and generates an opaque handle, which is transferred to Firmly backend services to complete the flow. The makeup of the handle varies per merchant and depends on the current product state of Firmly. 6. **The social media app runs the checkout process.** 1. The injected JavaScript raises the `StartCheckout` event with the opaque handle as an argument. 2. The social media app retrieves the relevant `httpOnly` cookies from the IAW. 3. The app calls [Session Transfer](/api-reference/session/session-transfer) — cookies plus opaque handle — against Firmly services. 4. Firmly services respond with the Firmly cart. 5. The social media site displays the Firmly checkout page with items and shipping info. 7. **The customer completes the transaction.** They select a payment method and complete the purchase on the checkout page. --- # Idempotency UCP clients pass an `Idempotency-Key` header on mutation operations so that retries — caused by network blips, timeouts, or any other transient failure — don't duplicate the underlying effect. > **Warning** > **Today this header is honored only by the UCP protocol bridge.** Core REST endpoints (`add-line-item`, `update-line-item`, `place-order`, `complete-order`, and other cart mutations) accept the header but do not deduplicate on it today — it's a no-op on those calls. For REST clients, see [Client-side dedup for REST](#client-side-dedup-for-rest) below. REST-side deduplication is on the roadmap. ## How it works on UCP When the UCP bridge receives a mutation with an `Idempotency-Key` header: 1. The first time a given key is seen, the operation runs normally and the response is cached. 2. A subsequent retry with the same key returns the **original cached response** instead of running the operation a second time. 3. If the same key is reused with a **different request body**, the bridge returns `409` with a UCP `messages[]` envelope carrying `code: "idempotency_conflict"` — a safety check that prevents accidentally reusing a key across different attempts. ## Generating keys One UUID per logical attempt. Reuse on retries; rotate when the attempt is genuinely new. | Scenario | New key? | |---|---| | Network timeout — same body, retry | No — reuse the key | | 5xx response — retry the same operation | No — reuse the key | | User changed their mind — new attempt | Yes — generate a new key | | Different cart / different card | Yes — generate a new key | > **Note** > The sample below shows the header-driven retry pattern **as it will work once core REST endpoints honor `Idempotency-Key`**. Today the header is ignored on `complete-order` (see the Warning above) — so on the REST path this retry loop must be paired with the client-side dedup guard described in [Client-side dedup for REST](#client-side-dedup-for-rest). On the UCP bridge, the header is honored as shown. ```javascript import { randomUUID } from 'crypto'; const key = randomUUID(); // one key for this logical attempt // On the UCP bridge the Idempotency-Key header is honored today. // On core REST complete-order it is ignored for now — pair this with // the client-side dedup guard below until REST support lands. const completeOrder = () => fetch(`${PAY_API}/api/v2/payment/domains/${domain}/complete-order`, { method: 'POST', headers: { 'x-firmly-authorization': authToken, 'Idempotency-Key': key, 'Content-Type': 'application/json', }, body: JSON.stringify(orderBody), }); // Safe to retry on transient failure with the SAME key for (let attempt = 0; attempt < 3; attempt++) { const resp = await completeOrder(); if (resp.ok) return resp.json(); if (resp.status >= 500) { await sleep(1000 * Math.pow(2, attempt)); // 1s, 2s, 4s backoff continue; } const err = await resp.json(); // On the UCP bridge a key reused with a different body returns a `messages[]` // envelope with code `idempotency_conflict`. Core REST doesn't deduplicate, so it // has no equivalent error — see "Conflict error format" below. throw new Error(`${err.error}: ${err.description}`); } ``` ## Key retention Keys cache for **24 hours**. After that, the same key counts as a new call. For a single user clicking "place order" once, 24 hours is more than enough. If your retry window legitimately spans more than a day, treat it as a new attempt and generate a new key. ## Client-side dedup for REST For destinations calling the core REST endpoints directly (not via the UCP bridge), retries currently re-run the operation. Guard against duplicates on your side: - **For `complete-order`:** if a request times out, re-fetch the cart before retrying. If the cart's `cart_status` is already `submitted`, the order placed despite the timeout — don't retry. - **For cart mutations:** keep a `last_known_cart_revision` and verify it before applying a retry, or accept the rare double-add and let the user remove duplicates. - **For payment:** never silently retry a declined payment with the same card — surface the decline to the user and offer alternatives. ## Conflict error format ```json { "messages": [ { "type": "error", "code": "idempotency_conflict", "content": "Idempotency key was used with a different request body", "severity": "recoverable" } ], "ucp": { "version": "2026-04-08" } } ``` If you see this in production, audit your retry logic — somewhere your code is generating the same UUID for two attempts that have different bodies. Common causes: - Generating the key from a request hash instead of a fresh UUID per attempt - Reusing a key across what should be different attempts (e.g., across user sessions) - Caching a key in shared storage incorrectly --- ## Related - [Errors & Conventions](/api-reference/errors-and-conventions) — the broader recovery catalog - [UCP overview](/solutions/agentic-commerce/protocols/ucp/) - [Rate limits](/api-reference/rate-limits) --- # In-Ad Checkout The full checkout — line items, address, payment, confirmation — renders inside the ad creative footprint. Used for in-feed shoppable ads on platforms that support interactive ad units. ## When this fits | Condition | Does this pattern fit? | |---|---| | Ad surface supports interactive elements (clickable forms, payment widgets inside the creative) | ✅ Yes | | Mobile feed (social, video, content discovery) | ✅ Yes — wallet payment shortens checkout dramatically | | Static display ad (no in-creative interactivity) | ❌ No — use Post-Click Landing | | Connected-TV ad (limited remote-control input) | ❌ No — use Post-Click Landing | ## Real-estate constraints In-ad checkout has limited space. Design choices: - **Single-screen flow** — address, payment, and confirmation in one scrollable view - **Wallet-first payment** — Google Pay button at the top of the checkout panel; card-via-JWE is a secondary option - **Pre-filled address** — wallet flows auto-fill name, address, email; viewer just confirms - **No multi-step navigation** — back/forward states inside an ad creative confuse the viewer; keep the flow linear ## What the destination owns | Layer | Owner | |---|---| | Ad creative rendering (HTML/JS or platform-specific format) | Destination | | In-ad checkout UI (form fields, wallet button, confirmation message) | Destination | | Cart / order orchestration | Firmly APIs | | Payment encryption + processing | Firmly APIs | | Order placement at merchant | Firmly APIs | | Conversion postback to ad platform | Destination (after order success) | ## Constraints to plan for - **Ad platform inspection.** Some ad platforms periodically inspect creative behavior. If your creative makes outbound HTTP requests (Firmly API calls) at impression time rather than at click time, the platform may flag the creative. Always make the first API call (`POST /browser-session`) on viewer interaction, not on impression. - **Sandboxed JS environments.** Some ad platforms run creatives in restricted iframes (no cookies, limited storage). Make sure your auth bootstrap doesn't depend on cross-origin cookies — Firmly's browser session works in restricted contexts. - **Limited error surfacing.** If `complete-order` fails, you have minimal space to show the viewer a recovery option. Default to a single, clear message ("Payment couldn't process. Try a different card or click here for full checkout") with a fallback CTA to the [Post-Click Landing](/solutions/ad-commerce/integration-patterns/post-click-landing). --- ## Related - [In-Feed Shoppable Ad use case](/solutions/ad-commerce/use-cases/in-feed-shoppable-ad) - [Single Product Purchase Flow](/solutions/ad-commerce/flows/single-product-purchase) - [Post-Click Landing](/solutions/ad-commerce/integration-patterns/post-click-landing) — the alternative pattern --- # In-Feed Shoppable Ad A viewer scrolling a feed (social, video content, news aggregator) sees a shoppable ad creative for a specific product. The ad creative includes price, image, and a Buy CTA. On click, an in-ad checkout opens — address, payment, place order — all inside the ad surface. The viewer never leaves the feed. This is the highest-conversion Ad Commerce pattern because every redirect to a separate landing or store is a drop-off opportunity. The constraint is that the ad surface must support in-feed interactive units. ## Recommended setup | Choice | Default | Why | |---|---|---| | **Integration pattern** | [In-Ad Checkout](/solutions/ad-commerce/integration-patterns/in-ad-checkout) | Keeps the viewer in-feed | | **Auth** | [Browser session](/api-reference/authentication/browser-session) | Ad surfaces run client-side per viewer | | **Payment** | Google Pay (mobile feeds), card via JWE (web feeds) | Wallet auth reduces friction the most in-feed | | **Attribution** | Click-ID (`fbclid`, `gclid`, `ttclid`) + UTM | Ad platform credits conversions; advertiser's analytics report on campaign performance | ## API sequence The flow follows the [Single Product Purchase](/solutions/ad-commerce/flows/single-product-purchase) shape. The ad creative encodes the SKU directly, so an explicit `discovery/search` is usually skipped. | Step | Endpoint | |---|---| | 1. Bootstrap session | [`POST /api/v1/browser-session`](/api-reference/authentication/browser-session) | | 2. Add to cart | [`POST /cart/line-items`](/api-reference/cart-management/add-line-item) | | 3. Set shipping address | [`POST /cart/shipping-info`](/api-reference/checkout/set-shipping-info) | | 4. Pick shipping method | [`POST /cart/shipment/methods`](/api-reference/shipment-configuration/set-shipping-method) | | 5. (Optional) Get delivery availability | [`POST /cart/shipments/get-availability`](/api-reference/shipment-configuration/get-availability) | | 6. (If required) Get + set merchant consents | [`GET /cart/consents`](/api-reference/checkout/get-consents) → [`PUT /cart/consents`](/api-reference/checkout/set-consents) | | 7. Get payment public key | [`GET /payment/key`](/api-reference/payment/get-public-key) | | 8. Complete order | [`POST /payment/complete-order`](/api-reference/payment/complete-order-v2) | | 9. Fire ad-platform postback | Per-platform conversion API (Meta CAPI, Google Ads, TikTok Events) | The valid `shipping_method_id`s for step 4 come from the cart itself — `cart.shipments[].shipping_method_options`, populated by step 3 (`set-shipping-info`). `get-availability` (step 5) is optional and returns delivery dates, time slots, or pickup locations for scheduled-delivery or in-store-pickup shipments — not shipping methods. Steps 2–6 build the cart, so step 8 finalizes it with [`complete-order`](/api-reference/payment/complete-order-v2) (body: `encrypted_card` + `billing_info`); use [`place-order`](/api-reference/payment/place-order-v2) only for the one-shot create-cart-and-order call. ## Considerations the ad surface owns - **Render in the ad's footprint.** In-ad checkout typically has limited vertical real estate. Design for a compressed checkout UX — single-screen address, one-tap wallet, minimal scroll. - **Capture the click identifier as early as it's available.** Persist whichever click identifier the platform exposes (`fbclid`, `gclid`, etc.) as soon as it appears — for most platforms this is at click time, when the identifier is appended to the click-through URL. Once the cart exists, bind it (folded into the `utm` string) via [Set Cart Attribution](/api-reference/cart-management/set-attribution) so it rides through to the order metadata and postback. - **Fire the postback after order success.** The conversion postback (Meta CAPI, Google Ads, etc.) must come after `cart_status === "submitted"`, not before. Otherwise the campaign learns from unconfirmed conversions. - **Inventory-aware creatives.** Ad campaigns can drive concurrent traffic spikes. If the ad targets a limited-stock SKU, fetch the product via [Get a Product](/api-reference/catalog/get-product) before the viewer clicks Buy and surface "out of stock" in the creative when availability reports it's unavailable. --- ## Related - [Single Product Purchase Flow](/solutions/ad-commerce/flows/single-product-purchase) — full API walkthrough - [In-Ad Checkout pattern](/solutions/ad-commerce/integration-patterns/in-ad-checkout) — UI hosting choice - [Post-Click Purchase](/solutions/ad-commerce/use-cases/post-click-purchase) — the alternative use case --- # Integration Patterns Ad Commerce integration patterns answer one question: **where does the checkout UI render?** Two patterns cover the vast majority of cases. For a post-click landing, the checkout UI can also be Firmly's [hosted checkout](/solutions/agentic-commerce/integration-patterns/hosted-checkout) rather than one you build. ## The two patterns - [In-Ad Checkout](/solutions/ad-commerce/integration-patterns/in-ad-checkout) — The entire checkout — address, payment, confirmation — renders inside the ad creative. No redirect. - [Post-Click Landing](/solutions/ad-commerce/integration-patterns/post-click-landing) — Click routes the viewer to a dedicated landing page where the full purchase completes. ## How to pick | If… | Pick | |---|---| | The ad surface supports interactive elements within the creative (social feeds, some video formats) | In-Ad Checkout | | The ad surface is static display, audio, or connected-TV — no in-feed interaction | Post-Click Landing | | The product detail needs richer presentation than the creative footprint allows | Post-Click Landing | | Maximum-conversion priority | In-Ad Checkout (every redirect is a drop-off) | ## How patterns relate to use cases | Pattern | Best-fit use case | |---|---| | [In-Ad Checkout](/solutions/ad-commerce/integration-patterns/in-ad-checkout) | [In-Feed Shoppable Ad](/solutions/ad-commerce/use-cases/in-feed-shoppable-ad) | | [Post-Click Landing](/solutions/ad-commerce/integration-patterns/post-click-landing) | [Post-Click Purchase](/solutions/ad-commerce/use-cases/post-click-purchase) | ## The shared platform Both patterns use the same Firmly API surface — auth, cart, checkout, payment, order placement. What varies is **where the UI renders** and **how much real estate is available** for the checkout flow. --- ## Related - [Single Product Purchase Flow](/solutions/ad-commerce/flows/single-product-purchase) — full API walkthrough applicable to both patterns - [Use Cases](/solutions/ad-commerce/use-cases/) — which scenario is being built - [Agentic Commerce → Integration Patterns](/solutions/agentic-commerce/integration-patterns/) — the broader 4-phase matrix that applies across solutions --- # Integration Patterns A Firmly integration is a combination of choices across four phases. Every implementation picks one option per phase. Authentication is always required. Cart orchestration and order placement on the merchant's platform always go through Firmly. This page is the **matrix view** — pick one option per phase and you have your integration shape. For a deep dive on the most common axis of choice (where the checkout UI lives), see the [Hosted](/solutions/agentic-commerce/integration-patterns/hosted-checkout), [Embedded](/solutions/agentic-commerce/integration-patterns/embedded-checkout), and [Deep Link / Headless](/solutions/agentic-commerce/integration-patterns/deep-link) sub-pages. ## The four phases | Phase | Option | Description | |---|---|---| | **Hosting** | A — Partner-Hosted | Partner hosts the experience on their own infrastructure | | | B — Firmly-Hosted PoC (UAT) | Firmly hosts everything in UAT, zero-trust email authentication, data removed after PoC | | **Authentication** | A — S2S Tokens | Partner server creates `device_id`, signs with S2S token | | | B — Browser Sessions | User's browser connects directly, Firmly generates `device_id` | | **Discovery** | A — Merchant Catalog | Firmly feeds catalog, partner pre-loads and serves | | | B — Catalog Full-text Search | Partner calls Firmly's search API at runtime | | | C — Partner's Own Catalog | Partner uses own catalog; Firmly not involved in discovery | | **Checkout** | A — Real-time | Partner UI collects guest credit card; Firmly tokenizes and places order via sync API | | | B — Async (VCC) | Partner takes full order + own payment; sends VCC to Firmly for merchant placement | | | C — Firmly Checkout UI | Partner hands off; Firmly overlay/dropin handles checkout end-to-end | ## Partner integration examples What varies most across partners is **who owns discovery** and **who owns the checkout UI**. | Partner profile | Authentication | Discovery | Checkout | |---|---|---|---| | Greenfield — no catalog, no checkout UI | A or B | A or B | **C** (Firmly UI) | | Has own catalog and search — no checkout UI | A or B | **C** (own catalog) | **C** (Firmly UI) | | Has own catalog, search, and checkout UI | A or B | **C** (own catalog) | **A** (real-time, guest CC) | | Has own catalog, search, checkout UI, and own payment | A or B | **C** (own catalog) | **B** (async, VCC) | Each row is a valid integration shape. Most destinations fall into one of these four profiles. All four profiles assume **Hosting Option A (Partner-Hosted)**; the Firmly-Hosted PoC option is used for UAT rather than a production profile. ## Where the checkout UI lives — the most common decision The Checkout phase has three options (A, B, C above). Each gets its own dedicated page with details on URLs, parameters, and code: - [Hosted Checkout](/solutions/agentic-commerce/integration-patterns/hosted-checkout) — **Checkout Option C** — Firmly hosts the checkout UI on a Firmly-rendered page. Partner redirects the user to the dropin. - [Embedded Checkout](/solutions/agentic-commerce/integration-patterns/embedded-checkout) — **Checkout Option C, iframe variant** — Firmly's checkout dropin runs inside the partner's surface as an iframe. Same UI, partner-branded wrapping. - [Deep Link / Headless](/solutions/agentic-commerce/integration-patterns/deep-link) — **Checkout Option A or B** — Partner drives every step through Firmly's API directly. No Firmly-rendered UI. ## Comparison — checkout UI sub-options | | Hosted (C) | Embedded (C, iframe) | Deep Link / Headless (A or B) | |---|---|---|---| | **Where checkout UI lives** | Firmly-hosted page | Inside partner surface, Firmly-rendered | Inside partner surface, partner-rendered | | **UI control** | Low | High (chrome around iframe) | Total | | **PCI scope on partner side** | None (Firmly handles) | Reduced (iframe) | Higher (depending on payment flow) | | **Best for** | First integration, low-touch surfaces | Mature surfaces wanting branded UX | Voice, conversational, fully autonomous flows | ## Build your integration — the API call order Whichever combination of phases you pick, every flow goes through the same Firmly APIs underneath. The list below is the order of operations for a complete purchase. Click any item to jump to the canonical reference. ### 1. Authenticate - [Authentication overview](/for-destinations/authentication) — pick the pattern - [Browser session](/api-reference/authentication/browser-session) — Auth Option B - [Server-to-server](/api-reference/authentication/server-to-server) — Auth Option A ### 2. Discover products *(if Discovery Option A or B)* - [Discovery overview](/api-reference/discovery/) - [Search](/api-reference/discovery/search) — Discovery Option B - [Catalog list](/api-reference/catalog/get-all-products) — Discovery Option A - [Get product](/api-reference/catalog/get-product) - [Get product from URL](/api-reference/catalog/get-product-from-url) *(Skip this phase if Discovery Option C — partner uses own catalog.)* ### 3. Build the cart - [Cart management overview](/api-reference/cart-management/) - [Get cart](/api-reference/cart-management/get-cart) - [Add line item](/api-reference/cart-management/add-line-item) - [Update line item](/api-reference/cart-management/update-line-item) - [Clear cart](/api-reference/cart-management/clear-cart) - [Add promo codes](/api-reference/promotions/add-promo-codes) - [Add addon](/api-reference/addon-management/add-addon) ### 4. Set shipping - [Checkout overview](/api-reference/checkout/) - [Set shipping info](/api-reference/checkout/set-shipping-info) - [Get shipping availability](/api-reference/shipment-configuration/get-availability) - [Set shipping method](/api-reference/shipment-configuration/set-shipping-method) - [Set fulfillment type](/api-reference/shipment-configuration/set-fulfillment-type) For multi-shipment carts, see [Shipping and Fulfillment](/api-reference/shipment-configuration/shipping-and-fulfillment). ### 5. Collect consents and billing - [Get consents](/api-reference/checkout/get-consents) - [Set consents](/api-reference/checkout/set-consents) - [Set billing info](/api-reference/checkout/set-billing-info) How consent fits into an agentic flow is covered in [Consent & Disclosure](/solutions/agentic-commerce/consent-and-disclosure). ### 6. Pay and place the order Card flows encrypt the card client-side with Firmly's public key, then submit. Express options follow their own sequence — Klarna is documented below; PayPal and Click to Pay require coordination with [Firmly](/contact) for the provider-specific sequence. - [Get payment public key](/api-reference/payment/get-public-key) - [Place order (v2)](/api-reference/payment/place-order-v2) - [Complete order (v2)](/api-reference/payment/complete-order-v2) - [Klarna express — start](/api-reference/payment/express-checkout/klarna/start) - [Klarna express — authorize](/api-reference/payment/express-checkout/klarna/authorize) - [Klarna express — complete order](/api-reference/payment/express-checkout/klarna/complete-order) - [PayPal express — start](/api-reference/payment/express-checkout/paypal/start) - [PayPal express — authorize](/api-reference/payment/express-checkout/paypal/authorize) - [PayPal express — complete order](/api-reference/payment/express-checkout/paypal/complete-order) ### Errors & recovery Any call above can return a recoverable error. The canonical catalog and recovery patterns: - [Errors & conventions](/api-reference/errors-and-conventions) - [Solution-level errors page](/solutions/agentic-commerce/operations/errors) ## Protocol vs. integration pattern The four phases describe **where each piece of the integration lives**. They're independent of which **protocol** the destination uses to talk to Firmly (UCP, MCP, ACP, or direct REST). Any protocol can be combined with any phase-option combination. See [Protocols](/solutions/agentic-commerce/protocols/) for the protocol comparison. ## End-to-end runnable example If you'd rather read code than narrative, the [Advanced Checkout Guide](/cookbook/advanced-checkout-guide) is the full sequence above as a runnable Node script — start there, then return to this page for the pattern-level guidance and the per-endpoint references. --- ## Related - [Agentic Commerce overview](/solutions/agentic-commerce/) - [Single-product flow](/solutions/agentic-commerce/flows/single-product-purchase) - [Multi-product flow](/solutions/agentic-commerce/flows/multi-product-purchase) - [Cart API Implementation Guide](/cookbook/full-cart-api-guide) --- # Integration Patterns Branded Commerce uses a single primary integration pattern — **Firmly-hosted under the partner's own domain**. Every page (landing page, PDP, checkout, thank-you) is rendered by Firmly's edge and served on a custom domain configured by the partner. Theming is applied from a single per-partner theme object so the buyer-facing identity is consistent end to end. There is no separate off-domain variant of Branded Commerce. The whole point is that the buyer never leaves the partner's domain. ## The four configuration dimensions | Dimension | Setting | |---|---| | **Hosting** | Firmly-hosted under the partner's domain (only mode today — fixed by the solution shape) | | **Theming** | Single theme per partner, applied to every page; supports per-property variants if the partner runs multiple brands (fixed by the solution shape) | | **Affiliate mode** | BYO (partner's own affiliate-network credentials) or Firmly-managed — the partner chooses | | **Ad-platform pixel channels** | Per platform (Meta, Google, TikTok, etc.), choose pixel-only (client-side) or dual-fire (client + server-side CAPI) — the partner chooses, determined by which credentials they supply | The first two are fixed by the solution shape; the last two are the real choices, configured during partner onboarding. ## Hosting — partner domain via Cloudflare for SaaS The partner adds **two DNS CNAME records** — one per environment: | Environment | Partner hostname | CNAME target | |---|---|---| | Production | `deals.partner.example` (or any subdomain) | `firmly.live` | | UAT / staging | `deals-staging.partner.example` | `firmlyuat.com` | Each CNAME must be DNS-only (grey-cloud) if the partner's DNS is on Cloudflare. Firmly enrolls each hostname in its matching Cloudflare zone and provisions TLS via Cloudflare for SaaS. Staging and production are **independent enrollments** — no "promotion" path. Staging stays in place after launch for ongoing pre-production testing. ## Theming — single theme object, applied to every page The partner provides brand assets and copy preferences during onboarding (see [Partner onboarding](/solutions/branded-commerce/operations/partner-onboarding) for the full intake). Firmly builds a theme object and applies it to all pages: | Category | What's needed | |---|---| | **Brand assets** | Logo files (light + dark, SVG preferred), favicon, hero imagery for landing pages | | **Typography** | Primary font family, weight scale, licensing, optional display font | | **Palette** | Primary, secondary/accent, text, background/surface, border, state colors | | **Button treatment** | Corner radius, fill style, hover state, CTA label case | | **Chrome** | Header logo placement, header density, back arrow style, footer links | | **Copy preferences** | Brand voice, promo language template, CTA verb, savings callout phrasing, merchant identity line | | **Legal copy** | T&C URL, privacy policy URL, per-surface disclaimers, jurisdiction | | **Merchant identity** | Prominent vs subtle display per merchant, show merchant domain or not | **Per-property theming.** Partners running multiple brand properties (e.g., several deal sites under one parent) can have one onboarding produce multiple theme variants, not one theme. ## Attribution mode — BYO or Firmly-managed Affiliate attribution is a **configured business choice**, not a setting a shopper or a normal drop-in integration changes at runtime. See the [Affiliate API overview](/api-reference/affiliate/) for the partner-only Start Journey flow and its operating boundaries. | Mode | Who has the affiliate-network accounts | Who fires the conversion | |---|---|---| | **BYO** | Partner — partner's own CJ / Impact / Awin / Rakuten / etc. credentials | Firmly fires through the partner's network using partner's credentials | | **Firmly-managed** | Firmly — Firmly's existing relationships and accounts | Firmly fires through its own credentials, settles commission to the partner per agreement | Choose during onboarding. Most partners with existing affiliate businesses pick BYO; partners new to affiliate marketing typically start with Firmly-managed. The flow for the buyer is identical in either mode — the difference is who provides the tracking relationship. ## Ad-platform pixel channels Per ad platform the partner runs campaigns on, choose between **client-side pixel only** and **dual-fire (client + server-side CAPI)**. The channel mix is determined by **which credentials the partner supplies**: | What the partner provides | Channel mix | |---|---| | Pixel ID / dataset ID only | Client-side pixel only | | Pixel ID + account ID + access token | Dual-fire — client-side pixel + server-side CAPI with `event_id` dedup | Recommended: provide both. The server-side channel covers conversions the client-side pixel misses due to ad blockers; the `event_id` deduplication prevents double-counting. Supported ad platforms: Meta (CAPI), Google Ads (Enhanced Conversions), TikTok, Pinterest, Snap, Reddit. The partner provides per-platform credentials during onboarding. ## Compliance and PCI The partner's domain serves Firmly-controlled pages. Payment data is captured by Firmly's checkout component and tokenized via the merchant's PSP — **never on the partner's side**. The partner takes on **no PCI obligations** through this integration. Unlike embedded-widget integrations, there is no partner-side iframe — checkout is a full-page Firmly-rendered surface on the partner's domain. PCI scope is entirely on Firmly's side. ## What the partner provides vs. what Firmly handles | Step | Partner | Firmly | |---|---|---| | DNS CNAME records | ✓ (two records, one per env) | — | | TLS provisioning | — | Via Cloudflare for SaaS | | Brand assets + copy preferences | ✓ (intake form) | Builds theme object | | Theme application across all pages | — | Applies same theme to every page | | Affiliate-network credentials (if BYO) | ✓ | Configures + fires | | Ad-platform credentials | ✓ (per platform) | Fires conversion events | | Merchant list + onboarding status | Agree with Firmly | Firmly onboards new merchants as needed | | Staging end-to-end testing | Both | Both | ## Pre-launch checklist Before going live: - [ ] Production CNAME resolves; TLS valid on partner hostname - [ ] Staging CNAME resolves; TLS valid on staging hostname; staging tested end-to-end - [ ] Theme reviewed on staging (Landing page, PDP, Checkout, Thank-you) - [ ] Affiliate mode chosen + credentials configured - [ ] Per-platform ad pixels configured (and, ideally, server-side credentials too for dual-fire) - [ ] At least one test order completes on staging end to end - [ ] Legal copy (T&C, privacy, disclaimers) approved and live --- ## Related - [Operations → Partner onboarding](/solutions/branded-commerce/operations/partner-onboarding) — the full one-time setup - [Operations → Operational workflow](/solutions/branded-commerce/operations/operational-workflow) — the ongoing per-product / per-campaign workflow - [Why Firmly](/solutions/branded-commerce/why-firmly) — what Firmly brings + ownership boundary - [Consent & Disclosure](/solutions/agentic-commerce/consent-and-disclosure) — pre-purchase disclosure responsibilities --- # Integration Patterns Marketplace integration patterns answer one question: **where does the marketplace UI render?** Two patterns cover the common shapes. ## The two patterns - [Operator-Hosted](/solutions/marketplace/integration-patterns/operator-hosted) — The marketplace is a standalone destination — operator-owned domain, full branded experience, complete shopping UI. - [Embedded Marketplace](/solutions/marketplace/integration-patterns/embedded-marketplace) — The marketplace UI lives inside another product (a banking app, a loyalty app, a publisher's site) as an embedded shopping section. ## How to pick | If… | Pick | |---|---| | Marketplace is the primary product (the whole site is the marketplace) | Operator-Hosted | | Marketplace is one feature inside a larger product (e.g., a bank app's rewards shopping section) | Embedded Marketplace | | You need full control of brand, navigation, and checkout flow | Operator-Hosted | | You're augmenting an existing app with shopping capability | Embedded Marketplace | Both patterns support the [Branded Marketplace](/solutions/marketplace/use-cases/branded-marketplace) use case; the choice is only where the UI lives. Every marketplace cart is single-merchant regardless of pattern. ## The shared platform Both patterns use the same Firmly API surface — auth, discovery, cart, checkout, payment, order placement. What varies is **where the UI lives** and **how the operator integrates Firmly's APIs into their stack**. --- ## Related - [Single Product Purchase Flow](/solutions/marketplace/flows/single-product-purchase) - [Multi-Product Purchase Flow](/solutions/marketplace/flows/multi-product-purchase) — multiple items from one merchant - [Use Cases](/solutions/marketplace/use-cases/) - [Agentic Commerce → Integration Patterns](/solutions/agentic-commerce/integration-patterns/) — the broader 4-phase matrix applicable across solutions --- # Integration Patterns Publisher Commerce integration patterns answer one question: **where does the buy UI render?** Two patterns cover the common shapes. ## The two patterns - [Embedded Buy Button](/solutions/publisher-commerce/integration-patterns/embedded-buy-button) — Buy Now buttons inline with the article. Checkout renders in a slide-in panel without taking the reader away from the article. - [Dedicated Landing](/solutions/publisher-commerce/integration-patterns/dedicated-landing) — Buy Now routes the reader to a separate landing page where the full checkout completes — useful when the publisher prefers a dedicated shopping experience. ## How to pick | If… | Pick | |---|---| | Reading-flow continuity is the priority | Embedded Buy Button | | Publisher prefers a dedicated shopping page (separate brand or fuller PDP) | Dedicated Landing | | Article references multiple products (roundup, gift guide) | Embedded Buy Button (cart accumulates across the article) | | Single product with rich detail (long-form review) | Either — Embedded Buy Button for inline; Dedicated Landing for a full PDP shopping experience | For which use case pairs with which pattern, see the mapping on [Use Cases → How use cases relate to integration patterns](/solutions/publisher-commerce/use-cases/#how-use-cases-relate-to-integration-patterns). ## The shared platform Both patterns use the same Firmly API surface — auth, cart, checkout, payment, order placement. What varies is **where the UI renders relative to the article**. --- ## Related - [Single Product Purchase Flow](/solutions/publisher-commerce/flows/single-product-purchase) - [Multi-Product Purchase Flow](/solutions/publisher-commerce/flows/multi-product-purchase) - [Use Cases](/solutions/publisher-commerce/use-cases/) - [Agentic Commerce → Integration Patterns](/solutions/agentic-commerce/integration-patterns/) — the broader 4-phase matrix applicable across solutions --- # Know Your Business (KYB) The merchant tells Firmly who they are — company information, branding, and legal documents — and submits the company information for Firmly to verify their business. **KYB approval is the gate that unlocks the rest of the Onboarding Wizard.** Post-onboarding, the same surface is the merchant's general account-settings page. ## The three tabs The KYB / general settings page is organized as three tabs: ### Company Info The KYB form itself. Required fields for submission: - **Company Name** - **Online Revenue band** Plus optional but encouraged: - Employee Count - Headquarters address (Street, City, State, Postal Code, Country) ### Brand Identity - Display Name - Primary brand color - Action color - Logo (large image upload) These values feed into the drop-in checkout (the Firmly-rendered checkout shown on destination surfaces) the merchant's buyers see. ### Terms & Privacy - Link to the merchant's privacy policy - Link to the merchant's terms of use ## The submission flow Once the merchant has filled in (at minimum) Company Name and Online Revenue and saved their changes, a **Submit for Review** call to action appears below the Company Info form. Pressing it transitions KYB to `pending` and notifies Firmly's reviewers. The expected review turnaround is communicated during onboarding, so the merchant knows when to expect a decision rather than waiting without a timeline. **Combined save-and-submit when coming from onboarding.** When the merchant arrives at this page via the onboarding task menu and KYB hasn't been submitted yet, the sticky footer's primary action becomes **Submit for Review** — saving the form and submitting for review are merged into a single button. ## KYB status banner The top of the Company Info tab shows the current KYB status: | Status | What the merchant sees | |---|---| | `pending` | "Your information is being reviewed by Firmly" — submit button hidden | | `approved` | Green "Business Verified" confirmation — submit button hidden | | `rejected` | Reviewer's notes inline, also surfaced against the KYB task in the wizard — merchant sees exactly what to fix | ## Why KYB is the wizard's first gate KYB is the only onboarding step that requires explicit Firmly review. Until it's approved, every later step in the wizard stays locked. This prevents a half-configured store from progressing while Firmly is still verifying who the merchant is. --- ## Related - [Onboarding wizard](/solutions/firmly-connect/onboarding/) — the 7-step sequence - [Catalog configuration](/solutions/firmly-connect/onboarding/catalog-configuration) — next step after KYB approval - [Agreement signing](/solutions/firmly-connect/onboarding/agreement-signing) — the participation form is prefilled from KYB --- # Marketplace > **Note** > **What's in this section:** Use Cases (which scenario you're building), Flows (the API sequence in detail), Integration Patterns (operator-hosted vs embedded), and Operations (sandbox + going live). ## What this solution enables Marketplace solutions let a destination operate as a marketplace: buyers search across many merchants in one branded experience, then buy — each checkout scoped to a single source merchant, which stays the seller of record. Use this when the destination is a true marketplace operator aggregating many merchants into one buyer-facing surface. ![How Marketplace fits — the operator's branded surface lets buyers discover products across many merchants; Firmly runs discovery and a single-merchant checkout; each source merchant stays the seller of record](/images/marketplace/how-marketplace-fits.svg) ## How Marketplace fits within Firmly The Firmly platform is shared across all solutions — the cart, discovery, payment, tax, shipping, and order-placement APIs are the same. Marketplace packages those shared features for one kind of destination: an operator aggregating many merchants into a single branded surface. Each solution section follows the same structure; [Agentic Commerce](/solutions/agentic-commerce/) is the most fully worked example. ## What's documented - [Why Firmly for Marketplace](/solutions/marketplace/why-firmly) — Positioning, scope, and what's specific to Marketplace versus the shared platform. - [Use Cases](/solutions/marketplace/use-cases/) — Common scenarios operators build with Marketplace. - [Flows](/solutions/marketplace/flows/single-product-purchase) — End-to-end user flows annotated with the canonical API sequence. - [Integration Patterns](/solutions/marketplace/integration-patterns/) — Operator-hosted or embedded — pick the surface that fits. - [Operations](/solutions/marketplace/operations/) — Sandbox setup and operational guidance. --- ## Related - [Solutions overview](/solutions/) — all Firmly solutions - [Destinations](/solutions/destination-surfaces/) — which destination types use which solution - [How Firmly Works](/how-firmly-works) — the underlying platform - [API Reference](/api-reference/) — every endpoint --- # Merchant home The operational landing page for a live merchant. An at-a-glance read on how the merchant's store is performing on Firmly's network — headline KPIs across the top, with deeper breakdowns below. While onboarding is still in progress, this same surface falls back to the onboarding task menu so the merchant always lands on something actionable. ## The live dashboard ### Headline KPI cards | KPI | What it shows | |---|---| | **Total Revenue** | Revenue this month, with month-over-month change | | **Average Order Value** | AOV this month, with month-over-month change | | **Active Destinations** | Number of platforms the merchant is live on | The reporting period is the calendar month, and each card compares this month against last month. ### Tabs Below the KPIs: | Tab | What it shows | |---|---| | **Overview** *(default)* | Cumulative Revenue line chart (this month vs last month, month-to-date) and a destinations donut | | **Destinations** | Per-destination performance breakdown | | **Top Products** | Best-selling products in the period | The dashboard is read-only reporting: the period is fixed to the calendar month (there's no custom date-range picker or data export today), and the Destinations tab links through to the [Destinations](/solutions/firmly-connect/onboarding/destinations-configuration) surface for per-destination detail. For order-level detail, use the Orders list in the portal. --- ## Related - [Audit logs](/solutions/firmly-connect/portal/audit-logs) — event feed - [Portal overview](/solutions/firmly-connect/portal/) --- # Multi-Product Purchase > **Note** > This is an **annotated flow** — the viewer experience alongside the API calls the ad surface makes. ## Scope A multi-product Ad Commerce cart holds **items from a single merchant** — a bundle ad creative (multiple SKUs in one click), or a post-click landing with related-product upsells. The cart-mutation, shipping, and order-completion mechanics are the shared Firmly cart flow — because the cart is built across those calls, checkout finalizes with `complete-order`, not the one-shot `place-order`. See [Agentic Commerce → Multi-Product Purchase](/solutions/agentic-commerce/flows/multi-product-purchase) for the cart-modification table, multi-shipment handling, and the race-condition retry pattern. This page covers the Ad-specific entry and cart-review surfaces. ## What's different from single-product 1. **Multi-item entry** — the ad creative lists multiple bundled SKUs at click time, or the post-click landing offers related products as upsells. 2. **Cart Review** — a compact cart panel or modal in the ad surface, or a full cart page on the landing. ## Multi-item entry in code For a bundle ad where the creative names multiple SKUs, add them sequentially: ```javascript // callFirmly: fetch wrapper adding x-firmly-authorization; see the Quickstart // DOMAIN: the merchant domain (e.g., staging.luma.gift) // Endpoint paths below are relative to /api/v2/domains/{domain} // Bundle SKUs from the ad creative metadata const bundle = [ { add_to_cart_ref: { variant_id: 'hoodie-black-m' }, quantity: 1 }, { add_to_cart_ref: { variant_id: 'beanie-wool' }, quantity: 1 } ]; let cart; for (const item of bundle) { cart = await callFirmly(`/api/v2/domains/${DOMAIN}/cart/line-items`, item); } // Cart now has all items; render the cart panel in the ad surface renderCartPanel(cart); ``` For a related-product upsell on a post-click landing, each Add is a separate `POST /cart/line-items`, with the cart panel updating after each. ## Cart Review surfaces ### Mode A — Compact cart panel (in-ad checkout) If the ad surface supports in-ad checkout (no redirect), the cart panel is a compact overlay inside the creative — quantity controls, remove buttons, and a Checkout CTA. ### Mode B — Post-click landing cart page For ad-click-to-landing flows, the cart is a full page on the landing surface with the standard cart UX (line items, totals, promo input, checkout button). ## Express checkout Ad surfaces lean on express checkout to cut drop-off — Google Pay (one tap on mobile), PayPal Express, or Klarna BNPL, each spanning the full cart rather than per-item. ## Attribution Click-ID, UTM, and order metadata flow identically to [Single Product](/solutions/ad-commerce/flows/single-product-purchase#attribution--closing-the-ad-loop) — the merchant sees one order with multiple line items, all tagged with the same ad-platform attribution. --- ## Related - [Single Product Purchase](/solutions/ad-commerce/flows/single-product-purchase) — the simpler shape - [Why Firmly](/solutions/ad-commerce/why-firmly) — what makes Ad Commerce different - [Integration Patterns](/solutions/ad-commerce/integration-patterns/) — in-ad checkout vs post-click landing --- # Multi-Product Purchase > **Note** > This is an **annotated flow** — it walks through the user experience alongside the API calls a developer makes. The order of operations and API specifics are grounded in the underlying platform; the presentation is sequenced for developer readability rather than split across separate UX and design docs. ## Scope Multi-product carts in Agentic Commerce contain **items from a single merchant**. The user discovers items iteratively through the conversation, reviews the cart, then checks out once. ## What's different from single-product Two things change: 1. **Iterative Discovery** — Discovery (Phase 3) repeats. The user adds an item, the agent confirms, the user is asked if they want more. The cart grows over multiple conversation turns. 2. **Cart Review** — a new phase between Discovery and Checkout where the user can adjust quantities and remove items before paying. Everything else — Hosting, Authentication, Checkout, Order placement — is identical to [Single Product](/solutions/agentic-commerce/flows/single-product-purchase). ## The six phases (single + Cart Review) | Phase | Single-Product | Multi-Product | |---|---|---| | 1. Hosting | Same | Same | | 2. Authentication | Same | Same | | 3. Discovery | Once | **Iterative — repeats per item** | | 3.5 Cart Review | — | **New — user adjusts before checkout** | | 4. Checkout | One pass | Same one pass, but cart has many line items | | 5. Order placement | Same | Same | ## Sequence diagram ```mermaid sequenceDiagram autonumber participant U as User participant A as Destination / Agent participant F as Firmly API participant M as Merchant Note over U,A: Phase 3 — Iterative Discovery (repeats per item) loop For each item the user names U->>A: "Add a hoodie" A->>F: POST /api/v1/discovery/search F-->>A: products[] A->>F: POST /cart/line-items F-->>A: cart A->>U: "Added. Anything else?" end Note over U,A: Phase 3.5 — Cart Review U->>A: "Show me the cart" A->>F: GET /cart F-->>A: { line_items, subtotal } A->>U: Cart summary U->>A: "Remove the tee" A->>F: PUT /cart/line-items/:id { quantity: 0 } F-->>A: updated cart U->>A: "Looks good, checkout" Note over U,A: Phase 4 — Checkout (single pass) A->>F: POST /cart/shipping-info F-->>A: cart with shipments[] + shipping_method_options loop Per shipment Note over A: Pick from shipment.shipping_method_options A->>F: POST /cart/shipment/methods end A->>F: GET /cart/consents F-->>A: consents[] (if merchant requires) A->>F: PUT /cart/consents A->>F: GET /payment/key F-->>A: JWK A->>F: POST /payment/complete-order (Idempotency-Key) F->>M: place multi-item order M-->>F: merchant order # F-->>A: { cart_status: "submitted", cart_id, urls, custom_properties } A->>U: "Order placed" ``` ## Iterative discovery in code Each item the user names goes through a search → add cycle. The cart accumulates across calls. ```javascript // User: "add a hoodie and a beanie" const items = [ { query: 'black hoodie medium' }, { query: 'wool beanie' } ]; // Searches are independent — run them in parallel. const searches = await Promise.all(items.map((item) => callFirmly(`/api/v1/discovery/search`, { query: item.query, page_size: 5 }) )); // Cart mutations are NOT independent — every add returns the full cart and // concurrent writes to the same cart race. Add serially. const adds = []; for (let i = 0; i < items.length; i++) { const variant = searches[i].products?.[0]?.variants?.[0]; if (!variant) { adds.push({ skipped: items[i].query }); continue; } const cart = await callFirmly(`/cart/line-items`, { add_to_cart_ref: variant.add_to_cart_ref, quantity: 1 }); adds.push({ added: variant, cart }); } // Report back to user const added = adds.filter(a => a.added); const skipped = adds.filter(a => a.skipped); agent.say(`Added ${added.length} items to your cart` + (skipped.length ? `. Couldn't find: ${skipped.map(s => s.skipped).join(', ')}` : '.')); ``` After each add, your agent can either continue discovery (*"Anything else?"*) or move to cart review. ## Cart Review in detail Before checkout, the user sees the full cart and can change it. There are two surface modes — pick whichever fits your agent: ### Mode A — Chat (text-only surfaces) The agent presents the cart as structured text with a checkout link. The user can say things like *"remove the socks"* or *"change shoes to size 11"*. Your agent updates the cart and re-presents it. ```javascript // Read the current cart const cart = await callFirmly(`/cart`, null, 'GET'); // Format for the user agent.say(formatCart(cart)); // → "1× Luma Hoodie (M, Black) — $45 // 1× Luma Beanie — $18 // 1× Luma Tee (L, White) — $22 // Subtotal: $85 // Anything to change?" // User: "remove the tee" // Match on the variant SKU (line_items expose `sku` / `base_sku`, not a product_id) const teeLineItem = cart.line_items.find(li => li.sku === 'tee-white-l'); await callFirmly(`/cart/line-items/${teeLineItem.line_item_id}`, { quantity: 0 }, 'PUT'); // Or set quantity = 0 to remove; or use DELETE for full clear ``` ### Mode B — Cart panel (rich surfaces) A cart panel slides into the surface (iframe, drawer, modal) showing all items with images, quantity controls, and remove buttons. The user adjusts directly in the panel. When satisfied, they click "Checkout" → checkout begins. If you're using [Embedded Checkout](/solutions/agentic-commerce/integration-patterns/embedded-checkout), the panel can listen to `firmly::CartUpdated` events to stay in sync. ## Common cart modifications Endpoint paths below are shown in shorthand. Every cart call is scoped to a domain — the full path is `/api/v2/domains/{domain}/cart/...` (see the [single-product flow](/solutions/agentic-commerce/flows/single-product-purchase) for fully-qualified examples). | Operation | Endpoint | Body | |---|---|---| | Read the cart | `GET /cart` | — | | Add a line item | `POST /cart/line-items` | `{ add_to_cart_ref, quantity }` | | Change quantity | `PUT /cart/line-items/:id` | `{ quantity: N }` | | Remove an item | `PUT /cart/line-items/:id` with `quantity: 0` (no per-item DELETE; `DELETE /cart/line-items` clears the whole cart) | — | | Clear the entire cart | `DELETE /cart/line-items` | — | | Apply a promo code | `POST /cart/promo-codes` | `{ promo_codes: ["CODE1"] }` | | Remove all promo codes | `DELETE /cart/promo-codes` | — | ## Shipping in multi-product carts There is **one shipping address for the cart**, since all items come from one merchant — but **shipping methods are chosen per shipment**. A single-shipment cart has one method to pick; a multi-shipment cart has one per `shipment_id`. For items that physically ship separately (multi-shipment) — same merchant, different warehouses or fulfillment dates — Firmly groups them into multiple `shipment_id`s in the cart. Walk each one: ```javascript const cart = await callFirmly(`/cart/shipping-info`, address); for (const shipment of cart.shipments) { // Shipping methods are populated inline on each shipment after set-shipping-info. const cheapest = shipment.shipping_method_options .sort((a, b) => a.price.value - b.price.value)[0]; await callFirmly(`/cart/shipment/methods`, { shipment_id: shipment.shipment_id, shipping_method_id: cheapest.id }); } ``` See [Multi-Shipment](/api-reference/shipment-configuration/shipping-and-fulfillment) for the details. ## Express checkout shortcuts For multi-product carts, express checkout options apply to the **full cart**, not per-item: - **PayPal Express** — one PayPal handoff for the whole cart total - **Click to Pay** — one Click to Pay auth covers the whole cart - **Klarna BNPL** — one Klarna agreement spans all items This is the same as single-product; the user sees one payment confirmation for everything. ## Race conditions to handle Multi-product flows are more exposed to mid-flow stock changes because there are more items and more time between discovery and checkout. ```javascript async function placeOrderWithRetry(cart) { try { // The cart was built over the previous calls, so finalize it with complete-order // (body = { encrypted_card, billing_info }); place-order would flush and rebuild it. return await callFirmly(`/payment/complete-order`, buildOrder(cart)); } catch (err) { // NotEnoughStockError is the wire error name (HTTP 409) — see the errors catalog if (err.error === 'NotEnoughStockError') { // Re-fetch the cart and re-read it; a line that dropped out of stock // surfaces as a cart notice on the affected line item. const updated = await callFirmly(`/cart`, null, 'GET'); const affected = updated.line_items.find(li => li.notices?.length); // Ask the user how to handle it agent.say(`${affected?.description ?? 'An item'} just went out of stock. ` + `Drop it from the order, or pick a different variant?`); // ... handle user response } throw err; } } ``` See [Errors & Conventions → Recovery patterns](/api-reference/errors-and-conventions#recovery-patterns-for-common-failure-modes) for more. ## The checkout tail is identical to single-product After cart review, checkout runs the same sequence as the single-product flow: set shipping info → set shipping method per shipment (from each shipment's `shipping_method_options`) → get/set merchant consents → get payment public key → complete order (v2, with `encrypted_card`). Because the cart was built over the previous calls, finalize it with [`complete-order`](/api-reference/payment/complete-order-v2) (existing cart), not `place-order` (the one-shot create-cart-and-order call). If the merchant requires consents and you skip them, `complete-order` returns `RequiredConsentsNotSigned` (412). See the [single-product flow's checkout steps](/solutions/agentic-commerce/flows/single-product-purchase#the-implementation-steps-phase-4-broken-out) for the fully-worked tail. --- ## Related - [Single-product purchase flow](/solutions/agentic-commerce/flows/single-product-purchase) — the checkout tail in full detail - [Cart API guide](/cookbook/full-cart-api-guide) — multi-step cart, shipments, addons - [Shipping & Fulfillment](/api-reference/shipment-configuration/shipping-and-fulfillment) — multi-shipment carts - [Errors & conventions](/api-reference/errors-and-conventions) — recovery patterns for every call above --- # Multi-Product Purchase > **Note** > This is an **annotated flow** — it walks through the buyer experience alongside the API calls the partner's surface makes. The order of operations and API specifics are grounded in the underlying platform; the presentation is sequenced for developer readability. ## Scope Multi-product carts in Branded Commerce contain **items from a single merchant**. Common entry points: a curated landing page (e.g., "Holiday Gift Guide" featuring 6 products), or upsell modules on a branded PDP ("Customers also bought…"). ## What's different from single-product Two things change: 1. **Multi-item discovery** — the buyer either lands on a curated landing page with multiple products (one click → multiple items in cart), or adds related items from PDPs. 2. **Cart Review** — a step between Discovery and Checkout where the buyer reviews and adjusts the cart before paying. In Branded Commerce this is typically a cart drawer or dedicated cart page on the partner's branded surface. Everything else — Hosting, Authentication, Checkout, Order placement — is identical to [Single Product](/solutions/branded-commerce/flows/single-product-purchase). ## The six phases (single + Cart Review) | Phase | Single-Product | Multi-Product | |---|---|---| | 1. Hosting | Same | Same | | 2. Authentication | Same | Same | | 3. Discovery | Page-load context, single SKU | **Curated landing or related-product upsell — multiple SKUs** | | 3.5 Cart Review | — | **New — buyer adjusts before checkout** | | 4. Checkout | One pass | Same one pass, but cart has many line items | | 5. Order placement | Same | Same | ## Sequence diagram ```mermaid sequenceDiagram autonumber participant C as Buyer participant B as Branded Page (Firmly-hosted, partner identity) participant F as Firmly API participant M as Merchant Note over C,B: Phase 3 — Multi-item discovery C->>B: Click ad → lands on curated landing page B->>F: POST /browser-session F-->>B: { access_token } loop For each item the buyer adds C->>B: Click Add for an item B->>F: POST /cart/line-items F-->>B: cart B->>C: "Added. Anything else?" end Note over C,B: Phase 3.5 — Cart Review C->>B: Open cart drawer / cart page B->>F: GET /cart F-->>B: { line_items, subtotal } B->>C: Branded cart summary with adjust / remove controls C->>B: Adjust quantities, remove items B->>F: PUT /cart/line-items/:id { quantity: N } F-->>B: updated cart C->>B: Click Checkout Note over C,B: Phase 4 — Checkout (single pass) B->>F: POST /cart/shipping-info F-->>B: cart with shipments[] + shipping_method_options loop Per shipment Note over B: Pick from shipment.shipping_method_options B->>F: POST /cart/shipment/methods end B->>F: GET /payment/key F-->>B: JWK B->>F: POST /payment/complete-order (Idempotency-Key) F->>M: place multi-item order with attribution M-->>F: merchant order # F-->>B: { cart_status: "submitted", cart_id, urls, custom_properties } B->>C: Branded thank-you page with all items ``` ## Multi-item discovery in code For a curated landing page where the partner pre-selected the products, all SKUs are known at page load. Add them one after another — each add mutates the same cart, so serial calls keep cart state consistent: ```javascript // Page knows the SKUs from the curated landing config const skus = [ { add_to_cart_ref: { variant_id: 'hoodie-black-m' }, quantity: 1 }, { add_to_cart_ref: { variant_id: 'beanie-wool' }, quantity: 1 }, { add_to_cart_ref: { variant_id: 'socks-pack' }, quantity: 2 } ]; // Add each — sequential to ensure cart state is consistent let cart; for (const item of skus) { cart = await callFirmly(`/api/v2/domains/${DOMAIN}/cart/line-items`, item); } // Cart now has all items; render the branded cart drawer renderCartDrawer(cart); ``` For a related-product upsell on a single PDP, the buyer adds one product, then sees recommended products. Each Add is a separate `POST /cart/line-items` call, with the cart drawer updating after each. ## Cart Review in detail Before checkout, the buyer sees the full cart and can change it. Branded Commerce supports two surface modes: ### Mode A — Cart drawer / slide-in panel The branded page renders a cart panel that slides in from the side. Quantities can be incremented/decremented inline, items can be removed, promo codes can be applied. The panel listens for cart-update responses and re-renders. ```javascript // Read the current cart const cart = await callFirmly(`/cart`, null, 'GET'); renderCartDrawer(cart); // Buyer clicks "+1" on the hoodie line const hoodieLine = cart.line_items.find(li => li.line_item_id === 'li_hoodie'); const updated = await callFirmly( `/cart/line-items/${hoodieLine.line_item_id}`, { quantity: hoodieLine.quantity + 1 }, 'PUT' ); renderCartDrawer(updated); // Buyer clicks Remove on the socks const socksLine = updated.line_items.find(li => li.line_item_id === 'li_socks'); await callFirmly(`/cart/line-items/${socksLine.line_item_id}`, { quantity: 0 }, 'PUT'); ``` ### Mode B — Dedicated cart page The buyer navigates to a dedicated `/cart` page on the branded surface. Full quantity controls, line-item images, subtotal/tax/shipping/total breakdown, promo-code input, and the Checkout button. This is the more common pattern for Branded Commerce since the surface is a full website, not a chat or app. ## Common cart modifications | Operation | Endpoint | Body | |---|---|---| | Add a line item | `POST /cart/line-items` | `{ add_to_cart_ref, quantity }` | | Change quantity | `PUT /cart/line-items/:id` | `{ quantity: N }` | | Remove an item | `PUT /cart/line-items/:id` with `{ quantity: 0 }` (no per-item DELETE; `DELETE /cart/line-items` clears the whole cart) | `{ quantity: 0 }` | | Clear the entire cart | `DELETE /cart/line-items` | — | | Apply a promo code | `POST /cart/promo-codes` | `{ promo_codes: ["CODE1"] }` | | Remove all promo codes | `DELETE /cart/promo-codes` | — | ## Shipping in multi-product carts Shipping uses **one shipping address for the whole cart**, since all items come from one merchant. Shipping methods are chosen **per shipment**: a single-warehouse cart has exactly one shipment, so it looks like one cart-level choice. For items that physically ship separately (multi-shipment) — same merchant, different warehouses or fulfillment dates — Firmly groups them into multiple `shipment_id`s in the cart. Walk each one: ```javascript const cart = await callFirmly(`/cart/shipping-info`, address); for (const shipment of cart.shipments) { // Shipping methods are populated inline on each shipment after set-shipping-info. const cheapest = shipment.shipping_method_options .sort((a, b) => a.price.value - b.price.value)[0]; await callFirmly(`/cart/shipment/methods`, { shipment_id: shipment.shipment_id, shipping_method_id: cheapest.id }); } ``` See [Multi-Shipment](/api-reference/shipment-configuration/shipping-and-fulfillment) for the details. ## Express checkout shortcuts For multi-product carts, express checkout options apply to the **full cart**, not per-item: - **Click to Pay** (Visa/Mastercard) — one Click to Pay auth covers the whole cart - **PayPal** — one PayPal handoff for the whole cart total - **Google Pay** *(planned)* — one wallet confirmation for the whole cart This matches the live payment methods on the buyer-facing pages: card, Click to Pay, and PayPal are live, Google Pay is planned. As with single-product, the buyer sees one payment confirmation for everything. ## Race conditions to handle Multi-product flows are more exposed to mid-flow stock changes because there are more items and more time between discovery and checkout. ```javascript async function placeOrderWithRetry(cart) { try { // The cart was built over the previous calls, so finalize it with complete-order // (body = { encrypted_card, billing_info }); place-order would flush and rebuild it. return await callFirmly(`/payment/complete-order`, buildOrder(cart)); } catch (err) { // The envelope's `code` is the numeric HTTP status; the stable name is in `error`. if (err.error === 'NotEnoughStockError') { const updated = await callFirmly(`/cart`, null, 'GET'); // The cart's notices flag the affected line; map it back to its line item by id. const outOfStock = updated.notices?.find(n => n.code === 'ITEM_OUT_OF_STOCK'); const affectedLine = updated.line_items.find(li => li.line_item_id === outOfStock?.item_id); // Surface to the buyer on the branded checkout page showStockMessage(`${affectedLine?.sku} just went out of stock. Drop it or pick a different variant?`); // ... handle buyer choice } throw err; } } ``` See [Errors & Conventions → Recovery patterns](/api-reference/errors-and-conventions) for more. ## Attribution in multi-product carts The attribution model is identical to single-product — UTM, click IDs, and partner identifier pass through to the merchant's OMS on `complete-order`. The merchant sees one order with multiple line items, all tagged with the same attribution data. --- ## Related - [Single Product Purchase](/solutions/branded-commerce/flows/single-product-purchase) — the simpler shape - [Buyer Purchase Flow](/solutions/branded-commerce/flows/buyer-purchase-flow) — the ad → PDP → checkout → thank-you walkthrough from the buyer's point of view - [Why Firmly for Branded Commerce](/solutions/branded-commerce/why-firmly) — what makes Branded Commerce different - [Operations](/solutions/branded-commerce/operations/) — onboarding partners, dashboard, operational workflow --- # Multi-Product Purchase > **Note** > This is an **annotated flow** — it walks through the buyer experience alongside the API calls the marketplace operator's UI makes. The order of operations and API specifics are grounded in the underlying platform; the presentation is sequenced for developer readability. ## Scope A multi-product marketplace cart holds **several items from one source merchant** — one cart, one checkout, one merchant order. Buyers can discover products across many merchants (marketplace search spans the operator's whole merchant set), but a single cart is scoped to one source merchant, which remains the seller of record. The API sequence is the shared Firmly cart flow — identical to [Agentic Commerce → Multi-Product Purchase](/solutions/agentic-commerce/flows/multi-product-purchase). This page covers only the marketplace-specific framing; follow the Agentic page for the full cart-mutation, shipping, and race-condition detail. ## What's different from single-product Two things change from [Single Product](/solutions/marketplace/flows/single-product-purchase): 1. **Iterative discovery** — the buyer adds several items (all from the same source merchant) before checking out. 2. **Cart Review** — a step between discovery and checkout where the buyer adjusts quantities and removes items. Authentication, payment, and order metadata are unchanged. ## The phases | Phase | Single-Product | Multi-Product | |---|---|---| | 1. Hosting | Same | Same | | 2. Authentication | Same | Same | | 3. Discovery | One search | Iterative — buyer adds multiple items | | 3.5 Cart Review | — | New — buyer adjusts the cart | | 4. Checkout | One pass | One pass | | 5. Order placement | One merchant order | One merchant order | ## Adding multiple items Each add targets the same source merchant (the `{domain}` in the cart endpoint URL). Add items **one after another, not in parallel** — concurrent adds mutate the same cart and can race, leaving stale cart state; see the [race-condition retry pattern](/solutions/agentic-commerce/flows/multi-product-purchase) on the Agentic page. ```javascript // callFirmly: fetch wrapper adding x-firmly-authorization; see the Quickstart // `results` = the products[] returned by POST /api/v1/discovery/search. // Each result carries an opaque add_to_cart_ref — carry it straight through // rather than hand-building variant_ids. const adds = [ { ref: results[0].add_to_cart_ref, quantity: 1 }, { ref: results[1].add_to_cart_ref, quantity: 1 }, { ref: results[2].add_to_cart_ref, quantity: 2 } ]; let cart; for (const item of adds) { cart = await callFirmly( `/api/v2/domains/${merchantDomain}/cart/line-items`, { add_to_cart_ref: item.ref, quantity: item.quantity } ); } renderMarketplaceCart(cart); ``` ## Cart review, shipping, and modifications These are the shared cart mechanics — see [Agentic Commerce → Multi-Product Purchase](/solutions/agentic-commerce/flows/multi-product-purchase) for the cart-modification table, multi-shipment handling, and the race-condition retry pattern. The marketplace operator renders them inside its own branded cart UI. ## Attribution Marketplace operator ID flows on the order metadata exactly as in [Single Product](/solutions/marketplace/flows/single-product-purchase#attribution), so the source merchant's OMS records the operator as the traffic source. --- ## Related - [Single Product Purchase](/solutions/marketplace/flows/single-product-purchase) — the simpler shape - [Why Firmly](/solutions/marketplace/why-firmly) — what makes Marketplace different - [Integration Patterns](/solutions/marketplace/integration-patterns/) — operator hosting, embedded options --- # Multi-Product Purchase > **Note** > This is an **annotated flow** — the reader experience alongside the API calls the publisher's surface makes. ## Scope A multi-product Publisher Commerce cart holds **items from a single merchant** — a shoppable article with multiple Buy Now buttons (gift guide, product roundup), or a related-product upsell in the in-context checkout panel. The cart-mutation, shipping, and order-completion mechanics are the shared Firmly cart flow — because the cart is built across those calls, checkout finalizes with `complete-order`, not the one-shot `place-order`. See [Agentic Commerce → Multi-Product Purchase](/solutions/agentic-commerce/flows/multi-product-purchase) for the cart-modification table, multi-shipment handling, and the race-condition retry pattern. This page covers the Publisher-specific discovery and cart-review surfaces. ## What's different from single-product 1. **Multi-button discovery** — the article has multiple Buy Now buttons, each adding to the same cart; a persistent cart badge shows the running count. 2. **Cart Review** — an in-context cart panel (slide-in or inline overlay) with quantity controls and a Checkout CTA. ## Multi-button discovery in code For a shoppable article with multiple Buy Now buttons, each click is an independent `POST /cart/line-items` call: ```javascript // callFirmly: fetch wrapper adding x-firmly-authorization; see the Quickstart // DOMAIN: the merchant domain (e.g., staging.luma.gift) // User clicks Buy on the hoodie async function onBuyClick(productRef) { const cart = await callFirmly( `/api/v2/domains/${DOMAIN}/cart/line-items`, { add_to_cart_ref: productRef, quantity: 1 } ); // line_items.length is the count of distinct lines; sum quantities for a total-units badge updateCartBadge(cart.line_items.reduce((n, li) => n + li.quantity, 0)); } // Each button on the article wires up its own onBuyClick document.querySelectorAll('[data-buy-now]').forEach(btn => { btn.addEventListener('click', () => onBuyClick(JSON.parse(btn.dataset.buyNow))); }); ``` A persistent cart badge ("3 items in cart") tells the reader their adds are accumulating across Buy Now clicks within the same article. ## In-context cart panel The cart panel slides in from the side or appears as an inline overlay on the article — line items, quantity controls, remove buttons, subtotal, and a Checkout CTA: ```javascript // Paths below are relative to /api/v2/domains/{domain} const cart = await callFirmly(`/api/v2/domains/${DOMAIN}/cart`, null, 'GET'); renderCartPanel(cart); // Reader clicks -1 on the hoodie const hoodieLine = cart.line_items.find(li => li.line_item_id === 'li_hoodie'); const updated = await callFirmly( `/api/v2/domains/${DOMAIN}/cart/line-items/${hoodieLine.line_item_id}`, { quantity: hoodieLine.quantity - 1 }, 'PUT' ); renderCartPanel(updated); ``` The panel can also offer a "save for later" affordance for browsable shoppable articles where the reader doesn't want to check out right away. ## Express checkout In-context surfaces lean on express checkout to minimize time away from the article — Google Pay, PayPal Express, Klarna BNPL, or Click to Pay, each spanning the full cart rather than per-item. ## Attribution Identical to [Single Product](/solutions/publisher-commerce/flows/single-product-purchase#attribution--article-to-conversion) — UTM, publisher identifier, and article reference pass through on `complete-order`. The merchant sees one order with multiple line items; the publisher's analytics can credit each line item to the article that drove the click. --- ## Related - [Single Product Purchase](/solutions/publisher-commerce/flows/single-product-purchase) — the simpler shape - [Why Firmly](/solutions/publisher-commerce/why-firmly) — what makes Publisher Commerce different - [Integration Patterns](/solutions/publisher-commerce/integration-patterns/) — embed component vs separate landing options --- # Onboarding After signing up at `merchant.firmly.ai`, every new merchant walks through the same task sequence in the same order. The one variation is CDN whitelisting (Task 6): it's conditional — Firmly determines whether it applies and, when it doesn't, skips it automatically, so most merchants never see it. Otherwise **most tasks are self-service forms or toggles**; only CDN whitelisting involves any technical work. The merchant submits the tasks they own; Firmly handles two of them on its side; **KYB approval gates everything else.** ## The seven tasks | # | Task | Who does it | What it is | |---|---|---|---| | 1 | **Complete integration** | Firmly | Firmly's integration systems connect to the merchant's commerce backend — automated; merchant has no "Start" button | | 2 | **[Know Your Business (KYB)](/solutions/firmly-connect/onboarding/know-your-business)** | Merchant | Company information, brand identity, terms and privacy — submitted for Firmly review | | 3 | **[Configure product catalog](/solutions/firmly-connect/onboarding/catalog-configuration)** | Merchant | Pick Entire Catalog (recommended) or a curated subset | | 4 | **[Configure destinations](/solutions/firmly-connect/onboarding/destinations-configuration)** | Merchant | Opt into specific destinations on Firmly's network | | 5 | **[Sign merchant agreement](/solutions/firmly-connect/onboarding/agreement-signing)** | Merchant | Review and sign the participation agreement | | 6 | **[Complete CDN whitelisting](/solutions/firmly-connect/onboarding/cdn-whitelisting)** | Merchant | Whitelist Firmly's traffic at the merchant's CDN/WAF *(most merchants don't need it)* | | 7 | **Go-live approval** | Firmly | Firmly reviews the merchant's configuration and approves them to go live | ## How the gating works The wizard is linear by construction: - **KYB must be approved before any later step unlocks.** Tasks 3–6 (catalog, destinations, agreement, CDN) all show as `Pending KYB approval` and are not clickable while KYB is `pending` or `rejected`. This prevents a half-configured store from progressing while Firmly is still verifying who the merchant is. - **Go-live additionally requires integration complete.** Even after KYB approval, the go-live task stays blocked with `Pending integration completion` until Firmly has finished the merchant integration. - **Go-live itself is Firmly-approved.** Submitting for go-live moves the task into `Awaiting approval`; Firmly reviews the merchant's configuration and either approves (the merchant is live) or rejects (the merchant sees rejection notes inline and can re-address them). ## Sub-pages Each merchant-actioned task has its own page below: - [Know Your Business (KYB)](/solutions/firmly-connect/onboarding/know-your-business) — company info + brand identity + KYB submission - [Catalog configuration](/solutions/firmly-connect/onboarding/catalog-configuration) — entire catalog vs subset - [Destinations configuration](/solutions/firmly-connect/onboarding/destinations-configuration) — opt into channels - [Agreement signing](/solutions/firmly-connect/onboarding/agreement-signing) — review and sign - [CDN whitelisting](/solutions/firmly-connect/onboarding/cdn-whitelisting) — *(most merchants don't need it)* --- ## Related - [Firmly Connect overview](/solutions/firmly-connect/) - [Portal](/solutions/firmly-connect/portal/) — what happens after go-live - [For Merchants quickstart](/for-merchants/quickstart) — the merchant-facing journey doc --- # Operational Workflow > **Note** > This page is the operational rhythm for running Branded Commerce after onboarding. If you're earlier in the process, start with the [Branded Commerce overview](/solutions/branded-commerce/) or [Partner onboarding](/solutions/branded-commerce/operations/partner-onboarding). After [partner onboarding](/solutions/branded-commerce/operations/partner-onboarding) is complete (domain, branding, ad pixels, affiliate mode, merchant list), the partner moves into the **operational rhythm** — publishing products and launching campaigns. This page covers the per-product workflow. The same shape applies whether the partner is publishing a [single-product deal](/solutions/branded-commerce/use-cases/single-product-deal), a [curated landing page](/solutions/branded-commerce/use-cases/curated-landing-page), or a [retail-media placement](/solutions/branded-commerce/use-cases/retail-media-placement). Landing pages have a few extra steps for the page itself — see [Curated landing pages](#curated-landing-pages--additional-steps) below. > **Note** > **Per-product publishing is manual today.** Each step is handled through direct coordination between the partner and Firmly's ops team. The [Branded Commerce dashboard](/solutions/branded-commerce/operations/dashboard) is already live for operational reporting (funnel, orders, merchants) — self-service product submission is the next automation phase. ## The four phases Every product goes through the same four phases. Phases 1 and 2 alternate between the partner and Firmly; phase 3 is the joint review; phase 4 is what happens once the product is live. ## Phase 1 — Partner provides inputs ### Identify product Partner selects a product to promote from an agreed merchant. **Owner:** Partner — **Output:** Merchant product URL ### Provide affiliate link Partner provides the affiliate link for this product. In BYO mode, this is the partner's own affiliate-tagged URL from their network. **Owner:** Partner — **Output:** Affiliate URL ### Provide offer details Partner provides promo code, discount amount, and display copy **per product**. The coupon, discount value, and copy are saved alongside the product URL and affiliate link as part of the same product configuration. **Owner:** Partner — **Output:** Promo code + discount + copy per product ### Provide campaign metadata Partner provides campaign context: campaign name, ad platform, target launch date, any reporting keys needed for reconciliation. **Owner:** Partner — **Output:** Campaign metadata record ## Phase 2 — Firmly configures the product ### Resolve product Firmly resolves the merchant product URL to a product identifier, fetches live catalog data (title, price, variants, images, stock) via the platform adapter. **Owner:** Firmly — **Output:** Product resolved with live data ### Resolve affiliate link Firmly resolves the affiliate URL, identifies the network, extracts merchant ID and affiliate parameters. **Owner:** Firmly — **Output:** Affiliate configuration saved ### Configure offer Firmly configures promo-code auto-application, discount messaging on PDP and checkout, savings callout on the thank-you page. **Owner:** Firmly — **Output:** Offer mechanics configured ### Create partner-branded PDP Firmly creates the PDP on the partner's domain — product data rendered with partner theme, promo applied, merchant identity displayed per partner preference. **Owner:** Firmly — **Output:** Partner-branded PDP live on staging ### Generate launch URL Firmly generates the final URL the partner will use in their ad creative. Includes the product path and any promo/tracking parameters. **Owner:** Firmly — **Output:** Launch URL ready for ad creative ## Phase 3 — Review and launch ### Partner reviews on staging Branding, pricing, promo, discount messaging, merchant identity all reviewed on the staging hostname. **Owner:** Partner — **Output:** Approval or change requests ### Go live Firmly publishes the PDP to production; the launch URL becomes active. **Owner:** Firmly — **Output:** PDP live on production ### Partner creates ad Partner sets up ad creative on their ad platform (Meta, Google, retail-media network, etc.) using the launch URL as the destination. **Owner:** Partner — **Output:** Ad campaign live ## Phase 4 — Conversion signals at order completion (automatic) These fire automatically the moment the order is placed with the merchant. No manual step required — included for workflow completeness. | Signal | What happens | Owner | |---|---|---| | **Affiliate conversion** | Firmly fires the conversion to the affiliate network using the pre-configured affiliate data | Firmly (automatic) | | **Ad conversion** | Firmly fires the conversion event to the partner's ad platforms using the configured pixels and the click context captured at buyer entry | Firmly (automatic) | ## Curated landing pages — additional steps For [curated landing pages](/solutions/branded-commerce/use-cases/curated-landing-page), the per-product workflow above repeats for each product on the page. There are additional steps for the landing page itself: | Step | What happens | Owner | |---|---|---| | **Curate product list** | Partner selects products for the landing page and provides affiliate link + offer details per product. Products can span multiple merchants | Partner | | **Provide page design** | Partner provides landing-page design direction — hero image, page title, section layout, editorial copy | Partner | | **Build landing page** | Firmly builds the landing page with the partner theme, product grid with live pricing, links to individual PDPs | Firmly | | **Review and approve** | Partner reviews the landing page on staging | Partner | | **Go live** | Firmly publishes the landing page; the launch URL for the landing page is active | Firmly | | **Partner promotes** | Partner uses the landing-page URL in ads, email, social, direct links | Partner | ### Multi-merchant landing pages A landing page can feature products from **multiple merchants** side by side, each with live pricing from its own merchant, while checkout stays single-merchant per purchase. The mechanics and the single-merchant-checkout constraint are documented once on [Curated landing page → Multi-merchant landing pages](/solutions/branded-commerce/use-cases/curated-landing-page#multi-merchant-landing-pages); the per-product configuration steps above apply to each product on the grid. ## What comes next The per-product publishing workflow above is **manual coordination** between the partner and Firmly's ops team. The operational [dashboard](/solutions/branded-commerce/operations/dashboard) is already live for reporting; self-service publishing and a public API are the next automation phases: | Phase | What changes | |---|---| | **Next — Self-service product submission** | Partner submits product URLs and affiliate links through the dashboard. Firmly resolves and configures automatically. Partner reviews and approves in the dashboard | | **After — API** | Partner integrates programmatically — product submission, launch-URL generation, and campaign metadata sync. Enables bulk product publishing and CI/CD-style campaign management | The documentation here will be updated as each phase ships. --- ## Related - [Partner onboarding](/solutions/branded-commerce/operations/partner-onboarding) — must be complete before this workflow begins - [Operations overview](/solutions/branded-commerce/operations/) - [Single-product deal](/solutions/branded-commerce/use-cases/single-product-deal) — what the buyer sees after this workflow runs - [Curated landing page](/solutions/branded-commerce/use-cases/curated-landing-page) — landing-page variant of the workflow --- # Operations Operations covers the post-launch work — getting a working sandbox, handling errors and edge cases, and the production launch checklist. Most operational mechanics are shared across solutions; this section calls out Ad Commerce specifics. ## What's in operations - **[Sandbox Setup](/solutions/ad-commerce/operations/sandbox-setup)** — get a sandbox App ID paired with a test merchant; verify the ad creative + checkout flow end-to-end before pointing it at live ad traffic. ## Operational mechanics shared with all solutions Most operational concerns are universal across Firmly solutions. For these, see the canonical references: | Topic | Where to read | |---|---| | Authentication patterns | [Authentication](/for-destinations/authentication) | | Error catalog and retry behavior | [Errors & Conventions](/api-reference/errors-and-conventions) | | Idempotency window | [Errors & Conventions → Idempotency](/api-reference/errors-and-conventions#idempotency) | | Rate limits | [Rate Limits](/api-reference/rate-limits) | | Production launch process | [Going Live](/for-destinations/going-live) | ## Ad Commerce-specific operational concerns | Concern | Detail | |---|---| | **Ad platform postback reliability** | Fire conversion postback (Meta CAPI, Google Ads Conversion, TikTok Events) after `complete-order` succeeds. Retry on 5xx/timeouts with backoff; on a 4xx, log and alert (a retry won't succeed). These failures should not affect viewer experience but do affect the campaign's optimization model | | **Click-ID drift** | A click-ID from one ad campaign should not leak into another viewer's session. Use cart-session-scoped persistence, not global state | | **Inventory pre-checks for limited stock** | Ad campaigns can drive concurrent traffic spikes. If you're advertising a limited-stock SKU, surface "out of stock" in the creative if a pre-check fails — better than letting the viewer reach `complete-order` and getting `NotEnoughStockError` (409) | | **Creative inspection by ad platforms** | Some ad platforms inspect creative behavior. Make sure all Firmly API calls fire on viewer interaction, not on impression render | --- ## Related - [Single Product Purchase Flow](/solutions/ad-commerce/flows/single-product-purchase) - [For Destinations → Going Live](/for-destinations/going-live) — the production launch checklist - [Errors & Conventions](/api-reference/errors-and-conventions) — error catalog and retry patterns --- # Operations Once you've picked an integration pattern and looked at the flow, these pages cover the operational side of running a destination integration. - [Sandbox Setup](/solutions/agentic-commerce/operations/sandbox-setup) — Get credentials, pick a test merchant, run a first verified call - [Errors](/solutions/agentic-commerce/operations/errors) — Agentic-specific recovery patterns - [Going Live](/solutions/agentic-commerce/operations/going-live) — Pre-launch checklist for flipping sandbox to production --- # Operations A Branded Commerce engagement has two operational rhythms: - **One-time partner onboarding** — domain, branding, ad pixels, affiliate mode, merchant list. Done once when the partner first comes online. - **Per-product / per-campaign workflow** — the recurring rhythm: partner identifies a product or curates a landing page, Firmly resolves and configures, partner reviews on staging, then go-live. Partner onboarding and the per-product workflow are currently handled through **direct coordination between the partner's team and Firmly's ops team**. Once a partner is live, they access their own operational data through the [Branded Commerce dashboard](/solutions/branded-commerce/operations/dashboard) — funnel reports, orders, merchant performance, team management. Further automation (self-service product submission, public API) is a future phase — see [What comes next](#what-comes-next) below. - [Partner onboarding](/solutions/branded-commerce/operations/partner-onboarding) — The one-time setup — every step that must be complete before any product can be published. Domain, branding, ad pixels, affiliate mode, merchants, testing, performance tracking. - [Operational workflow](/solutions/branded-commerce/operations/operational-workflow) — The recurring rhythm — per-product configuration from partner input to ad launch. Four phases: partner provides inputs, Firmly configures, review and launch, conversion signals at order completion. - [Dashboard](/solutions/branded-commerce/operations/dashboard) — The logged-in operational surface — funnel reports, orders, merchant performance, team management, audit logs. ## What "operational" means here Branded Commerce operations are a partner-and-Firmly working relationship — both sides have specific responsibilities at each step, both have things to do, both have approval gates. The pages in this section document **who does what, when** — both partner-side and Firmly-side responsibilities are captured on the same page, so there's no ambiguity at each step. ## Sandbox Every Branded Commerce engagement gets a **staging environment** alongside production: | Environment | Hostname | Purpose | |---|---|---| | Production | `deals.partner.example` (or any partner subdomain) | Live buyer traffic | | UAT / Staging | `deals-staging.partner.example` | Pre-production testing — themes, new campaigns, smoke tests before launch | Staging is **not** retired after launch — it stays in place permanently for ongoing pre-production testing. Every new product or campaign is validated on staging first. The partner provides the staging CNAME during onboarding; Firmly enrolls it in Cloudflare for SaaS and provisions TLS just like production. ## Performance tracking Partners running paid ads need visibility into how their spend converts. Two dimensions are tracked: | # | Dimension | How it works | |---|---|---| | 1 | **Engagement funnel** | Firmly tracks sessions, buy-now clicks, and orders, with drop-off analysis and friction signals between steps. Surfaced through the [Branded Commerce dashboard](/solutions/branded-commerce/operations/dashboard) funnel report | | 2 | **ROAS / ad-platform conversion tracking** | Firmly fires ad-platform conversion events with preserved click IDs (`fbclid`, `gclid`, etc.). The channel mix is determined by which credentials the partner supplies per platform — see [Integration Patterns → Ad-platform pixel channels](/solutions/branded-commerce/integration-patterns/#ad-platform-pixel-channels) | ### One known limitation — "Visit Merchant" path When the buyer taps **VISIT [MERCHANT].COM** on the PDP and completes the purchase on the merchant's own website: | | Buy on Firmly | Visit Merchant | |---|---|---| | **Affiliate attribution** | Tracked | Tracked (affiliate redirect) | | **Ad ROAS** | Tracked (Firmly fires the pixel) | **Not tracked** — Firmly does not control the merchant's pages | This is a fundamental constraint — Firmly can only fire the partner's ad pixels on pages it hosts. Partners should be aware during onboarding that ROAS measurement covers Firmly-hosted conversions only. Affiliate commission is tracked regardless of path. ## What comes next Automation is arriving in three stages. The [Branded Commerce dashboard](/solutions/branded-commerce/operations/dashboard) (the Destination Dashboard scoped to Branded Commerce) has shipped — partners can already see funnel reports, orders, merchant performance, and audit logs. Onboarding and per-product publishing remain manual today; the next two stages automate them. | Stage | What changes | |---|---| | **Today — dashboard live** | Partners have a logged-in dashboard for funnel reports, orders, merchants, settings, team, audit logs. Onboarding and per-product publishing are direct coordination between partner and Firmly ops | | **Next — Self-service product submission** | Partner submits product URLs and affiliate links through the dashboard. Firmly resolves and configures automatically. Partner reviews and approves in the dashboard | | **After — API** | Partner integrates programmatically — product submission, launch-URL generation, campaign metadata sync. Enables bulk product publishing and CI/CD-style campaign management | The documentation here will be updated as each phase ships. --- ## Related - [Partner onboarding](/solutions/branded-commerce/operations/partner-onboarding) — one-time setup - [Operational workflow](/solutions/branded-commerce/operations/operational-workflow) — ongoing per-product rhythm - [Integration Patterns](/solutions/branded-commerce/integration-patterns/) — the technical setup - [Why Firmly](/solutions/branded-commerce/why-firmly) — ownership boundary --- # Operations Operations covers the post-launch work — getting a working sandbox, handling errors and edge cases, and the production launch checklist. Most operational mechanics are shared across solutions; this section calls out the Marketplace specifics. ## What's in operations - **[Sandbox Setup](/solutions/marketplace/operations/sandbox-setup)** — get a sandbox App ID paired with a few test merchants; verify discovery across merchants and a single-merchant checkout end-to-end. ## Operational mechanics shared with all solutions Most operational concerns are universal across Firmly solutions: | Topic | Where to read | |---|---| | Authentication patterns | [Authentication](/for-destinations/authentication) | | Error catalog and retry behavior | [Errors & Conventions](/api-reference/errors-and-conventions) | | Idempotency window | [Errors & Conventions → Idempotency](/api-reference/errors-and-conventions#idempotency) | | Rate limits | [Rate Limits](/api-reference/rate-limits) | | Production launch process | [Going Live](/for-destinations/going-live) | ## Marketplace-specific operational concerns | Concern | Detail | |---|---| | **Multi-merchant sandbox setup** | Marketplace testing benefits from a sandbox App ID paired with several test merchants, so search-across-merchants (discovery) can be exercised. Ask Firmly to provision a few diverse test merchants | | **Merchant enablement and curation** | The operator decides which merchants appear in marketplace search. Keep an internal process for enabling, ordering, and removing merchants | | **Discovery latency across merchants** | Search spans many merchants; design the results UI to tolerate variable response times as the catalog grows | | **Operator-level reconciliation** | Marketplace orders carry the operator identifier in metadata. The operator's reconciliation system should match orders by operator ID across merchant order management systems | --- ## Related - [Single Product Purchase Flow](/solutions/marketplace/flows/single-product-purchase) - [Multi-Product Purchase Flow](/solutions/marketplace/flows/multi-product-purchase) — multiple items from one merchant - [For Destinations → Going Live](/for-destinations/going-live) — the production launch checklist - [Errors & Conventions](/api-reference/errors-and-conventions) — error catalog and retry patterns --- # Operations Operations covers the post-launch work — getting a working sandbox, integrating with the publisher's CMS, and the production launch checklist. Most operational mechanics are shared across solutions; this section calls out Publisher Commerce specifics around affiliate attribution and CMS embed maintenance. ## What's in operations - **[Sandbox Setup](/solutions/publisher-commerce/operations/sandbox-setup)** — get a sandbox App ID paired with test merchants; verify the article embed + checkout flow end-to-end. ## Operational mechanics shared with all solutions Most operational concerns are universal across Firmly solutions: | Topic | Where to read | |---|---| | Authentication patterns | [Authentication](/for-destinations/authentication) | | Error catalog and retry behavior | [Errors & Conventions](/api-reference/errors-and-conventions) | | Idempotency window | [Errors & Conventions → Idempotency](/api-reference/errors-and-conventions#idempotency) | | Rate limits | [Rate Limits](/api-reference/rate-limits) | | Production launch process | [Going Live](/for-destinations/going-live) | ## Publisher Commerce-specific operational concerns | Concern | Detail | |---|---| | **Affiliate attribution accuracy** | Order metadata must carry the publisher identifier and article identifier on every order. Reconcile against the publisher's own affiliate tracking weekly to confirm conversion attribution matches | | **CMS embed maintenance** | When the Buy Now embed format changes (e.g., new SKU format), publishers must roll the change across all CMS embeds. Plan a CMS migration when versioning the embed | | **Article-driven traffic spikes** | A popular article can produce concurrent traffic spikes against a single merchant. Coordinate with Firmly on rate-limit posture for high-traffic launches | | **Stale product references** | Articles live for years; products go out of stock or change SKUs. Plan a periodic sweep to detect Buy Now buttons pointing at stale products and either refresh or remove | | **Editorial / commercial separation** | Some publishers maintain editorial-commercial boundaries — articles that are sponsored vs. organically curated should be distinguished in attribution metadata if the publisher tracks this in analytics | --- ## Related - [Single Product Purchase Flow](/solutions/publisher-commerce/flows/single-product-purchase) - [Multi-Product Purchase Flow](/solutions/publisher-commerce/flows/multi-product-purchase) - [For Destinations → Going Live](/for-destinations/going-live) — the production launch checklist - [Errors & Conventions](/api-reference/errors-and-conventions) — error catalog and retry patterns --- # Operator-Hosted The marketplace is a standalone product running on the operator's own domain. The operator builds the full shopping UI — homepage, search, product detail, cart, checkout, order history — using Firmly's APIs for the underlying commerce work. ## When this fits This pattern fits when: - The marketplace is the primary product - The operator wants full brand control - Buyers search across many merchants in one surface — discovery spans the operator's merchant set - The operator wants to own the full checkout UX If the marketplace is instead one feature inside a larger product, use [Embedded Marketplace](/solutions/marketplace/integration-patterns/embedded-marketplace). ## What the operator owns | Layer | Owner | |---|---| | Marketplace domain and infrastructure | Operator | | Full UI — homepage, search, PDP, cart, checkout, account, order history | Operator | | Merchant catalog presentation (filters, sort, listings) | Operator | | Cart and checkout UI | Operator | | Checkout flow design | Operator (typically; can use Firmly's [hosted checkout](/solutions/agentic-commerce/integration-patterns/hosted-checkout) instead) | | Auth and session management | Operator (using Firmly browser-session or S2S underneath) | | Cart / order orchestration | Firmly APIs | | Payment + order placement | Firmly APIs | ## Discovery spans merchants; checkout is single-merchant Marketplace search returns products across the operator's whole merchant set, so the operator's UI typically shows merchant identity alongside each listing. Each cart, however, is scoped to one source merchant — build the cart and checkout UI around a single-merchant cart per the [Single Product](/solutions/marketplace/flows/single-product-purchase) and [Multi-Product](/solutions/marketplace/flows/multi-product-purchase) flows. --- ## Related - [Branded Marketplace use case](/solutions/marketplace/use-cases/branded-marketplace) - [Single Product Purchase Flow](/solutions/marketplace/flows/single-product-purchase) - [Multi-Product Purchase Flow](/solutions/marketplace/flows/multi-product-purchase) - [Embedded Marketplace](/solutions/marketplace/integration-patterns/embedded-marketplace) — the alternative pattern --- # Partner Onboarding The one-time setup that must be complete before any product can be published on Branded Commerce. This is the partner-and-Firmly checklist for the first day of an engagement. > **Note** > **Today, this is manual.** Every step below is handled through direct coordination between the partner's team and Firmly's ops team. A self-service onboarding flow is a future phase. ## Onboarding steps | Step | What happens | Owner | Output | |---|---|---|---| | **Domain setup** | Partner adds two DNS CNAME records — production hostname and staging hostname — to the CNAME targets Firmly provides. Each must be DNS-only (grey-cloud) if the partner's DNS is on Cloudflare. Firmly enrolls each hostname in its matching Cloudflare zone and provisions TLS via Cloudflare for SaaS | Partner (DNS) / Firmly (TLS) | Both partner domains resolve with active TLS | | **Branding** | Partner provides brand assets and copy preferences (see [Branding intake](#branding-intake) below). Firmly applies theming to all page templates | Partner (assets) / Firmly (theming) | Partner theme configured and ready to render every page | | **Language and locale** | Partner specifies market(s) and language(s) the pages render in (see [Language and locale](#language-and-locale) below) | Partner (requirements) / Firmly (config) | Locale configuration set | | **Ad-platform pixel setup** | Partner provides per-platform credentials for every ad platform they run campaigns on. What the partner provides determines the channel mix per platform — see [Ad-platform credentials](#ad-platform-credentials) below | Partner (credentials) / Firmly (config) | Per-platform conversion-signal configuration | | **Affiliate mode** | Partner and Firmly agree on **BYO** (partner's own affiliate network credentials) or **Firmly-managed** attribution | Both | Affiliate attribution mode configured | | **Merchant list** | Partner and Firmly align on which merchants to support. Firmly checks onboarding status — onboards new merchants as needed | Both | Approved merchant list with onboarding status | | **Testing** | End-to-end flow validation on the staging domain — at least one full order placed | Both | Staging environment verified | | **Performance tracking** | Agree on tracking requirements — see the [Operations overview](/solutions/branded-commerce/operations/#performance-tracking) | Both | Tracking configuration documented | ## Domain setup detail Two CNAME records, one per environment: | Environment | Partner hostname | CNAME points to | |---|---|---| | Production | `deals.partner.example` (or any partner subdomain) | `firmly.live` | | UAT / staging | `deals-staging.partner.example` | `firmlyuat.com` | Both are independent enrollments — there is no "promote staging to production" path; they coexist permanently. Staging stays in place after launch for ongoing pre-production testing of new campaigns and theme changes. If the partner's DNS lives on Cloudflare, both CNAMEs must be set to DNS-only (grey-cloud icon). Cloudflare-on-Cloudflare orange-cloud routing breaks TLS provisioning. ## Branding intake The partner provides brand assets, copy preferences, and legal text. Firmly builds a theme and applies it to every page template (Landing page, PDP, Checkout, Thank-you). ### What the partner provides | Category | What's needed | Example | |---|---|---| | **Brand assets** | Logo files (light + dark, SVG preferred), favicon (32×32), hero imagery for landing pages | Partner primary logo + dark variant | | **Typography** | Primary font family, weight scale, licensing terms, optional display font | Inter 400/600/700, Google Fonts–hosted | | **Palette** | Primary, secondary/accent, text, background/surface, border, state colors | Primary `#6a1b9a`, background `#fafafa` | | **Button treatment** | Corner radius, fill style, hover state, CTA label case | 6 px radius, solid fill, uppercase labels | | **Chrome** | Header logo placement, header density, back-arrow style, footer links | Logo left, compact header, chevron back arrow | | **Copy preferences** | Brand voice, promo language template, CTA verb, savings callout phrasing, merchant identity line | *"BUY NOW"*, *"You saved {amount} with {partner}!"* | | **Legal copy** | T&C URL, privacy policy URL, per-surface disclaimers, jurisdiction/market | US market, T&C at `partner.example/terms` | | **Merchant identity** | Prominent vs subtle display per merchant; show merchant domain or not | *"Shopping with [Merchant]"* in header vs footer-only | ### How the handoff works | # | Step | Owner | |---|---|---| | 1 | **Intake** — Firmly sends the branding questionnaire to the partner's design/brand contact | Firmly | | 2 | **Partner completes** — provides assets, answers copy/layout questions, supplies legal URLs | Partner | | 3 | **Theme build** — Firmly builds the theme object and applies it to all page templates | Firmly | | 4 | **Staging review** — Firmly deploys themed pages to the staging domain; partner reviews branding on Landing page, PDP, Checkout, Thank-you | Both | | 5 | **Feedback and iteration** — partner flags branding issues; Firmly adjusts the theme | Both | | 6 | **Sign-off** — partner's design/brand contact approves the theme for production | Partner | ### Per-property theming Some partners operate multiple brand properties (e.g., several deal sites under one parent). Each property may have its own logo, palette, and copy voice. The theme is configurable per property — one onboarding produces multiple theme variants, not one. ## Ad-platform credentials Per ad platform the partner runs campaigns on, channel mix is determined by **which credentials the partner supplies**: | Provided | Channel mix | |---|---| | Pixel ID / dataset ID only | Client-side pixel only | | Pixel ID + account ID + access token | Dual-fire — client-side pixel + server-side CAPI with `event_id` dedup | Recommended: provide both. Server-side fires cover conversions the client-side pixel misses due to ad blockers. The `event_id` deduplication ensures one conversion event per order, not two. Supported platforms: Meta (CAPI), Google Ads (Enhanced Conversions), TikTok, Pinterest, Snap, Reddit. The partner provides credentials per platform — Firmly does not share credentials across platforms. ## Language and locale Pages contain content from multiple sources; each has its own language concern: | Content source | Language determined by | |---|---| | **Product data** (title, description, images) | The merchant — fetched from the merchant's catalog in whatever language the merchant serves | | **Partner branding copy** (CTA verbs, promo messaging, savings callout) | The partner — provided during onboarding as copy preferences | | **Checkout labels** (form fields, error messages, payment method names) | Firmly — rendered by the Drop-in Checkout component | | **Legal copy** (T&C, privacy policy, disclaimers) | The partner — provided as URLs and inline text during onboarding | If the partner operates in a non-English market where the merchant catalog returns English data, the result is mixed-language pages. Confirm the merchant catalog language during onboarding before going live in non-English markets. ## Attribution metadata fields When an order is placed, Branded Commerce carries attribution data from the branded page through to the merchant's OMS so the merchant's own reporting can reconcile partner-driven orders. Three categories flow through: | Category | What it carries | Source | |---|---|---| | **UTM params** | `utm_source`, `utm_campaign`, `utm_content` | Captured from the ad-click URL on the branded page and set on the cart session | | **Ad-click IDs** | `fbclid`, `gclid`, `ttclid`, and other platform click identifiers | Captured from the ad-click URL; used for the ad platform's conversion postback | | **Partner identifier** | Identifies which partner surface drove the order | Derived from the partner's configuration; set automatically on the cart session | > **Note** > The exact metadata field names the merchant's OMS reads for each category are configured per merchant during onboarding — the mapping depends on the merchant's platform and is confirmed during the merchant-list step. Coordinate the concrete field mapping with your Firmly contact before go-live. ## Pre-launch checklist Sign off on every item below before publishing the first product: - [ ] Production CNAME resolves; TLS valid on the partner hostname - [ ] Staging CNAME resolves; TLS valid; staging tested end-to-end - [ ] Theme reviewed and approved on staging (Landing page, PDP, Checkout, Thank-you) - [ ] Affiliate mode chosen (BYO or Firmly-managed) + credentials configured - [ ] Per-platform ad pixels configured (dual-fire preferred where possible) - [ ] Merchant list agreed + onboarding status confirmed for each merchant - [ ] At least one test order placed on staging end-to-end - [ ] Legal copy (T&C, privacy, disclaimers) approved and live --- ## Related - [Operations overview](/solutions/branded-commerce/operations/) - [Operational workflow](/solutions/branded-commerce/operations/operational-workflow) — the per-product / per-campaign rhythm after onboarding is complete - [Integration Patterns](/solutions/branded-commerce/integration-patterns/) — the technical setup - [Why Firmly](/solutions/branded-commerce/why-firmly) --- # Portal Once a merchant is live, the Merchant Portal is where they run their store on Firmly's network day-to-day. It's the same surface that hosted the Onboarding Wizard — the page flips from the Onboarding Wizard task menu to the post-onboarding Merchant Portal home. ## What's in the portal - [Merchant home](/solutions/firmly-connect/portal/merchant-home) — KPIs across the top (revenue, AOV, active destinations), with deeper breakdowns below. - [Audit logs](/solutions/firmly-connect/portal/audit-logs) — Append-only record of every team action and configuration change. Compliance and "who turned this on?" answers. - [Team management](/solutions/firmly-connect/portal/team-management) — Invite teammates, change roles, remove members, transfer ownership. Roles: Primary Owner, Owner, Editor, Viewer. - [Domains and SSO](/solutions/firmly-connect/portal/domains-and-sso) — Register domains, verify with DNS TXT, enforce SSO per-domain, configure Identity Providers (OIDC, SAML). - [UCP configuration](/solutions/firmly-connect/portal/ucp-configuration) — Forward the merchant's `/.well-known/ucp` endpoint to Firmly. Per-platform setup guides plus a verification probe. ## How the portal is organized | Area | What lives there | |---|---| | **Home** | KPIs and breakdowns — the at-a-glance read | | **Orders** | Order list + detail (read-only — order edits happen in the merchant's commerce backend) | | **Catalog** | Catalog scope configuration + read-only product list | | **Destinations** | Per-destination toggles + performance breakdown | | **Audit Logs** | Append-only event feed *(role-gated — Owner / Primary Owner / Firmly admin only)* | | **Settings** | KYB / company info, brand identity, domains, SSO, CDN, UCP, agreement, notifications | | **Team** | Team management | | **Profile** | User-level profile and sessions (not merchant-scoped) | ## Two states on the merchant home The merchant home surface has **two states on the same page**: - **Onboarding in progress** — renders the [Onboarding Wizard](/solutions/firmly-connect/onboarding/) task menu - **Live** — renders the dashboard with KPIs and breakdowns The page switches to the live dashboard automatically once onboarding is complete and Firmly has approved go-live. ## Role-based access | Role | Can do | |---|---| | **Primary Owner** | Everything, plus ownership transfer (exactly one Primary Owner per merchant) | | **Owner** | Everything except ownership transfer | | **Editor** | Edit settings and operational data, except the owner-only areas below | | **Viewer** | Read-only | Some features — **audit logs, SSO configuration, ownership transfer, and the custom adapter editor** — are restricted to Owner / Primary Owner / Firmly admin only; Editors are excluded from these. The custom adapter editor lives under Settings for merchants on a custom stack (see [Credentials & API Access → Custom adapter merchants](/for-merchants/credentials-and-api-access#custom-adapter-merchants)). --- ## Related - [Firmly Connect overview](/solutions/firmly-connect/) - [Onboarding Wizard](/solutions/firmly-connect/onboarding/) — what happens before the merchant goes live - [For Merchants](/for-merchants/) — the merchant-facing journey doc --- # Post-Click Landing The ad creative click routes the viewer to a dedicated landing — a full page outside the ad surface — where the product detail, address, payment, and confirmation render. Used when in-feed checkout is not supported or when the post-click experience benefits from a richer presentation. ## When this fits | Condition | Does this pattern fit? | |---|---| | Static display ad, audio ad, connected-TV ad | ✅ Yes — these don't support in-feed checkout | | Ad creative footprint is too small for full checkout | ✅ Yes | | Product needs richer presentation (image gallery, video, configurator) | ✅ Yes | | In-feed conversion priority over richer presentation | ❌ Use [In-Ad Checkout](/solutions/ad-commerce/integration-patterns/in-ad-checkout) instead | ## How the click-through flows | Stage | What happens | |---|---| | **Impression** | Ad renders in the ad surface (display network, video player, audio ad) | | **Click** | Viewer clicks the ad → ad platform redirects to the landing URL with click-ID and UTM params appended | | **Landing renders** | Landing page captures click-ID + UTM, renders product detail, starts a Firmly browser session | | **Checkout** | Viewer fills address + payment on the landing | | **Order placement** | `POST /payment/complete-order` (finalizes the cart built on the landing) with click-ID + UTM in order metadata | | **Postback** | Landing fires the conversion postback to the ad platform | ## Real-estate advantages Unlike in-ad checkout, the landing has the full screen. Design choices: - **Multi-step flow** — product detail → address → payment can be separate sections or pages - **Richer payment menu** — card, PayPal Express, Klarna BNPL, Google Pay all shown - **Trust signals** — reviews, trust badges, return policy can fit on the page - **Cross-sell** — related products can be offered before checkout completes ## What the destination owns | Layer | Owner | |---|---| | Landing page (HTML/JS or a Firmly-hosted template) | Destination — or partner running the landing | | Click-ID + UTM capture and persistence | Destination | | Checkout UI | Destination (or Firmly's [hosted checkout](/solutions/agentic-commerce/integration-patterns/hosted-checkout) if preferred) | | Cart / order orchestration | Firmly APIs | | Payment + order placement | Firmly APIs | | Conversion postback | Destination (after order success) | ## Constraints to plan for - **Click-ID persistence.** If the viewer takes a few minutes on the landing before checking out, the click-ID must persist across page navigations. Store it in the cart session or in client-side state. - **Mobile-first.** Most ad clicks come from mobile. Optimize landing for fast load, one-thumb completion, wallet payment options. - **A/B testing.** Landing pages benefit from variant testing. Plan for at least two layouts and a way to attribute conversion rate per variant. - **Drop-off recovery.** Some viewers will abandon. Plan email capture or retargeting tags so subsequent campaigns can follow up. --- ## Related - [Post-Click Purchase use case](/solutions/ad-commerce/use-cases/post-click-purchase) - [Single Product Purchase Flow](/solutions/ad-commerce/flows/single-product-purchase) - [In-Ad Checkout](/solutions/ad-commerce/integration-patterns/in-ad-checkout) — the alternative pattern --- # Post-Click Purchase A viewer clicks a display ad, video ad, or audio ad (e.g., a spoken URL or QR prompt) and lands on a dedicated page where the product detail, address, and payment all live. The landing is purpose-built for conversion — single-product or curated-bundle, with the click-ID carried through so the ad platform credits the conversion correctly. This pattern fits when the ad surface does not support in-feed checkout — many display networks, video platforms, and connected-TV surfaces fall in this category. The landing is owned by the advertiser, the ad platform, or a partner running the post-click experience. ## Recommended setup | Choice | Default | Why | |---|---|---| | **Integration pattern** | [Post-Click Landing](/solutions/ad-commerce/integration-patterns/post-click-landing) | The viewer expects a full landing experience after clicking through | | **Auth** | [Browser session](/api-reference/authentication/browser-session) | The landing renders per viewer | | **Payment** | Card via JWE, PayPal Express, Klarna BNPL | Landing has full screen for richer payment options | | **Attribution** | Click-ID + UTM params | Carried in the landing URL; persisted in the cart session | ## API sequence The flow follows the [Single Product Purchase](/solutions/ad-commerce/flows/single-product-purchase) shape. The landing URL encodes the SKU; the page resolves it on load. | Step | Endpoint | |---|---| | 1. Capture click-ID and UTM from landing URL | Client-side | | 2. Bootstrap session | [`POST /api/v1/browser-session`](/api-reference/authentication/browser-session) | | 3. Render product detail | (Optional) [`GET /domains-products/{domain}/{handle}`](/api-reference/catalog/get-product) | | 4. Add to cart | [`POST /cart/line-items`](/api-reference/cart-management/add-line-item) | | 5. Set shipping address | [`POST /cart/shipping-info`](/api-reference/checkout/set-shipping-info) | | 6. Pick shipping method (from `cart.shipments[].shipping_method_options`) | [`POST /cart/shipment/methods`](/api-reference/shipment-configuration/set-shipping-method) | | 7. (Optional) Get delivery availability | [`POST /cart/shipments/get-availability`](/api-reference/shipment-configuration/get-availability) | | 8. (If required) Get + set merchant consents | [`GET /cart/consents`](/api-reference/checkout/get-consents) → [`PUT /cart/consents`](/api-reference/checkout/set-consents) | | 9. Get payment public key | [`GET /payment/key`](/api-reference/payment/get-public-key) | | 10. Complete order | [`POST /payment/complete-order`](/api-reference/payment/complete-order-v2) | | 11. Fire ad-platform postback | Per-platform conversion API | Steps 4–9 build the cart, so step 10 finalizes that existing cart with [`complete-order`](/api-reference/payment/complete-order-v2) (body: `encrypted_card` + `billing_info`). Use [`place-order`](/api-reference/payment/place-order-v2) only for the one-shot path that creates the cart and places the order in a single call. ## Considerations the landing owns - **Persist click-ID in the cart session.** If the viewer navigates around the landing before checking out, the click-ID must persist so the eventual order metadata still carries it. - **One landing template, many campaigns.** Reuse the same landing template across campaigns; vary it through URL parameters (SKU, UTM content) rather than spinning up new landings per creative. - **Mobile-first.** Most ad clicks come from mobile. Optimize the landing for one-thumb completion: short address forms, wallet payment options surfaced first. - **Drop-off recovery.** Some viewers will abandon mid-checkout. Consider whether the landing offers email capture or retargeting tags to enable follow-up campaigns. --- ## Related - [Single Product Purchase Flow](/solutions/ad-commerce/flows/single-product-purchase) — full API walkthrough - [Post-Click Landing pattern](/solutions/ad-commerce/integration-patterns/post-click-landing) — UI hosting choice - [In-Feed Shoppable Ad](/solutions/ad-commerce/use-cases/in-feed-shoppable-ad) — the alternative use case --- # Protocols Firmly's underlying API is the same regardless of who's calling it — but **how an AI surface communicates with Firmly** varies by ecosystem. Different AI platforms have adopted different open standards for agent-driven commerce, and Firmly speaks all of them. This page covers what Firmly supports and how to pick. ## The protocols Firmly supports | Protocol | Owner / Spec | Best for | |---|---|---| | **UCP** — Universal Commerce Protocol | Google (open standard) | AI search surfaces that adopted UCP | | **MCP** — Model Context Protocol | Anthropic (open standard) | Any agent built on the MCP standard; works with any LLM or agent framework | | **ACP** — Agentic Commerce Protocol | OpenAI (separate spec) | OpenAI commerce surfaces | | **Direct REST** | — | Custom agents / backend integrations / when no protocol bridge fits | All of them ultimately call the same Firmly cart + checkout APIs underneath — what differs is **session management, transport, and who controls the checkout UI.** ## Picking a protocol | Your agent runs on... | Use | |---|---| | An AI search surface using UCP | **UCP** | | Any agent built on the Model Context Protocol standard | **MCP** | | An OpenAI commerce surface | **ACP** | | A custom backend or runtime | **Direct REST API** | If you're building a custom agent and want maximum control, use the **Direct REST API** path documented in [API Reference](/api-reference/). If you're integrating into an existing AI platform, use the platform's protocol. ## Protocol comparison | Aspect | UCP | MCP | |---|---|---| | **Spec owner** | Google (open) | Anthropic (open) | | **Session model** | Multi-step checkout session | Tool-use calls | | **Checkout UI** | Surface-native | Agent-controlled; widget for MCP-Apps-compatible hosts | | **Transport** | HTTPS REST | SSE / HTTP (MCP-Apps hosts) | | **Discovery layer** | Surface's own product index | Firmly's discovery tools | > **Note** > ACP (OpenAI's Agentic Commerce Protocol) is a separate spec; like UCP-style surfaces, ACP surfaces handle discovery on their own platform. Firmly's ACP bridge documentation is in progress — [contact Firmly](/contact) for current status. ## What's shared across all protocols The protocol layer is a **translation layer** — it converts platform-specific requests into Firmly's cart and checkout operations. Underneath, Firmly does the same things regardless of which protocol called it: - Cart orchestration - Payment processing - Tax + shipping orchestration (using the merchant's rules) - Order placement to the merchant's platform - Affiliate attribution This is why a merchant onboarded on Firmly is **automatically reachable through every supported protocol** without any per-protocol work on the merchant side. ## How protocols map to the purchase flow | Phase | UCP | MCP | |---|---|---| | **Discovery** | The surface's own product index | Firmly discovery tools | | **Cart creation** | UCP session API | MCP cart tools | | **Shipping & promo** | UCP session updates | MCP shipping + promo tools | | **Payment + order** | UCP complete-session | MCP payment tool | ## The architectural insight UCP and ACP-style surfaces handle discovery on their own platforms (their product indices). MCP relies on Firmly's discovery tools because it's a general-purpose agent protocol without a built-in product index. For checkout, all protocols ultimately call the same Firmly cart and payment APIs. The protocol wrapper translates the request format; the underlying cart orchestration and order placement logic is shared. ## Implications for your build If you're choosing between protocols, three questions matter most: 1. **Does my agent ALREADY use one of these protocols?** If yes, use it. The platform-native path is always cheaper than going custom. 2. **Do I need to control the checkout UI?** UCP gives Google's surface control of UI; MCP gives your agent control; Direct REST gives you full UI control. 3. **What's my discovery story?** UCP and ACP-style surfaces use their own product index; MCP uses Firmly's discovery tools; Direct REST is whatever you build. ## UCP — deep-dive UCP has the deepest Firmly integration of the three protocols. See the [UCP sub-pages](/solutions/agentic-commerce/protocols/ucp/) for: - [UCP overview](/solutions/agentic-commerce/protocols/ucp/) — what UCP is and why Firmly implements it - [Checkout flow](/solutions/agentic-commerce/protocols/ucp/checkout-flow) — the three-step session lifecycle - [Implementation](/solutions/agentic-commerce/protocols/ucp/implementation) — service architecture, API mapping, well-known manifest - [Security](/solutions/agentic-commerce/protocols/ucp/security) — request authentication, signature verification, rate limiting - [Merchant onboarding](/solutions/agentic-commerce/protocols/ucp/merchant-onboarding) — Google Merchant Center setup - [Roadmap](/solutions/agentic-commerce/protocols/ucp/roadmap) — phased implementation status - [Firmly Card handler](/solutions/agentic-commerce/protocols/ucp/firmly-card-handler) — proposed encrypted card handler --- ## Related - [How Firmly works](/how-firmly-works) — the platform under all protocols - [Cart lifecycle](/api-reference/cart-management/cart-lifecycle) — the state machine your protocol calls drive - [Agentic Commerce overview](/solutions/agentic-commerce/) — solution-level guidance for agent integrations - [Integration patterns](/solutions/agentic-commerce/integration-patterns/) — Hosted vs Embedded vs Headless (independent of protocol) --- # Publisher Commerce > **Note** > **What's in this section:** Use Cases (which scenario you're building), Flows (the API sequence in detail), Integration Patterns (embedded buy-button vs dedicated landing), and Operations (sandbox setup and operational guidance). ## What this solution enables Publisher Commerce lets editorial publications — recommendation sites, comparison guides, content publishers — sell inside their articles: the reader buys in place, without clicking out to a merchant site. ![How Publisher Commerce fits — the editorial surface hosts checkout inside the article, Firmly runs the commerce backend, and the merchant stays the seller of record](/images/publisher-commerce/how-publisher-commerce-fits.svg) ## How Publisher Commerce fits within Firmly The Firmly platform is shared across all solutions — the cart, discovery, payment, tax, shipping, and order-placement APIs are the same. Publisher Commerce packages those shared features for one kind of destination: editorial and content surfaces that sell inside their articles. Publisher Commerce sections follow the same structure as Agentic Commerce; see [Agentic Commerce](/solutions/agentic-commerce/) for the fully worked end-to-end example. ## What's documented - [Why Firmly for Publisher Commerce](/solutions/publisher-commerce/why-firmly) — Positioning, scope, and what's specific to Publisher Commerce versus the shared platform. - [Use Cases](/solutions/publisher-commerce/use-cases/) — The feature menu — what destinations and merchants can use. - [Flows](/solutions/publisher-commerce/flows/single-product-purchase) — End-to-end user flows annotated with the canonical API sequence. - [Integration Patterns](/solutions/publisher-commerce/integration-patterns/) — Embedded buy button or dedicated landing — pick the surface that fits. - [Operations](/solutions/publisher-commerce/operations/) — Sandbox setup and operational guidance. --- ## Related - [Solutions overview](/solutions/) — all Firmly solutions - [Destinations](/solutions/destination-surfaces/) — which destination types use which solution - [How Firmly Works](/how-firmly-works) — the underlying platform - [API Reference](/api-reference/) — every endpoint --- # Publisher sites Publisher sites are content-first companies — editorial media, deal and coupon sites, reviews, buying guides, and vertical communities — whose primary business is generating audience attention through content and monetizing that attention. As a commerce destination, publisher sites are the highest-intent category: users arrive via a deal roundup, a product review, an editorial pick, or a buying guide, and they are typically much closer to purchase than users from organic search or generic social feeds. Firmly is the commerce backend; the publisher owns the editorial voice and reader relationship. ## The commerce challenge - Affiliate economics are leaky — readers click out, merchants drop the cookie or de-attribute, and conversions go unreported - Recommendation articles produce intent; capturing the transaction inside the publisher's surface lifts conversion meaningfully - Building checkout inside an editorial CMS is engineering work in a category where editorial revenue and engineering capacity are both squeezed - Per-merchant deals don't scale — your editorial covers categories across hundreds of brands ## Which Firmly solutions apply **Publisher Commerce** as the anchor; **Agentic Commerce** for the AI-driven editorial agent layer. ## Recommended integration | Choice | Default | Why | |---|---|---| | **Auth** | [Browser session](/api-reference/authentication/browser-session) per reader | Each article session creates a transactional session | | **Integration pattern** | [Hosted checkout](/solutions/agentic-commerce/integration-patterns/hosted-checkout) or [Embedded checkout](/solutions/agentic-commerce/integration-patterns/embedded-checkout) | Publishers split — some prefer Firmly-hosted (lightest lift), others prefer embedded inside the article surface | | **Protocol** | Direct REST | Publisher CMSes typically have backend services that integrate cleanly with REST | | **Discovery scope** | Curated by editorial focus (apparel publisher → apparel merchants, etc.) | Editorial relevance trumps catalog breadth | ## Typical use cases - [AI Shopping Copilot](/solutions/agentic-commerce/use-cases/shopping-copilot) — The baseline copilot flow — discover, cart, place-order. - [Vertical Specialist](/solutions/agentic-commerce/use-cases/vertical-specialist) — Editorial categories map cleanly to vertical-specialist flows (fashion, beauty, fitness). - [Deal & Coupon Hunting](/solutions/agentic-commerce/use-cases/deal-coupon-hunting) — "Wirecutter-style" deal recommendations with codes applied at checkout. - [Smart Gifting](/solutions/agentic-commerce/use-cases/smart-gifting) — Gift guides convert to gift purchases without leaving the article. ## What to think about - **Affiliate attribution.** Firmly relays the originating publisher to the merchant, so commissions and origination credit flow back deterministically — much better than third-party cookie attribution. See [How Firmly Works](/how-firmly-works). - **Editorial trust posture.** Pre-purchase disclosure matters in editorial contexts; readers expect transparency. See [Consent & Disclosure](/solutions/agentic-commerce/consent-and-disclosure). - **Embedded vs hosted.** Publishers with strong article-page UX prefer embedded; smaller publishers prefer hosted because it's the lightest lift. - **Curated merchant set.** Publisher-specific catalog scope (only merchants the editorial focus has actually reviewed) is usually a configuration choice on the App ID. - **Multi-product carts.** Gift guides and category roundups generate multi-product carts naturally — see [Multi-product flow](/solutions/agentic-commerce/flows/multi-product-purchase). ## Getting started 1. **[Sandbox Setup](/for-destinations/sandbox-setup)** — credentials and a test merchant aligned with the publisher's editorial focus 2. **[Browser session authentication](/api-reference/authentication/browser-session)** — per-reader sessions 3. **[Hosted Checkout](/solutions/agentic-commerce/integration-patterns/hosted-checkout)** or **[Embedded Checkout](/solutions/agentic-commerce/integration-patterns/embedded-checkout)** — pick by editorial UX appetite 4. **[Publisher Commerce overview](/solutions/publisher-commerce/)** — the solution-level frame --- ## Related - [Agentic Commerce overview](/solutions/agentic-commerce/) - [Publisher Commerce overview](/solutions/publisher-commerce/) - [How Firmly Works — affiliate attribution](/how-firmly-works) --- # Recipes A **recipe** is a copy-pasteable end-to-end build for a *specific* agentic buying scenario. Each one combines the API calls with the dialogue, device, or trigger context that scenario requires. ## What's here today - [Chat to Checkout](/solutions/agentic-commerce/recipes/chat-to-checkout) — Annotated multi-turn dialogue from product mention to confirmed order — disambiguation, confirmation, and error recovery branches with the API calls inline at each turn. - [Wallet / Pass Purchase](/solutions/agentic-commerce/recipes/wallet-pass-purchase) — Purchase initiated from a digital wallet or pass — identity and payment already on the device, different starting context than a chat. For the canonical end-to-end Node script (generic flow, no scenario context), see the [Advanced Checkout Guide](/cookbook/advanced-checkout-guide). --- ## Related - [Use Cases](/solutions/agentic-commerce/use-cases/) — pick a scenario first - [Flows](/solutions/agentic-commerce/flows/single-product-purchase) — the abstract API sequence - [Integration Patterns](/solutions/agentic-commerce/integration-patterns/) — hosting, auth, discovery, checkout choices - [Cookbook](/cookbook/) — cross-solution how-tos --- # Retail-media Placement > **Note** > This is one common pattern partners build with Branded Commerce. Many other shapes are possible — adapt or combine use cases to fit your specific campaign. Retail-media networks — Walmart Connect, Target Roundel, Amazon Ads, Instacart Ads, and similar — sell sponsored-product placements alongside their organic search and category results. A partner running campaigns on these networks can route the sponsored click to **partner-branded checkout** instead of the network's native PDP. The mechanics are the same as a [single-product deal](/solutions/branded-commerce/use-cases/single-product-deal) or [curated landing page](/solutions/branded-commerce/use-cases/curated-landing-page) — the variation is the **ad source** and the implications for attribution and brand control. ## When this fits - The partner is running paid sponsored-product placements on a retail-media network - The partner wants the buyer to land on its own surface (carrying its brand, ad creative, and promo) rather than the retail network's default product page - The partner wants its ad-platform conversion signals to fire on its own pages (not be lost to the retail network's pixel) ## What the buyer sees Identical to the use case the ad routes to: - If the sponsored ad promotes one product → [single-product deal](/solutions/branded-commerce/use-cases/single-product-deal) - If the sponsored ad promotes a curated set → [curated landing page](/solutions/branded-commerce/use-cases/curated-landing-page) The buyer's experience is partner-branded throughout — they may not even realize the click came through a retail-media network. ## What's different from generic social/search ads | Aspect | Retail-media placement | Generic social/search ad | |---|---|---| | **Ad source** | Retail-media network (Walmart Connect, Target Roundel, Amazon Ads, Instacart Ads) | Social or search platform (Meta, Google, TikTok) | | **Bidding context** | Sponsored placement on retail-network search/category results | Audience-targeted ad on social/search inventory | | **Click attribution** | Retail-network click-tracking + partner's affiliate parameters | Ad-platform click-tracking + affiliate parameters | | **Landing destination** | Partner's domain (`deals.partner.example/...`) — same as any other Branded Commerce flow | Partner's domain | | **Pixel firing for conversion** | Retail-network's tag fires on click; partner's ad-platform pixels fire on Firmly-hosted pages | Partner's ad-platform pixels fire on Firmly-hosted pages | The Branded Commerce hosting layer is agnostic to ad source — the same partner-branded PDP and checkout work for any incoming click. ## Setup considerations specific to retail media - **Sponsored URL** — the partner provides the retail-network ad system with the partner-domain landing URL. The retail network's click-tracker wraps it; the buyer's browser still ends up on the partner's domain - **Promo handling** — promo codes from the retail network can be auto-applied just like any other entry point. Embed the promo in the URL (`?promo=CODE`) - **Click ID preservation** — if the retail network passes a click ID parameter, Firmly stores it server-side through the session so conversion postbacks can include it - **Multi-platform pixel fan-out** — partners running retail-media plus social plus search can configure all of these pixels in onboarding; Firmly fires every configured pixel from the partner's domain ## What the partner owns vs. what Firmly handles Same model as every Branded Commerce use case. The additional partner responsibility specific to retail-media: - **Retail-network campaign setup** — the partner runs the campaign on Walmart Connect, Target Roundel, Amazon Ads, Instacart Ads directly; Firmly is not involved in placement, bidding, or ad creative on the retail network's side - **Per-network click-ID handling** — if the retail network's click attribution requires server-side postbacks, the partner supplies the network credentials during [Partner Onboarding → Ad-platform credentials](/solutions/branded-commerce/operations/partner-onboarding#ad-platform-credentials) so Firmly can fire postbacks Firmly's responsibilities are unchanged: render the partner-branded PDP, orchestrate cart/checkout/payment, place the order with the merchant, fire affiliate + ad-platform conversion signals. ## Performance tracking - **Affiliate attribution** — works exactly as it does for other ad sources. The retail-network conversion postback (if the network supports one) is fired by Firmly using the partner-supplied credentials - **Ad-platform conversion signals** — fire to whatever pixels the partner has configured (Meta CAPI, Google Ads, TikTok, etc.). The retail network's own pixel typically lives on the click side, not on Firmly's pages ## Pre-purchase disclosure Same as the other use cases — partner T&C + privacy and merchant T&C are displayed at checkout. See [Consent & Disclosure](/solutions/agentic-commerce/consent-and-disclosure). --- ## Related - [Single-product deal](/solutions/branded-commerce/use-cases/single-product-deal) — most retail-media placements route to a single product - [Curated landing page](/solutions/branded-commerce/use-cases/curated-landing-page) — for sponsored placements that promote a themed roundup - [Operations → Partner onboarding](/solutions/branded-commerce/operations/partner-onboarding) — where ad-platform pixel and affiliate-network credentials are configured - [Operations → Operational workflow](/solutions/branded-commerce/operations/operational-workflow) — per-product setup --- # SSO > **Note** > **Centralize dashboard access in your Identity Provider (IdP).** Configure Firmly Connect to delegate sign-in to any OpenID Connect or SAML 2.0 Identity Provider, scoped per email domain you own. ## What you get - **Centralized Identity** — Your team logs in to Firmly Connect using the same Identity Provider they already use everywhere else. - **Per-Domain Control** — Each verified email domain has its own IdP configuration. Different domains can use different IdPs. - **Strict Enforcement** — When SSO enforcement is enabled for a domain, OTP and magic-link login are blocked — every user on that domain must authenticate through your IdP. ## How SSO works Setting up SSO is a five-step flow: register a domain, verify ownership, configure an Identity Provider, bind the IdP to the verified domain, and finally turn on enforcement. ```mermaid graph LR A[Register Domain] --> B[Verify Ownership
via DNS TXT] B --> C[Configure IdP
OIDC or SAML] C --> D[Bind IdP
to Domain] D --> E[Enforce SSO
per Domain] ``` You **must** verify the domain *and* bind it to an enabled IdP before the **SSO Enforced** toggle becomes available. This prevents an organization from locking itself out of an unverified domain or a domain with no working IdP. ## Per-domain enforcement Enforcement is scoped to one verified email domain at a time — it is never global. **Example:** turning **SSO Enforced** ON for `.com` affects only users with `@.com` email addresses — users on any other verified domain are unaffected. When enforcement is ON for a domain: - Every user whose email belongs to that domain must complete an SSO sign-in through the bound IdP. - One-time-passcode (OTP) and magic-link logins are **blocked** for that domain. There is no self-service bypass — if the IdP breaks and locks the team out, contact Firmly to recover access. - Users on other (unenforced) domains are unaffected and can continue to log in via OTP or magic link. You can step back from enforcement without deleting any configuration: - **Disable the IdP** — the **Enabled** toggle on the IdP form turns enforcement OFF everywhere it is bound, while preserving the IdP configuration. - **Toggle SSO Enforced OFF** on a specific domain — users on that domain regain OTP / magic-link access. > **Warning** > Once enforcement is ON for a domain, users on that domain who are not provisioned (or not reachable) through the bound IdP will lose dashboard access. Always run a successful **Test Connection** on the IdP, and try a real SSO sign-in, **before** turning the **SSO Enforced** toggle ON. ## Supported protocols - [Generic OpenID Connect](/solutions/firmly-connect/sso/generic-oidc) — Connect any OIDC-compliant Identity Provider — Okta, Microsoft Entra ID, Google, Auth0, Keycloak, and more. - [Generic SAML 2.0](/solutions/firmly-connect/sso/generic-saml) — Connect any SAML 2.0-compliant Identity Provider, with optional one-click setup via IdP metadata XML. > **Note** > Provider-specific templates (Okta, Microsoft Entra ID, Google Workspace, Auth0, OneLogin) appear in the IdP picker as **Coming Soon** and are not yet selectable. Use the Generic OIDC or Generic SAML guide above — both protocols are fully supported with any compliant provider. ## Setup checklist ### Verify a domain Add an email domain in **Settings → Domains** and prove ownership by publishing a DNS TXT record. See [Verify a Domain](/solutions/firmly-connect/sso/domain-verification). ### Add an Identity Provider Open **Settings → Single Sign-On**, click **Add Identity Provider**, and choose [Generic OIDC](/solutions/firmly-connect/sso/generic-oidc) or [Generic SAML 2.0](/solutions/firmly-connect/sso/generic-saml). ### Bind the IdP to your verified domains On the IdP configuration form, select one or more verified domains under **Authorized Domains**. At least one domain must be bound before the IdP can be enabled. ### Test the connection, then enable the IdP Click **Test Connection** to perform a live round trip through your IdP and confirm it succeeds, then turn the **Enabled** toggle on. Always run a successful Test Connection *before* enabling the IdP. ### Enforce SSO on the domain Return to **Settings → Domains** and turn the **SSO Enforced** toggle on for each domain you want to lock down. See [enforcement details](/solutions/firmly-connect/sso/domain-verification#enforce-sso-for-the-domain). ## Next steps - [Verify a Domain](/solutions/firmly-connect/sso/domain-verification) — Register and prove ownership of an email domain. - [Configure Generic OIDC](/solutions/firmly-connect/sso/generic-oidc) — Set up an OpenID Connect Identity Provider. - [Configure Generic SAML](/solutions/firmly-connect/sso/generic-saml) — Set up a SAML 2.0 Identity Provider. --- # Sandbox Setup This page walks the destination engineer through getting a working Ad Commerce sandbox. The mechanics mirror the destination-side sandbox setup in [For Destinations → Sandbox Setup](/for-destinations/sandbox-setup) — Ad Commerce uses the same App ID + test merchant pairing as every other solution. ## What you need from Firmly Contact [Firmly](/contact) and ask for: 1. **A sandbox App ID** (`_appId`) — a UUID scoped to a non-production environment 2. **A test merchant domain** — typically something like `staging.luma.gift`, with a non-empty catalog you can advertise against 3. **Ad-platform sandbox account** (if applicable) — Meta Ads sandbox, Google Ads test campaign, etc. — set up separately on the ad platform's side Firmly issues: - Sandbox App ID - Test merchant pairing - Optional server-to-server secret if needed for backend creative serving ## Endpoints | Surface | Host | |---|---| | General API (auth, discovery, cart, checkout) | `https://api.firmly.work` | | Payment (key, place-order) | `https://cc.firmly.work` | > **Note** > **Sandbox and production are different hosts.** The sandbox host is `api.firmly.work`; production uses a different host, published at go-live. See [Base URLs](/api-reference/) — never hard-code a host, read it from configuration. ## Smoke-test the integration Once you have your sandbox credentials, run the three calls from [For Destinations → Sandbox Setup](/for-destinations/sandbox-setup) to confirm auth, discovery, and the payment key work. Then verify the Ad Commerce flow end-to-end: 1. **Render a test ad creative** — point it at a sandbox SKU from the test merchant catalog 2. **Click through** — the ad's click should hit your landing or in-ad surface 3. **Confirm click-ID capture** — your landing/creative should parse the click-ID parameter from the click URL 4. **Run a sandbox purchase** — use a test card (`4111111111111111`) and confirm `cart_status === "submitted"` 5. **Confirm the order landed** — the order should carry the click-ID in its metadata. Destinations don't have direct access to the test merchant's OMS, so verify via the order-placement response (`cart_id`, `custom_properties`) and the [Destination Dashboard](/for-destinations/destination-dashboard), or ask your Firmly contact to confirm the order in the test merchant's OMS ## Ad-platform sandbox setup Set this up separately on the ad platform's side: - **Meta** — Meta Business Manager has a sandbox/test mode for ad accounts; create a test campaign that doesn't spend real ad budget - **Google Ads** — use Google Ads Test Accounts for end-to-end ad serving without billing - **TikTok** — TikTok Marketing API has a sandbox endpoint for testing creative + conversion tracking - **Other ad platforms** — see the platform's developer documentation for sandbox details Wire the ad-platform sandbox to your Firmly sandbox App ID so end-to-end tests don't touch production data on either side. ## Common setup issues | Symptom | Likely cause | Fix | |---|---|---| | `401` on browser-session | Sandbox App ID not loaded into the creative | Confirm the creative is reading the sandbox App ID, not production | | Empty `products` array on `discovery/search` | Test merchant has no products | Ask Firmly to load sample products into the test merchant | | Click-ID missing from order metadata | Click-ID not persisted between click and `complete-order` | Audit your cart-session persistence logic | | Conversion postback firing on impression | Postback wired to the wrong event | Move postback to fire on `cart_status === "submitted"` | ## Going live When the sandbox flow looks healthy end-to-end: 1. Request a production App ID from [Firmly](/contact) 2. Confirm the live merchants you'll advertise against — production App IDs are scoped to specific merchants 3. Move your ad-platform setup from sandbox to production 4. Switch from test cards to real cards — test card numbers are rejected in production, which accepts real cards and wallet payments 5. Run the [Going Live](/for-destinations/going-live) checklist for the universal launch concerns --- ## Related - [For Destinations → Sandbox Setup](/for-destinations/sandbox-setup) — the universal sandbox setup - [Single Product Purchase Flow](/solutions/ad-commerce/flows/single-product-purchase) - [Going Live](/for-destinations/going-live) — the production launch checklist --- # Sandbox Setup The mechanics — credentials, endpoints, test cards, and the three verification calls — are the canonical destination-side setup: follow **[For Destinations → Sandbox Setup](/for-destinations/sandbox-setup)** end-to-end. This page covers only what's specific to an Agentic Commerce build. ## Agentic-specific checks - **`404 ucp_disabled` on discovery/search** (a UCP-envelope code) means the test merchant hasn't opted into agentic surfaces — ask [Firmly](/contact) to enable UCP for the test merchant. - **Merchant scope** — confirm your sandbox App ID has merchants attached; discovery returns an empty `products` array otherwise. - **Protocol path** — if you're integrating via [UCP, MCP, or ACP](/solutions/agentic-commerce/protocols/) rather than direct REST, verify the protocol endpoint against the same sandbox App ID before building the full flow. - **Agentic Pay** — enrolling cards and paying with network tokens needs an Agentic Pay API token and network sandbox test cards in addition to the App ID; the generic test cards are not enrollable. See [Agentic Pay in the sandbox](/for-destinations/sandbox-setup#agentic-pay-in-the-sandbox). ## Going from sandbox to production The universal steps are in [For Destinations → Sandbox Setup](/for-destinations/sandbox-setup#going-from-sandbox-to-production). For an agentic destination, additionally: - Confirm your [consent and disclosure model](/solutions/agentic-commerce/consent-and-disclosure) is implemented for production traffic — the user must review and confirm order details before `complete-order`. - Run the full [Going Live](/solutions/agentic-commerce/operations/going-live) checklist. --- ## Related - [For Destinations → Sandbox Setup](/for-destinations/sandbox-setup) — the canonical setup - [Advanced Checkout Guide](/cookbook/advanced-checkout-guide) — run the full purchase flow - [Going Live](/solutions/agentic-commerce/operations/going-live) — the agentic pre-launch checklist --- # Sandbox Setup This page walks the operator's engineering team through getting a working Marketplace sandbox. The mechanics mirror the destination-side sandbox setup in [For Destinations → Sandbox Setup](/for-destinations/sandbox-setup) — Marketplace adds the wrinkle of wanting **several test merchants** so search-across-merchants (discovery) can be exercised. ## What you need from Firmly Contact [Firmly](/contact) to request sandbox access, and you'll receive: 1. **A sandbox App ID** (`_appId`) — a UUID scoped to a non-production environment 2. **A few test merchant pairings** — 2–3 diverse test merchant domains so discovery across merchants can be exercised 3. **Optional: server-to-server secret** — if your operator backend acts as a marketplace-level orchestrator Tell Firmly the kind of catalog you need to test — different product categories, shipping zones, payment options — so the test merchants are diverse enough to surface real edge cases. ## Endpoints | Surface | Host | |---|---| | General API (auth, discovery, cart, checkout) | `https://api.firmly.work` | | Payment (key, place-order) | `https://cc.firmly.work` | > **Note** > **Sandbox and production are different hosts.** The sandbox host is `api.firmly.work`; production uses a different host, published at go-live. See [Base URLs](/api-reference/) — never hard-code a host, read it from configuration. ## Smoke-test the integration Once you have your sandbox credentials, run the basic three calls from [For Destinations → Sandbox Setup](/for-destinations/sandbox-setup) to confirm auth, discovery, and the payment key work. Then verify the Marketplace flows: ### Discovery across merchants 1. **Search without a merchant filter** — `POST /api/v1/discovery/search` should return products spanning your test merchants, each with its source `domain` 2. **Confirm merchant identity** — each result carries the source merchant so your UI can label listings ### Single-merchant checkout 1. **Add 2 items from one test merchant** — `POST /cart/line-items` twice, scoped to that merchant's `{domain}` 2. **Set shipping + payment + complete order** — confirm `cart_status === "submitted"` 3. **Verify the order landed** — the operator ID should be in the order metadata. Operators don't have direct access to a test merchant's OMS, so verify via the complete-order response (`cart_id`, `custom_properties`) and the [Destination Dashboard](/for-destinations/destination-dashboard), or ask your Firmly contact to confirm the order and its metadata in the test merchant's OMS ## Common setup issues | Symptom | Likely cause | Fix | |---|---|---| | `401` on browser-session | Sandbox App ID not loaded | Confirm operator code reads sandbox App ID, not production | | Search returns one merchant only | Discovery call filtered to a single merchant, or only one test merchant provisioned | Remove the filter; ask Firmly for more test merchants | | Cart add rejected | `POST /cart/line-items` not scoped to the item's source merchant `{domain}` | Audit cart-add logic | | Shipping methods missing | Reading methods from `get-availability` (it doesn't return them), or not walking every shipment | Read `shipping_method_options` from each `cart.shipments[]` entry (populated by `set-shipping-info`), not just the first | ## Going live When the sandbox flow looks healthy end-to-end: 1. Request a production App ID from [Firmly](/contact) 2. Confirm the production merchants you'll aggregate — production App IDs are scoped to specific merchants 3. Start with a small set of merchants you've tested with extensively 4. Run the [Going Live](/for-destinations/going-live) checklist for universal launch concerns --- ## Related - [For Destinations → Sandbox Setup](/for-destinations/sandbox-setup) — the universal sandbox setup - [Multi-Product Purchase Flow](/solutions/marketplace/flows/multi-product-purchase) — multiple items from one merchant - [Going Live](/for-destinations/going-live) — the production launch checklist --- # Sandbox Setup This page walks the publisher's engineering team through getting a working Publisher Commerce sandbox. The mechanics mirror the destination-side sandbox setup in [For Destinations → Sandbox Setup](/for-destinations/sandbox-setup) — Publisher Commerce adds the wrinkle of testing the **CMS embed format** end-to-end. ## What you need from Firmly Contact [Firmly](/contact) to request sandbox access, and you'll receive: 1. **A sandbox App ID** (`_appId`) — a UUID scoped to a non-production environment 2. **A test merchant domain** — typically `staging.luma.gift` with a non-empty catalog of products 3. **Optional: server-to-server secret** — if your publisher backend pre-renders Buy Now button data ## Endpoints | Surface | Host | |---|---| | General API (auth, discovery, cart, checkout) | `https://api.firmly.work` | | Payment (key, place-order) | `https://cc.firmly.work` | > **Note** > **Sandbox and production are different hosts.** The sandbox host is `api.firmly.work`; production uses a different host, published at go-live. See [Base URLs](/api-reference/) — never hard-code a host, read it from configuration. ## Smoke-test the integration Once you have your sandbox credentials, run the basic three calls from [For Destinations → Sandbox Setup](/for-destinations/sandbox-setup) to confirm auth, discovery, and the payment key work. Then verify Publisher Commerce-specific flows: ### CMS embed smoke-test 1. **Author a test article in your CMS** with a Buy Now button embed pointing at a sandbox SKU 2. **Render the article** in your staging environment 3. **Confirm the button renders correctly** — image, price, and click-handler all wired up. Where the button sources its image and price (fetched by the component vs. supplied in the embed) depends on the embed format Firmly provides during onboarding — confirm the source with your Firmly contact if the values are missing 4. **Click Buy Now** — slide-in panel opens with cart pre-populated 5. **Run a test purchase** — use the sandbox test card from [For Destinations → Sandbox Setup](/for-destinations/sandbox-setup), confirm `cart_status === "submitted"` 6. **Confirm article identifier in order metadata** — the test merchant's order metadata should include the publisher ID + article ID ### Multi-product article smoke-test (for roundup articles) 1. **Author a test roundup article** with 3+ Buy Now buttons for different products from the same test merchant 2. **Click Buy on multiple products** — confirm cart badge increments 3. **Open the cart panel** — verify all items present with correct quantities 4. **Complete checkout** — confirm a single order is placed with all line items ### Sticky-cart smoke-test 1. **Scroll deep into a long article** — confirm cart badge stays visible (sticky behavior) 2. **Add an item, close the panel** — cart badge persists 3. **Open the panel later in the same session** — items still in cart 4. **Navigate to a different article (same publisher)** — confirm whether cart persists per your publisher's chosen policy ## Common setup issues | Symptom | Likely cause | Fix | |---|---|---| | Buy Now button doesn't render | CMS embed format mismatch | Confirm the embed shortcode matches the format Firmly's component expects | | `401` on browser-session | Sandbox App ID not loaded into the embed | Confirm the embed reads sandbox App ID, not production | | Multiple Buy Now clicks bootstrap separate sessions | Each click creates a new session | Audit session-persistence logic; reuse the existing token across clicks | | Article ID missing from order metadata | Article context not attached to the cart session (the cart is created implicitly by the first `POST /cart/line-items`; the article ID must be set on the session so it rides through to `complete-order`) | Audit where the article ID is sourced and how it's attached to the cart session — the exact carrier field is confirmed with Firmly during onboarding | ## CMS-specific notes | CMS type | Common gotcha | |---|---| | Block-based CMS | Buy Now block may not render in the CMS's visual preview — test in front-end render only | | Structured / headless CMS | Custom block needs explicit data mapping to the Firmly embed config | | Custom CMS | Sandbox testing requires a staging environment; don't test on production article URLs | ## Going live When the sandbox flow looks healthy end-to-end: 1. Request a production App ID from [Firmly](/contact) 2. Confirm the production merchants you'll feature in articles — production App IDs are scoped to specific merchants 3. Update CMS embed config to point at production App ID 4. Plan a soft launch with a small set of articles before broad rollout 5. Run the [Going Live](/for-destinations/going-live) checklist for universal launch concerns --- ## Related - [For Destinations → Sandbox Setup](/for-destinations/sandbox-setup) — the universal sandbox setup - [Single Product Purchase Flow](/solutions/publisher-commerce/flows/single-product-purchase) - [Multi-Product Purchase Flow](/solutions/publisher-commerce/flows/multi-product-purchase) - [Going Live](/for-destinations/going-live) — the production launch checklist --- # Scheduled or Triggered Buying Agent > **Note** > This is one common pattern customers build with Firmly. Many other shapes are possible — adapt or combine use cases to fit your specific build. The user sets a standing rule and the agent acts on it without re-asking each time: - *"Restock my coffee every 4 weeks"* - *"Buy this jacket if it drops below $120"* - *"Reorder my dog's food when I'm running low"* The **destination** owns the scheduler, the trigger, and the rule storage. **Firmly** executes the commerce side of each cycle — discovery, cart, payment, order placement — using saved payment credentials and the user's saved address. ## What Firmly does (and doesn't) for this scenario | Layer | Owner | |---|---| | The schedule / cron / event listener | **Destination** — Firmly has no native subscription or recurring-order API | | The trigger condition (price drop, inventory threshold, time elapsed) | **Destination** | | The user's standing-rule policy (spending cap, frequency limits) | **Destination** | | Each individual order's discovery, cart, payment, and order placement | **Firmly** | | Enrolled card for reuse | **Firmly** — via [Agentic Pay](/solutions/agentic-commerce/agentic-pay) | | Saved address | **Destination** stores it; Firmly accepts it in `set-shipping-info` | Firmly alone can't support this scenario — the scheduler must live on your side. If the destination doesn't have one, build it first. ## Recommended setup | Choice | Default | Why | |---|---|---| | **Integration pattern** | [Deep Link / Headless](/solutions/agentic-commerce/integration-patterns/deep-link) | No UI — the agent runs in the background and just calls APIs | | **Auth** | [Server-to-server](/api-reference/authentication/server-to-server) | The scheduler is backend; S2S is the right shape | | **Payment** | [Agentic Pay](/solutions/agentic-commerce/agentic-pay) | Enroll the card once, then reference it each cycle with Select Card; unattended cycles add a mandate at Create Intent (see the boundary note below) | > **Warning** > **Reuse vs. mandate.** Saved-card reuse runs through [Agentic Pay](/solutions/agentic-commerce/agentic-pay): [Select Card](/api-reference/agentic-pay/select-card) references the enrolled card without re-collecting the PAN. When cycles fire **unattended** (no live human at checkout), the card network also needs a mandate proving the cardholder pre-authorized that specific charge — reuse without one can be declined for the same reasons described in [Autonomous Agent Purchasing](/solutions/agentic-commerce/use-cases/autonomous-agent-purchasing). Agentic Pay attaches that mandate at [Create Intent](/api-reference/agentic-pay/create-intent). The exact boundary depends on the card, the network, and the merchant — confirm with [Firmly](/contact) for your setup. ## API sequence (per cycle) | # | Endpoint | Purpose | |---|---|---| | 1 | (none) | Destination's scheduler fires | | 2 | [Server-to-server auth](/api-reference/authentication/server-to-server) header | Identify the user/device for this cycle | | 3 | *(optional)* [Discovery search](/api-reference/discovery/search) | Re-resolve product (price-drop trigger may have driven discovery already) | | 4 | [Add line item](/api-reference/cart-management/add-line-item) | Build the cycle's cart | | 5 | [Set shipping info](/api-reference/checkout/set-shipping-info) | Reuse the user's saved address; populates the `shipments` array with `shipping_method_options` | | 6 | [Get shipping availability](/api-reference/shipment-configuration/get-availability) | *(Optional)* Delivery dates / time slots / pickup locations | | 7 | [Set shipping method](/api-reference/shipment-configuration/set-shipping-method) | Pick a default method from the shipment's `shipping_method_options` (often the cheapest for replenishment) | | 8 | … then the checkout + Agentic Pay tail | Get/set consents → set billing info, then pay against the built cart with Agentic Pay: [Select Card](/api-reference/agentic-pay/select-card) → [Create Intent](/api-reference/agentic-pay/create-intent) → [Wallet Complete Order](/api-reference/payment/wallet-complete-order). Because the cycle's cart was built above, finalize against it, not the one-shot `place-order`. See the [single-product flow](/solutions/agentic-commerce/flows/single-product-purchase#the-implementation-steps-phase-4-broken-out) for the cart-building phases | At order placement, pay against the user's enrolled card through Agentic Pay — [Select Card](/api-reference/agentic-pay/select-card) references the stored `virtual_card_id`, and unattended cycles add the per-cycle mandate at [Create Intent](/api-reference/agentic-pay/create-intent). The documented `complete-order` request takes a fresh encrypted card, not a saved-token field, so saved-card reuse runs through Agentic Pay (see the boundary note above). Use a fresh `Idempotency-Key` per cycle so retries don't double-place. (The `Idempotency-Key` header is honored on the UCP bridge; on core REST `complete-order`, guard against double-placement on the destination side.) ## Agent considerations - **Confirm before the first cycle.** Even if subsequent cycles are silent, the *first* time a recurring rule fires, surface the order to the user before placing. The user may have changed their mind. - **Spending caps.** Implement a per-transaction and per-period cap on the destination side. Firmly enforces no caps by default — see [Consent & Disclosure](/solutions/agentic-commerce/consent-and-disclosure). - **Stock and price changes.** A scheduled order can fail at order-placement time if stock dropped or the price changed materially. Decide policy in advance: silent retry next cycle, fall back to a similar product, or notify the user. - **Revocation.** The user must be able to cancel the rule in conversation at any time. Firmly does not own the rule; the destination does. --- ## Related - [Server-to-server authentication](/api-reference/authentication/server-to-server) — the right auth for backend schedulers - [AI Shopping Copilot](/solutions/agentic-commerce/use-cases/shopping-copilot) — the manual-purchase counterpart - [Consent & Disclosure](/solutions/agentic-commerce/consent-and-disclosure) — spending controls and revocation patterns - [Errors & conventions](/api-reference/errors-and-conventions) — `NotEnoughStockError` and price-change handling --- # Shoppable Article A reader is on a publisher's article (review, recommendation, tutorial) where specific products are referenced. Embedded Buy Now buttons next to product mentions let the reader purchase without leaving the article. Cart, address, and payment render inline as a slide-in panel. This is the canonical Publisher Commerce pattern. The reader's reading flow is preserved — they can buy, close the panel, and continue reading. ## Recommended setup | Choice | Default | Why | |---|---|---| | **Integration pattern** | [Embedded Buy Button](/solutions/publisher-commerce/integration-patterns/embedded-buy-button) | Keeps the reader in the article | | **Auth** | [Browser session](/api-reference/authentication/browser-session) | Per-reader article session | | **Payment** | Google Pay (mobile), Card via JWE, PayPal Express | Wallet auth is the fastest checkout path for a reader who is mid-article | | **Attribution** | UTM params + publisher identifier + article identifier | Publisher's analytics know which articles drive orders | ## API sequence The flow follows the [Single Product Purchase](/solutions/publisher-commerce/flows/single-product-purchase) shape. The Buy Now button names the SKU directly through the [Embedded Buy Button](/solutions/publisher-commerce/integration-patterns/embedded-buy-button) embed — no live discovery needed. | Step | Endpoint | |---|---| | 1. Bootstrap session | [`POST /api/v1/browser-session`](/api-reference/authentication/browser-session) | | 2. Add to cart | [`POST /cart/line-items`](/api-reference/cart-management/add-line-item) | | 3. Set shipping address | [`POST /cart/shipping-info`](/api-reference/checkout/set-shipping-info) | | 4. Pick shipping method | [`POST /cart/shipment/methods`](/api-reference/shipment-configuration/set-shipping-method) | | 5. (Optional) Get delivery availability | [`POST /cart/shipments/get-availability`](/api-reference/shipment-configuration/get-availability) | | 6. (If required) Get + set merchant consents | [`GET /cart/consents`](/api-reference/checkout/get-consents) → [`PUT /cart/consents`](/api-reference/checkout/set-consents) | | 7. Get payment public key | [`GET /payment/key`](/api-reference/payment/get-public-key) | | 8. Complete order | [`POST /payment/complete-order`](/api-reference/payment/complete-order-v2) | The valid `shipping_method_id`s for step 4 come from the cart itself — `cart.shipments[].shipping_method_options`, populated by step 3 (`set-shipping-info`). `get-availability` (step 5) is optional and returns delivery dates, time slots, or pickup locations for scheduled-delivery or in-store-pickup shipments — not shipping methods. Steps 2–6 build the cart, so step 8 finalizes it with [`complete-order`](/api-reference/payment/complete-order-v2) (body: `encrypted_card` + `billing_info`); use [`place-order`](/api-reference/payment/place-order-v2) only for the one-shot create-cart-and-order call. ## Considerations the article surface owns - **Buy Now button placement.** Buttons go near the product mention, not at the end of the article. Readers should not have to scroll back to find the buy CTA after reading about the product. - **Inline checkout panel.** When the reader clicks Buy Now, the checkout opens as a slide-in panel or modal that doesn't displace the article content. Closing the panel returns the reader to where they were. - **Cart badge.** A persistent cart indicator (e.g., a small badge in the corner) shows the reader that items have been added. Accumulating several items across multiple Buy Now clicks is the [Curated Product Roundup](/solutions/publisher-commerce/use-cases/curated-product-roundup) pattern — see that page when an article references several products. - **Sticky behavior on long articles.** For long-form pieces, the cart badge stays visible as the reader scrolls. - **Inline confirmation.** Order success surfaces inline — the reader gets confirmation in the panel and continues reading. The merchant's full thank-you page is linked but not forced. --- ## Related - [Single Product Purchase Flow](/solutions/publisher-commerce/flows/single-product-purchase) — full API walkthrough - [Embedded Buy Button pattern](/solutions/publisher-commerce/integration-patterns/embedded-buy-button) - [Curated Product Roundup](/solutions/publisher-commerce/use-cases/curated-product-roundup) — multi-item variant --- # Single Product Purchase > **Note** > This is an **annotated flow** — the viewer experience alongside the API calls the ad surface makes. The underlying API sequence is the shared Firmly cart flow — identical to [Agentic Commerce → Single Product Purchase](/solutions/agentic-commerce/flows/single-product-purchase), which has the full curl-by-curl walkthrough. This page covers only what's specific to Ad Commerce: click-ID capture, an ad creative that names the SKU, and the conversion postback. ## The five phases, Ad-Commerce framing | Phase | What happens | |---|---| | **1. Hosting** | Ad creative or post-click landing surface | | **2. Authentication** | `POST /api/v1/browser-session` (or use [server-to-server auth](/for-destinations/authentication) directly) | | **3. Discovery** | The ad creative encodes the SKU (via the `click_through` URL) — usually no live `discovery/search` call | | **4. Checkout** | The shared cart → shipping → payment → complete-order sequence | | **5. Order placement** | Order lands in the merchant's OMS with click-ID; a conversion postback fires to the ad platform | ## Sequence diagram ```mermaid sequenceDiagram autonumber participant V as Viewer participant A as Ad Surface participant F as Firmly API participant M as Merchant participant P as Ad Platform V->>A: Click shoppable ad Note over A: fbclid / gclid / ttclid captured A->>F: POST /browser-session F-->>A: { access_token } A->>V: In-ad checkout or post-click PDP V->>A: Click Buy A->>F: POST /cart/line-items F-->>A: { cart } A->>F: POST /cart/shipping-info F-->>A: { cart with shipments + shipping_method_options } opt Scheduled delivery / pickup A->>F: POST /cart/shipments/get-availability F-->>A: { delivery dates / time slots } end A->>F: POST /cart/shipment/methods F-->>A: { cart } V->>A: Enter card or click Google Pay A->>F: GET /payment/key F-->>A: { JWK } Note over A: JWE-encrypt card A->>F: POST /payment/complete-order (Idempotency-Key) F->>M: place order with click-ID metadata M-->>F: merchant order # F-->>A: { cart_status: "submitted", cart_id, urls, custom_properties } A->>P: postback (conversion event with click-ID) A->>V: Confirmation Note over A: Firmly's scope ends here.
Post-order belongs to the merchant. ``` ## What's specific to Ad Commerce - **Click-ID capture.** On ad click, capture the platform's click-ID (`fbclid` for Meta, `gclid` for Google, `ttclid` for TikTok, `epik` for Pinterest) and persist it for the session — before any API call. - **The ad encodes the SKU.** The creative's `click_through` URL carries the product handle or variant ID, so add-to-cart can skip discovery. - **Wallet-first payment.** Mobile ad surfaces lean on Google Pay to cut drop-off; card via JWE is the fallback. - **Conversion postback.** After `cart_status === "submitted"`, fire the ad platform's conversion event with the click-ID (Meta CAPI, Google Ads, TikTok Events, Pinterest CAPI). Wire it after success, never before. On a 5xx or network error, retry with backoff; on a 4xx, log and alert (the payload is malformed and a retry will fail again) — either way, don't surface it to the viewer, who has already paid. ## Attribution — closing the ad loop What defines the Ad Commerce flow is **proper attribution back to the ad platform**. Three data flows matter: | Data | Direction | Why | |---|---|---| | Click-ID (`fbclid`, `gclid`, etc.) | Ad click → session → order metadata | Ad platform credits the conversion | | UTM params | Ad click → session → merchant OMS | Merchant's own attribution reports | | Conversion postback | Order placement → ad platform | Optimization model gets the signal to find more conversions | Bind the click-ID and UTM params to the cart with [Set Cart Attribution](/api-reference/cart-management/set-attribution) (`PUT .../cart/attribution`), called after add-to-cart and before checkout. It takes four optional string fields — `utm`, `referrer_url`, `referral_code`, and `landing_page` — which flow through to the merchant's order metadata. Fold the click-ID into the `utm` query string (e.g. `utm_source=meta&fbclid=...`), and use `referrer_url` / `landing_page` for the ad and post-click URLs. The conversion postback is your call to fire after order success — Set Cart Attribution feeds the order metadata; it does not fire the postback. Without the postback, the campaign won't learn — every order should fire one. ## The shared cart sequence The add-to-cart, shipping, and order-completion calls are identical across solutions, including the usual checkout tail (set shipping method → get/set consents → billing → payment key → complete order). Because the cart is built across those calls, the tail finalizes with [`complete-order`](/api-reference/payment/complete-order-v2) (existing cart), not the one-shot `place-order`. Follow [Agentic Commerce → Single Product Purchase](/solutions/agentic-commerce/flows/single-product-purchase) for the step-by-step, or the [Advanced Checkout Guide](/cookbook/advanced-checkout-guide) for a runnable script. --- ## Related - [Multi-Product Purchase](/solutions/ad-commerce/flows/multi-product-purchase) — multiple items in one ad-driven cart - [Why Firmly](/solutions/ad-commerce/why-firmly) — what makes Ad Commerce different - [Integration Patterns](/solutions/ad-commerce/integration-patterns/) — in-ad checkout vs post-click landing --- # Single Product Purchase > **Note** > This is an **annotated flow** — it walks through the user experience alongside the API calls a developer makes. The order of operations and API specifics are grounded in the underlying platform; the presentation is sequenced for developer readability rather than split across separate UX and design docs. This page is the flow-level walkthrough. For a runnable script that executes this exact flow end-to-end, see the [Advanced Checkout Guide](/cookbook/advanced-checkout-guide) — both pages describe the same multi-step `/api/v2` sequence; this one is annotated for clarity, the other is meant to run. ## The five canonical phases Every Firmly purchase moves through five phases. The single-product flow is the simplest instance. | Phase | What happens | What you do | |---|---|---| | **1. Hosting** | Your surface is reachable (your domain in production, or a Firmly UAT environment for testing) | One-time configuration with Firmly | | **2. Authentication** | A Firmly session is established | `POST /api/v1/browser-session` (or use S2S directly) | | **3. Discovery** | Resolve user intent to a real merchant SKU with live price and stock | `POST /api/v1/discovery/search` or `GET /api/v1/domains-products/{domain}/{handle}` | | **4. Checkout** | Cart, address, shipping, payment, place order | A short sequence of calls (see below) | | **5. Order placement** | Order lands in the merchant's OMS with destination attribution | `POST /payment/complete-order` | ## Sequence diagram ```mermaid sequenceDiagram autonumber participant U as User participant A as Destination / Agent participant F as Firmly API participant M as Merchant U->>A: "Order me a $50 gift card" A->>F: POST /browser-session F-->>A: { access_token } A->>F: POST /api/v1/discovery/search { query } F->>M: catalog query M-->>F: products F-->>A: { products[] } A->>U: "Found: Luma $50 Gift Card. Confirm?" U->>A: "Yes" A->>F: POST /cart/line-items F-->>A: { cart } A->>F: POST /cart/shipping-info F-->>A: { cart with shipments + shipping_method_options } opt Scheduled delivery / pickup A->>F: POST /cart/shipments/get-availability F-->>A: { delivery dates / time slots } end A->>F: POST /cart/shipment/methods F-->>A: { cart } A->>F: GET /cart/consents F-->>A: { consents[] (if merchant requires) } A->>F: PUT /cart/consents F-->>A: { cart } A->>F: GET /payment/key F-->>A: { JWK } Note over A: JWE-encrypt card locally A->>F: POST /payment/complete-order (Idempotency-Key) F->>M: place order M-->>F: merchant order # F-->>A: { cart_status: "submitted", cart_id, platform_order_number, urls, custom_properties } A->>U: "Order placed — see merchant's thank-you page" Note over A: Firmly's scope ends here.
Post-order belongs to the merchant. ``` ## The implementation steps (Phase 4 broken out) ### Intent User tells your agent what they want. Your agent extracts product, options, quantity. *No API calls yet.* ### Discover (Phase 3) ```bash curl -X POST https://api.firmly.work/api/v1/discovery/search \ -H "x-firmly-authorization: $TOKEN" \ -H "Content-Type: application/json" \ -d '{"query": "gift card", "page_size": 5}' ``` Response contains `products[]` (across all merchants your App ID can reach). Each product has a `domain` field identifying its merchant, plus `variants[]`. Each variant has an `add_to_cart_ref` — keep it as an opaque handle. ### Add to cart (Phase 4 begins) ```bash curl -X POST https://api.firmly.work/api/v2/domains/staging.luma.gift/cart/line-items \ -H "x-firmly-authorization: $TOKEN" \ -H "Content-Type: application/json" \ -d '{"add_to_cart_ref": {...}, "quantity": 1}' ``` Cart is created implicitly. Response is the full cart object. ### Set shipping address (Phase 4) ```bash curl -X POST https://api.firmly.work/api/v2/domains/staging.luma.gift/cart/shipping-info \ -H "x-firmly-authorization: $TOKEN" \ -H "Content-Type: application/json" \ -d '{ "first_name": "Agent", "last_name": "Tester", "email": "agent@example.com", "phone": "+15551234567", "address1": "500 Howard St", "city": "San Francisco", "state_or_province": "CA", "country": "US", "postal_code": "94105" }' ``` Response includes updated `shipments[]` with `shipment_id`s. **Optimization tip**: if you know the user's postal code before you have their full address (e.g. from a saved profile), set it earlier via [Set Postal Code](/api-reference/session/set-postal-code) — Firmly stores it session-wide and the merchant often has shipping rates pre-warmed by the time you set the full address. ### Pick a shipping method (Phase 4) > **Note** > **Shipping methods come from the cart, not from `get-availability`.** After step 4, `cart.shipments[].shipping_method_options` already lists the available methods — Firmly populates them inline. Pick a `shipping_method_id` from there and record it with `POST /cart/shipment/methods`. > > `get-availability` is a separate, **optional** call that returns delivery dates, time slots, or pickup locations for scheduled-delivery or in-store-pickup shipments — not shipping methods. It requires a `shipment_id` and returns `501 NotImplemented` on merchants whose adapters don't support it. ```bash # Read available methods from cart.shipments[].shipping_method_options (set in step 4), # then record the choice curl -X POST https://api.firmly.work/api/v2/domains/staging.luma.gift/cart/shipment/methods \ -H "x-firmly-authorization: $TOKEN" \ -H "Content-Type: application/json" \ -d '{"shipment_id": "01e232ec-6202-5cb1-25fa-6fe46cc569a9", "shipping_method_id": "method_standard"}' # Optional: for scheduled-delivery / pickup, fetch delivery dates & time slots first curl -X POST https://api.firmly.work/api/v2/domains/staging.luma.gift/cart/shipments/get-availability \ -H "x-firmly-authorization: $TOKEN" \ -H "Content-Type: application/json" \ -d '{"shipment_id": "01e232ec-6202-5cb1-25fa-6fe46cc569a9"}' ``` ### (If required) Capture merchant consents Some merchants require the user to agree to terms-of-sale, warranty, or delivery acknowledgments before order placement (this is **merchant-required consent**, distinct from your agent's own user-confirmation step). Before `complete-order`: 1. `GET /api/v2/domains/{domain}/cart/consents` — returns an array of required consents with `id`, `html`/`text` to display, `required`, `explicit` flags 2. If the array is non-empty, surface each `text` to the user, get explicit agreement, then `PUT /api/v2/domains/{domain}/cart/consents` with `{consents: [{id, revoke: false}, ...]}` If you skip this and the merchant required consents, `complete-order` returns `RequiredConsentsNotSigned` (412). See [Get Consents](/api-reference/checkout/get-consents) and [Set Consents](/api-reference/checkout/set-consents). ### Encrypt payment + complete order (Phase 4 ends) > **Warning** > Payment calls go to a different host — **cc.firmly.work**, not api.firmly.work. This is easy to miss. Get the payment public key, JWE-encrypt the card, then submit. See the [Advanced Checkout Guide](/cookbook/advanced-checkout-guide) for the full JWE encryption code. **Note the host change**: every call up to this point used `https://api.firmly.work`; payment calls (get public key and `complete-order`) go to the dedicated payment host `https://cc.firmly.work`. Switch hosts for the payment steps to avoid a copy-paste 404. ```bash curl -X POST https://cc.firmly.work/api/v2/payment/domains/staging.luma.gift/complete-order \ -H "x-firmly-authorization: $TOKEN" \ -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" \ -d '{ "encrypted_card": "eyJh...", "billing_info": { ... } }' ``` **Why `complete-order` and not `place-order`?** The cart was built over the previous calls (add line item → shipping info → shipping method → consents), so `complete-order` finalizes that **existing** cart — the body carries only `encrypted_card` and `billing_info` (shipping was already set in the earlier steps). Reach for [`place-order`](/api-reference/payment/place-order-v2) instead only on the **one-shot** path: it creates a cart *and* places the order in a single call, and therefore requires an `items[]` array plus `shipping_info` in the body because there's no prior cart to finalize. Verify the request body against [Complete Order](/api-reference/payment/complete-order-v2). Response includes `cart_status: "submitted"`, `cart_id`, and `urls.order_status_page` for customer-facing tracking. The merchant's native order number comes back in the first-class `platform_order_number` field (some merchants also echo platform-specific identifiers in `custom_properties`). ### Surface the placed order to the user Firmly's scope ends at order placement. After `complete-order` succeeds, surface the order confirmation to the user using the response: - `urls.thank_you_page` — the merchant's own confirmation URL; route the user there to continue their relationship with the merchant - `cart_id` and the merchant's native order number from `platform_order_number` — for the user's reference Anything post-order — order status, tracking, returns, refunds, cancellations — lives in the merchant's native order management system. The user contacts the merchant directly through the merchant's existing post-order support channels. ## What can go wrong at each step | Step | Most common failure | Recovery | |---|---|---| | Discover | Empty results, `StoreUnavailable` | Check domain spelling, confirm merchant is enabled for agentic | | Add to cart | `ProductNotFound`, `NotEnoughStockError` | Re-fetch product or pick another variant | | Set shipping | `InvalidInputBody` | Validate address fields client-side first | | Shipping methods | No methods returned | Address may not be deliverable — ask user for an alternative | | Place order | `CreditCardDeclined`, `NotEnoughStockError` (race with another buyer) | Ask user for different payment method, or re-quote with new stock | | Post-order status read | `404` (rare, transient) | Retry with backoff | See [Errors](/solutions/agentic-commerce/operations/errors) for the full catalog. ## What's in a cart response Every cart-mutation endpoint returns the **full cart object** in the response, so your agent doesn't have to re-fetch. Real shape (anonymized from a QA trace): ```json { "cart_id": "00000000-0000-0000-0000-000000000000", "cart_status": "active", "schema_version": "2.0", "display_name": "Example Merchant", "shop_id": "merchant.example", "platform_id": "example_commerce", "shop_properties": { "paypal": { "clientId": "...", "merchantId": "..." } }, "line_items": [ { "line_item_id": "00000000-0000-0000-0000-000000000000", "sku": "variant-123", "base_sku": "product-123", "quantity": 1, "msrp": { "currency": "USD", "value": 25.00, "number": 2500, "symbol": "$" }, "price": { "currency": "USD", "value": 25.00, "number": 2500, "symbol": "$" }, "line_price": { "currency": "USD", "value": 25.00, "number": 2500, "symbol": "$" }, "requires_shipping": true, "image": { "type": "large", "url": "https://cdn.example.com/..." }, "platform_line_item_id": "...", "description": "Example Product", "variant_description": "Default" } ], "shipments": [], "addons": { "offers": [], "selections": [] }, "sub_total": { "currency": "USD", "value": 25.00, "number": 2500, "symbol": "$" }, "shipping_total": { "currency": "USD", "value": 0.00, "number": 0, "symbol": "$" }, "tax_total": { "currency": "USD", "value": 0.00, "number": 0, "symbol": "$" }, "fees": [{ "description": "Recycle fee", "currency": "USD", "value": 2.00, "number": 200, "symbol": "$" }], "fee_total": { "currency": "USD", "value": 2.00, "number": 200, "symbol": "$" }, "addon_total": { "currency": "USD", "value": 0.00, "number": 0, "symbol": "$" }, "total": { "currency": "USD", "value": 27.00, "number": 2700, "symbol": "$" }, "session": { "requires_login": false, "is_email_registered": false, "is_logged_in": false, "cookies": [] }, "urls": {}, "payment_method_options": [ { "type": "CreditCard", "wallet": "user" }, { "type": "PayPal", "wallet": "paypal" } ] } ``` ### Field reference | Field | What it is | |---|---| | `cart_id` | UUID for this cart. Stable across cart-mutation calls within the same session. | | `cart_status` | Cart state: `active` while building, `submitted` after the order is placed. | | `schema_version` | Cart envelope schema version (`"2.0"`). | | `display_name` / `shop_id` / `platform_id` | Merchant identity. `platform_id` is the literal identifier of the merchant's underlying commerce platform. | | `shop_properties` | Merchant-configured properties — most commonly the PayPal client/merchant IDs needed if you're using PayPal Express. | | `line_items[]` | Each item in the cart with quantity, price, image, and a stable `line_item_id` you use in subsequent `PUT`/`DELETE` calls. | | `shipments[]` | Populated only after `set-shipping-info`. Each shipment has its own `shipment_id` for shipping-method selection. | | `addons` | Merchant add-on offers (warranties, gift wrap, etc.) and the user's selections. | | `sub_total` / `shipping_total` / `tax_total` / `addon_total` / `total` | Money values. **All money objects** use the shape `{currency, value, number, symbol}` — `value` is a decimal, `number` is the integer in minor units (e.g. cents). | | `session` | Session state including login/registration flags and cookies. | | `urls` | Filled in after the order is placed with `thank_you_page` and `order_status_page` URLs (empty before placement). | | `payment_method_options` | Available payment methods for this cart. Each entry has a `type` and `wallet`. | After the order is placed, the same shape comes back with `cart_status: "submitted"`, populated `urls`, a first-class `platform_order_number` (the merchant's native order number), and a `custom_properties` block with any additional platform-specific identifiers. ## Runnable end-to-end The [Advanced Checkout Guide](/cookbook/advanced-checkout-guide) is this exact flow — the multi-step `/api/v2` cart — as a complete Node script you can run today. Start there if you want working code, return here for the conceptual walkthrough. --- # Single Product Purchase > **Note** > This is an **annotated flow** — it walks through the buyer experience alongside the API calls the partner's surface makes. The order of operations and API specifics are grounded in the underlying platform; the presentation is sequenced for developer readability. This page is the flow-level walkthrough for Branded Commerce. For a runnable script that executes the same multi-step `/api/v2` sequence end-to-end, see the [Advanced Checkout Guide](/cookbook/advanced-checkout-guide) — the API calls are identical across all solutions; this page covers the Branded-specific framing. ## The five canonical phases Every Firmly purchase moves through five phases. In Branded Commerce, the experience runs on Firmly-hosted partner-branded pages (the partner's brand identity layered on Firmly's commerce backend). | Phase | What happens | What you do | |---|---|---| | **1. Hosting** | Firmly-hosted partner-branded pages — your domain, your brand, Firmly's commerce backend | One-time configuration with Firmly | | **2. Authentication** | A Firmly session is established | `POST /api/v1/browser-session` (or use S2S directly) | | **3. Discovery** | Buyer clicks an ad and lands on a Firmly-hosted page for a specific product or curated landing | Page-load context resolves the product/SKU; usually no live `discovery/search` call — the link itself names the SKU | | **4. Checkout** | Cart, address, shipping, payment, place order | Five sub-calls (see below) | | **5. Order placement** | Order lands in the merchant's existing OMS as a native order, with attribution tagged | `POST /payment/complete-order` | ## Sequence diagram ```mermaid sequenceDiagram autonumber participant C as Buyer participant B as Branded Page (Firmly-hosted, partner identity) participant F as Firmly API participant M as Merchant C->>B: Click ad → lands on branded PDP Note over B: utm_source, utm_campaign, click ID captured B->>F: POST /browser-session F-->>B: { access_token } B->>C: Render branded PDP (product, price, Add to Cart) C->>B: Click "Buy Now" B->>F: POST /cart/line-items F-->>B: { cart } B->>C: Render branded cart / checkout page C->>B: Fill shipping address B->>F: POST /cart/shipping-info F-->>B: { cart with shipments + shipping_method_options } opt Scheduled delivery / pickup B->>F: POST /cart/shipments/get-availability F-->>B: { delivery dates / time slots } end B->>F: POST /cart/shipment/methods F-->>B: { cart } C->>B: Enter card details (or click Click to Pay / PayPal) B->>F: GET /payment/key F-->>B: { JWK } Note over B: JWE-encrypt card client-side B->>F: POST /payment/complete-order (Idempotency-Key) F->>M: place order with attribution (UTM + partner ID) M-->>F: merchant order # F-->>B: { cart_status: "submitted", cart_id, urls, custom_properties } B->>C: Render branded thank-you page Note over B: Firmly's scope ends here.
Post-order belongs to the merchant. ``` ## The implementation steps (Phase 4 broken out) ### Ad click captured Buyer clicks an ad and lands on a Firmly-hosted branded page (e.g., `partner.example.com/holiday-deals/hoodie`). The page captures attribution params (`utm_source`, `utm_campaign`, `utm_content`, `fbclid`, `gclid`, etc.) from the URL and persists them client-side for the session. *No API call yet.* ### Discover (Phase 3) — page-load context For Branded Commerce, the landing URL usually names the SKU directly, so an explicit `discovery/search` call isn't always required. If you do need search (e.g., a curated landing with multiple options): ```bash curl -X POST https://api.firmly.work/api/v1/discovery/search \ -H "x-firmly-authorization: $TOKEN" \ -H "Content-Type: application/json" \ -d '{"query": "hoodie", "page_size": 5}' ``` Response contains `products[]` (across all merchants your App ID can reach). Each product has a `domain` field identifying its merchant, plus `variants[]`. Each variant has an `add_to_cart_ref` — keep it as an opaque handle. ### Add to cart (Phase 4 begins) Buyer clicks Buy Now on the branded PDP. ```bash curl -X POST https://api.firmly.work/api/v2/domains/staging.luma.gift/cart/line-items \ -H "x-firmly-authorization: $TOKEN" \ -H "Content-Type: application/json" \ -d '{"add_to_cart_ref": {...}, "quantity": 1}' ``` Cart is created implicitly. Response is the full cart object. ### Set shipping address (Phase 4) Buyer fills the address on the branded checkout page. ```bash curl -X POST https://api.firmly.work/api/v2/domains/staging.luma.gift/cart/shipping-info \ -H "x-firmly-authorization: $TOKEN" \ -H "Content-Type: application/json" \ -d '{ "first_name": "Consumer", "last_name": "Tester", "email": "consumer@example.com", "phone": "+15551234567", "address1": "500 Howard St", "city": "San Francisco", "state_or_province": "CA", "country": "US", "postal_code": "94105" }' ``` Response includes updated `shipments[]` with `shipment_id`s. **Optimization tip**: pre-set the postal code from the buyer's geo IP via [Set Postal Code](/api-reference/session/set-postal-code) — Firmly stores it session-wide and the merchant often has shipping rates pre-warmed by the time the full address is submitted. ### Pick a shipping method (Phase 4) > **Note** > **Shipping methods come from the cart, not from `get-availability`.** After step 4, `cart.shipments[].shipping_method_options` already lists the available methods — Firmly populates them inline. Pick a `shipping_method_id` from there and record it with `POST /cart/shipment/methods`. > > `get-availability` is a separate, **optional** call that returns delivery dates, time slots, or pickup locations for scheduled-delivery or in-store-pickup shipments — not shipping methods. It requires a `shipment_id` and returns `501 NotImplemented` on merchants whose adapters don't support it. ```bash # Read available methods from cart.shipments[].shipping_method_options (set in step 4), # then record the choice curl -X POST https://api.firmly.work/api/v2/domains/staging.luma.gift/cart/shipment/methods \ -H "x-firmly-authorization: $TOKEN" \ -H "Content-Type: application/json" \ -d '{"shipment_id": "01e232ec-6202-5cb1-25fa-6fe46cc569a9", "shipping_method_id": "method_standard"}' # Optional: for scheduled-delivery / pickup, fetch delivery dates & time slots first curl -X POST https://api.firmly.work/api/v2/domains/staging.luma.gift/cart/shipments/get-availability \ -H "x-firmly-authorization: $TOKEN" \ -H "Content-Type: application/json" \ -d '{"shipment_id": "01e232ec-6202-5cb1-25fa-6fe46cc569a9"}' ``` ### (If required) Capture merchant consents Some merchants require the buyer to agree to terms-of-sale, warranty, or delivery acknowledgments before order placement. Before `complete-order`: 1. `GET /api/v2/domains/{domain}/cart/consents` — returns an array of required consents with `id`, `html`/`text` to display, `required`, `explicit` flags 2. If the array is non-empty, surface each `text` on the branded checkout page, get explicit agreement, then `PUT /api/v2/domains/{domain}/cart/consents` with `{consents: [{id, revoke: false}, ...]}` If you skip this and the merchant required consents, `complete-order` returns `RequiredConsentsNotSigned` (412). See [Get Consents](/api-reference/checkout/get-consents) and [Set Consents](/api-reference/checkout/set-consents). ### Encrypt payment + complete order (Phase 4 ends) Get the payment public key, JWE-encrypt the card, then submit. Branded Commerce checkout supports card via JWE encryption, Click to Pay (Visa/Mastercard), and PayPal as live payment methods; Google Pay is planned. Pick what aligns with the partner's audience. Payment calls go to the `cc.firmly.work` host, not the `api.firmly.work` host every prior call used — the payment surface is served from its own hostname. ```bash curl -X POST https://cc.firmly.work/api/v2/payment/domains/staging.luma.gift/complete-order \ -H "x-firmly-authorization: $TOKEN" \ -H "Idempotency-Key: $(uuidgen)" \ -H "Content-Type: application/json" \ -d '{ "encrypted_card": "eyJh...", "billing_info": { ... } }' ``` **Why `complete-order` and not `place-order`?** The cart was built over the previous calls (add line item → shipping info → shipping method → consents), so `complete-order` finalizes that **existing** cart — the body carries only `encrypted_card` and `billing_info` (shipping was already set earlier). Use [`place-order`](/api-reference/payment/place-order-v2) instead only for the **one-shot** path: it creates a cart *and* places the order in a single call, and requires an `items[]` array plus `shipping_info` because there's no prior cart to finalize. Verify the request body against [Complete Order](/api-reference/payment/complete-order-v2). Response includes `cart_status: "submitted"`, `cart_id`, and `urls.order_status_page` for the branded thank-you page. The merchant's native order number is returned as `platform_order_number`. **Attribution note:** Pass UTM params and ad-click IDs (`fbclid`, `gclid`, etc.) in the order metadata so the merchant's downstream attribution reporting can reconcile. See [Partner Onboarding → Attribution metadata fields](/solutions/branded-commerce/operations/partner-onboarding#attribution-metadata-fields) for the fields the merchant expects. ### Render branded thank-you page Firmly's scope ends at order placement. The branded thank-you page typically: - Confirms the order with the merchant's order number from `platform_order_number` - Maintains the partner's brand identity (logo, colors, copy) - Links to the merchant's own order status or support if the buyer needs post-order help Anything post-order — tracking, returns, refunds — lives in the merchant's native OMS. The buyer contacts the merchant directly through the merchant's existing channels. ## What can go wrong at each step | Step | Most common failure | Recovery | |---|---|---| | Discover | Empty results, `StoreUnavailable`, `DomainNotFound` | Check domain spelling, confirm merchant is enabled for Branded | | Add to cart | `ProductNotFound`, `NotEnoughStockError` (409) | Re-fetch product or surface "out of stock" on the branded page | | Set shipping | `InvalidInputBody` (400) | Validate address fields client-side first | | Shipping methods | No methods returned | Address may not be deliverable — ask buyer for an alternative | | Place order | `CreditCardDeclined` (422), `NotEnoughStockError` (race with another buyer) | Offer alternative payment, or re-quote with new stock | See [Errors & Conventions](/api-reference/errors-and-conventions) for the full catalog and the exact PascalCase error names. ## Attribution — keeping the partner's identity intact The Branded Commerce flow's identity is the partner's brand on the front end, the merchant's order on the back end, and **attribution data flowing both ways** so reporting reconciles correctly. | Data | Direction | Why | |---|---|---| | UTM params (`utm_source`, `utm_campaign`, `utm_content`) | Ad click → branded page → order metadata → merchant OMS | Lets the merchant's own attribution reports reflect partner-driven orders | | Click IDs (`fbclid`, `gclid`, `ttclid`, etc.) | Ad click → branded page → order metadata → ad platform postback | Allows the ad platform to credit the conversion | | Partner identifier | Branded page session → Firmly's attribution service → merchant OMS | Lets the merchant see "orders from Partner X" without manual reconciliation | Pass-through is automatic when the partner page sets these on the cart session. See [Partner Onboarding → Attribution metadata fields](/solutions/branded-commerce/operations/partner-onboarding#attribution-metadata-fields) for the field mapping. ## What's in a cart response Every cart-mutation endpoint returns the **full cart object** in the response, so the partner's page doesn't have to re-fetch. The shape is identical across all Firmly solutions — see [Cart Lifecycle](/api-reference/cart-management/cart-lifecycle) for the full field reference. ## Runnable end-to-end The [Advanced Checkout Guide](/cookbook/advanced-checkout-guide) is the same multi-step `/api/v2` sequence as a complete Node script you can run today. Start there if you want working code, return here for the conceptual walkthrough framed for Branded Commerce. --- ## Related - [Buyer Purchase Flow](/solutions/branded-commerce/flows/buyer-purchase-flow) — the ad → PDP → checkout → thank-you walkthrough from the buyer's point of view - [Multi-Product Purchase](/solutions/branded-commerce/flows/multi-product-purchase) — multiple items in one branded cart - [Why Firmly for Branded Commerce](/solutions/branded-commerce/why-firmly) — what makes Branded Commerce different - [Operations](/solutions/branded-commerce/operations/) — onboarding partners, dashboard, operational workflow --- # Single Product Purchase > **Note** > This is an **annotated flow** — the buyer experience alongside the API calls the marketplace operator's UI makes. The underlying API sequence is the shared Firmly cart flow — identical to [Agentic Commerce → Single Product Purchase](/solutions/agentic-commerce/flows/single-product-purchase), which has the full curl-by-curl walkthrough and the cart-response field reference. This page covers only what's specific to Marketplace: the operator-owned surface, discovery across merchants, and operator attribution. ## The five phases, Marketplace framing | Phase | What happens | |---|---| | **1. Hosting** | The marketplace operator's own UI — their domain, their brand | | **2. Authentication** | `POST /api/v1/browser-session` (or use [server-to-server auth](/for-destinations/authentication) directly) | | **3. Discovery** | The operator's search calls `POST /api/v1/discovery/search`; results span the operator's merchant set, each with a `domain` identifying its source merchant | | **4. Checkout** | The shared cart → shipping → payment → complete-order sequence, rendered in the operator's UI | | **5. Order placement** | Order lands in the source merchant's OMS with marketplace-operator attribution | ## Sequence diagram ```mermaid sequenceDiagram autonumber participant U as Buyer participant O as Marketplace Operator UI participant F as Firmly API participant M as Merchant U->>O: Search "black hoodie" O->>F: POST /browser-session F-->>O: { access_token } O->>F: POST /discovery/search F-->>O: products[] (across many merchants) O->>U: Show marketplace search results U->>O: Click listing → operator-rendered PDP U->>O: Click Buy O->>F: POST /cart/line-items F-->>O: { cart } O->>U: Operator-branded checkout page U->>O: Fill shipping address O->>F: POST /cart/shipping-info F-->>O: { cart with shipments + shipping_method_options } opt Scheduled delivery / pickup O->>F: POST /cart/shipments/get-availability F-->>O: { delivery dates / time slots } end O->>F: POST /cart/shipment/methods F-->>O: { cart } U->>O: Enter card O->>F: GET /payment/key F-->>O: { JWK } Note over O: JWE-encrypt card O->>F: POST /payment/complete-order (Idempotency-Key) F->>M: place order with marketplace-operator metadata M-->>F: merchant order # F-->>O: { cart_status: "submitted", cart_id, urls, custom_properties } O->>U: Marketplace-branded confirmation Note over O: Firmly's scope ends here.
Post-order belongs to the source merchant. ``` ## What's specific to Marketplace - **Discovery spans merchants.** `discovery/search` returns products across every merchant the operator's App ID can reach; each product carries a `domain` field, and the operator's UI typically shows merchant identity alongside the listing. - **The cart is scoped to the listing's source merchant** — the `{domain}` in the cart endpoint URL comes from the product the buyer picked. - **Operator-branded confirmation.** The operator's confirmation page shows the merchant's native order identifier under the marketplace's brand, and links to the merchant's order status for post-order detail. Anything post-order — tracking, returns, refunds — lives with the source merchant. ## Attribution What defines the Marketplace flow is **the marketplace operator as the traffic source** while the source merchant retains the seller-of-record relationship with the buyer. | Data | Direction | Why | |---|---|---| | Marketplace operator ID | Operator UI session → order metadata → merchant OMS | Lets the merchant see "orders from Operator X" | | Per-listing source merchant | Discovery response → cart `{domain}` | Each product carries its source merchant | | Order completion event | Complete-order response → operator's own reporting | Operator's marketplace analytics | > **Note** > The operator ID is tied to the operator's App ID rather than set per call, and it is written into the order metadata that the merchant's OMS receives. The exact metadata field name depends on the merchant's platform and is confirmed during onboarding — coordinate the concrete field with your Firmly contact before relying on it for reconciliation. ## What can go wrong Because a marketplace surface aggregates many merchants, the most common failures show up at discovery: | Step | Failure | What it means for the operator | |---|---|---| | Discover | `StoreUnavailable` / `DomainNotFound` | A listing points at a merchant that isn't enabled for the operator's surface, or the domain is wrong — hide or refresh the listing | | Discover | `404 ucp_disabled` (UCP layer only) | The merchant isn't enabled for agentic/UCP traffic on this surface — remove it from marketplace search until enabled | | Add to cart | `ProductNotFound`, `NotEnoughStockError` (409) | The listing is stale — re-fetch the product or mark it out of stock | | Place order | `CreditCardDeclined` (422) | Payment failed — let the buyer retry with another method | See [Errors & Conventions](/api-reference/errors-and-conventions) for the full catalog and exact error names, or the [For Destinations troubleshooting](/troubleshooting/common-issues) table. ## The shared cart sequence The add-to-cart, shipping, and order-completion calls are identical across solutions, including the usual checkout tail (set shipping method → get/set consents → billing → payment key → complete order). Because the cart is built across those calls, the tail finalizes with [`complete-order`](/api-reference/payment/complete-order-v2) (existing cart), not the one-shot `place-order`. Follow [Agentic Commerce → Single Product Purchase](/solutions/agentic-commerce/flows/single-product-purchase) for the step-by-step and the cart-response field reference, or the [Advanced Checkout Guide](/cookbook/advanced-checkout-guide) for a runnable script. --- ## Related - [Multi-Product Purchase](/solutions/marketplace/flows/multi-product-purchase) — cart with multiple items from one merchant - [Why Firmly](/solutions/marketplace/why-firmly) — what makes Marketplace different - [Integration Patterns](/solutions/marketplace/integration-patterns/) — operator-hosted vs embedded --- # Single Product Purchase > **Note** > This is an **annotated flow** — the reader experience alongside the API calls the publisher's surface makes. The underlying API sequence is the shared Firmly cart flow — identical to [Agentic Commerce → Single Product Purchase](/solutions/agentic-commerce/flows/single-product-purchase), which has the full curl-by-curl walkthrough. This page covers only what's specific to Publisher Commerce: in-context checkout, a Buy Now button that encodes the SKU, and publisher/affiliate attribution. ## The five phases, Publisher-Commerce framing | Phase | What happens | |---|---| | **1. Hosting** | Where checkout renders: the publisher's site or article surface | | **2. Authentication** | `POST /api/v1/browser-session` (or use [server-to-server auth](/for-destinations/authentication) directly) | | **3. Discovery** | The Buy Now button encodes the SKU via the [Embedded Buy Button](/solutions/publisher-commerce/integration-patterns/embedded-buy-button) embed — usually no live `discovery/search` call | | **4. Checkout** | The shared cart → shipping → payment → complete-order sequence, rendered inline on the article | | **5. Order placement** | Order lands in the merchant's OMS with publisher attribution | ## Sequence diagram ```mermaid sequenceDiagram autonumber participant R as Reader participant P as Publisher Article participant F as Firmly API participant M as Merchant R->>P: Read article Note over P: UTM + publisher ID captured from page context P->>F: POST /browser-session F-->>P: { access_token } R->>P: Click Buy Now button P->>F: POST /cart/line-items F-->>P: { cart } P->>R: Render in-context checkout (slide-in or inline panel) R->>P: Fill shipping address P->>F: POST /cart/shipping-info F-->>P: { cart with shipments + shipping_method_options } opt Scheduled delivery / pickup P->>F: POST /cart/shipments/get-availability F-->>P: { delivery dates / time slots } end P->>F: POST /cart/shipment/methods F-->>P: { cart } R->>P: Enter card or click PayPal / Google Pay P->>F: GET /payment/key F-->>P: { JWK } Note over P: JWE-encrypt card P->>F: POST /payment/complete-order (Idempotency-Key) F->>M: place order with publisher attribution M-->>F: merchant order # F-->>P: { cart_status: "submitted", cart_id, urls, custom_properties } P->>R: Inline confirmation, reader stays on article Note over P: Firmly's scope ends here.
Post-order belongs to the merchant. ``` > **Note** > The two shipping paths use different segments on purpose: availability is `POST /cart/shipments/get-availability` (plural `shipments`) and recording the choice is `POST /cart/shipment/methods` (singular `shipment`). Both are correct — match the exact spelling in the API reference. ## What's specific to Publisher Commerce - **In-context checkout.** Checkout renders inline or in a slide-in panel on the article — the reader never leaves the page. After `complete-order`, a compact inline confirmation shows the merchant order ID; the reader closes the panel and keeps reading. - **The embed encodes the SKU.** The Buy Now button names the product at content-publish time, so add-to-cart can skip discovery. - **Postal-code pre-warm (optimization).** Pre-set the postal code from the reader's geo IP via [Set Postal Code](/api-reference/session/set-postal-code) so the merchant's shipping rates are pre-warmed by the time the full address is submitted. ## Attribution — article-to-conversion What defines the Publisher Commerce flow is **the article as the surface that drove discovery and the publisher as the traffic source**. | Data | Direction | Why | |---|---|---| | UTM params (`utm_source`, `utm_campaign`, `utm_content`) | Page context → cart session → order metadata → merchant OMS | Merchant attribution reports credit the publisher | | Publisher identifier | Page context → cart session → Firmly attribution → merchant OMS | "Orders from Publisher X" without manual reconciliation | | Article identifier | Page context → cart session → publisher's own analytics | Publisher knows which articles drove orders | | Affiliate commission posting | Order placement → Firmly affiliate service → publisher's payout system | Publisher gets paid the commission | > **Note** > Attribution is set on the cart session with [Set Cart Attribution](/api-reference/cart-management/set-attribution) (`PUT .../cart/attribution`), called after add-to-cart and before checkout. It carries four optional string fields — `utm`, `referrer_url`, `referral_code`, and `landing_page` — which ride through to the merchant's order metadata. Map the data model above onto them: put the campaign query string in `utm`, the publisher identifier in `referral_code`, the referring article URL in `referrer_url`, and the landing URL in `landing_page`. The article identifier can be encoded into the `utm` string (e.g. `utm_content=article-123`) or the URLs. Firmly-managed affiliate commission posting is configured separately during onboarding. ## The shared cart sequence The add-to-cart, shipping, and order-completion calls are identical across solutions, including the usual checkout tail (set shipping method → get/set consents → billing → payment key → complete order). Because the cart is built across those calls, the tail finalizes with [`complete-order`](/api-reference/payment/complete-order-v2) (existing cart), not the one-shot `place-order`. Follow [Agentic Commerce → Single Product Purchase](/solutions/agentic-commerce/flows/single-product-purchase) for the step-by-step, or the [Advanced Checkout Guide](/cookbook/advanced-checkout-guide) for a runnable script. --- ## Related - [Multi-Product Purchase](/solutions/publisher-commerce/flows/multi-product-purchase) — multiple items in one in-context cart - [Why Firmly](/solutions/publisher-commerce/why-firmly) — what makes Publisher Commerce different - [Integration Patterns](/solutions/publisher-commerce/integration-patterns/) — embed component vs separate landing options --- # Single-product Deal > **Note** > This is one common pattern partners build with Branded Commerce. Many other shapes are possible — adapt or combine use cases to fit your specific campaign. The partner runs an ad promoting one specific product deal — e.g., *"Save 20% on the Radiant Tee with code SAVE20"*. The buyer taps the ad, lands directly on the product detail page on the partner's domain, and completes checkout — all without leaving the partner's surface. There is no category browsing step. The ad links straight to a PDP. ## What the buyer sees ### 1. Ad click A paid ad (social, search, display, retail-media, or QR-code-driven) carrying the deal message and a CTA. The ad links to a URL on the partner's domain with the product and promo code embedded: ```text https://deals.partner.example/buy/?promo=SAVE20 ``` The promo code is auto-applied — the buyer does not need to enter it manually. ### 2. PDP — full page A full-page, partner-branded product detail page. Not a slide-out — the entire page is hosted on the partner's domain. **Header (two-part):** 1. **Partner header** — partner branding (logo, name) plus a "Powered by Firmly" attribution. A back arrow returns to the referring page. 2. **Merchant identity** — *"You are shopping with [Merchant]"* with the merchant's domain. **Product content:** - Product images with thumbnail navigation - Product name - Promotional pricing — discounted price prominently, original price with strikethrough, savings callout ("Save $20"), promo reference ("with code SAVE20") - Product description (full merchant description) - Variant selectors — size, color, or other variants with prices per variant - Quantity selector - Key benefits — bullet list with checkmarks **Two CTAs at the bottom:** 1. **BUY NOW FROM [MERCHANT]** *(primary, solid)* — proceeds to checkout 2. **VISIT [MERCHANT].COM** *(secondary, outlined)* — redirects to the merchant's product page on their own site. Affiliate parameters are preserved in the redirect URL — the partner still earns commission. The promo code from the ad is visible throughout the PDP — in the pricing section and as a banner below the header. ### 3. Checkout — full page After the buyer taps **BUY NOW**, a full-page partner-branded checkout replaces the PDP. **Header** — same two-part structure: partner branding plus *"You are checking out with [Merchant]"*. **Order summary** — collapsible section showing the product name and total price; expanding reveals full product details, promo confirmation, subtotal, shipping, tax, discount, and total due today. **Express checkout** — wallet options available alongside standard card entry: - Click to Pay (Visa/Mastercard) — live - PayPal — live - Google Pay — planned Clicking an express option skips address and payment entry — the wallet returns both a shipping address and payment authorization. **Standard form** (when not using an express wallet): - Email — with a Click to Pay consent notice below the field - Shipping address — name, address fields, city, ZIP, state, phone - Shipping method — available options with prices and a *Change* link - Payment — card number, MM/YY, CVV. Billing-address-same-as-shipping checkbox defaults to checked - Order summary at the bottom with the full breakdown **Place order** — the buyer taps **PLACE ORDER**. A legal footer links to the partner's and merchant's terms and to Firmly's privacy policy; the full list of documents surfaced at checkout is under [Pre-purchase disclosure](#pre-purchase-disclosure) below. **Payment failure** — if payment fails (e.g., card declined), the error displays inline on the same page: - Error banner with the failure reason - Card field highlighted red with inline error text - **TRY AGAIN** *(primary)* — buyer corrects and retries - **VISIT [MERCHANT].COM** *(secondary)* — redirects to the merchant's site with affiliate parameters preserved ### 4. Thank-you page After order placement, the checkout transitions to a thank-you page under the same partner branding. - **Success indicator** — confirmation heading - **Merchant confirmation notice** — *"[Merchant] will send the order confirmation"* - **Savings callout** — *"You just saved $[amount] with [Partner]! Coupon SAVE20 was applied to your order"* - **Order details** — merchant name, order number from the merchant, order total, payment method (card type + last 4), email, shipping-to address, shipping method + estimated delivery - **Merchant links** — Contact, Returns, Terms — pointing to the merchant's own pages so the buyer can reach the merchant directly after the order - **Footer** — *"Powered by Firmly"* plus Terms and Privacy links ## What the partner owns vs. what Firmly handles | | Partner | Firmly | |---|---|---| | Ad creative + ad-platform setup | ✓ | — | | Brand assets (logo, colors, fonts) | ✓ | Applies to all pages | | Domain (e.g., `deals.partner.example`) | DNS CNAME | TLS via Cloudflare for SaaS | | Legal text (T&C, privacy, disclaimers) | ✓ | Renders on pages | | Product selection + promo configuration | ✓ | Resolves and configures | | Live product data fetch | — | Via merchant platform adapter | | Cart, shipping, tax, payment orchestration | — | ✓ | | Affiliate attribution + conversion posting | Network credentials (BYO) or delegates | Executes | | Ad-platform conversion signals | Pixel IDs | Fires (Meta CAPI, Google Ads, TikTok, etc.) | ## Performance tracking **Affiliate attribution** is preserved from ad click through order confirmation. The partner earns commission on every completed purchase, in either BYO or Firmly-managed mode. **Ad conversion signals** fire to the originating ad platform after order confirmation — Meta CAPI, Google Ads Enhanced Conversions, TikTok / Pinterest / Snap / Reddit Conversions APIs — using the partner's pixel IDs and click context stored at entry. > **Note** > **ROAS tracking covers Firmly-hosted conversions only.** When a buyer clicks **VISIT [MERCHANT].COM** and completes the purchase on the merchant's own site, the affiliate commission is still tracked (via the affiliate redirect), but ad ROAS is not — Firmly can only fire the partner's ad pixels on pages it hosts. ## Pre-purchase disclosure The partner's T&C + privacy policy plus the merchant's T&C are both displayed at checkout — see [Consent & Disclosure](/solutions/agentic-commerce/consent-and-disclosure) for the broader pattern of what to surface before order placement. --- ## Related - [Curated landing page](/solutions/branded-commerce/use-cases/curated-landing-page) — the multi-product variant - [Buyer purchase flow](/solutions/branded-commerce/flows/buyer-purchase-flow) — the full sequence diagrammed - [Operations → Operational workflow](/solutions/branded-commerce/operations/operational-workflow) — per-product setup - [Integration Patterns](/solutions/branded-commerce/integration-patterns/) --- # Smart Gifting & Occasion Shopping > **Note** > This is one common pattern customers build with Firmly. Many other shapes are possible — adapt or combine use cases to fit your specific build. The user wants to send a gift — *"a birthday gift for my mom under $75, with gift wrap, by Friday"*. The agent searches across merchants, picks an item that matches the budget and occasion, adds gift wrap as an addon, optionally bundles a digital gift card, sets the recipient's address, and completes checkout via the user's express wallet. This is the **single richest scenario** in terms of Firmly capabilities touched in one flow: discovery, addons, gift card line items, recipient address, and express checkout. ## Recommended setup | Choice | Default | Why | |---|---|---| | **Integration pattern** | [Embedded checkout](/solutions/agentic-commerce/integration-patterns/embedded-checkout) | Wallet sheet handoff (Google Pay) needs an iframe context | | **Protocol** | MCP or direct REST | MCP tools cover the discovery + cart + addon flow natively | | **Flow shape** | Single- or multi-product depending on bundle | A standalone gift = single; gift + gift card = multi | ## API sequence | # | Endpoint | Purpose | |---|---|---| | 1 | [Browser session](/api-reference/authentication/browser-session) | Auth | | 2 | [Discovery search](/api-reference/discovery/search) | Find gift candidates matching budget + occasion | | 3 | [Get product](/api-reference/catalog/get-product) | Variants + check that addons (e.g., gift wrap) are offered | | 4 | [Add line item](/api-reference/cart-management/add-line-item) | Add the gift | | 5 | [Add addon](/api-reference/addon-management/add-addon) | Add gift wrap, gift message, warranty, or other addon the merchant offers | | 6 | *(optional)* [Add line item](/api-reference/cart-management/add-line-item) | Add a digital gift card as a separate line item | | 7 | [Set shipping info](/api-reference/checkout/set-shipping-info) | **Recipient's** address, not the user's; populates `shipments` with `shipping_method_options` | | 8 | [Get shipping availability](/api-reference/shipment-configuration/get-availability) | *(Optional)* Delivery dates / time slots / pickup locations | | 9 | [Set shipping method](/api-reference/shipment-configuration/set-shipping-method) | Pick a method from the shipment's `shipping_method_options` (often expedited for occasions) | | 10 (conditional) | [Get consents](/api-reference/checkout/get-consents) → [Set consents](/api-reference/checkout/set-consents) | If the merchant requires consents; skipping them makes `complete-order` return `RequiredConsentsNotSigned` (412) | | 11 | [Set billing info](/api-reference/checkout/set-billing-info) | **Buyer's** billing address (often differs from shipping) | | 12 | Express checkout — Google Pay / PayPal / Click to Pay | Wallet handoff. See [Smart Payment Selection → Path B](/solutions/agentic-commerce/use-cases/smart-payment#path-b--express-wallet-google-pay--paypal--click-to-pay) for the express-wallet sequence | ## Key agent considerations - **Recipient ≠ buyer.** Shipping address is the recipient; billing address is the buyer's. The agent must collect both — and ask the user to confirm the recipient's address before placing the order. - **Gift wrap is merchant-specific.** Not every merchant offers it. Check `cart.addons.offers` for the available add-ons before promising the user gift wrap. - **Gift message length limits vary.** A gift message is carried as an addon property when the merchant's gift-wrap addon supports it — set it through the addon, not on the cart. See [Add addon](/api-reference/addon-management/add-addon) for the addon payload. Truncate cleanly if the user's message exceeds the merchant's limit. - **Delivery date promises.** "By Friday" is a shipping-method choice plus the merchant's processing time. Don't promise a date based on shipping speed alone — confirm against the merchant's lead time. - **Gift cards.** A digital gift card is just another line item. Multi-product flow handles both physical + digital in one cart and one order — see [Wallet pass purchase](/solutions/agentic-commerce/recipes/wallet-pass-purchase). --- ## Related - [Addon management](/api-reference/addon-management/) — gift wrap, warranties - [Wallet pass purchase recipe](/solutions/agentic-commerce/recipes/wallet-pass-purchase) — digital pass / gift card pattern - [Smart payment selection](/solutions/agentic-commerce/use-cases/smart-payment) — wallet checkout paths - [Multi-product purchase flow](/solutions/agentic-commerce/flows/multi-product-purchase) — bundling gift + gift card --- # Smart Payment Selection Agent > **Note** > This is one common pattern customers build with Firmly. Many other shapes are possible — adapt or combine use cases to fit your specific build. The user reaches checkout and the agent picks the best payment method given the user's preferences and the cart context: a fresh card, an express wallet (Google Pay, PayPal, Click to Pay), Buy Now Pay Later (Klarna), a saved card, or Agentic Pay for autonomous purchases. The agent then runs the right sequence for the chosen path. This scenario covers the **breadth of Firmly's payment surface** in one flow. It's a strong fit for any destination that wants to differentiate on a frictionless payment experience. ## Recommended setup | Choice | Default | Why | |---|---|---| | **Integration pattern** | [Deep Link / Headless](/solutions/agentic-commerce/integration-patterns/deep-link) for full control; [Embedded](/solutions/agentic-commerce/integration-patterns/embedded-checkout) for native UI | Express wallets need a UI handoff (wallet sheets) — embedded covers that for free | | **Protocol** | Direct REST | Payment paths are payment-specific; protocol doesn't change the sequence | ## Payment paths Firmly supports five payment paths. The agent picks based on what the cart returns in `payment_method_options`. ### Path A — Card via encrypted JWE | # | Endpoint | Purpose | |---|---|---| | 1 | [Get payment public key](/api-reference/payment/get-public-key) | RSA public key | | 2 | *(client-side)* JWE-encrypt the card | Local — no network call | | 3 | [Complete order (v2)](/api-reference/payment/complete-order-v2) | Submit `encrypted_card` and finalize the existing cart | ### Path B — Express wallet (Google Pay / PayPal / Click to Pay) Express wallets carry their own authentication and tokenization. If you use the dropin (hosted or embedded), it handles the wallet sheet and runs the sequence below for you: - See [Hosted checkout](/solutions/agentic-commerce/integration-patterns/hosted-checkout) or [Embedded checkout](/solutions/agentic-commerce/integration-patterns/embedded-checkout) for the wallet handoff - After the wallet authorizes, order completion returns the finalized cart just like Path A, but with a wallet-tokenized payment reference instead of `encrypted_card` To run a wallet **headlessly** (no dropin), call the express-checkout endpoints directly. They are served from `api.firmly.work` at `/api/v1/domains/{domain}/express/{gateway}/…` — a different host from the card [Complete Order](/api-reference/payment/complete-order-v2) endpoint. The sequence differs per wallet. **Google Pay — single step.** No `start` or `authorize` call; place the order directly with the credentials from the Google Pay SDK. | # | Endpoint | Purpose | |---|---|---| | 1 | [Complete order — Google Pay](/api-reference/payment/express-checkout/google-pay/complete-order) | Place the order with the Google Pay credentials | Google Pay accepts three credential shapes (Aurus Pay references, the token flow, or the Braintree nonce flow) depending on the merchant's processor: a single `google_pay_token` (Stripe, Adyen) or a Braintree `nonce` with `email` and `google_pay_address`. Send exactly one shape. **PayPal — start → authorize → complete-order.** PayPal uses the same three-step express-checkout shape as Klarna (Path C), on the `/express/paypal/…` paths: create the session, confirm the buyer's `paypal_token` and `payer_id`, then place the order. As with Klarna, `complete-order` authorizes on its own if you pass the token and skip the explicit authorize step. | # | Call | Purpose | |---|---|---| | 1 | [Start PayPal](/api-reference/payment/express-checkout/paypal/start) | Open the PayPal session and get the EC token | | 2 | [Authorize PayPal](/api-reference/payment/express-checkout/paypal/authorize) | Record the buyer's approval (`paypal_token` + `payer_id`) — optional; step 3 authorizes on its own | | 3 | [Complete order — PayPal](/api-reference/payment/express-checkout/paypal/complete-order) | Place the order and charge the buyer | **Click to Pay** is not one of the express-checkout gateways (which cover Google Pay, PayPal, and Klarna). Click-to-Pay-style wallet credentials complete through [Wallet Complete Order](/api-reference/payment/wallet-complete-order) instead — the same endpoint the Agentic Pay path uses (see Path E). ### Path C — Klarna BNPL (pay in 4) | # | Endpoint | Purpose | |---|---|---| | 1 | [Start Klarna](/api-reference/payment/express-checkout/klarna/start) | Initialize the BNPL session | | 2 | [Authorize Klarna](/api-reference/payment/express-checkout/klarna/authorize) | User confirms terms; Klarna returns authorization | | 3 | [Complete order — Klarna](/api-reference/payment/express-checkout/klarna/complete-order) | Place the order against the merchant | ### Path D — Saved card (reused via Agentic Pay) When the user has a card they've used before, the agent reuses it without re-collecting the PAN. Saved-card reuse runs through [Agentic Pay](/solutions/agentic-commerce/agentic-pay): the card is enrolled once while the cardholder is present, and each later purchase calls [Select Card](/api-reference/agentic-pay/select-card) to reference the enrolled `virtual_card_id` — no fresh public key, no PAN re-entry. > **Note** > [Complete Order](/api-reference/payment/complete-order-v2) takes a fresh JWE-encrypted card (Path A); it has no separate saved-token field. Saved-card reuse therefore goes through Agentic Pay whether or not the cardholder is present. For **unattended / cardholder-not-present** purchases the network also requires a mandate, which Agentic Pay attaches at [Create Intent](/api-reference/agentic-pay/create-intent) — see Path E and [Autonomous Agent Purchasing](/solutions/agentic-commerce/use-cases/autonomous-agent-purchasing). ### Path E — Agentic Pay (network-token-routed) For autonomous agent purchasing (the user authorized the agent to buy without being present at transaction time) or biometric / passkey confirmation per purchase, use the [Agentic Pay](/solutions/agentic-commerce/agentic-pay) flow. The cardholder enrolls **once** via Firmly's Network Token Router; each subsequent payment runs `select-card → intent → complete` against the user's `virtual_card_id`, with mandate-based spending limits enforced at the network level. Enrollment is a one-time step (cardholder present): | # | Endpoint | Purpose | |---|---|---| | 1 | [Enroll](/api-reference/agentic-pay/enroll) | One-time card enrollment via the Network Token Router | Each payment then runs: | # | Endpoint | Purpose | |---|---|---| | 1 | [Select Card](/api-reference/agentic-pay/select-card) | Resolve the user's stored `virtual_card_id` — no PAN re-entry | | 2 | [Create Intent](/api-reference/agentic-pay/create-intent) | Authorize a specific payment intent (with mandate limits if autonomous) | | 3 | [Wallet Complete Order](/api-reference/payment/wallet-complete-order) | Place the order against the merchant | See the [Agentic Pay Integration Guide](/solutions/agentic-commerce/agentic-pay-integration) for the full sequence, including the iframe handshake and OTP/FIDO verification paths. ## Agent decision logic A simple decision tree the agent can apply: ```text if agent_acting_autonomously or biometric_per_purchase: use Path E (Agentic Pay) else if cart.total < user.bnpl_threshold and klarna_available: use Path C (Klarna) else if user.has_google_pay or user.has_paypal or user.has_click_to_pay: use Path B (express wallet) else if user.has_saved_card: use Path D (saved card) else: use Path A (fresh card via JWE) ``` The destination owns this decision logic. Firmly executes whichever path is chosen. --- ## Related - [Agentic Pay](/solutions/agentic-commerce/agentic-pay) — Network Token Router, mandate-based autonomous payment, biometric/passkey verification - [Autonomous Agent Purchasing](/solutions/agentic-commerce/use-cases/autonomous-agent-purchasing) — the destination-pattern view of mandate-based payment - [Get payment public key](/api-reference/payment/get-public-key) — public key, JWE encryption - [Express checkout (Klarna)](/api-reference/payment/express-checkout/klarna/start) — full Klarna sequence - [AI Shopping Copilot](/solutions/agentic-commerce/use-cases/shopping-copilot) — base discovery + cart flow - [Errors & conventions](/api-reference/errors-and-conventions) — `CreditCardDeclined` and related codes --- # Social commerce Firmly Social Commerce Checkout lets a shopper buy from a merchant site inside a social platform's in-app webview, without leaving the app. - [How JavaScript injection works](/solutions/social-commerce/js-injection) --- # Social platforms Social platforms are where commerce discovery happens through scrolling, sharing, and creator-driven recommendation rather than search or editorial. The destination is the social surface itself: an in-feed product card, a messaging thread that includes a buyable link, a creator-promoted product, a shop tab inside a social app. The Firmly platform supports social-driven commerce so the buyer can complete a purchase without leaving the social context. ## What this category covers Social platforms as a destination category includes: | Type | What it does | |---|---| | **In-feed shoppable content** | Product cards rendered inline with social posts, with checkout completing in the social surface or a partner-branded surface | | **Messaging-driven commerce** | Buyable links shared in DMs and group chats, with purchase completing in-thread | | **Creator-driven commerce** | Influencer and creator product placements where purchase happens without leaving the creator's surface | | **Social shop tabs** | Dedicated commerce surfaces inside a social platform | ## Why social platforms are a Firmly destination Social-driven commerce introduces challenges that Firmly's existing platform solves: - **Continuity of context** — leaving the social surface to complete a purchase typically loses the discovery context; in-surface or partner-branded checkout preserves it. - **Creator attribution** — when a creator drives the purchase, attribution back to the creator (for revenue share) requires the same affiliate infrastructure as publisher attribution. - **Multi-merchant inventory** — creators recommend across many merchants; one Firmly integration reaches all of them, with no per-merchant build on the social platform's side. - **Compliance and disclosure** — sponsored social content has specific disclosure requirements; pre-purchase consent UX is documented under [Consent & Disclosure](/solutions/agentic-commerce/consent-and-disclosure). ## Which Firmly solutions apply | Solution | When to use it | |---|---| | **[Branded Commerce](/solutions/branded-commerce/)** | When the social surface routes to a partner-branded checkout under the social platform's or creator's domain. | | **[Publisher Commerce](/solutions/publisher-commerce/)** | When creator-driven commerce sits on top of editorial-style content with affiliate economics. | | **[Ad Commerce](/solutions/ad-commerce/)** | When commerce is driven from paid social placements. | ## Status today Social platforms are on the Firmly roadmap as a dedicated destination category. The underlying platform infrastructure (cart, checkout, attribution, creator-revenue routing) is in production and used by adjacent categories. Social-specific buildout — including per-platform integration patterns, creator-attribution flows, and disclosure UX — depends on partner demand and is scoped during onboarding. ## What to think about - **Attribution flow.** Social attribution often involves both an ad-platform pixel and a creator-revenue split. Both need to fire correctly. - **Cross-app handoff.** Many social commerce flows hand off to a mobile browser for the final step; carrying cart state and click context through the handoff is essential. - **Creator economics.** When creators drive purchases, the revenue split needs to be deterministic and visible. --- ## Related - [Branded Commerce overview](/solutions/branded-commerce/) - [Publisher Commerce overview](/solutions/publisher-commerce/) - [Ad Commerce overview](/solutions/ad-commerce/) - [Consent & Disclosure](/solutions/agentic-commerce/consent-and-disclosure) --- # Solutions Firmly powers commerce across five destination-side surfaces, plus **Firmly Connect** — the merchant-side control panel. Each solution combines the same core platform — catalog, cart, checkout, orders, wallet — assembled differently to fit the context. Same auth, same APIs; a solution is how you *frame* the integration, not a separate build. Not sure which one is you? Jump to [Find your fit](#find-your-fit). - [Agentic Commerce](/solutions/agentic-commerce/) — Enable AI agents, chatbots, and wallets to complete purchases on behalf of users - [Publisher Commerce](/solutions/publisher-commerce/) — Monetize editorial and content surfaces with embedded commerce - [Ad Commerce](/solutions/ad-commerce/) — Turn ads into shoppable, checkout-capable experiences - [Marketplace](/solutions/marketplace/) — Search across many merchants in one branded surface; single-merchant checkout - [Branded Commerce](/solutions/branded-commerce/) — White-labeled checkout on the partner's own domain — from ad click to order without leaving the partner's brand - [Firmly Connect](/solutions/firmly-connect/) — The merchant-side control panel — connect a store once and distribute to every destination on Firmly's network ## Find your fit
Pick whichever you already know — **your industry**, or **where the buyer sees the product**. Both land you on the same solution. ### By your industry | Industry | Primary solution | Common use cases | Why this fit | |---|---|---|---| | **Publishers & editorial** | [Publisher Commerce](/solutions/publisher-commerce/) | Shoppable Article, Curated Product Roundup | In-context buy-now buttons keep the reader on the article surface | | **Ad networks & shoppable ads** | [Ad Commerce](/solutions/ad-commerce/) | In-Feed Shoppable Ad, Post-Click Purchase | Click-ID + ad-platform postback are first-class concerns; payment-method emphasis depends on the ad surface | | **Marketplaces & multi-brand aggregators** | [Marketplace](/solutions/marketplace/) | Branded Marketplace | Operator aggregates many merchants into one branded surface; search spans merchants, each checkout is single-merchant | | **Branded & affiliate networks** | [Branded Commerce](/solutions/branded-commerce/) | Single-product deal, Curated landing page, Retail-media placement | White-labeled partner-branded pages with UTM + partner attribution | | **Wallets, banks & connected devices** | [Agentic Commerce](/solutions/agentic-commerce/) + [Agentic Pay](/solutions/agentic-commerce/agentic-pay) | Scheduled Buying, Autonomous Agent Purchasing | Cardholder-not-present scenarios require Agentic Pay for mandate-based payment | | **AI assistants & search** | [Agentic Commerce](/solutions/agentic-commerce/) | Shopping Copilot, Smart Payment, Smart Gifting | Conversational discovery + multi-turn cart review fit the agentic flow naturally | | **A merchant connecting your store** | [Firmly Connect](/solutions/firmly-connect/) | Catalog scope + destination opt-ins | Make your store reachable to every destination on Firmly's network, with one connection | ### By where the buyer sees it The [destination surface](/solutions/destination-surfaces/) — where the buyer actually encounters the product — maps to a solution too: | Buyer surface | Solution | Status today | |---|---|---| | [Publisher sites](/solutions/destination-surfaces/publisher-sites) | Publisher Commerce | Available | | [Ads](/solutions/destination-surfaces/ads) | Ad Commerce | Emerging | | [AI surfaces](/solutions/destination-surfaces/ai-surfaces) | Agentic Commerce | Available | | [Social platforms](/solutions/destination-surfaces/social-platforms) | — | Roadmap | | [Connected TV](/solutions/destination-surfaces/ctv) | — | Roadmap | See [Destination surfaces](/solutions/destination-surfaces/) for what each category supports today and what's on the roadmap. ## When you span more than one Some products legitimately use several solutions. A few common patterns: - **A publisher that also runs ad campaigns** — Publisher Commerce for the editorial articles + Ad Commerce for the campaign creatives. Same App ID, different integration patterns. - **A marketplace with branded landing pages** — Marketplace for the aggregated multi-merchant storefront + Branded Commerce for the high-conversion deal pages. - **An AI shopping copilot embedded in a banking app** — Agentic Commerce for the conversational discovery + Agentic Pay for the cardholder-not-present payment. The good news: **Firmly's API surface is universal.** Same auth, same cart, same checkout, same order placement. Solutions are how the docs frame the *narrative* around the same APIs — they don't require separate integrations. If your industry isn't listed exactly, pick the closest one — the use cases are starting points to adapt. [Contact Firmly](/contact) for industry-specific guidance. - [Social commerce](/solutions/social-commerce/index.md) --- # Team management The surface where the merchant manages who has access to their dashboard and at what permission level. Owners can invite new teammates, change their roles, remove them, and transfer primary ownership. Pending invitations are listed alongside current members so the merchant can see at a glance who has been invited but not yet joined. ## Role hierarchy From highest to lowest privilege: | Role | Permissions | Per-merchant count | |---|---|---| | **Primary Owner** | Full access, team management, **only role that can transfer ownership** | Exactly one | | **Owner** | Full access + team management (within the rules below) | Unlimited | | **Editor** | Edit settings and most operational data | Unlimited | | **Viewer** | Read-only access | Unlimited | Plus **Firmly admins** can do all of the above regardless of their own merchant role. ## Role-gated actions The rules below are enforced both in the UI (buttons hidden / disabled) and on the server: | Action | Who can do it | |---|---| | Invite new members | Owner, Primary Owner, Firmly admin | | Change roles | Owner, Primary Owner, Firmly admin (within their own level) | | Remove members | Owner, Primary Owner, Firmly admin | | Transfer ownership | **Only the current Primary Owner** | | Cancel a pending invitation | Owner, Primary Owner, Firmly admin | Editors and Viewers cannot invite or manage members. ## Inviting a member Clicking **Invite Member** opens a dialog that collects: - Invitee's email - Role to grant (Owner / Editor / Viewer) Primary Owner is **not** an invitable role — there is exactly one per merchant, and it only changes via [ownership transfer](#ownership-transfer). Submitting the form creates a pending invitation and dispatches the invitation email. The table refreshes to show the new pending row. The invitee-facing flow works like this: the invitation goes to the invitee's email and links to an invitation confirmation card. An existing Firmly user accepts in one click; a brand-new user is walked through profile creation before accepting. ## Pending invitations Pending invitations render alongside accepted members in the same table, marked with a "pending" status. Each pending row shows: - Invitee email - Role they're invited as - Who invited them - When the link expires Owners can cancel a pending invitation from the row action menu. ## Per-member row actions Row actions appear only for members whose role is **below the current user's**. Within those rows, a user can promote a member up to (but not above) their own level: | Action | What it does | |---|---| | **Change Role** | Opens a dialog that allows promoting / demoting to any role at or below the current user's level | | **Remove Member** | Opens a confirmation dialog that explicitly states the user will lose access immediately | So an Owner manages Editors and Viewers and can promote one up to Owner (their own level), but Owners don't see row actions on other Owners. ## Ownership transfer Only the current Primary Owner sees the **Transfer Ownership** action. The confirmation dialog is intentionally heavy — it states that: - The current Primary Owner becomes an Owner - The chosen member becomes the new Primary Owner - The change is logged in the audit trail ## Self-management guardrails - A user **cannot change their own role** from this page - A Primary Owner **cannot remove themselves** — they must transfer ownership first These constraints ensure a merchant account always retains a Primary Owner who can perform owner-level operations. ## Audit trail Every team action (invite, accept, role change, removal, ownership transfer, invite cancellation) writes a typed event to the [Audit logs](/solutions/firmly-connect/portal/audit-logs) with the actor's email recorded. --- ## Related - [Audit logs](/solutions/firmly-connect/portal/audit-logs) - [Domains and SSO](/solutions/firmly-connect/portal/domains-and-sso) — SSO enforcement affects how team members sign in - [Portal overview](/solutions/firmly-connect/portal/) --- # UCP Checkout Flow This page walks through how a purchase works through UCP — from the moment Google initiates a checkout to the moment the order is placed on the merchant's platform. ## Session model UCP uses a three-step checkout session lifecycle. Each step maps directly to Firmly's existing cart and checkout APIs: 1. **CreateCheckoutSession** — Google sends the product and user context. Firmly initializes a cart on the merchant's platform and returns session state. 2. **UpdateCheckoutSession** — Google sends shipping address, shipping method, or promo changes. Firmly updates the cart and returns new totals and available options. 3. **CompleteCheckoutSession** — Google sends payment authorization. Firmly tokenizes the payment, places the order on the merchant's platform, and returns confirmation. The user never leaves Google's surface during this flow. Google owns the UI; Firmly owns the commerce backend. ## Step 1 — Create session Google calls `POST /checkout-sessions` with line items and buyer context. Firmly: 1. Generates a `device_id` via `crypto.randomUUID()` (this becomes the session ID) 2. Calls `POST /api/v2/domains/{domain}/cart/line-items?flush_cart=false` to create the cart 3. Stores the session mapping in the session store 4. Returns the UCP-formatted session response The session starts in `incomplete` status — shipping address, shipping method, and buyer email are still missing. **Line item limitation**: cart contents are fixed at session creation. UCP does not allow adding, removing, or changing item quantities via the update endpoint. The user finalizes product selection on the Google AI surface before the checkout session begins. | Modifiable via Update? | Fields | |---|---| | Yes | Shipping address, shipping method, buyer info, payment instrument | | No | Line items, quantities | ## Step 2 — Update session Google calls `PUT /checkout-sessions/{id}` as the user fills in checkout details. The wrapper inspects which fields changed and routes to the appropriate Firmly APIs: | Field present | What Firmly does | |---|---| | `fulfillment.methods[].destinations[]` (with `selected_destination_id`) | Calls `POST /cart/shipping-info` — but only when the address is complete and differs from the last submitted address (see buffering below) | | `fulfillment.methods[].groups[].selected_option_id` | Calls `POST /cart/shipment/methods` with the `shipment_id` + `shipping_method_id` | | `discounts.codes` | Applies promo codes via `POST` / `DELETE /cart/promo-codes` (replacement semantics; an empty array clears all) | | `buyer` | Held in session state — used later during order completion | | `payment` | Held in session state — used later during order completion | **Shipping info buffering** — Google may send partial address updates as the user types. The wrapper buffers these in `pending_shipping_info` and only calls the shipping-info API when the address is complete and different from `submitted_shipping_info`. This avoids unnecessary backend calls during partial entry. ## Step 3 — Complete order Google calls `POST /checkout-sessions/{id}/complete` when the user confirms. Firmly: 1. Retrieves the session from the session store 2. Applies the stored buyer info and payment data 3. Calls `POST /api/v1/domains/{domain}/cart/complete-order` 4. Returns the UCP-formatted order confirmation The session transitions to `completed` — a terminal state. ## Session lifecycle Sessions progress through these states as the checkout advances: | Status | Meaning | |---|---| | `incomplete` | Initial state — missing required fields (buyer email, shipping address, or shipping method) | | `ready_for_complete` | All required fields present, ready for order completion | | `complete_in_progress` | Order completion is underway | | `completed` | Order successfully placed (terminal) | | `canceled` | Session explicitly canceled (terminal) | | `requires_escalation` | Needs human intervention | The session can move back from `ready_for_complete` to `incomplete` if a required field is removed (for example, the user clears the shipping address). Both `incomplete` and `ready_for_complete` can be canceled at any time. ## Discount support Discount codes are handled through the checkout session's update step (and can also be supplied at creation). Firmly maps UCP `discounts.codes` to the merchant's promo-code endpoints: | UCP operation | Firmly API | |---|---| | Apply / replace discount codes | `POST /api/v2/domains/{domain}/cart/promo-codes` | | Clear all discount codes | `DELETE /api/v2/domains/{domain}/cart/promo-codes` | | Get applied discounts | Included in the `GET /api/v2/domains/{domain}/cart` response (`coupons`) | `discounts.codes` uses replacement semantics: the submitted array replaces the currently applied set, and an empty array clears all codes. Codes are matched case-insensitively and de-duplicated; a strict superset of the current set is applied additively, and any other change is performed as a clear-and-re-add. A rejected code does not fail the update — Firmly returns the updated cart with a recoverable warning in `messages[]`. Rejection codes include `discount_code_invalid`, `discount_code_user_ineligible`, `discount_code_combination_disallowed`, and `discount_service_unavailable`. ## External references | Resource | Description | |---|---| | [UCP REST Binding](https://ucp.dev/specification/checkout-rest/) | REST API specification for the checkout session endpoints | | [Native Checkout Guide](https://developers.google.com/merchant/ucp/guides/checkout/native) | How native checkout works on Google's surfaces | | [Checkout Session Lifecycle](https://developers.google.com/merchant/ucp/guides/checkout/native/lifecycle) | Google's documentation on session states and transitions | | [Fulfillment & Shipping](https://developers.google.com/merchant/ucp/guides/checkout/native/fulfillment) | How shipping options and address collection work in UCP | --- ## Related - [UCP overview](/solutions/agentic-commerce/protocols/ucp/) — what UCP is and why Firmly implements it - [UCP implementation](/solutions/agentic-commerce/protocols/ucp/implementation) — service architecture, API mapping - [UCP security](/solutions/agentic-commerce/protocols/ucp/security) — how requests are authenticated and protected --- # UCP Implementation This page covers the build details of Firmly's UCP wrapper — service architecture, how UCP operations map to Firmly APIs, session state management, and the well-known manifest that Google uses for discovery. ## Service architecture The UCP wrapper is a Firmly edge service that sits between Google and Firmly's existing APIs. It translates UCP protocol requests into Firmly cart and checkout calls. | Component | Purpose | |---|---| | **Wrapper service** | Request routing, signature verification, API translation | | **Session store** | Session state mapping (UCP session ↔ Firmly cart), idempotency cache | | **Configuration** | Firmly API credentials, signing keys | Running at the edge gives low latency globally and DDoS protection, with the session store holding checkout session state. ## API mapping The wrapper translates each UCP operation to one or more Firmly API calls. All use V2 except order completion, which uses V1: | UCP Operation | Firmly API Call | |---|---| | Create session | `POST /api/v2/domains/{domain}/cart/line-items?flush_cart=false` | | Get session | `GET /api/v2/domains/{domain}/cart` | | Update shipping address | `POST /api/v2/domains/{domain}/cart/shipping-info` | | Update shipping method | `POST /api/v2/domains/{domain}/cart/shipment/methods` | | Apply / replace discount codes | `POST /api/v2/domains/{domain}/cart/promo-codes` | | Clear discount codes | `DELETE /api/v2/domains/{domain}/cart/promo-codes` | | Complete order (card / direct) | `POST /api/v1/domains/{domain}/cart/complete-order` | | Complete order (Google Pay) | `POST /api/v1/domains/{domain}/express/google-pay/complete-order` | | Cancel session | No carts-service call — the session status is flipped to `canceled` in the session store | Key details: - **`flush_cart=false`** — line items are added without clearing existing cart contents - **Shipping method** — requires a `shipment_id` from the cart response to select a method - **Discount codes** — `discounts.codes` uses replacement semantics; the promo-codes endpoint is additive, so removals are handled as a clear-and-re-add - **Cancel** — cancellation only flips the checkout session's status; it does not clear the backing cart - **Device ID = Session ID** — the UCP session ID is used as the Firmly device ID ### Session ID format The UCP session ID is a UUID generated by Firmly's UCP service. The same value identifies both the UCP checkout session and the underlying Firmly cart / device session, so the wrapper resolves the session against Firmly's cart layer without any additional mapping step. ```text 9cf76530-1344-420f-9ca6-c7a96fb6db45 ``` UCP clients pass this value back in the path of subsequent calls (`UpdateCheckoutSession`, `CompleteCheckoutSession`) to refer to the same session. ## Session state Each checkout session is held in the session store (the `ucp_sessions` KV namespace) under a `session:{sessionId}` key, and expires after 7 days: | Key pattern | Value | |---|---| | `session:{sessionId}` | `{ checkout_id, cart_id, domain, status, created_at, updated_at, expires_at, pending_shipping_info, submitted_shipping_info, selected_fulfillment_option_id }` | The session stores both the Firmly cart mapping and transient data that UCP needs but Firmly doesn't store natively — pending shipping info (for buffering partial address entry), the submitted shipping info, and the selected fulfillment option. The buyer's email is folded into the pending shipping info; the payment instrument is supplied on the complete call and is not held in session state. ### Idempotency handling Idempotency responses are stored **separately from session metadata**, in the same `ucp_sessions` KV namespace but under standalone keys of the form `idempotency:{operation}:{key}` — where `operation` is `create`, `update`, `complete`, or `cancel` (and the cart-resource equivalents `cart_create`, `cart_update`, `cart_cancel`). Each entry stores `{ response, fingerprint }`, where the fingerprint is derived from the request body. When a request arrives with an `Idempotency-Key` header: 1. Look up `idempotency:{operation}:{key}` 2. If found and the fingerprint matches, return the cached response immediately 3. If found but the fingerprint differs, reject with `409` (see [Idempotency](/solutions/agentic-commerce/protocols/ucp/idempotency)) 4. If not found, process the request and store the response Idempotency entries are honored for **24 hours** (see [Idempotency](/solutions/agentic-commerce/protocols/ucp/idempotency) for the canonical behavior). This prevents duplicate orders from network retries or agent errors. ## Internal service communication The UCP wrapper reaches Firmly's cart and checkout services over Firmly's internal network — traffic that never traverses the public internet, so no external integrator interacts with it. On each translated call the wrapper generates a `device_id` via `crypto.randomUUID()` (which doubles as the UCP `session_id`) and forwards it alongside the App ID. ## Well-known manifest Google discovers Firmly's UCP capabilities through a manifest served from the merchant's own domain at `/.well-known/ucp`. The merchant forwards that path to Firmly, and `api.firmly.work` is the origin that generates the manifest (see [UCP Configuration](/solutions/firmly-connect/portal/ucp-configuration) for how forwarding is set up): ```text GET https:///.well-known/ucp Accept: application/json ``` The manifest tells Google what checkout capabilities are available, which endpoints to call, how to process payments, and how to verify response signatures. The example below is the current default (`2026-04-08`) manifest, redacted: ```json { "ucp": { "version": "2026-04-08", "supported_versions": { "2026-01-11": "https://staging.luma.gift/.well-known/ucp/2026-01-11", "2026-01-23": "https://staging.luma.gift/.well-known/ucp/2026-01-23", "2026-04-08": "https://staging.luma.gift/.well-known/ucp/2026-04-08" }, "services": { "dev.ucp.shopping": [ { "version": "2026-04-08", "spec": "https://ucp.dev/2026-04-08/specification/overview", "transport": "rest", "schema": "https://ucp.dev/2026-04-08/services/shopping/rest.openapi.json", "endpoint": "https://api.firmly.work/api/2026-04-08/ucp/rest/domain/staging.luma.gift" }, { "version": "2026-04-08", "spec": "https://ucp.dev/2026-04-08/specification/overview", "transport": "mcp", "schema": "https://ucp.dev/2026-04-08/services/shopping/mcp.openrpc.json", "endpoint": "https://api.firmly.work/api/2026-04-08/ucp/mcp/domain/staging.luma.gift" } ] }, "capabilities": { "dev.ucp.shopping.cart": [ { "version": "2026-04-08", "spec": "https://ucp.dev/2026-04-08/specification/cart", "schema": "https://ucp.dev/2026-04-08/schemas/shopping/cart.json" } ], "dev.ucp.shopping.checkout": [ { "version": "2026-04-08", "spec": "https://ucp.dev/2026-04-08/specification/checkout", "schema": "https://ucp.dev/2026-04-08/schemas/shopping/checkout.json" } ], "dev.ucp.shopping.fulfillment": [ { "version": "2026-04-08", "spec": "https://ucp.dev/2026-04-08/specification/fulfillment", "schema": "https://ucp.dev/2026-04-08/schemas/shopping/fulfillment.json", "extends": "dev.ucp.shopping.checkout" } ], "dev.ucp.shopping.discount": [ { "version": "2026-04-08", "spec": "https://ucp.dev/2026-04-08/specification/discount", "schema": "https://ucp.dev/2026-04-08/schemas/shopping/discount.json", "extends": ["dev.ucp.shopping.cart", "dev.ucp.shopping.checkout"] } ], "dev.ucp.shopping.catalog.search": [ { "version": "2026-04-08", "spec": "https://ucp.dev/2026-04-08/specification/catalog/search", "schema": "https://ucp.dev/2026-04-08/schemas/shopping/catalog_search.json" } ], "dev.ucp.shopping.catalog.lookup": [ { "version": "2026-04-08", "spec": "https://ucp.dev/2026-04-08/specification/catalog/lookup", "schema": "https://ucp.dev/2026-04-08/schemas/shopping/catalog_lookup.json" } ] }, "payment_handlers": { "com.google.pay": [ { "id": "gpay", "version": "2026-01-23", "spec": "https://pay.google.com/gp/p/ucp/2026-01-23/", "config_schema": "https://pay.google.com/gp/p/ucp/2026-01-23/schemas/config.json", "instrument_schemas": ["https://pay.google.com/gp/p/ucp/2026-01-23/schemas/card_payment_instrument.json"], "config": { "gateway": "", "gatewayMerchantId": "" } } ] } }, "signing_keys": [ { "kid": "ucp-firmly-key-1", "kty": "EC", "crv": "P-256", "x": "", "y": "", "use": "sig", "alg": "ES256" } ] } ``` The `signing_keys` array supports key rotation — add the new public key, start signing with it, then remove the old key after a transition period. `signing_keys` is a top-level sibling of `ucp`; `payment_handlers` is nested inside `ucp`. The [Firmly Card handler](/solutions/agentic-commerce/protocols/ucp/firmly-card-handler) (a proposal) also appears under `payment_handlers` (keyed by `ai.firmly.card`) for merchants where it is enabled. > **Note** > This is the modern manifest shape — everything under a top-level `ucp` object, `capabilities` as a namespace-keyed map, `payment_handlers` as a namespace-keyed map nested inside `ucp`. That shape was introduced in manifest version `2026-01-23` and is used by every version from `2026-01-23` onward, including the current default `2026-04-08`. The earlier `2026-01-11` manifest uses the legacy shape — `capabilities` as an array of objects and payment declared under a top-level `payment.handlers` array. The `ai.firmly.card` handler is itself versioned `2026-04-08`. See the [Firmly Card handler](/solutions/agentic-commerce/protocols/ucp/firmly-card-handler) page for the `payment_handlers` fragment. --- ## Related - [UCP overview](/solutions/agentic-commerce/protocols/ucp/) — what UCP is and why Firmly implements it - [UCP checkout flow](/solutions/agentic-commerce/protocols/ucp/checkout-flow) — the three-step session walkthrough - [UCP security](/solutions/agentic-commerce/protocols/ucp/security) — request authentication and abuse prevention --- # UCP Merchant Onboarding Merchants must complete several configuration steps before enabling UCP checkout on Google AI surfaces. ## Google Merchant Center configuration | Step | Details | |---|---| | **1. Account setup** | Merchant Center account in good standing with approved products for free listings | | **2. Return policy** | Configure return cost, return window, and link to full policy. Advanced accounts (Merchant Center multi-seller accounts) configure per sub-account | | **3. Customer support** | Set contact information for "Contact Merchant" link on order confirmation | | **4. Waitlist enrollment** | Join Google's waitlist for explicit approval before going live on AI surfaces | ## Product feed configuration Attributes must be provided via supplemental feed, Content API (`products.insert`), or Merchant API (`productInputs.insert`): | Attribute | Required | Purpose | |---|---|---| | `native_commerce: true` | Yes | Opts product into checkout experience | | `merchant_item_id` | If IDs differ | Maps feed product ID to Checkout API ID | | `consumer_notice` | For regulated items | Prop 65, safety warnings (max 1000 chars, supports ``, `
`, ``) | ## Excluded product categories The following product types are **not eligible** for UCP checkout: - Subscriptions - Personalized / customized goods - Pre-orders - Age-restricted items - Services and rentals ## Firmly-specific onboarding For Firmly merchants to enable UCP: | Step | Details | |---|---| | **1. Merchant Center link** | Merchant connects their Google Merchant Center account | | **2. Domain verification** | Verify ownership of the domain used for UCP endpoints | | **3. `/.well-known/ucp` forwarding** | Configure the merchant domain to forward `/.well-known/ucp` to Firmly — see [UCP Configuration](/solutions/firmly-connect/portal/ucp-configuration) for the forwarding table and per-platform guides | | **4. Product feed sync** | Ensure Firmly product catalog syncs with Merchant Center feed | | **5. UCP enablement** | Enable the UCP integration for the merchant's domain in Firmly admin | ## Onboarding checklist ### Prerequisites - [ ] Active Firmly merchant account - [ ] Google Merchant Center account in good standing - [ ] Products approved for free listings in Google Merchant Center ### Google configuration - [ ] Return policy configured (cost, window, policy link) - [ ] Customer support contact information set - [ ] Enrolled in Google's UCP waitlist - [ ] Waitlist approval received ### Product feed - [ ] `native_commerce: true` attribute added to eligible products - [ ] `merchant_item_id` configured (if Firmly IDs differ from feed IDs) - [ ] `consumer_notice` added for regulated items - [ ] Excluded categories removed from UCP feed ### Firmly configuration - [ ] Google Merchant Center account linked - [ ] Domain ownership verified - [ ] `/.well-known/ucp` forwarding configured and verified ([UCP Configuration](/solutions/firmly-connect/portal/ucp-configuration)) - [ ] Firmly product catalog synced with the Merchant Center feed - [ ] UCP integration enabled for the merchant's domain in Firmly admin ### Validation Firmly ops runs these checks against the merchant's sandbox during onboarding — coordinate with your Firmly contact to execute a test session: - [ ] Test checkout session creation - [ ] Test changing buyer info - [ ] Test changing shipping info - [ ] Test changing shipping methods - [ ] If you have a test store, place a test order end-to-end ## Feed attribute details ### `native_commerce` ```text native_commerce: true ``` This boolean attribute opts a product into the Google AI checkout experience. Products without this attribute will not appear in the Google AI purchase flows. ### `merchant_item_id` ```text merchant_item_id: "SKU-12345" ``` Required when the product ID in the Merchant Center feed differs from the ID used in the Checkout API. This enables Google to map user selections to the correct product. --- ## Related - [UCP overview](/solutions/agentic-commerce/protocols/ucp/) - [UCP implementation](/solutions/agentic-commerce/protocols/ucp/implementation) — service architecture, API mapping, well-known manifest - [UCP checkout flow](/solutions/agentic-commerce/protocols/ucp/checkout-flow) --- # UCP Roadmap This page covers UCP's capabilities, Firmly's current implementation status against the protocol, and the planned roadmap. ## UCP protocol — capabilities and extensions UCP defines a set of core capabilities and optional extensions that expand what a checkout session can do. ### Core capabilities | Capability | Description | |---|---| | **Checkout** | Session-based cart management: create, update, complete, cancel | | **Identity Linking** | OAuth 2.0 flow — lets AI agents act on a user's behalf on a merchant site | ### Checkout extensions | Extension | ID | Description | |---|---|---| | Fulfillment | `dev.ucp.shopping.fulfillment` | Shipping options, pickup locations, delivery windows | | Discount | `dev.ucp.shopping.discount` | Promo code validation and auto-discount application | | AP2 Mandate | `dev.ucp.shopping.ap2_mandate` | Cryptographic authorization for autonomous agentic transactions | | Buyer Consent | No registered extension ID | User authorization and privacy consent tracking | ### Transport bindings REST (primary), MCP, A2A, Embedded Protocol. Firmly implements the REST and MCP bindings (see the table below); A2A and the Embedded Protocol are not implemented. ## What Firmly implements The table below maps each UCP capability to Firmly's current status: | Capability / Feature | Status | Notes | |---|---|---| | Checkout — Create session | ✅ Implemented | Idempotency-aware; generates session and device IDs | | Checkout — Update session | ✅ Implemented | Shipping info, shipping method, buyer info; buffers partial updates | | Checkout — Complete session | ✅ Implemented | Google Pay (gateway path); the encrypted card path is proposed (see [Firmly Card handler](/solutions/agentic-commerce/protocols/ucp/firmly-card-handler)) | | Checkout — Cancel session | ✅ Implemented | Flips the session status to `canceled`; does not clear the backing cart | | Cart resource (pre-purchase) | ✅ Implemented | `dev.ucp.shopping.cart` — create, get, update (full-replacement line items), cancel (`2026-04-08`) | | Catalog — search & lookup | ✅ Implemented | `dev.ucp.shopping.catalog.search` + `.lookup` — keyword/filter search, PDP-URL lookup, product detail (`2026-04-08`) | | Fulfillment extension | ✅ Implemented | Shipping method negotiation via update step | | Discount extension | ✅ Implemented | `discounts.codes` via the promo-codes endpoint; replacement semantics; rejections surfaced in `messages[]` | | Discovery endpoint (`/.well-known/ucp`) | ✅ Implemented | Dynamic per-merchant manifest with payment handlers and signing keys | | REST transport binding | ✅ Implemented | Primary binding for all capabilities | | MCP transport binding | ✅ Implemented | Streamable HTTP (JSON-RPC 2.0); endpoint advertised in discovery | | Idempotency | ✅ Implemented | 24-hour TTL per operation | | ES256 signing (outbound) | ✅ Implemented | ECDSA P-256 key pair; public JWK published in the discovery manifest | | Signature verification (inbound) | ✅ Implemented | RFC 9421 verified when a signature is present (ES256; keys from the caller's `UCP-Agent` profile); invalid → `401` | | UCP-Agent handling | ✅ Implemented | Profile fetched and cached; agent identity recorded on the trace; the signature is verified when the request is signed | | Destination API-key auth | ✅ Implemented | `X-API-Key` scheme (`api_key_required` / `api_key_invalid`) | | Order Management | 🔜 Planned | Future phase | | Identity Linking | ❌ Not planned | Out of scope — see note below | | AP2 Mandate extension | 🔜 Planned | Future phase | Signing is optional per the UCP signatures specification: unsigned requests are currently accepted as anonymous (a deployment policy, with the agent profile still recorded for audit), while any signature that is presented is always verified. See [UCP security](/solutions/agentic-commerce/protocols/ucp/security) for the full model. Identity Linking (the OAuth 2.0 flow that lets agents act on a user's behalf on the merchant's own site) is out of scope for Firmly's UCP integration. Firmly manages buyer identity internally through its own session and payment tokenization layer; a separate OAuth delegation flow with each merchant platform is not needed for the checkout paths Firmly supports. ## Catalog over UCP The UCP specification centers on checkout and, at its origin, assumed product discovery was solved upstream (a shopping index, merchant feeds, or a platform's own search), taking over only once a buyer signals intent to purchase. Firmly extends UCP with catalog capabilities — `dev.ucp.shopping.catalog.search` (keyword and filter search) and `dev.ucp.shopping.catalog.lookup` (batch PDP-URL lookup and full product detail with option/variant selection). Both shipped at manifest version `2026-04-08` and are exposed over the REST and MCP bindings, giving agents a discovery layer over the same integration that handles checkout rather than relying on a separate upstream index. ## Phased roadmap | Phase | Status | Scope | |---|---|---| | Phase 1 | ✅ Implemented | Native checkout — Create, Update, Complete, Cancel sessions | | Phase 2 | ✅ Implemented | Fulfillment support — shipping method negotiation | | Phase 3 | ✅ Implemented | Google Pay payment path | | Phase 4 | ✅ Implemented | Discount extension — promo code application via the checkout/cart update step | | Phase 5 | ✅ Implemented | Cart resource, catalog search/lookup, and the MCP transport binding (`2026-04-08`) | | Phase 6 | Planned | AP2 Mandate — cryptographic authorization for agentic transactions | | Phase 7 | Future | Merchant-side UCP adapter — place orders on UCP-compliant merchants | **Discount extension.** Firmly implements UCP's discount extension. When a buyer enters a promotion code on the AI checkout surface, Firmly maps `discounts.codes` to the merchant's promo-code endpoint (`POST` / `DELETE .../cart/promo-codes`) and returns updated line-item totals and a revised order summary. Codes use replacement semantics (an empty array clears all applied codes), and a rejected code is surfaced as a recoverable warning in `messages[]` rather than failing the update. For merchants with active promotions — flash sales, loyalty discounts, coupon campaigns — this matches what a buyer expects from a standard web checkout. --- ## Related - [UCP overview](/solutions/agentic-commerce/protocols/ucp/) - [UCP checkout flow](/solutions/agentic-commerce/protocols/ucp/checkout-flow) - [UCP implementation](/solutions/agentic-commerce/protocols/ucp/implementation) - [Firmly Card Handler](/solutions/agentic-commerce/protocols/ucp/firmly-card-handler) — encrypted card payment via Firmly Vault --- # UCP Security This page covers how UCP requests are authenticated, verified, and protected. ## Request authentication UCP requests carry a set of standard headers. Firmly supports two caller-authentication schemes — RFC 9421 HTTP message signatures (agent signing) and a destination API key — plus the headers UCP uses for idempotency and tracing: | Header | Purpose | |---|---| | `Signature` | RFC 9421 HTTP message signature (ES256) proving the request's authenticity | | `Signature-Input` | RFC 9421 signature metadata — covered components, `keyid`, `created`, and algorithm | | `Content-Digest` | RFC 9530 SHA-256 digest of the request body (present on requests that carry a body) | | `UCP-Agent` | Agent profile URL identifying the caller (e.g., `profile="https:///ucp-agent"`) | | `X-API-Key` | Destination API key (an alternative to agent signing) | | `Idempotency-Key` | Prevents duplicate processing of retried mutations (see [Idempotency](/solutions/agentic-commerce/protocols/ucp/idempotency)) | | `Request-Id` | Unique identifier for request tracing | Firmly evaluates the API key first: if an `X-API-Key` is present it is validated and, on success, the request proceeds without signature verification. Otherwise the request is handled on the agent-signing path below. ## Agent signature verification (RFC 9421) When a request carries `Signature` and `Signature-Input`, Firmly verifies it per RFC 9421: 1. Parse `UCP-Agent` for the caller's `profile` URL. A signature with no `UCP-Agent` header is rejected with `400 missing_agent_header` — the profile URL is the only way to locate the signing keys. 2. Fetch the agent profile document from that HTTPS URL and read its `signing_keys` (a JWKS). Profiles are cached at the edge (~1 hour), fetched with a 3-second timeout and a 64 KB size cap. A profile that cannot be fetched, is malformed, or is missing `signing_keys` fails with `502 agent_profile_fetch_failed`. 3. Verify the ES256 (ECDSA P-256 / SHA-256) signature. The `keyid` in `Signature-Input` must match a JWK `kid` in the profile. Covered components: | Component | When required | |---|---| | `@method`, `@authority`, `@path` | Always | | `@query` | When the request URL has a query string | | `ucp-agent` | When the `UCP-Agent` header is present | | `idempotency-key` | On state-changing methods (POST/PUT/PATCH/DELETE) that send the header | | `content-digest` | When the request carries a body — verified against the SHA-256 of the body | A signature that fails any check is rejected with `401 agent_signature_invalid`. > **Note** > Per the UCP signatures specification, signing is optional for cart, catalog, and checkout traffic — callers should sign but are not required to. An unsigned request is treated as anonymous, and the `UCP-Agent` profile (when supplied) is still recorded on the request trace for audit. When a deployment disables anonymous access, an unsigned request is rejected with `401 agent_signature_required`. ## Destination API-key authentication Destinations that integrate over an API key present it in `X-API-Key` (keys are prefixed `fucp_live`). Firmly resolves the merchant-and-destination configuration, hashes the presented key (SHA-256), and matches it against that destination's active keys: | Outcome | Response | |---|---| | A key is required for this merchant/destination but none was presented | `401 api_key_required` | | Key is malformed, unknown, inactive, or not valid for this merchant | `401 api_key_invalid` | | Key is configured for a different UCP version than the requested route | `401 api_key_invalid` | A merchant/destination can be configured to require an API key as its public default; in that case an unsigned, keyless request is rejected with `401 api_key_required`. ## Response signing Firmly signs its own successful (2xx) responses with RFC 9421, setting `Signature`, `Signature-Input`, and `Content-Digest`. The signature uses an ES256 (ECDSA P-256) key whose public JWK is published in the discovery manifest's `signing_keys` array (key id `ucp-firmly-key-1`), so callers can verify Firmly's responses. Discovery (`/.well-known/ucp`) responses and streaming (`text/event-stream`) responses are not signed. ## Domain validation Before building a manifest or translating a call, Firmly resolves and validates the merchant domain: | Step | Description | |---|---| | 1. Resolve domain | Discovery reads the merchant domain from the `x-firmly-host` header (or the `domain` query parameter); REST and MCP take it from the URL path (`/domain/{domain}`) | | 2. Validate merchant | Load the shop configuration; an unknown merchant fails with `404 merchant_not_found` | | 3. Check UCP status | A merchant with UCP disabled (`ucp_disabled`) fails with `404 ucp_disabled` | ## Abuse prevention | Measure | How it works | |---|---| | **Agent signatures** | RFC 9421 signatures prove request authenticity and integrity, with the body covered by `content-digest` | | **Idempotency** | Duplicate mutations with the same `Idempotency-Key` return the cached response; a reused key with a different body returns `409` (see [Idempotency](/solutions/agentic-commerce/protocols/ucp/idempotency)) | | **Replay dedup** | Handled at the idempotency layer rather than the signature layer — the verifier does not enforce a `created` freshness window beyond rejecting timestamps more than 24 hours in the future | | **Audit logging** | Every request records the caller (agent profile or destination), request id, and outcome on the request trace | ### Rate limits Rate limiting is not currently enforced by the UCP service. Firmly-wide rate limits may apply as a platform policy; where enforced, thresholds are communicated during onboarding and exceeding them returns `429 Too Many Requests` with a `retry-after` header. ### Transport security - HTTPS only (enforced at the edge) - All communication encrypted in transit - TLS 1.2+ required --- ## Related - [UCP overview](/solutions/agentic-commerce/protocols/ucp/) - [UCP checkout flow](/solutions/agentic-commerce/protocols/ucp/checkout-flow) - [UCP implementation](/solutions/agentic-commerce/protocols/ucp/implementation) — service architecture, idempotency handling, signing keys - [Rate Limits](/api-reference/rate-limits) — Firmly-wide rate limiting --- # UCP configuration **What this gives you:** Firmly hosts a UCP (Universal Commerce Protocol) version of your store — a machine-readable commerce surface that AI agents can discover and buy from. You don't build or maintain UCP yourself: Firmly generates your UCP manifest, answers agent requests, and translates them to your platform behind the scenes. All you do here is point one well-known path — `/.well-known/ucp` — on your domain at Firmly, then verify it. For the conceptual background on UCP itself, see [Protocols → UCP overview](/solutions/agentic-commerce/protocols/ucp/). > **Note** > **Prerequisite:** the domain you're configuring must be verified first — see [Domains and SSO](/solutions/firmly-connect/portal/domains-and-sso) for DNS TXT verification. ## The forwarding pattern Your domain needs to forward `/.well-known/ucp` requests to Firmly's hosted UCP endpoint, with an `x-firmly-host` header set to your own domain: | Source | Destination | |---|---| | `https:///.well-known/ucp` | `https://api.firmly.work/.well-known/ucp` | The page walks you through doing this on the platform you're already on. ## Three "What is UCP?" anchors Above the setup steps, the page summarizes why this exists in three cards: | Card | Summary | |---|---| | **Commerce Discovery** | A standardized way for agents to discover product data and capabilities | | **AI-Ready** | Machine-readable metadata so agents don't need a custom integration per merchant | | **Secure by Design** | Firmly handles auth and abuse mitigation on the well-known endpoint | ## Platform-specific setup guides A dropdown picks the merchant's edge platform; the steps below it rewrite for that platform: | Platform | Setup pattern | |---|---| | **Cloudflare** | Worker script intercepting `/.well-known/ucp` and forwarding with the `x-firmly-host` header; Worker route assigned in the dashboard | | **Akamai** | Origin server pointing to `api.firmly.work`, path-based rule that injects the `x-firmly-host` header | | **Fastly** | Backend pointing to `api.firmly.work`, VCL snippet in `vcl_recv` that sets the backend and the `x-firmly-host` header on matching requests | | **CloudFront (AWS)** | Origin + cache behavior + Lambda@Edge / CloudFront Function to add the header | Your own domain is interpolated into the code blocks (`x-firmly-host: `) so you can copy-paste without editing. Each code / config block has a copy button. ## Verification probe After applying the configuration, you click **Verify Configuration**. Firmly sends a probe to `https:///.well-known/ucp` and checks that your edge forwarded the request with the correct `x-firmly-host` header and returned Firmly's UCP manifest. | Outcome | What happens | |---|---| | **Success** | The page flips into a "Verified by … at …" state and the verification status is recorded server-side | | **Failure** | The page surfaces an error pointing you to the most likely misconfigurations | ## Once verified — you're discoverable A successfully verified UCP endpoint is what makes your store findable to agents on Firmly's network — without it, agents can't auto-discover your commerce capabilities. ## Role gating | Action | Who can do it | |---|---| | Run verification | Owner, Primary Owner, Firmly admin | | View configuration | Any role | Lower roles see the page read-only. --- ## Related - [Protocols → UCP overview](/solutions/agentic-commerce/protocols/ucp/) — what UCP is - [Protocols → UCP merchant onboarding](/solutions/agentic-commerce/protocols/ucp/merchant-onboarding) — Google Merchant Center side of the setup - [Domains and SSO](/solutions/firmly-connect/portal/domains-and-sso) — domain verification (a prerequisite) - [Audit logs](/solutions/firmly-connect/portal/audit-logs) — UCP verification events logged here --- # UCP The Universal Commerce Protocol is an open standard launched in early 2026 by Google in collaboration with major retailers and platforms. It defines how AI agents conduct complete commerce transactions — from cart initialization to payment to order placement — through a single, interoperable interface. UCP powers purchasing on Google's AI surfaces. When a user instructs a Google AI surface to buy something, UCP is the protocol that handles the checkout session between Google and the merchant's backend. ## Session model Every UCP purchase flows through three steps: 1. **CreateCheckoutSession** — initialize a cart with the selected products 2. **UpdateCheckoutSession** — collect shipping address, method, buyer info, and payment 3. **CompleteCheckoutSession** — place the order and return confirmation A cancel operation is also available to abort sessions that don't progress to completion. Sessions move through states (`incomplete` → `ready_for_complete` → `complete_in_progress` → `completed`) — this is the happy path; see [Checkout flow](/solutions/agentic-commerce/protocols/ucp/checkout-flow) for the full state table, including `canceled` and `requires_escalation`. ## Transport UCP can run over REST, MCP, A2A (Agent2Agent), or as an Embedded Protocol (a UCP session embedded directly inside the host surface rather than reached over a network binding). Firmly implements the **REST binding** (the primary path) and the **MCP binding** (Streamable HTTP / JSON-RPC 2.0, advertised in the discovery manifest); A2A and the Embedded Protocol are not implemented. Beyond checkout, Firmly also exposes the pre-purchase **Cart** resource and **catalog search/lookup** over both bindings — see the [Roadmap](/solutions/agentic-commerce/protocols/ucp/roadmap) for the full capability status. ## Discovery Merchants publish a capability manifest at `/.well-known/ucp`, telling UCP clients what payment methods, extensions, and signing keys they support. Firmly generates this manifest dynamically per merchant. ## Division of responsibility Google owns discovery (its Shopping index, product feeds, Merchant Center) and the checkout UI — it collects the user's address and payment. The merchant's backend owns cart orchestration, shipping rates, payment processing, and order placement. **UCP is the contract between them.** ## Why Firmly integrates with UCP UCP creates an opportunity on two sides: ### Destination side — implemented Firmly has merchant adapters across a broad, growing set of industry-standard commerce platforms and custom platforms. When Firmly implemented UCP, every one of those merchants became available on Google's AI surfaces and any AI agent that speaks UCP — without any additional integration work on the merchant's part. The mechanics: Firmly built a UCP wrapper service that sits in front of its existing cart and checkout APIs. Google calls Firmly's UCP endpoints; Firmly translates those calls into its internal cart operations, retrieves shipping options, tokenizes payment, and places the order on the merchant's native platform. The merchant never changes anything. The user never leaves the AI surface. Firmly handles everything in between. Google owns the user-facing checkout UI. Firmly owns the commerce infrastructure behind it. ### Merchant side — planned UCP also creates a new category of merchants: platforms and retailers that natively speak UCP. Once a merchant implements UCP, any compliant agent can transact with them using a single, reusable integration. For Firmly, this represents a future direction in how merchant adapters are built. Rather than a bespoke integration for each new merchant, Firmly could build one UCP merchant adapter — and any merchant that has implemented UCP would automatically be supported. This is not yet built; it represents a planned direction as UCP adoption grows. ## Architecture Firmly sits between Google and the merchant's native platform. The UCP service receives requests from Google, translates them into Firmly's internal cart and checkout APIs, and forwards results back in UCP format. The merchant platform — regardless of which commerce platform the merchant runs — is unaware of UCP entirely. It sees only Firmly's standard adapter calls. On the Google side, Firmly publishes a dynamic discovery manifest per merchant, advertising supported payment methods, active extensions, and the public JWK used for signature verification. On the merchant side, Firmly calls into its existing adapter layer — the same code that powers every other Firmly checkout flow. The boundary is clean by design: **Google owns the user and the UI; Firmly owns the commerce.** ## Sub-pages - [Checkout Flow](/solutions/agentic-commerce/protocols/ucp/checkout-flow) — The three-step session lifecycle (Create → Update → Complete), state transitions, and what each step does. - [Implementation](/solutions/agentic-commerce/protocols/ucp/implementation) — Service architecture, UCP-to-Firmly API mapping, session state, well-known manifest. - [Security](/solutions/agentic-commerce/protocols/ucp/security) — Authentication headers, signature verification, domain validation, rate limiting. - [Merchant Onboarding](/solutions/agentic-commerce/protocols/ucp/merchant-onboarding) — Google Merchant Center setup, product feed configuration, validation checklist. - [Roadmap](/solutions/agentic-commerce/protocols/ucp/roadmap) — Protocol capabilities and extensions, implementation status, phased roadmap. - [Firmly Card Handler](/solutions/agentic-commerce/protocols/ucp/firmly-card-handler) — Proposed `ai.firmly.card` handler for encrypted card checkout through Firmly Vault. ## External references | Resource | Description | |---|---| | [ucp.dev](https://ucp.dev/) | Protocol specification and overview | | [Google UCP Guide](https://developers.google.com/merchant/ucp/guides) | Google's integration guide for merchants and platforms | | [UCP REST Binding](https://ucp.dev/specification/checkout-rest/) | REST API specification for checkout session endpoints | | [Native Checkout Guide](https://developers.google.com/merchant/ucp/guides/checkout/native) | How native checkout works on Google's surfaces | --- ## Related - [Protocols overview](/solutions/agentic-commerce/protocols/) — UCP vs MCP vs ACP comparison - [Agentic Commerce overview](/solutions/agentic-commerce/) — the broader solution - [Idempotency](/solutions/agentic-commerce/protocols/ucp/idempotency/index.md) --- # Use Cases These are common patterns destinations build with Ad Commerce. The list is not exhaustive — Firmly's APIs support more shapes. Use these as starting points; adapt or combine them to fit the build. ## Common use cases - [In-Feed Shoppable Ad](/solutions/ad-commerce/use-cases/in-feed-shoppable-ad) — A single-product ad inside a feed (social, video, content) where purchase completes inside the ad surface — no redirect. - [Post-Click Purchase](/solutions/ad-commerce/use-cases/post-click-purchase) — A banner or video ad routes the viewer to a dedicated landing where the purchase completes. Landing is owned by the advertiser or the ad platform. Each use case pairs with an [Integration Pattern](/solutions/ad-commerce/integration-patterns/): **In-Feed Shoppable Ad** uses [In-Ad Checkout](/solutions/ad-commerce/integration-patterns/in-ad-checkout), and **Post-Click Purchase** uses [Post-Click Landing](/solutions/ad-commerce/integration-patterns/post-click-landing). ## How to read these pages Every use case page follows the same shape as Agentic Commerce's [Use Cases](/solutions/agentic-commerce/use-cases/): 1. **What the use case is** — one-paragraph viewer story 2. **Recommended setup** — a table covering integration pattern, auth, payment, and attribution 3. **API sequence** — the call order, each row linking to the API reference 4. **Considerations** — destination-side logic the ad surface owns --- ## Related - [Why Firmly for Ad Commerce](/solutions/ad-commerce/why-firmly) — what's specific to this solution - [Integration Patterns](/solutions/ad-commerce/integration-patterns/) — where the checkout UI lives - [Single Product Purchase Flow](/solutions/ad-commerce/flows/single-product-purchase) — the full API sequence - [For Destinations](/for-destinations/) — the destination engineer's side --- # Use Cases These are the common use cases customers build with Firmly. The list isn't exhaustive — Firmly's APIs support many more shapes. Use these as starting points; adapt or combine them to fit your build, and [contact Firmly](/contact) if your scenario doesn't match any of these. Every destination category ([AI surfaces](/solutions/destination-surfaces/ai-surfaces), [publisher sites](/solutions/destination-surfaces/publisher-sites), [ads](/solutions/destination-surfaces/ads), and others) can use any of these patterns. If you're not sure where to start, **begin with AI Shopping Copilot** — it's the baseline flow every other use case builds on. ## Common use cases - [AI Shopping Copilot](/solutions/agentic-commerce/use-cases/shopping-copilot) — General-purpose discovery → cart → checkout. The baseline. - [Deal & Coupon Hunting](/solutions/agentic-commerce/use-cases/deal-coupon-hunting) — Find deal-eligible items and apply promo codes at checkout. - [Smart Payment Selection](/solutions/agentic-commerce/use-cases/smart-payment) — Card, BNPL, express wallets, saved cards — pick the best path per transaction. - [Vertical Specialist](/solutions/agentic-commerce/use-cases/vertical-specialist) — Variant-rich discovery + multi-product cart for fashion, beauty, supplements. - [Smart Gifting & Occasion](/solutions/agentic-commerce/use-cases/smart-gifting) — Find a gift, add gift wrap, optionally bundle a gift card, express checkout. - [Scheduled / Triggered Buying](/solutions/agentic-commerce/use-cases/scheduled-buying) — Replenishment, restock, price-drop auto-buy. The destination schedules; Firmly executes. - [Autonomous Agent Purchasing](/solutions/agentic-commerce/use-cases/autonomous-agent-purchasing) — Mandate-based payment when the cardholder isn't present at checkout — Agentic Pay's Network Token Router with network-enforced spending limits. ## How use cases relate to destinations Use cases are common patterns; destinations are who builds them. The same use case appears in many destination-type pages because every destination can apply it: | Use case | Most relevant destination types | |---|---| | AI Shopping Copilot | Every destination — this is the baseline | | Deal & Coupon Hunting | AI chat product, AI answer engine, publisher, bank (with card-linked offer overlay) | | Smart Payment Selection | Wallet, bank, AI chat product | | Vertical Specialist | Brand-loyalty, publisher, AI chat product | | Smart Gifting & Occasion | AI chat product, wallet, publisher | | Scheduled / Triggered Buying | Wallet, bank, connected device | | Autonomous Agent Purchasing | Wallet, bank, connected device, brand-loyalty (when the user isn't at the screen at checkout) | Don't see your destination? See [Destinations](/solutions/destination-surfaces/). ## How to use these pages Most use case pages follow the same shape: 1. **What the use case is** — one-paragraph user story 2. **Recommended setup** — integration pattern, protocol, auth, flow shape 3. **API sequence** — the exact call order, each row linking to the canonical reference 4. **Agent considerations** — destination-side logic you need to own (some pages fold this into the API sequence when there's little to add) 5. **Related** — adjacent use cases, deeper guides, error handling ## Each use case — what to read next | Use case | Closest flow | Closest integration pattern | Closest recipe | |---|---|---|---| | Shopping Copilot | [Single-product](/solutions/agentic-commerce/flows/single-product-purchase) | Any | [Chat to Checkout](/solutions/agentic-commerce/recipes/chat-to-checkout) | | Deal & Coupon Hunting | [Single-product](/solutions/agentic-commerce/flows/single-product-purchase) or [Multi-product](/solutions/agentic-commerce/flows/multi-product-purchase) | [Deep Link](/solutions/agentic-commerce/integration-patterns/deep-link) | [Chat to Checkout](/solutions/agentic-commerce/recipes/chat-to-checkout) | | Smart Payment Selection | [Single-product](/solutions/agentic-commerce/flows/single-product-purchase) | [Embedded](/solutions/agentic-commerce/integration-patterns/embedded-checkout) for wallet UI | — | | Vertical Specialist | [Multi-product](/solutions/agentic-commerce/flows/multi-product-purchase) | [Embedded](/solutions/agentic-commerce/integration-patterns/embedded-checkout) | — | | Smart Gifting | [Single-product](/solutions/agentic-commerce/flows/single-product-purchase) or [Multi-product](/solutions/agentic-commerce/flows/multi-product-purchase) | [Embedded](/solutions/agentic-commerce/integration-patterns/embedded-checkout) | [Wallet pass purchase](/solutions/agentic-commerce/recipes/wallet-pass-purchase) | | Scheduled / Triggered Buying | [Single-product](/solutions/agentic-commerce/flows/single-product-purchase) | [Deep Link](/solutions/agentic-commerce/integration-patterns/deep-link) | — | | Autonomous Agent Purchasing | [Single-product](/solutions/agentic-commerce/flows/single-product-purchase) | [Deep Link](/solutions/agentic-commerce/integration-patterns/deep-link) | — | --- # Use Cases Branded Commerce supports a small set of partner-facing patterns that all share the same underlying shape: ad → partner-branded page → checkout → order. The variations are in **what kind of landing page** the ad routes to, and **what kind of inventory** the partner is curating. These are starting points; adapt or combine them to fit your campaigns. ## Common use cases - [Single-product deal](/solutions/branded-commerce/use-cases/single-product-deal) — Ad → partner-branded PDP → checkout. The simplest path — ad creative promotes one specific product with a promo code, and the buyer lands directly on the PDP for that product. - [Curated landing page](/solutions/branded-commerce/use-cases/curated-landing-page) — Ad → partner-branded occasion page with a product grid → PDP → checkout. For gift guides, seasonal events ("Mother's Day", "Back to School"), and themed deal roundups across one or more merchants. - [Retail-media placement](/solutions/branded-commerce/use-cases/retail-media-placement) — Sponsored-product ads placed on retail-media networks routed to partner-branded checkout instead of the network's native PDP — ad-message continuity preserved, attribution intact. ## How use cases relate to ad sources Every use case can be driven by any traffic source. The use case is about what the **landing experience** is; the source is about where the click comes from. | Use case | Best-fit traffic sources | |---|---| | Single-product deal | Social ads with a specific CTA, search ads pointing at one product, deal-newsletter links, direct deep-links | | Curated landing page | Email campaigns, occasion-driven social ads, content/editorial roundups, influencer "shop my picks" | | Retail-media placement | Walmart Connect, Target Roundel, Amazon Ads, Instacart Ads sponsored product placements | ## How to use these pages Most use case pages follow the same shape (the retail-media page varies, since its focus is where the placement fits rather than a phase-by-phase walkthrough): 1. **What the pattern is** — one-paragraph user story 2. **What the buyer sees** — phase-by-phase walkthrough of the partner-branded experience 3. **What the partner owns vs. what Firmly handles** 4. **Performance tracking** — affiliate attribution and ad conversion signals for this pattern 5. **Related** — adjacent use cases, deeper guides ## Each use case — what to read next | Use case | Closest flow | Integration pattern | |---|---|---| | Single-product deal | [Buyer purchase flow](/solutions/branded-commerce/flows/buyer-purchase-flow) | Firmly-hosted under partner's domain | | Curated landing page | [Buyer purchase flow](/solutions/branded-commerce/flows/buyer-purchase-flow) with a landing-page entry phase | Firmly-hosted, multi-merchant possible | | Retail-media placement | [Buyer purchase flow](/solutions/branded-commerce/flows/buyer-purchase-flow) | Firmly-hosted, sponsored-product entry | --- ## Related - [Branded Commerce overview](/solutions/branded-commerce/) - [Flows](/solutions/branded-commerce/flows/single-product-purchase) - [Integration Patterns](/solutions/branded-commerce/integration-patterns/) - [Operations → Partner onboarding](/solutions/branded-commerce/operations/partner-onboarding) --- # Use Cases These are common patterns destinations build with Marketplace. The list is not exhaustive — Firmly's APIs support more shapes. Use these as starting points; adapt or combine them to fit the build. ## Branded Marketplace - [Branded Marketplace](/solutions/marketplace/use-cases/branded-marketplace) — Operator runs a fully branded marketplace UI with a curated merchant selection. Buyers search across merchants; each cart is scoped to one source merchant. Branded Marketplace pairs with either [Operator-Hosted](/solutions/marketplace/integration-patterns/operator-hosted) or [Embedded Marketplace](/solutions/marketplace/integration-patterns/embedded-marketplace) — the choice is where the marketplace UI lives, not what the buyer can do. --- ## Related - [Why Firmly for Marketplace](/solutions/marketplace/why-firmly) — what's specific to this solution - [Integration Patterns](/solutions/marketplace/integration-patterns/) — where the UI lives - [Single Product Purchase Flow](/solutions/marketplace/flows/single-product-purchase) — the full API sequence - [Multi-Product Purchase Flow](/solutions/marketplace/flows/multi-product-purchase) — multiple items from one merchant - [For Destinations](/for-destinations/) — the destination engineer's side --- # Use Cases These are common patterns publishers build with Publisher Commerce. The list is not exhaustive — Firmly's APIs support more shapes. Use these as starting points; adapt or combine them to fit your integration. ## Common use cases - [Shoppable Article](/solutions/publisher-commerce/use-cases/shoppable-article) — A standard editorial article with one or more Buy Now buttons embedded inline. The reader can purchase the mentioned product without leaving the article. - [Curated Product Roundup](/solutions/publisher-commerce/use-cases/curated-product-roundup) — A "best of" or gift-guide article featuring 5–15 products. Readers add multiple items to one cart and check out once. ## How use cases relate to integration patterns Each use case typically pairs with one of the [Integration Patterns](/solutions/publisher-commerce/integration-patterns/): | Use case | Best-fit integration pattern | |---|---| | Shoppable Article | [Embedded Buy Button](/solutions/publisher-commerce/integration-patterns/embedded-buy-button) | | Curated Product Roundup | [Embedded Buy Button](/solutions/publisher-commerce/integration-patterns/embedded-buy-button) or [Dedicated Landing](/solutions/publisher-commerce/integration-patterns/dedicated-landing) | ## How to read these pages Every use case page follows the same shape as Agentic Commerce's [Use Cases](/solutions/agentic-commerce/use-cases/): 1. **What the use case is** — one-paragraph reader story 2. **Recommended setup** — integration pattern, attribution, payment options 3. **API sequence** — the call order, each row linking to the API reference 4. **Considerations** — publisher-side logic the article surface owns --- ## Related - [Why Firmly for Publisher Commerce](/solutions/publisher-commerce/why-firmly) — what's specific to this solution - [Integration Patterns](/solutions/publisher-commerce/integration-patterns/) — where the buy UI lives - [Single Product Purchase Flow](/solutions/publisher-commerce/flows/single-product-purchase) — the full API sequence - [For Destinations](/for-destinations/) — the destination engineer's side --- # Verify a Domain > **Note** > **SSO and enforcement are scoped per email domain.** Before you can bind an Identity Provider to a domain or enforce SSO on it, you must register the domain in Firmly Connect and prove ownership by publishing a DNS TXT record at its apex. ## Why verification is required Single Sign-On in Firmly Connect is keyed to email domains. Each domain you register is independent — you can bind different Identity Providers to different domains, and enforce SSO on some domains while leaving others on OTP or magic-link login. Before any of that, Firmly needs to confirm that you actually control the domain. Domain verification ensures that no one can hijack the SSO flow for a domain they don't own. An unverified domain can exist in the dashboard, but it **cannot** be bound to an IdP and the **SSO Enforced** toggle is unavailable. Register the **bare email domain** your team's addresses use. If your users sign in with addresses on a subdomain (for example `@corp.yourstore.example`), register that exact subdomain as its own domain — a verified apex domain does not automatically cover subdomain email addresses. ## Add a domain ### Open Settings → Domains Navigate to the **Domains** page in your Merchant Portal settings. ### Click Add domain A dialog appears prompting for the domain name. ### Enter the email domain and submit Enter the bare domain only (for example, `yourstore.example` — not `https://yourstore.example` or `mail.yourstore.example`). ### Copy the DNS TXT details The dashboard immediately opens a **Setup instructions** dialog containing the TXT host, value, and a copy button. Keep this dialog open while you publish the record. ![Add domain dialog](/images/firmly-connect/sso/domain-add-dialog.png) ## Publish the DNS TXT record In your DNS provider's control panel, create a new TXT record on the apex of the domain you registered, using the values from the **Setup instructions** dialog. | Field | Value | | ------------- | ---------------------------------------------------------------------------------- | | **Host / Name** | `@` (the apex of the domain — some DNS UIs accept the bare domain instead) | | **Type** | `TXT` | | **Value** | `firmly_connect_dashboard_sso=` — the unique token shown in the Setup instructions dialog | | **TTL** | Use your DNS provider's default | > **Warning** > The TXT record value must contain the **entire** string, including the `firmly_connect_dashboard_sso=` prefix. Do not paste only the token portion — verification will fail. ![DNS TXT record details with copy button](/images/firmly-connect/sso/domain-txt-record.png) ## Verify ownership ### Confirm the record is live (optional but recommended) Run `dig TXT yourstore.example +short` (or `nslookup -q=txt yourstore.example` on Windows) from a terminal, or use your DNS provider's lookup tool. You should see the `firmly_connect_dashboard_sso=...` value returned. ### Click Verify now On the **Setup instructions** dialog — or from the Actions menu on the domain row — click **Verify now**. Firmly performs a DNS lookup of the TXT record at the apex of the domain. ### Watch for the Verified badge On success, the domain row shows a green **Verified** badge. The domain is now eligible to be bound to an IdP and to have enforcement enabled. > **Note** > **DNS propagation** can take anywhere from a few minutes to several hours, depending on your provider and the previous TTL. If verification fails, wait a few minutes and try again. Confirming the record with `dig` (or your provider's lookup tool) before clicking **Verify now** avoids unnecessary failures. > **Note** > **Rate limits** apply to verification attempts, both per domain and per source IP. If you hit the limit you'll see a "too many attempts" message — wait roughly a minute before retrying. ## What you can do once verified A verified domain unlocks two capabilities: - **Bind to an Identity Provider** — the domain becomes selectable in the **Authorized Domains** section of any OIDC or SAML IdP configuration. See the [Generic OIDC](/solutions/firmly-connect/sso/generic-oidc) and [Generic SAML](/solutions/firmly-connect/sso/generic-saml) guides. - **Enforce SSO** — the **SSO Enforced** toggle on the domain row becomes available, but only after at least one *enabled* IdP is bound to the domain. ## Enforce SSO for the domain Once a domain is verified **and** bound to at least one enabled Identity Provider, the **SSO Enforced** toggle on the Domains table becomes interactive. The toggle's tooltip tells you exactly which gating condition (if any) is preventing it from being enabled: - **ON** — SSO is enforced: every user on this domain must sign in via SSO. OTP and magic-link login are blocked, with no self-service bypass. - **OFF** *(available)* — the domain is verified and has an enabled IdP, so you can enforce SSO — but it isn't enforced yet, and users can still use OTP or magic link. - **Grayed out — domain not verified** — verify the domain before you can enforce SSO. - **Grayed out — no enabled IdP bound** — bind this domain to an enabled Identity Provider (on the SSO page) before you can enforce SSO. > **Warning** > **Enforcement takes effect immediately.** The moment the **SSO Enforced** toggle is on, OTP and magic-link login stop working for every user with an email on this domain — there is no grace period and no self-service bypass (if the IdP breaks and locks the team out, contact Firmly to recover access). Always run a successful **Test Connection** on your IdP, and complete at least one real SSO sign-in, *before* enabling enforcement. To step back from enforcement without losing any configuration, you have two options: - **Toggle SSO Enforced off** on the domain row — users on that domain regain OTP / magic-link login. - **Disable the IdP** by turning its **Enabled** toggle off on the SSO page — this turns enforcement off everywhere the IdP is bound, while preserving all configuration values. ## Removing or re-verifying a domain Deleting a domain from the Domains table removes it from any IdP bindings and is recorded in your audit log. There is no time-based re-verification — once a domain is verified it stays verified until you delete it. If you need to move a domain to a different organization in Firmly Connect, delete it from the source organization first, then add and re-verify it in the target organization. ## Next steps - [Configure Generic OIDC](/solutions/firmly-connect/sso/generic-oidc) — Set up an OpenID Connect Identity Provider and bind it to your verified domain. - [Configure Generic SAML](/solutions/firmly-connect/sso/generic-saml) — Set up a SAML 2.0 Identity Provider and bind it to your verified domain. --- # Vertical Specialist Agent > **Note** > This is one common pattern customers build with Firmly. Many other shapes are possible — adapt or combine use cases to fit your specific build. The user wants something category-specific — *"build me an outfit for a wedding"*, *"a skincare set for sensitive skin"*, *"a 30-day fitness supplement stack"*. The agent does discovery with vertical-aware filters, lets the user pick variants (size, shade, dosage), builds a multi-product cart, and checks out. This scenario exercises Firmly's **multi-product cart**, **variant selection**, and the merchant adapters' vertical-specific product data. It's the canonical "category specialist" shape. ## Recommended setup | Choice | Default | Why | |---|---|---| | **Integration pattern** | [Embedded checkout](/solutions/agentic-commerce/integration-patterns/embedded-checkout) | Variant selectors (size grid, shade swatches) are easier in a rendered UI than pure text | | **Protocol** | [MCP](/solutions/agentic-commerce/protocols/) for conversational AI surfaces; direct REST for headless | MCP exposes Firmly tools the LLM can call iteratively | | **Flow shape** | [Multi-product purchase](/solutions/agentic-commerce/flows/multi-product-purchase) | Multiple items, one merchant, one checkout | ## Vertical patterns Firmly preserves each category's specific product detail and checkout behavior across discovery, cart, and checkout, so the destination doesn't have to special-case every category itself. | Vertical | What the product page needs | What the cart / checkout needs | |---|---|---| | **Apparel** | Size grid, color swatches, fit guidance | Standard shipping; sometimes multi-shipment when sizes ship from different warehouses | | **Beauty / skincare** | Shade selectors, ingredient lists, sample requests | Standard shipping | | **Fitness supplements** | Dosage selectors, flavor variants, bundle pricing | Multi-product cart for stacks; sometimes scheduled re-orders (see [Scheduled buying](/solutions/agentic-commerce/use-cases/scheduled-buying)) | | **Flowers** | Arrangement size, stem selection, vase options | Recipient address, delivery date, gift message, occasion; scheduled delivery window | | **Furniture** | Room dimensions, fabric options, assembly | White-glove delivery scheduling | | **Electronics** | Warranties, trade-ins, bundles | Per-line shipping from multiple warehouses | ## API sequence | # | Endpoint | Purpose | |---|---|---| | 1 | [Browser session](/api-reference/authentication/browser-session) | Auth | | 2 | [Discovery search](/api-reference/discovery/search) | Find candidates within the vertical | | 3 | [Get product](/api-reference/catalog/get-product) | Fetch full variants — size grid / shade swatches / dosage options | | 4 | [Add line item](/api-reference/cart-management/add-line-item) | Add the first item with the chosen variant | | 5 | *(repeat 3–4 per additional item)* | Iterative multi-product build | | 6 | [Get cart](/api-reference/cart-management/get-cart) | Re-inspect — the user may want to adjust quantities | | 7 | [Set shipping info](/api-reference/checkout/set-shipping-info) | Address; populates `shipments` with `shipping_method_options` (multi-shipment is common in apparel) | | 8 | [Get shipping availability](/api-reference/shipment-configuration/get-availability) | *(Optional)* Delivery dates / time slots / pickup locations | | 9 | [Set shipping method](/api-reference/shipment-configuration/set-shipping-method) | Pick a method per shipment from its `shipping_method_options` | | 10 | … then the standard checkout tail | Get/set consents → set billing info → get payment public key → complete order (v2, with `encrypted_card`). Because the cart was built above, finalize it with [`complete-order`](/api-reference/payment/complete-order-v2), not the one-shot `place-order`. See the [single-product flow](/solutions/agentic-commerce/flows/single-product-purchase#the-implementation-steps-phase-4-broken-out) | ## Multi-shipment specifics For apparel, items frequently ship from different warehouses. The cart response groups them into `shipments[]`. Walk each `shipment_id` separately for availability and method selection. See [Shipping & Fulfillment](/api-reference/shipment-configuration/shipping-and-fulfillment). --- ## Related - [Multi-product purchase flow](/solutions/agentic-commerce/flows/multi-product-purchase) — full walkthrough - [Why Firmly](/solutions/agentic-commerce/why-firmly) — why platform adapters matter for verticals - [Shipping & Fulfillment](/api-reference/shipment-configuration/shipping-and-fulfillment) — multi-shipment carts - [Cart API guide](/cookbook/full-cart-api-guide) — multi-step cart with variants --- # Wallet / Pass Purchase When the originating surface is a wallet, payment app, or digital pass, the user has identity and payment context **already available on the device**. The Firmly flow can lean on that context — making the conversation between the user, the wallet, and Firmly much shorter than a typical agentic flow. ## What's different from a generic agent A generic AI agent has to collect identity, address, and payment from the user during the conversation. A wallet already has all of these: | Context | Generic agent | Wallet | |---|---|---| | Who the user is | Collected during conversation | Already known (wallet account) | | Payment instrument | Card collected and tokenized in-flow | Already provisioned in the wallet | | Shipping address | Asked during checkout | Available from the wallet profile | | Identity confirmation | Conversational confirm | Biometric / device unlock | The result: a wallet-initiated purchase can be a **two-tap experience** — see product, confirm, done. ## Typical sequence ### User taps a buy action in the wallet The wallet hosts a product card, pass, or message that includes a "buy" or "purchase" action. The user taps it. ### Wallet collects biometric / device confirmation Face ID, fingerprint, PIN — whatever the wallet uses to confirm the user is present and consents. This is the **consent capture moment** — record it on the wallet side. ### Wallet calls Firmly with pre-filled context The wallet makes the agentic purchase calls (Catalog → Cart → Shipping → Complete Order), passing identity, address, and payment from the wallet's own profile. No additional user input. ### Order placed Firmly returns the merchant order number. The wallet shows confirmation in its own UI. ### Wallet updates the pass If the purchase was for a pass-like item (gift card, ticket, voucher), the wallet provisions the new pass on the device. The user sees it immediately. ## Identity handoff If the merchant supports it, the wallet can assert the user's identity so the order appears under the user's existing merchant account — not as a guest order. This is what [Firmly Connect](/solutions/firmly-connect/sso/) handles. The wallet bootstraps a Firmly session and includes a signed identity assertion (typically OIDC or SAML) that maps to the user's merchant account. The merchant sees a logged-in user place the order, with loyalty and saved addresses flowing through correctly. If the merchant doesn't support identity federation, the order is placed as a guest with the wallet's address and email — still valid, but not tied to the user's existing merchant account. ## Payment handoff Three patterns, depending on the wallet's capabilities: ### Pattern A — Wallet tokenizes, Firmly forwards The wallet has a card-on-file. It uses its own tokenization to produce a token; the token is encrypted (JWE) and passed to Firmly's `complete-order` as `encrypted_card`. This is the simplest pattern and works for any wallet with a stored card. The user never re-enters card details. ### Pattern B — Network token from the wallet For wallets with network token capability (e.g. Click to Pay, Paze), the wallet returns a network token from the card network. The token has a one-time cryptogram tied to the user's biometric confirmation. Firmly forwards this to the merchant's PSP. This pattern has better authorization rates because the cryptogram is treated as strong cardholder authentication. ### Pattern C — Wallet is the payment For wallet-native payment methods (PayPal, Klarna, Affirm), the wallet handles the entire payment flow itself. The Firmly call uses the express-checkout endpoints (e.g. [Klarna Express Checkout](/api-reference/payment/express-checkout/klarna/start)) instead of `encrypted_card`. ## Shipping for digital vs physical goods Wallet purchases tend to skew digital — gift cards, vouchers, subscriptions, passes. For these: - Skip the shipping address entirely (some merchants accept orders with no shipping info for digital SKUs) - Email is the delivery channel — pre-fill from the wallet profile - The "fulfillment" is the wallet provisioning the new pass For physical goods purchased from a wallet, the wallet's saved shipping address pre-fills `cart/shipping-info` and the flow is identical to a generic agent's flow from that point on. ## Sample code — minimal wallet flow The sample below omits response-status checks for brevity. In production, check `response.ok` on every call and handle failures — reuse the [Deep Link error-handling shape](/solutions/agentic-commerce/integration-patterns/deep-link#error-handling-shape) rather than assuming each `fetch` succeeded. For a physical-goods purchase, a shipping **method** must also be selected before `complete-order` (read the options from the `set-shipping-info` response's `shipping_method_options`, then call `set-shipping-method`); the digital-goods path below skips it because there is nothing to ship. ```javascript // Wallet has already authenticated the user via biometric. // Wallet has the user's saved address and a tokenized payment method. import { CompactEncrypt, importJWK } from 'jose'; import { randomUUID } from 'node:crypto'; async function purchaseFromWallet({ appId, domain, productRef, walletContext }) { // 1. Bootstrap Firmly session with the wallet's identity assertion const session = await fetch(`https://api.firmly.work/api/v1/browser-session`, { method: 'POST', headers: { 'x-firmly-app-id': appId, // Optionally: 'x-firmly-identity-assertion': walletContext.signedIdentity } }).then(r => r.json()); const auth = { 'x-firmly-authorization': session.access_token, 'Content-Type': 'application/json' }; // 2. Add to cart await fetch(`https://api.firmly.work/api/v2/domains/${domain}/cart/line-items`, { method: 'POST', headers: auth, body: JSON.stringify({ add_to_cart_ref: productRef, quantity: 1 }) }); // 3. Physical goods: set shipping address, then pick a method. // Digital goods: skip this whole block — nothing to ship. if (walletContext.shippingAddress) { // set-shipping-info returns the cart with shipping_method_options // populated inline on each shipment. const cart = await fetch(`https://api.firmly.work/api/v2/domains/${domain}/cart/shipping-info`, { method: 'POST', headers: auth, body: JSON.stringify(walletContext.shippingAddress) }).then(r => r.json()); // Pick a method per shipment (here: the first available on the first shipment) const shipment = cart.shipments?.[0]; await fetch(`https://api.firmly.work/api/v2/domains/${domain}/cart/shipment/methods`, { method: 'POST', headers: auth, body: JSON.stringify({ shipment_id: shipment?.shipment_id, shipping_method_id: shipment?.shipping_method_options?.[0]?.id }) }); } // 4. Encrypt the wallet's tokenized payment const jwk = await fetch(`https://cc.firmly.work/api/v1/payment/key?format=JWK`).then(r => r.json()); const publicKey = await importJWK(jwk, 'RSA-OAEP-256'); const encryptedCard = await new CompactEncrypt( new TextEncoder().encode(JSON.stringify(walletContext.paymentToken)) ) .setProtectedHeader({ alg: 'RSA-OAEP-256', enc: 'A256GCM', kid: jwk.kid }) .encrypt(publicKey); // 5. Complete the order. The cart built above is the source of truth for line items // and shipping, so complete-order finalizes that existing cart — the body carries // only encrypted_card + billing_info. (place-order would flush and rebuild the cart // from an items[] array; that's the one-shot path, not this one.) // See the complete-order v2 reference for the authoritative request body. const order = await fetch(`https://cc.firmly.work/api/v2/payment/domains/${domain}/complete-order`, { method: 'POST', headers: { ...auth, 'Idempotency-Key': randomUUID() }, body: JSON.stringify({ encrypted_card: encryptedCard, billing_info: walletContext.billingAddress || walletContext.shippingAddress }) }).then(r => r.json()); return { cartId: order.cart_id, // Firmly's internal ID statusUrl: order.urls?.thank_you_page, // merchant's confirmation page merchantRef: order.platform_order_number, // merchant's order number total: order.total }; } ``` ## Consent in wallet flows Unlike a generic agent (where consent is a conversational *"yes, buy"*), wallet consent is the **biometric confirmation on the device** plus the **on-screen total shown before the biometric prompt**. Record: - Wallet user ID - Timestamp - The displayed product, total, and merchant name - The biometric type used (Face ID, Touch ID, PIN — without the biometric data itself) - The session ID and resulting merchant order number This is your evidence for any future dispute. See [Consent & Disclosure](/solutions/agentic-commerce/consent-and-disclosure). --- # Why Firmly Connect Firmly Connect is the single integration point that distributes a merchant's catalog and checkout across every destination Firmly is connected to — so a merchant reaches AI surfaces, marketplaces, and publishers without building a separate integration for each one. ## What's in place ### Self-service onboarding A 7-step wizard handles the entire onboarding journey — KYB, catalog scope selection, destination opt-in, agreement signing, optional CDN whitelisting. The merchant submits forms and clicks toggles; Firmly handles the platform integration on its side. Most merchants onboard with little or no code. ### Adapters for a wide range of commerce platforms Firmly speaks each merchant's native API across a wide range of industry-standard commerce platforms and custom platforms. Orders land in the merchant's native order management system as if a customer placed them directly. The merchant's existing back-office workflows are unchanged. ### Distribution to every connected destination Once the merchant goes live, their catalog is reachable across the full Firmly network — AI shopping agents, publishers, marketplaces, social surfaces. New destinations connect to Firmly; merchants on Firmly Connect get distribution automatically. ### Identity and access controls Owners, editors, and viewers; per-domain SSO enforcement; Generic OIDC and SAML 2.0 today, with templates for Okta, Microsoft Entra ID, Google Workspace, Auth0, and OneLogin coming; and team invitations with role-based access. The roles, per-domain SSO, and OIDC/SAML support are built and configured through the dashboard; the named provider templates are on the way. ### Audit logging Every team action and configuration change writes a typed event to the audit log, surfaced in the portal with the actor's email recorded. ### Custom adapter support For merchants on a headless or custom commerce stack, Firmly Connect includes an in-dashboard code editor for the JavaScript adapter Firmly executes against their backend. Most merchants never need this — they sit on top of a prebuilt platform adapter. ## What the merchant doesn't have to do - Provide API credentials *(Firmly handles platform integration)* - Negotiate individual destination contracts *(opt-in via toggles)* - Implement protocol bridges *(Firmly speaks [UCP, ACP, MCP, and direct REST](/solutions/agentic-commerce/protocols/) — Universal Commerce Protocol, Agentic Commerce Protocol, Model Context Protocol, and direct REST)* - Build a separate AI-commerce checkout *(orders land in their existing OMS)* - Configure per-destination catalogs *(curate once via catalog configuration)* ## When Firmly Connect fits - The merchant has a store on any industry-standard commerce platform or a custom platform and wants to be reachable in AI shopping - The merchant wants to control which destinations they sell through without doing per-destination integration work - The merchant has identity / security requirements (SSO, audit trail, role-based access) - The merchant wants their existing back-office workflows to keep running unchanged --- ## Related - [Firmly Connect overview](/solutions/firmly-connect/) — the product summary - [Onboarding](/solutions/firmly-connect/onboarding/) — the 7-step wizard - [Portal](/solutions/firmly-connect/portal/) — daily operations - [For Merchants](/for-merchants/) — merchant-facing journey docs --- # Why Firmly for Ad Commerce Ad Commerce runs on the same Firmly platform as every other solution — you don't rebuild commerce to make an ad shoppable. What Ad Commerce adds is the framing and the attribution loop specific to advertising surfaces. ## What's shared with the rest of Firmly Discovery, cart, checkout, tax, shipping, payment, and order placement are the shared platform, documented once and used across solutions. In brief, that platform gives Ad Commerce: - **Broad merchant reach** through one integration — Firmly speaks each merchant's native API, so a single ad campaign can route to any onboarded merchant. - **Live product and pricing data** fetched from the merchant at request time — no stale catalog snapshot in the creative. - **A full cart-to-order flow** — cart, tax, shipping, payment, and order placement, with the order landing in the merchant's own OMS. - **PCI-scoped payment handling** on Firmly's side, so the ad surface never touches card data. See [Agentic Commerce → Why Firmly](/solutions/agentic-commerce/why-firmly) for the fully worked example of what the platform provides. ## What's specific to Ad Commerce - **Click-ID attribution and the conversion postback are first-class.** Firmly carries the ad platform's click-ID (`fbclid`, `gclid`, `ttclid`, `epik`) from the ad click through to the merchant's order metadata — bind it to the cart with [Set Cart Attribution](/api-reference/cart-management/set-attribution) via the `utm` field (alongside `referrer_url`, `referral_code`, and `landing_page`) — and the flow ends by firing the conversion event back to the ad platform so the campaign's optimization model learns. - **In-ad checkout works within the creative's constraints.** Purchase can complete inside the ad unit (sandboxed iframe, single-screen flow) or route to a post-click landing — see [Integration Patterns](/solutions/ad-commerce/integration-patterns/). - **Wallet-first payment.** Mobile ad surfaces lean on Google Pay to cut drop-off, with card data encrypted using JWE (JSON Web Encryption) as the fallback. - **The ad encodes the product.** The creative names the SKU, so most flows skip discovery entirely. ## Start here - [Overview](/solutions/ad-commerce/) — What Ad Commerce enables and how it fits within Firmly. - [Single Product Purchase](/solutions/ad-commerce/flows/single-product-purchase) — The flow, with click-ID capture and the conversion postback. - [Integration Patterns](/solutions/ad-commerce/integration-patterns/) — In-ad checkout vs post-click landing. - [API Reference](/api-reference/) — Every endpoint that powers Ad Commerce. --- # Why Firmly for Agentic Commerce Agentic commerce needs three things to be real: a way to reach many merchants without per-merchant negotiation, a way to land orders inside merchants' existing systems so their back-office workflows continue unchanged, and the commerce plumbing (cart, payment, tax, shipping, attribution) to be done correctly every time. Firmly already has all three, deployed across production merchant integrations. This page explains what is in place and why that matters for an agentic surface or a merchant evaluating agentic readiness. ## What Firmly is Firmly is the commerce backend that connects an AI surface (destination) to merchant commerce — across industry-standard and custom commerce platforms alike. It provides: - **Discovery** across the connected merchant catalogs - **Cart orchestration** including line items, addons, shipping, promo codes - **Payment tokenization** across PSPs, PayPal, Click to Pay, and Klarna - **Tax and shipping totals** relayed from the merchant's platform, which calculates them from its live rules — Firmly relays the results in the cart, it doesn't compute them - **Order placement** to the merchant's native platform so it lands as a normal customer order - **Affiliate attribution** so commissions and origination credit flow correctly to the destination ## What Firmly is not - Not the merchant of record — the merchant is the seller - Not a payment processor — the merchant's PSP charges the card - Not the agent — the destination owns the conversation and the user-facing surface ## The four things Firmly brings to agentic commerce ### 1. Merchants are already onboarded Merchants on Firmly are already connected to platform adapters, payment infrastructure, and affiliate routing. Bringing a merchant into agentic commerce means configuring a connection that already exists, not building a new one. A destination that integrates with Firmly reaches every connected merchant automatically. ### 2. Native platform adapters Firmly speaks each merchant's native API across a wide range of industry-standard commerce platforms and custom platforms. Orders land in the merchant's native order management system as if a customer placed them directly. The merchant's existing back-office workflows are unchanged. This is the reason merchants are willing to be on Firmly: zero workflow disruption. ### 3. Payment + attribution infrastructure already in production Firmly handles card tokenization across PSPs, PayPal, Click to Pay, and Klarna, and identifies traffic origin — detecting intermediary versus direct networks and posting attribution as merchant-originated traffic. These are not new for agentic commerce — they already run for non-agentic flows. Agentic surfaces inherit them. ### 4. Protocol translation on top of one platform Firmly speaks UCP (Google's standard), MCP (Anthropic's standard), ACP (OpenAI's standard), and direct REST. The underlying cart and checkout are identical across all of them. A destination picks the protocol that matches its agent stack; merchants do nothing different. ## Where vertical specifics live Firmly preserves the category-specific details that make each purchase correct — apparel size grids, flower delivery windows, furniture assembly options — across discovery, cart, and checkout, so the destination doesn't have to handle each category itself. For a worked-out comparison across apparel, beauty, supplements, flowers, furniture, and electronics, see the [Vertical Specialist use case](/solutions/agentic-commerce/use-cases/vertical-specialist). ## Who owns what | Responsibility | Destination | Firmly | Merchant | |---|---|---|---| | Conversational / agent UX | ✓ | — | — | | User consent and disclosure | ✓ | — | — | | Product discovery + search | depending on integration | ✓ | catalog source | | Cart, line items, addons | — | ✓ | rules | | Address validation | — | ✓ | rules | | Tax calculation | — | relays | calculates | | Shipping availability + methods | — | ✓ | rules | | Payment tokenization, PCI scope | — | ✓ | — | | Order placement to merchant | — | ✓ | — | | Affiliate attribution | — | ✓ | — | | Everything after order placement | — | — | ✓ | **Reading the cells:** ✓ = owns it outright. "rules" = the merchant's platform configuration governs the behavior and Firmly applies it. "relays" = Firmly passes the merchant's result through without computing it. "calculates" = the merchant's platform computes the value. "catalog source" = the merchant is the system of record for the data. "depending on integration" = ownership varies by the integration pattern you pick. The destination owns the experience and the consent layer. Firmly owns the commerce plumbing between the destination and the merchant — through to the moment the order is placed. Everything after that lives in the merchant's own systems. ## When Firmly fits - The destination needs reach across many merchants without negotiating per-merchant deals - The destination wants orders to land in merchants' native systems so the merchant's existing workflows continue unchanged - The destination wants a single integration that works regardless of the agent protocol (UCP, MCP, ACP, REST) - The destination is comfortable owning the conversational and consent layer on its side — Firmly does not impose a checkout UX ## When Firmly does not fit - The destination only needs to integrate with one merchant and that merchant has a usable API — direct integration may be simpler - The destination is itself the merchant (a first-party storefront) — a commerce platform is the right shape, not a routing layer - The destination needs a payment processor or fraud engine on its side — those are different categories --- ## Related - [Agentic Commerce overview](/solutions/agentic-commerce/) - [Integration Patterns](/solutions/agentic-commerce/integration-patterns/) - [Protocols](/solutions/agentic-commerce/protocols/) - [How Firmly works](/how-firmly-works) - [Consent & Disclosure](/solutions/agentic-commerce/consent-and-disclosure) --- # Why Firmly for Branded Commerce Branded Commerce needs four things to work end-to-end: a way to reach many merchants, payment infrastructure that the partner doesn't have to build, attribution that flows correctly through affiliate networks, and edge hosting that puts the experience under the partner's own domain. Firmly already has all four — Branded Commerce extends that infrastructure with partner-branded page hosting, promo handling, and engagement analytics. ## What Branded Commerce needs | Need | Why | |---|---| | **PCI handling without partner exposure** | Partners running deal ads don't want to take on PCI obligations outside their core competency | | **Broad merchant coverage** | Partners reach many merchants through Firmly's single integration, not a separate build per merchant | | **Attribution that works through affiliate networks** | The partner's commercial model depends on the affiliate network correctly crediting the conversion | | **Edge hosting under the partner's own domain** | Ad-message continuity requires the buyer to stay on the partner's surface — first-party cookies, the partner's pixels, the partner's TLS | | **Real-time merchant data** | Price, stock, variants, and images need to come from the merchant's catalog at PDP render time, not a stale snapshot | ## What Firmly brings ### Platform adapters Firmly speaks each merchant's native API — across a wide range of industry-standard commerce platforms and custom platforms. Partners don't need to know how each merchant works. Merchant integration is ongoing; new merchants are onboarded as partner demand requires. ### Payment infrastructure Tokenization across PSPs, PayPal, Click to Pay, and other accelerated payment methods. Partners never touch payment data. PCI scope sits entirely with Firmly. ### Affiliate attribution Traffic origin identification, detection of whether traffic reaches the merchant via an intermediary network or a direct affiliate relationship, and conversion posting as merchant-originated traffic. Works in either **BYO mode** (partner's own affiliate network credentials) or **Firmly-managed mode**. ### Edge hosting Firmly's edge service serves partner-branded pages globally with low latency, DDoS protection, and custom-domain support. The buyer's browser sees the partner's domain end to end. ### Ad-platform signal delivery Conversion events fire back to the originating ad platform — Meta CAPI, Google Ads Enhanced Conversions, TikTok / Pinterest / Snap / Reddit Conversions APIs — using the partner's pixel IDs and stored click context. The partner's ad campaign can attribute the conversion and optimize spend. ## What Firmly is not - **Not the partner** — the partner owns brand, ad creative, legal text, design direction, and the buyer relationship - **Not the merchant** — the merchant remains the seller of record; orders land in the merchant's existing platform - **Not the legal author** — partner provides T&C, privacy policy, disclaimers; Firmly renders them - **Not a marketing platform** — partners run their own ad campaigns; Firmly only fires conversion signals after the order - **Not a customer-service backstop** — the merchant's existing back-office workflows continue from order placement onward ## Who owns what | Responsibility | Partner | Firmly | Merchant | |---|---|---|---| | Brand and visual identity | ✓ | — | — | | Ad creative and campaign management | ✓ | — | — | | Domain and DNS | ✓ | TLS provisioning | — | | Legal text (T&C, privacy, disclaimers) | ✓ | Renders on the page | Merchant T&C displayed alongside | | Page templates and theming | Design direction | Implements theme | — | | Product data (title, price, variants, stock) | — | Fetches via adapter | Source of truth | | Cart construction and validation | — | ✓ | Cart system | | Tax and shipping calculation | — | Orchestrates | Source of truth | | Payment tokenization, PCI scope | — | ✓ | — | | Order placement | — | ✓ | Receives the order | | Affiliate attribution + conversion posting | Credentials (BYO) | Executes | — | | Ad conversion signals | Pixel IDs | Fires events | — | | Engagement analytics | Receives | Tracks | — | | Everything after order placement | — | — | ✓ (existing back-office workflows) | The partner owns the buyer experience and the commercial relationships. Firmly owns the commerce plumbing in between. The merchant remains the seller — orders land in their native platform and their existing back-office workflows continue unchanged. ## When Branded Commerce fits - The partner has a captive audience clicking on deal ads and wants to keep them on its own domain through to order - The partner wants to differentiate on ad-to-checkout UX without taking on PCI compliance or per-merchant integration - The partner wants to support enough merchants that negotiating per-merchant integrations doesn't scale - The partner already has ad-platform credentials and pixel configurations it wants Firmly to fire through ## When Branded Commerce doesn't fit - The partner is itself the merchant (a first-party storefront) — a commerce platform is the right shape, not a hosting layer - The partner needs full control over the checkout HTML/CSS at the source level — Firmly's themed templates are the surface - The partner's audience is AI agents rather than human buyers — see [Agentic Commerce](/solutions/agentic-commerce/) instead --- ## Related - [Branded Commerce overview](/solutions/branded-commerce/) - [Integration Patterns](/solutions/branded-commerce/integration-patterns/) - [Cart Lifecycle](/api-reference/cart-management/cart-lifecycle) - [Consent & Disclosure](/solutions/agentic-commerce/consent-and-disclosure) --- # Why Firmly for Marketplace Marketplace runs on the same Firmly platform as every other solution. What Marketplace adds is the operator framing: one branded surface where buyers search across many merchants, with each checkout scoped to a single source merchant. ## What's shared with the rest of Firmly Discovery, cart, checkout, tax, shipping, payment, and order placement are the shared platform, documented once and used across solutions. In brief, that platform gives a marketplace operator: - **Cross-merchant discovery** through one integration — search returns products across the operator's whole merchant set, each result carrying its source merchant. - **Live product and pricing data** fetched from each merchant at request time — no stale marketplace index to maintain. - **A single-merchant cart-to-order flow** — cart, tax, shipping, payment, and order placement, with each order landing in the source merchant's own OMS. - **PCI-scoped payment handling** on Firmly's side, so the operator's surface never touches card data. See [Agentic Commerce → Why Firmly](/solutions/agentic-commerce/why-firmly) for the fully worked example of what the platform provides. ## What's specific to Marketplace - **Discovery spans many merchants.** Marketplace search returns products across the operator's whole merchant set in one results surface; each result carries its source merchant. - **Single-merchant checkout.** Each cart is scoped to one source merchant, which stays the seller of record; the operator's UI carries the marketplace brand. - **Curation.** The operator decides which merchants appear in marketplace search and how listings are presented; product-level ratings and review counts from the catalog can be surfaced on listings. - **Operator attribution.** The marketplace operator ID is included in every order's metadata, so the operator's analytics and any commission tracking can attribute revenue. See [Single Product Purchase → Attribution](/solutions/marketplace/flows/single-product-purchase#attribution) for how the operator ID is configured and where it appears. ## Start here - [Overview](/solutions/marketplace/) — What Marketplace enables and how it fits within Firmly. - [Branded Marketplace](/solutions/marketplace/use-cases/branded-marketplace) — The primary use case. - [Integration Patterns](/solutions/marketplace/integration-patterns/) — Operator-hosted vs embedded. - [API Reference](/api-reference/) — Every endpoint that powers Marketplace. --- # Why Firmly for Publisher Commerce Publisher Commerce runs on the same Firmly platform as every other solution — you don't rebuild commerce to make an article shoppable. What Publisher Commerce adds is in-context checkout and the publisher attribution model. ## What's shared with the rest of Firmly Discovery, cart, checkout, tax, shipping, payment, and order placement are the shared platform, documented once and used across solutions. In brief, that platform gives Publisher Commerce: - **Broad merchant reach** through one integration — Firmly speaks each merchant's native API, so a Buy Now button can point at any onboarded merchant. - **Live product and pricing data** fetched from the merchant at request time — the article shows current price and availability, not a stale snapshot. - **A full cart-to-order flow** — cart, tax, shipping, payment, and order placement, with the order landing in the merchant's own OMS. - **PCI-scoped payment handling** on Firmly's side, so the publisher's article surface never touches card data. See [Agentic Commerce → Why Firmly](/solutions/agentic-commerce/why-firmly) for the fully worked example of what the platform provides. ## What's specific to Publisher Commerce - **In-context checkout keeps the reader on the article.** Buy Now buttons open an inline or slide-in checkout; after purchase the reader closes the panel and keeps reading — no redirect to a separate storefront. - **CMS embed authoring.** Writers drop a Buy Now embed into the article at publish time; the embed names the product, so most flows skip discovery. See [Embedded Buy Button](/solutions/publisher-commerce/integration-patterns/embedded-buy-button). - **Publisher and affiliate attribution.** UTM params, the publisher identifier, and the article identifier ride through to the merchant's OMS. Set them on the cart with [Set Cart Attribution](/api-reference/cart-management/set-attribution) — `utm`, `referrer_url`, `referral_code`, and `landing_page`. Affiliate commission posting to the publisher's payout system is a Firmly-managed service configured during onboarding — coordinate the setup with your Firmly contact. ## Start here - [Overview](/solutions/publisher-commerce/) — What Publisher Commerce enables and how it fits within Firmly. - [Single Product Purchase](/solutions/publisher-commerce/flows/single-product-purchase) — The in-context flow, with publisher attribution. - [Integration Patterns](/solutions/publisher-commerce/integration-patterns/) — Embedded buy button vs dedicated landing. - [API Reference](/api-reference/) — Every endpoint that powers Publisher Commerce. --- # Allowlist Firmly in your fraud tooling Firmly validates cards with a `$0` authorization before placing an order, but a merchant's own fraud tooling — whether it's built into your payment processor or a separate fraud/risk service — can still reject a legitimate order. Orders placed through Firmly can look different from a shopper on your own storefront, so a strict fraud rule may block them. If legitimate orders placed through Firmly are being fraud-blocked, **add an allow rule** so your fraud tooling trusts Firmly's traffic. ## The allow rule Firmly's requests carry a recognizable identifier you can match on. In your fraud or risk tool, add an **allow** (allowlist) rule with this condition: ```text allow if user_agent = "firmly.ai " ``` - The `` must be at least 32 characters. You can create your own, or Firmly will provide one. - Match on the full `user_agent` string so only Firmly's traffic is allowed through. ## Where you set it The exact steps depend on your payment processor or fraud provider — most expose a **rules** or **allowlist** section where you add a condition like the one above. If you're not sure where to configure it for your provider, [contact Firmly](/contact) and we'll point you to the right place. --- # Common Issues If something isn't working the way you expected, scan this page first. Each item is a real symptom-and-fix pair from common integration confusions — not raw API error codes (those are in [Errors & Conventions](/api-reference/errors-and-conventions)). ## Authentication and session ### "My App ID returns 401 / unauthorized" - Confirm you're using the App ID for the right environment (sandbox vs production) — they're different - Check the `x-firmly-app-id` header spelling — it's case-sensitive - Confirm the merchant domain you're calling is configured with Firmly. An unconfigured domain returns `404 DomainNotFound` rather than an authentication error, so check the error code before suspecting the App ID. New merchants are enabled by [Firmly](/contact) ### "My session JWT expired faster than I expected" - Browser session tokens have a 1-hour active lifetime, renewable while session state persists (~7 days from last activity) - After 1 hour, call `/api/v1/browser-session` again to refresh - For backend agents, use [server-to-server auth](/api-reference/authentication/server-to-server) instead — no session expiration concern ### "I can't tell if I'm hitting sandbox or production" - General calls go to the sandbox hosts `api.firmly.work` (general) and `cc.firmly.work` (payment). **Production uses different hosts**, provided by Firmly at go-live - Which environment you're in is determined by your **App ID** (sandbox vs. production) and the **merchant domain** you call - A **sandbox App ID** against the sandbox hosts with a test merchant (e.g., `staging.luma.gift`) is non-production end-to-end ### "I'm getting a 403 / Forbidden on calls that should work" Some HTTP clients send a default `User-Agent` (for example `Python-urllib`, or an unlabeled agent) that the sandbox's bot-protection blocks with a `403`. `curl`, browsers, and mainstream SDKs usually pass as-is; setting a browser-style `User-Agent` header explicitly makes every client work, so it's the reliable fix if you hit a `403`. ```bash curl -X POST https://api.firmly.work/api/v1/browser-session \ -H "x-firmly-app-id: " \ -H "User-Agent: Mozilla/5.0 (compatible)" ``` ## Discovery and catalog ### "Discovery returns an empty `products` array" - Confirm the merchant has products loaded into the catalog ([Firmly](/contact) can verify) - Confirm at least one merchant is configured in the environment you're calling — discovery returns an empty list when none are - The `query` is searched against catalog text — overly narrow queries return nothing; broaden to test ### "Product images aren't loading" - Product image `url` fields are merchant-served, not Firmly-served. Image loading depends on the merchant's CDN - Some merchants serve relative URLs; treat the `url` field as authoritative and don't reconstruct paths yourself ## Cart ### "My cart disappears after I expected it to persist" - Cart state in Firmly's edge has a 7-day TTL - After 7 days, the cart is garbage-collected and `GET /cart` returns `404 CartNotFound` — add an item to create a new cart - For agents that build a cart over days/weeks, store the relevant pieces (line item references, addresses) on your side ### "Setting a new shipping address removed my shipping method selection" - This is expected behavior. Shipping methods are address-specific. After changing the address, re-read the shipment's `shipping_method_options` from the cart and re-select a method. ### "Promo code returned 200 but the cart total didn't change" - The code may have been silently rejected (e.g., minimum cart value not met, category exclusion, expired) - Always re-read the cart after applying a promo and compare the field the promo actually moves — `sub_total` for line-item discounts, but `total` / `cart_discount` for order-level and free-shipping promos - Check `cart.notices` for codes like `PROMO_NOT_APPLICABLE` or `PROMO_EXPIRED` ## Shipping and fulfillment ### "I see multiple `shipment_id`s in one cart for the same merchant" - Multi-shipment is intentional for merchants whose items ship from different warehouses or have different fulfillment timelines - Walk each `shipment_id` separately, reading its `shipping_method_options` and recording a method — see [Shipping & Fulfillment](/api-reference/shipment-configuration/shipping-and-fulfillment) ### "Get-availability returns 501 NotImplemented" - Some merchants (V1 adapters) don't expose this endpoint. It doesn't block checkout: `get-availability` only returns delivery dates, time slots, and pickup locations — never shipping methods. Read shipping methods from `cart.shipments[].shipping_method_options` (populated inline after `set-shipping-info`) and proceed. ## Payment and place-order ### "Place-order returns 200 but the merchant says no order arrived" - Check `cart.cart_status` in the response — it should be `submitted` for a successful placement - Check `platform_order_number` in the cart response for the merchant's native order number - Some merchants delay reflecting orders in their admin UI for a few seconds after placement; re-check shortly ### "I'm getting different results when I retry a place-order call" - The core REST endpoints don't deduplicate on `Idempotency-Key` today — a retry re-runs the operation - Before retrying, re-read the cart and check `cart_status`: if it's `submitted`, the original attempt succeeded and retrying would double-place - See [Idempotency in Errors & Conventions](/api-reference/errors-and-conventions#idempotency) ## Dropin and embedded checkout ### "The embedded iframe loads but I don't see any postMessage events" - Confirm your `event.origin` check matches the Firmly dropin origin your representative provided - Ensure your iframe has `allow="payment; clipboard-read; clipboard-write"` - Check the browser console for cross-origin warnings ### "The user completed checkout in the dropin but my page didn't update" - Listen for `firmly::OrderPlaced` postMessage events — this is the canonical signal - See [Embedded Checkout — postMessage events](/solutions/agentic-commerce/integration-patterns/embedded-checkout) ## Status-code lookup When you get an HTTP status back and want to know where to start, use this table. The named `error` value in the response body is the precise signal — the [full error catalog](/api-reference/errors-and-conventions) maps each name to its cause and recovery. | Status | Likely cause | Where to look | |---|---|---| | **400** | Bad request — malformed body, a missing required parameter, or an invalid query value | The endpoint's own Error Responses, plus [Errors & Conventions](/api-reference/errors-and-conventions) | | **401** | Unauthorized — missing, expired, or invalid token, or an App ID not recognized in this environment | [Authentication](/api-reference/authentication/) and the "My App ID returns 401" item above | | **403** | Forbidden — the credential is recognized but not permitted for this merchant or resource (App ID scoped away from the merchant) | [Security Model → per-merchant isolation](/foundations/security-model) · [Firmly](/contact) to confirm scope | | **404** | Not found — `DomainNotFound` (wrong domain or environment), `CartNotFound` (cart expired or never created), or `ProductNotFound` | The endpoint's Error Responses; Discovery and Cart items above | | **409** | Conflict — a business-logic clash such as `NotEnoughStockError`, `ShipmentNotAvailable`, or `InvalidPromoCode`. Re-read the cart before retrying. **Also** `payment_challenge_required`, which is not a failure: the shopper must complete card verification, then you resume | [Errors & Conventions](/api-reference/errors-and-conventions) · [Resume After Challenge](/api-reference/payment/complete-order-v2-resume) | | **412** | Precondition failed — a required step wasn't completed or the merchant doesn't support it: `OperationNotSupported`, `RequiredConsentsNotSigned`, `CountryNotSupported`, `CheckoutError` | [Errors & Conventions](/api-reference/errors-and-conventions) | | **422** | Unprocessable — a valid body rejected downstream; most card declines (`CreditCard*`) and `UnprocessableEntity`. Don't silently retry a decline | [Complete Order → Error Responses](/api-reference/payment/complete-order-v2#error-responses) | | **429** | Rate limited (`RateLimited`) — too many requests. Honor the `Retry-After` header and back off | [Rate Limits](/api-reference/rate-limits) | | **5xx** | Server or merchant unavailable — `503 StoreUnavailable` (merchant adapter temporarily unreachable) or `500 Unexpected`. Retry with exponential backoff | [Errors & Conventions](/api-reference/errors-and-conventions) | ## Payment encryption (JWE) errors If a payment call fails with a decryption or key error, the card object was almost certainly encrypted in a way Firmly can't unwrap. The card never left your side in cleartext (encryption happens client-side — see [Security Model → Card encryption](/foundations/security-model)), so these are all fixable before you retry. Common causes: - **Wrong or stale key id (`kid`)** — the `kid` in your JWE protected header doesn't match the key Firmly is currently using. Re-fetch [Get Public Key](/api-reference/payment/get-public-key), use the `kid` it returns (also in the `x-firmly-kid` response header), and re-encrypt. - **Expired / rotated public key** — Firmly rotates the payment key periodically, so a cached key can go stale. Re-fetch the key on any decryption/key error and retry once; the refetch-on-error pattern is safe regardless of cache age. - **Algorithm mismatch** — the JWE must use `RSA-OAEP-256` for key wrapping and `A256GCM` for content encryption. A raw RSA-OAEP ciphertext (e.g. from Web Crypto `subtle.encrypt`) is not a JWE and won't decrypt — use a maintained JOSE library and set both `alg` and `enc` in the protected header. - **Malformed card number** — the plaintext card object's `number` (PAN) is incomplete or malformed before encryption. This decrypts fine but is rejected downstream as `CreditCardInvalidNumber` (422) — re-collect the card details. ## Still stuck If your symptom isn't here, check: - [FAQ](/faq) — conceptual / process questions - [Errors & Conventions](/api-reference/errors-and-conventions) — specific HTTP / UCP error codes - [Firmly](/contact) for issues that need account-level inspection --- # Reporting an Issue When something is wrong and you can't resolve it, send us this list. It is the same list every time, and it is usually enough to find your exact request in our logs on the first reply. For routine issues, email the details to [firmlydocs@firmly.ai](mailto:firmlydocs@firmly.ai). If your live integration is down, contact your Firmly account team or on-call contact directly. The docs inbox is not monitored 24/7. Use the list below when you report the incident. ## What to send | What it is | Where to find it | |---|---| | **`CF-RAY`** — Identifies one request; the most useful detail for finding the exact call. | The `CF-RAY` response header on every Firmly response | | **`device_id` (optional)** — Identifies the buyer's session across calls. | The [browser-session](/api-reference/authentication/browser-session) response or session JWT | | **Time (UTC)** — Narrows the search. | When you made the request | > **Warning** > **Don't send your App ID or your Server-to-Server secret.** An App ID authenticates on its > own — anyone holding it can call the API as you. If you need to tell us which App ID you were > using, send the **first 8 characters only**. That is enough for us to identify it and not > enough for anyone to use it. ## Reading the CF-RAY header Every response from Firmly carries it: ```bash curl -i https://api.firmly.work/api/v1/browser-session \ -X POST -H "x-firmly-app-id: YOUR_APPLICATION_ID" | grep -i '^cf-ray' ``` ``` cf-ray: 881d0d5048e6752c-SEA ``` The part after the dash is the Cloudflare location that served the request. Send the whole value, including it. Capture it in your own logging too — the header is on successful responses as well as failures, so logging it for every call means you already have it when something goes wrong later. ## An example report ``` CF-RAY: 881d0d5048e6752c-SEA Time (UTC): 2026-10-13T14:22:06Z device_id (optional): fdf5c4d6-4f21-43a8-90f1-11e202e5d782 ``` ## Before you send Two things resolve most reports without an email: - If the response includes an **`error` value**, look it up in [Errors & Conventions](/api-reference/errors-and-conventions). Every error we return is listed there with what causes it and how to recover. - **Check [Common issues](/troubleshooting/common-issues)** for the symptom. Configuration mismatches and first-week gotchas are collected there. --- # Technical FAQ For evaluation-stage questions, see the [General FAQ](/faq). For solution-specific questions, see the [Agentic Commerce](/solutions/agentic-commerce/faq) or [Branded Commerce](/solutions/branded-commerce/faq) FAQ. ## Environments and credentials ### What's the difference between sandbox and production? Different hosts, different App IDs, different merchant domains. The sandbox host is `api.firmly.work`; the production host differs and is published at go-live. Sandbox App IDs reach test merchant stores (typically `staging.` prefix domains) and production App IDs reach live merchants, because each environment carries its own set of configured merchants. Read the host from configuration rather than hard-coding it, so the move to production is a config change. ### How do I get a sandbox App ID? Contact [Firmly](/contact). They provision the App ID and the test merchant pairing. ### Can I move from sandbox to production without code changes? Yes — for the API integration. Going live is a configuration change (swap the App ID, swap the merchant domain). What does change: real cards instead of test cards, real merchant catalogs, real fulfillment. ### Which base URLs do I use? | Purpose | Base URL | |---|---| | Main API (cart, checkout, discovery, etc.) | `https://api.firmly.work` | | Commerce / checkout API (place-order family) | `https://cc.firmly.work` | | Test merchant for sandbox | `staging.luma.gift` | See [Authentication](/for-destinations/authentication) for the auth headers each requires. ## Authentication ### When should I use browser session vs server-to-server? | Use browser session when… | Use server-to-server when… | |---|---| | The destination acts on behalf of a specific user session | The destination is a backend service with its own identity | | You need cart and order tied to a user's device | You're orchestrating from a backend (scheduled buying, B2B) | | The session is short-lived (per chat or shopping session) | You need long-lived service identity | See [Authentication](/for-destinations/authentication). ### How long does a session JWT live? Active for 1 hour; renewable while the session state is still retained (~7 days from last activity — not a fixed server-enforced window). After that, bootstrap a fresh session via [Browser Session](/api-reference/authentication/browser-session) or [Server-to-Server](/api-reference/authentication/server-to-server). ### Can I share a session JWT across users? No. Each session JWT is tied to a single `device_id`. Reusing a JWT for a different user mixes their cart state. ## Protocols ### Do I have to use UCP, MCP, or ACP? No. Direct REST is always available and is the universal path. The protocols are translation layers for specific agent platforms. See [Protocols](/solutions/agentic-commerce/protocols/). ### Which protocol should my AI chat product use? If your platform supports MCP-Apps, use MCP. Otherwise direct REST. See [AI surfaces](/solutions/destination-surfaces/ai-surfaces). ### Can I mix protocols in a single flow? No. A given session uses one protocol. The choice is per-integration, not per-call. ## Idempotency and retries ### What's the idempotency window? 24 hours per `Idempotency-Key`. Same key + same request payload within the window returns the cached response. Same key + different payload returns an idempotency conflict error. See [Idempotency](/solutions/agentic-commerce/protocols/ucp/idempotency). ### Which endpoints accept Idempotency-Key? The **UCP protocol bridge** deduplicates on it for create/complete/cancel operations. The core REST endpoints accept the header but do not act on it today — send it for forward compatibility, not for retry-safety. ### How do I retry safely after a network blip? On the UCP bridge, reuse the **same** `Idempotency-Key` — Firmly returns the original response if the operation completed. On the core REST endpoints, re-read state before retrying: after a failed `place-order`, fetch the cart and check `cart_status` — if it's `submitted`, the order went through and you must not retry. ## Rate limits ### What are the rate limits? Limits vary by endpoint and authentication mode. The endpoints most likely to hit limits are the OTP / verification endpoints. Specific thresholds are shared during commercial onboarding. See [Rate Limits](/api-reference/rate-limits) for the current limits. ### How do I detect a rate-limit hit? HTTP `429 Too Many Requests`. The response includes a `Retry-After` header indicating how long to wait before retrying. ### Are rate limits per-device or per-account? Per-device for browser-session calls. Per-account for server-to-server. The exact scope is endpoint-specific — see [Rate Limits](/api-reference/rate-limits). ## Versioning ### How are API versions handled? V1 and V2 endpoints coexist. New integrations should use V2 for cart, place-order, and complete-order. V1 is maintained for existing integrations. See [API Reference](/api-reference/). ### Will V1 stay around? V1 endpoints stay supported as long as merchants and destinations rely on them. There is no scheduled deprecation today. The [Changelog](/resources/changelog) tracks any version changes. --- ## Related - [General FAQ](/faq) — evaluation-stage questions - [Agentic Commerce FAQ](/solutions/agentic-commerce/faq) — solution-specific - [Branded Commerce FAQ](/solutions/branded-commerce/faq) — solution-specific - [Idempotency](/solutions/agentic-commerce/protocols/ucp/idempotency) - [Rate Limits](/api-reference/rate-limits) - [Protocols](/solutions/agentic-commerce/protocols/) - [Errors & Conventions](/api-reference/errors-and-conventions) - [Common issues](/troubleshooting/common-issues) --- # Troubleshooting When something doesn't work the way you expected, start here. This section covers the most common confusions encountered in the first week of integration — not API errors (those live in [Errors & Conventions](/api-reference/errors-and-conventions)) but operational gotchas, configuration mismatches, and "is this supposed to work this way?" questions. - [Common issues](/troubleshooting/common-issues) — Symptoms and fixes — "I'm seeing X" → "do Y." Concrete scenarios with root causes. - [General FAQ](/faq) — Questions developers ask once and then never again — auth, sandbox vs production, multi-merchant, scope. - [Reporting an issue](/troubleshooting/reporting-an-issue) — What to send us when you need help — the one list, same every time. - [Technical FAQ](/troubleshooting/faq-technical) — Deeper implementation questions — request shapes, error handling, encryption, and edge cases. ## Where this section sits in the docs | If you're seeing... | Go to | |---|---| | A specific HTTP error or UCP error code | [Errors & Conventions](/api-reference/errors-and-conventions) | | A symptom or "this isn't doing what I expected" | [Common issues](/troubleshooting/common-issues) | | A conceptual or process question | [General FAQ](/faq) | | A deeper implementation question | [Technical FAQ](/troubleshooting/faq-technical) | | A platform-specific behavior question | The relevant [platform page](/for-merchants/supported-platforms) | | Something you cannot resolve and need us to trace | [Reporting an issue](/troubleshooting/reporting-an-issue) | | An open question after reading the above | [Firmly](/contact) | ## When to escalate If you've checked the catalog and FAQ, instrumented logs, and still can't reproduce or resolve, see **[Reporting an issue](/troubleshooting/reporting-an-issue)**. It lists exactly what to send — the `CF-RAY` header above all — so we can find your request on the first reply. - [Allowlist Firmly in your fraud tooling](/troubleshooting/allowlist-firmly/index.md) ---