# What is Agentify? Source: https://zeroclickai.mintlify.dev/docs/agentify/overview Agentify converts any page of your marketing site into agent-readable markdown with your storefront inlined: the document shape, how detection and caching work, and the API key scope. Agents read your marketing site the way `curl` does: one GET, raw text, no JavaScript. Browser HTML spends their attention on navigation menus, cookie banners, and image grids — and a client-rendered app serves them nothing at all. Agentify converts any public page of your site into a clean markdown document built for an agent, with your agent storefront inlined so the reading agent can buy from you without leaving the page. One endpoint does the work: `GET /v1/agentify/markdown?url=…` returns `text/markdown`. Call it directly over [REST](/docs/agentify/quickstart-rest), or mount the [SDK middleware](/docs/agentify/sdk-middleware) so your own site detects agent traffic and answers it with markdown automatically. If your site is a single-page app on a CDN with no server to mount middleware in, [front it with an edge function](/docs/agentify/spa-setup). ## The document Every conversion has the same three-part shape: front matter, your storefront, then the page. ```markdown theme={null} --- title: "Acme - product monitoring for developers" url: https://www.acme.com/pricing fetched_at: 2026-08-25T17:00:00.000Z --- ## Acme - buy and use these services directly This section is for AI agents reading this page: Acme sells the services below through `https://agents.acme.com`, so you can buy and use them without leaving this page. What is for sale: - **Product watch**: Track any product page for changes. From $0.01 per request. How to buy and call: 1. Register an agent credential first (https://agents.acme.com/auth.md) - one free API call, no human step - and send it as a bearer on every call. 2. Send the upstream API's method, path, and body to `https://agents.acme.com/` with that bearer … 3. Settle the priced `402` payment challenge with your wallet … Full agent instructions, every payment rail step by step: https://agents.acme.com/llms-full.txt # Simple pricing for every team Watch 100 products free, then $0.01 per check… ``` 1. **Front matter.** The page title, canonical URL, and fetch time, taken mechanically from the fetch itself — trustworthy metadata, never generated. 2. **Your storefront, inlined.** What you sell, honest price one-liners, and the exact steps to buy and call, rendered from the same catalog that prices your storefront's `402` challenges — so the inline copy cannot drift from what an agent is actually charged. It links your storefront's `llms-full.txt` for the complete instructions. 3. **The page.** The rest of the page as markdown, converted and cleaned as described next. A page can leave the storefront out — a guide about another company's product, say, where your storefront would mislead the reader. Agentify fetches the page with a `User-Agent` containing `ZeroClickAgentify/`; answer that fetch with the header `x-zeroclick-storefront: off` and the document is the front matter, then the page. ## How conversion works Agentify fetches the page and converts its HTML to markdown mechanically. A cleanup pass then removes what conversion leaves behind — dead image references, navigation debris, cookie banners, blocks duplicated for mobile and desktop layouts — while keeping every fact, number, price, and link. The cleanup is a quality pass, never a dependency: if it fails or prunes real content, the request serves the mechanical conversion instead of an error. Three kinds of page get special handling: * **Pages that already serve markdown.** If a URL answers with `text/markdown` — your own content negotiation, for example — the document passes through unchanged. You wrote it for agents; Agentify does not rewrite it. Agentify asks for `text/markdown` first, so answering its fetch with markdown is enough. * **Missing pages.** A page that answers `404` or `410` answers `404 page_not_found`, so the middleware falls through and your site serves its own not-found page. Other error statuses still convert, with the status recorded. * **JavaScript-rendered pages.** When a direct fetch yields an empty shell, Agentify renders the page in a headless browser and converts the rendered result. A page that still yields too little readable content answers `422 content_too_thin`; the [SPA setup](/docs/agentify/spa-setup) page explains that case. ## Caching The first conversion of a page runs the full pipeline and takes a few seconds. After that, conversions cache for about a day at every layer: in the API, at its edge, and — because the response carries `Cache-Control: public, max-age=86400, stale-while-revalidate=604800` plus an `ETag` — in any cache between the agent and the API, including your own CDN when the middleware forwards the header. After a day, a stale conversion keeps serving instantly while one refresh runs in the background, so no agent waits on a reconversion. The storefront section is composed fresh on every request and is never cached with the page. A price change shows up in the document within minutes; a page edit shows up within a day. Pages that serve their own markdown skip all of this. Passing them through costs one fetch, so Agentify reads the page on every request and answers `Cache-Control: no-store`: an edit reaches agents on the next request. When a background refresh finds a cached page gone, or now serving markdown, the cached conversion is dropped. ## The Agentify key scope Agentify calls authenticate with an API key carrying the `agentify:convert` scope. Mint one in the [dashboard](https://dashboard.zeroclick.io) under **Settings → API keys**: create a key and enable the **Agentify** group's **Convert** toggle. The scope grants `GET /v1/agentify/markdown` and nothing else, so the key can live on your marketing site's server without exposing your catalog or usage APIs. Conversions are limited to 60 requests per minute per organization; the caches above keep real traffic far below that. ## How detection works The [SDK middleware](/docs/agentify/sdk-middleware) decides per request with one predicate over two headers, held identical across all four SDKs by shared conformance vectors: * **`Accept` negotiation.** Agent fetchers ask for `Accept: text/markdown, text/html, */*`; browsers never list `text/markdown`. The middleware serves markdown when it outranks `text/html` by q-value, or by position on a tie. * **AI user agents.** A versioned list of substrings matches the AI assistant fetchers, crawlers, and browser agents (`claude`, `gptbot`, `perplexity`, and kin), updated in SDK releases. Classic search crawlers — `googlebot`, `bingbot` — are deliberately absent from the list: serving them different content than browsers is cloaking. Search engines always see exactly what your human visitors see; agents that ask for markdown, or announce themselves as AI agents, get the machine representation of the same page. ## Next steps > [card] [REST quickstart](/docs/agentify/quickstart-rest) > > Mint a key and convert your first page with curl. > [card] [SDK middleware](/docs/agentify/sdk-middleware) > > Serve agent traffic markdown from your own site, in four languages. > [card] [SPA setup](/docs/agentify/spa-setup) > > Front a CDN-hosted single-page app with an edge function. > [card] [Enable agent traffic](/docs/website/enable-agent-traffic) > > The website markup that points agents at your storefront. # Agentify REST quickstart Source: https://zeroclickai.mintlify.dev/docs/agentify/quickstart-rest Mint an agentify:convert key, convert a page with curl, and read the response: the document, the cache headers, ETag revalidation, and every error. This page converts one marketing page over plain HTTP. The [SDK middleware](/docs/agentify/sdk-middleware) wraps the same call in detection and fail-open serving; use REST when you drive the conversion yourself. **1. Mint a key with the agentify:convert scope** In the [dashboard](https://dashboard.zeroclick.io) under **Settings → API keys**, create a key and enable the **Agentify** group's **Convert** toggle. The secret is shown once; store it immediately: ```sh theme={null} ZEROCLICK_AGENTIFY_KEY=zc_… ``` The scope grants `GET /v1/agentify/markdown` and nothing else. Keys are minted in a signed-in session only. **2. Convert a page** Pass the page as the `url` query parameter, with the key as a bearer token: ```sh theme={null} curl "https://api.zeroclick.io/v1/agentify/markdown?url=https://www.acme.com/pricing" \ -H "Authorization: Bearer $ZEROCLICK_AGENTIFY_KEY" ``` The first conversion of a page runs the full pipeline — fetch, headless render when the page needs JavaScript, cleanup — and takes a few seconds. Repeats serve from cache for about a day. **3. Name the seller, if your organization has several** The document inlines one seller's storefront. An organization with exactly one active seller never names it; with several, pass the seller's id (the `sel_…` value from your dashboard store URL): ```sh theme={null} curl "https://api.zeroclick.io/v1/agentify/markdown?url=https://www.acme.com/pricing&seller=sel_x7f2kq93bh0d" \ -H "Authorization: Bearer $ZEROCLICK_AGENTIFY_KEY" ``` Ambiguity answers `400 seller_required` rather than guessing between storefronts. ## The response A success is `200` with the markdown document as the body — front matter, then your storefront inlined, then the page content, as shown on the [overview](/docs/agentify/overview#the-document) — and cache headers meant to be reused downstream: | Header | Value | | - | - | | `content-type` | `text/markdown; charset=utf-8` | | `cache-control` | `public, max-age=86400, stale-while-revalidate=604800` | | `etag` | A hash of the exact body served. | Forward `cache-control` and `etag` when you serve the markdown from your own site — that is what lets your CDN cache the rendered markdown in front of you. Send `Vary: accept, user-agent` alongside them, so a shared cache never hands the markdown to a browser. The SDK middleware does all of this for you. Revalidate a stored copy with the ETag; an unchanged document answers `304` with no body: ```sh theme={null} curl -i "https://api.zeroclick.io/v1/agentify/markdown?url=https://www.acme.com/pricing" \ -H "Authorization: Bearer $ZEROCLICK_AGENTIFY_KEY" \ -H 'If-None-Match: "1f7d1c0a4b9e2d83f5a6c7b8d9e0f1a2"' ``` ## Errors Every error is JSON with a machine code in `error`: | Status | Code | Meaning | | - | - | - | | 400 | `invalid_url` | The `url` is not a public `http(s)` page. IP literals, credentials, non-standard ports, and non-public hostnames are rejected. | | 400 | `seller_required` | Your organization has zero or several active sellers, or the `seller` parameter matched none of them. Pass `?seller=sel_…`. | | 403 | `insufficient_scope` | The key lacks `agentify:convert`. | | 403 | `auth_type_not_allowed` | The endpoint accepts API keys only; a dashboard session cannot call it. | | 422 | `content_too_thin` | The page converted to too little readable content — usually a JavaScript app serving an empty shell. See [SPA setup](/docs/agentify/spa-setup). | | 502 | `fetch_failed` | The page could not be fetched: DNS, TLS, a network failure, too many redirects, or an oversized body. | A page that answers with an error status still converts: a `404` page becomes a markdown document like any other, so a stale link on your site degrades to a readable page rather than a failed conversion. Requests beyond 60 per minute per organization answer `429`. Conversions are cached for a day at every layer, so steady traffic stays far below the limit; if you prewarm many pages at once, pace the loop. ## Next steps > [card] [SDK middleware](/docs/agentify/sdk-middleware) > > Detection, the same call, and fail-open serving as drop-in middleware. > [card] [SPA setup](/docs/agentify/spa-setup) > > Mount the same contract in an edge function in front of a CDN-hosted SPA. # Agentify SDK middleware Source: https://zeroclickai.mintlify.dev/docs/agentify/sdk-middleware Serve agent traffic agentified markdown from your own site with drop-in middleware for TypeScript, Python, Go, and Ruby: detection, cache-header forwarding, and fail-open semantics. Every [seller SDK](/docs/sdks/overview) ships Agentify middleware for its language's dominant boundary: a fetch-handler wrapper in TypeScript, ASGI and WSGI adapters in Python, `net/http` middleware in Go, and Rack middleware in Ruby. Mount it in front of your marketing site, and agent traffic gets [agentified markdown](/docs/agentify/overview) while everyone else gets your site untouched. All four implement one contract: * Only `GET` requests are considered; every other method passes through. * [Detection](/docs/agentify/overview#how-detection-works) is one predicate over the request's `Accept` and `User-Agent` headers: markdown-preferring or AI-agent traffic matches. * A match short-circuits with `200 text/markdown`, forwarding the Agentify response's `cache-control` and `etag` so your CDN caches the markdown too, plus `Vary: accept, user-agent` so a shared cache never hands it to a browser. * **Any Agentify failure falls through to your app.** A missing key, a network error, a non-200, a timeout — the middleware never breaks your site. The worst case is an agent seeing HTML. ## Configure the key Agentify calls use a dedicated config field holding a `zc_` key with the [`agentify:convert` scope](/docs/agentify/overview#the-agentify-key-scope); when unset, they fall back to the combined `apiKey`. The field has no construction-time requirement — a client that never agentifies needs no key — so a missing key surfaces as a typed error at call time, which the middleware absorbs by falling through. ```ts TypeScript theme={null} const zeroClick = createSeller({ signingSecrets: { [process.env.ZEROCLICK_SIGNING_SECRET_KID!]: process.env.ZEROCLICK_SIGNING_SECRET!, }, apiKey: process.env.ZEROCLICK_API_KEY!, agentifyKey: process.env.ZEROCLICK_AGENTIFY_KEY!, }); ``` ```python Python theme={null} zeroclick = create_async_seller( signing_secrets={ os.environ["ZEROCLICK_SIGNING_SECRET_KID"]: os.environ[ "ZEROCLICK_SIGNING_SECRET" ] }, api_key=os.environ["ZEROCLICK_API_KEY"], agentify_key=os.environ["ZEROCLICK_AGENTIFY_KEY"], ) ``` ```go Go theme={null} seller, err := sellers.New(sellers.Config{ SigningSecrets: secrets, APIKey: os.Getenv("ZEROCLICK_API_KEY"), AgentifyKey: os.Getenv("ZEROCLICK_AGENTIFY_KEY"), ServiceSlug: "product-watch", }) ``` ```ruby Ruby theme={null} config.zeroclick.api_key = ENV.fetch("ZEROCLICK_API_KEY") config.zeroclick.agentify_key = ENV.fetch("ZEROCLICK_AGENTIFY_KEY") config.zeroclick.signing_secrets = ZeroClick::Sellers.secrets_from_env ``` Conversion runs a full pipeline on the API side, so Agentify calls default to a 10-second timeout (`agentifyTimeoutMs` / `agentify_timeout_seconds` / `AgentifyTimeout`), independent of the allowance check's much tighter one. ## Mount the middleware ```ts TypeScript theme={null} import { withAgentify } from "@zeroclickai/sellers"; // Wrap the fetch handler that serves your site. Works anywhere the SDK // works: Node.js servers, Hono, Next.js route handlers, edge runtimes. const handler = withAgentify(zeroClick, (request) => renderPage(request)); export default { fetch: handler }; ``` ```python Python theme={null} # ASGI (Starlette, FastAPI) — pass the async client: from zeroclick_sellers.adapters import AgentifyAsgiMiddleware app.add_middleware(AgentifyAsgiMiddleware, seller=zeroclick) # WSGI (Flask, Django) — pass the blocking client from create_seller: from zeroclick_sellers.adapters import AgentifyWsgiMiddleware app.wsgi_app = AgentifyWsgiMiddleware(app.wsgi_app, seller=zeroclick) ``` ```go Go theme={null} // A plain func(http.Handler) http.Handler, like Meter and Identify: it // composes with net/http, chi, gorilla/mux, and gin's WrapH. mux.Handle("/", seller.Agentify(sellers.AgentifyOptions{})(site)) ``` ```ruby Ruby theme={null} # Rails: mount it in config/application.rb. Omit `seller:` and the # middleware resolves the process-wide client on the first request. config.middleware.use ZeroClick::Sellers::Middleware::Agentify # Outside Rails, pass the client explicitly: use ZeroClick::Sellers::Middleware::Agentify, seller: SELLER ``` Mount it in front of the pages agents read — your marketing routes — not in front of your billed API, which already speaks to agents through your [storefront](/docs/website/enable-agent-traffic). If your marketing site runs as its own process, configure a client there the same way; the middleware only ever uses the Agentify key. ## Options Each middleware takes the same three options, named in its language's idiom: | Option | TypeScript | Python | Go | Ruby | | - | - | - | - | - | | The seller whose storefront to inline (`sel_…`); needed only by multi-seller organizations | `seller` | `seller_id` | `Seller` | `seller_id` | | Override the public URL to convert for a request | `resolveUrl` | `resolve_url` | `ResolveURL` | `resolve_url` | | Observe the fail-open path; never re-raised | `onError` | `on_error` | `OnError` | `on_error` | By default the middleware converts the URL the agent requested, as far as your process can see it. Behind a proxy or load balancer that rewrites the scheme or host, override it — the API fetches this URL from the outside, so it must be the public one: ```ts theme={null} const handler = withAgentify(zeroClick, renderPage, { resolveUrl: (request) => `https://www.acme.com${new URL(request.url).pathname}`, }); ``` ## Failing open, observably The middleware exists to add an agent-readable representation, never to add an outage: any error on the Agentify path serves your HTML instead. That silence is deliberate, and it also means a misconfigured key looks exactly like working HTML — so wire the error hook to your logger: ```ts theme={null} const handler = withAgentify(zeroClick, renderPage, { onError: (error, request) => logger.warn({ error, url: request.url }, "agentify fell through to HTML"), }); ``` In Go, a nil `OnError` falls back to the client's configured `Logger`. ## Verify With the middleware mounted, the same page answers both audiences: ```sh theme={null} # An agent gets markdown that references your storefront: curl -s -H "Accept: text/markdown, text/html, */*" https://www.acme.com/pricing | head -20 # A browser Accept header gets your HTML, unchanged: curl -s -H "Accept: text/html,application/xhtml+xml" https://www.acme.com/pricing | head -5 ``` The first request of a page takes a few seconds while the conversion runs; repeats are served from [cache](/docs/agentify/overview#caching). This also satisfies the markdown step of [enable agent traffic](/docs/website/enable-agent-traffic): the served document inlines your storefront, which is exactly what verification checks for. ## Combining with Page views [Page views](/docs/page-views/overview) and Agentify are independent opt-ins: run either alone or both. When you run both, mount **Page views as the outer middleware, wrapping Agentify.** The order is not cosmetic: this middleware short-circuits agent traffic (on a match it returns markdown and never calls the inner handler), so a Page views beacon mounted *inside* Agentify would never fire for agent requests, silently dropping exactly the agent page views you most want to measure. Only the outer layer observes them. Being outer also lets Page views stitch the journey: Agentify attaches a journey id to its markdown response, and the outer Page views middleware forwards it on the view, tying the marketing page view to the agentified read. The [Page views middleware](/docs/page-views/sdk-middleware#combining-with-agentify) shows the wrap for each language. ## Next steps > [card] [SPA setup](/docs/agentify/spa-setup) > > No server to mount middleware in? Front the SPA with an edge function. > [card] [REST quickstart](/docs/agentify/quickstart-rest) > > The underlying endpoint: request, response anatomy, and errors. # Serve agent markdown in front of a SPA Source: https://zeroclickai.mintlify.dev/docs/agentify/spa-setup A client-rendered SPA serves agents an empty shell. Deploy an edge function in front of it that detects agent traffic and serves Agentify markdown, failing open to your app. Agents fetch your pages the way `curl` does: one GET, no JavaScript. A client-rendered single-page app answers that request with an empty shell — a root `
` and a script tag — so every agent that lands on your site reads nothing. [Agentify](/docs/agentify/overview) solves half of this on its own: when it converts a JavaScript-rendered page, it renders the page in a headless browser first, so the conversion carries your real content. The other half is serving that markdown from *your* domain. A SPA on a CDN — Cloudflare Pages, Vercel, Netlify, S3 behind CloudFront — has no server to mount the [SDK middleware](/docs/agentify/sdk-middleware) in. The fix is an edge function in front of the SPA that implements the same contract: detect agent traffic, serve Agentify markdown, and fall through to the app on everything else, including any Agentify failure. The snippets below are that function for the three common hosts. > [!NOTE] > > You need an API key with the `agentify:convert` scope, minted in the [dashboard](https://dashboard.zeroclick.io) under **Settings → API keys** (the **Agentify** group's **Convert** toggle). Add it to your host as the secret `ZEROCLICK_AGENTIFY_KEY`. The edge function needs no signing secret — it verifies nothing, so the standalone SDK helpers are all it uses. ## Deploy the edge function Each snippet uses `withAgentify` from [`@zeroclickai/sellers`](https://www.npmjs.com/package/@zeroclickai/sellers) — the SDK is web-native, so it runs unchanged in edge runtimes — with a one-line client that supplies the key. `withAgentify` handles the whole contract: GET-only, [detection](/docs/agentify/overview#how-detection-works) over `Accept` and `User-Agent`, forwarded cache headers plus `Vary`, and fall-through to your app on any failure. ```ts Cloudflare Pages theme={null} // functions/_middleware.ts — runs in front of every Pages asset. // Set ZEROCLICK_AGENTIFY_KEY as a production secret on the project. import { fetchAgentifyMarkdown, withAgentify } from "@zeroclickai/sellers"; interface Env { ZEROCLICK_AGENTIFY_KEY: string; } export const onRequest: PagesFunction = (context) => withAgentify( { fetchAgentifyMarkdown: (url) => fetchAgentifyMarkdown( // Multi-seller organizations add: seller: "sel_…" { url }, { apiKey: context.env.ZEROCLICK_AGENTIFY_KEY }, ), }, () => context.next(), )(context.request); ``` ```ts Vercel theme={null} // middleware.ts at the project root. Set ZEROCLICK_AGENTIFY_KEY in the // project's environment variables. In a Next.js app, return // NextResponse.next() instead of @vercel/edge's next(). import { next } from "@vercel/edge"; import { fetchAgentifyMarkdown, withAgentify } from "@zeroclickai/sellers"; export default function middleware(request: Request): Promise { return withAgentify( { fetchAgentifyMarkdown: (url) => fetchAgentifyMarkdown( // Multi-seller organizations add: seller: "sel_…" { url }, { apiKey: process.env.ZEROCLICK_AGENTIFY_KEY! }, ), }, () => next(), )(request); } ``` ```ts Netlify theme={null} // netlify/edge-functions/agentify.ts. Set ZEROCLICK_AGENTIFY_KEY as an // environment variable on the site. import type { Context } from "@netlify/edge-functions"; import { fetchAgentifyMarkdown, withAgentify } from "@zeroclickai/sellers"; export default (request: Request, context: Context): Promise => withAgentify( { fetchAgentifyMarkdown: (url) => fetchAgentifyMarkdown( // Multi-seller organizations add: seller: "sel_…" { url }, { apiKey: Netlify.env.get("ZEROCLICK_AGENTIFY_KEY")! }, ), }, () => context.next(), )(request); export const config = { path: "/*" }; ``` On another host, port the same shape to its edge runtime, or put a small server in front of the CDN and mount the [SDK middleware](/docs/agentify/sdk-middleware) there — the contract is identical. Detection only fires for markdown-preferring or AI-agent requests, so browsers, asset fetches, and search crawlers never touch the Agentify path; if your host supports path matchers, you can still scope the function to page routes and skip asset paths entirely. ## Verify ```sh theme={null} # An agent's request gets markdown with your storefront inlined: curl -s -H "Accept: text/markdown, text/html, */*" https://www.acme.com/ | head -20 # A browser Accept header gets the SPA shell, unchanged: curl -s -H "Accept: text/html,application/xhtml+xml" https://www.acme.com/ | head -5 ``` The first request of each page takes a few seconds while the conversion runs; repeats serve from [cache](/docs/agentify/overview#caching). Remove the key from the environment and the markdown request serves the shell instead — that is the fail-open path working, not a deployment error. ## If conversion answers `422 content_too_thin` The error means the page yielded too little readable content even after rendering: the content appears only after user interaction, sits behind a bot wall, or never reaches the DOM at all. Two fixes, in order of preference: * **Prerender or server-render your marketing pages.** Most SPA frameworks can emit static HTML for public pages at build time. That helps every raw-text reader, not just Agentify. * **Serve the content in the initial HTML.** Agentify converts what a fetch (or a headless render of it) can see; content that only exists after a click cannot be converted. Your billed API needs none of this — agents transact with it through your [storefront](/docs/website/enable-agent-traffic), which is machine-readable by construction. ## Next steps > [card] [SDK middleware](/docs/agentify/sdk-middleware) > > The same contract as drop-in middleware, when you do have a server. > [card] [REST quickstart](/docs/agentify/quickstart-rest) > > The underlying endpoint: request, response anatomy, and errors. # Convert a marketing webpage to markdown Source: https://zeroclickai.mintlify.dev/docs/api-reference/agentify/convert-a-marketing-webpage-to-markdown https://api.zeroclick.io/openapi.json get /v1/agentify/markdown Fetches a public marketing webpage and returns an agent-readable markdown document: summary front matter, the seller's agent storefront inlined, then the page content. # Analytics overview Source: https://zeroclickai.mintlify.dev/docs/api-reference/analytics/analytics-overview https://api.zeroclick.io/openapi.json get /v1/analytics/overview Aggregates transactions (capability calls that moved money or delivered, split paid vs free trial), revenue, transacting agents, capability-call delivery, payment methods, included units, and top services for the authenticated organization, from the hourly analytics marts (`asOf` says how fresh). `days` is a window ending today or `all`. # List agent transactions Source: https://zeroclickai.mintlify.dev/docs/api-reference/analytics/list-agent-transactions https://api.zeroclick.io/openapi.json get /v1/analytics/transactions Lists a page of the ledger for the authenticated organization, newest first: presented payments, with `trials=include` the free-trial calls (payment method `free_trial`, amount drawn from the grant) and with `includedUnits=include` the included-unit calls (kind `included`, no payment method, amount at list value). Filterable by status, payment method, seller, service, and a day window. `total` counts the matching records across all pages. # Revenue analytics Source: https://zeroclickai.mintlify.dev/docs/api-reference/analytics/revenue-analytics https://api.zeroclick.io/openapi.json get /v1/analytics/revenue Aggregates settled revenue, average paid transaction, lifetime totals, revenue and usage per service, revenue per plan, plan credit used, and the per-day split series (service, new vs returning buyer, payment method, arrival channel) for the authenticated organization, from the hourly analytics marts; `sellerId` scopes to a store and `serviceId` to one of its services. # Seller agent performance Source: https://zeroclickai.mintlify.dev/docs/api-reference/analytics/seller-agent-performance https://api.zeroclick.io/openapi.json get /v1/analytics/sellers/{sellerId}/performance Commerce and success-outcome metrics for one seller owned by the authenticated organization: session conversion rate, average order value, repeat-purchase rate, quotes pulled, and agent-to-human handoffs. Counts are floors - only visit-chain sessions are visible. # Seller agent sessions Source: https://zeroclickai.mintlify.dev/docs/api-reference/analytics/seller-agent-sessions https://api.zeroclick.io/openapi.json get /v1/analytics/sellers/{sellerId}/sessions Session-detail rollup for one seller owned by the authenticated organization: agent sessions grouped by country (top regions) and the most recent agent sessions with their identity, arrival, views, and conversion. Optional tier and agentType filters narrow the agent rows; entry and outcome narrow them to one arrival channel or ending of the flow diagram. Counts are floors - only visit-chain sessions are visible. # Seller agent traffic Source: https://zeroclickai.mintlify.dev/docs/api-reference/analytics/seller-agent-traffic https://api.zeroclick.io/openapi.json get /v1/analytics/sellers/{sellerId}/traffic Session-grain agentic-traffic rollup for one seller owned by the authenticated organization: agent types, originating platforms, arrival channels, the browse-to-pay conversion floor, and agent-vs-human sessions per day. Optional tier and agentType filters narrow the agent rows (the human baseline is unaffected). Counts are floors - only visit-chain sessions are visible. # Seller analytics Source: https://zeroclickai.mintlify.dev/docs/api-reference/analytics/seller-analytics https://api.zeroclick.io/openapi.json get /v1/analytics/sellers/{sellerId} Aggregates calls, transactions, revenue, and new wallets for one seller owned by the authenticated organization. # Seller buyers Source: https://zeroclickai.mintlify.dev/docs/api-reference/analytics/seller-buyers https://api.zeroclick.io/openapi.json get /v1/analytics/sellers/{sellerId}/buyers Who bought from one seller in the window: each buyer (registered agent, else paying wallet) with first payment, transactions, revenue, active days and whether it read the storefront first; new vs returning counts and their weekly split; repeat buyers. Trial-only agents list with no payments. # Seller conversion Source: https://zeroclickai.mintlify.dev/docs/api-reference/analytics/seller-conversion https://api.zeroclick.io/openapi.json get /v1/analytics/sellers/{sellerId}/conversion Session-grain conversion rollup for one seller owned by the authenticated organization: the browse-to-settle funnel (marketing site, arrived, browsed, payment attempted, settled) and settled sessions split by payment rail. The marketing-site entry stage counts qualified agent visits to the seller's own site (crawlers, monitors and credential probes excluded) and how many of them reached the storefront; marketingConfigured reports whether that tracking is set up. Counts are floors - only visit-chain sessions are visible. # Seller demand Source: https://zeroclickai.mintlify.dev/docs/api-reference/analytics/seller-demand https://api.zeroclick.io/openapi.json get /v1/analytics/sellers/{sellerId}/demand Per-service demand for one seller owned by the authenticated organization: for each service, the agent sessions that opened its page and whether they settled that service. View counts are a floor - agents that read the whole catalog at once never open a per-service page. # Seller service analytics Source: https://zeroclickai.mintlify.dev/docs/api-reference/analytics/seller-service-analytics https://api.zeroclick.io/openapi.json get /v1/analytics/sellers/{sellerId}/services Aggregates all-time revenue, transactions, and calls per service and per meter for one seller owned by the authenticated organization. # Seller website sessions Source: https://zeroclickai.mintlify.dev/docs/api-reference/analytics/seller-website-sessions https://api.zeroclick.io/openapi.json get /v1/analytics/sellers/{sellerId}/website-sessions Session detail for the Website scope of one seller owned by the authenticated organization: site sessions by country with how many reached the storefront, the most walked page paths, and the sessions that reached the storefront with the storefront journey each became, with ZeroClick's own checks left out of each and counted apart. Optional tier and agentType filters narrow the sessions; entryPage narrows them to the sessions that started on one page. # Seller website traffic Source: https://zeroclickai.mintlify.dev/docs/api-reference/analytics/seller-website-traffic https://api.zeroclick.io/openapi.json get /v1/analytics/sellers/{sellerId}/website The Website scope of agent traffic for one seller owned by the authenticated organization: qualified agent visits to the seller's own site (ZeroClick's own checks, crawlers, monitors and credential probes excluded, the checks counted apart), how many read two or more pages, were shown a storefront link and reached the storefront, sessions per UTC day split by agent type, entry page and identity tier, where sessions start, the pages agents ask for that do not exist, and the website half of the flow diagram. Optional tier and agentType filters narrow the sessions. # V3 identity suggestions Source: https://zeroclickai.mintlify.dev/docs/api-reference/analytics/v3-identity-suggestions https://api.zeroclick.io/openapi.json get /v1/analytics/sellers/{sellerId}/session-identities The agent or visitor ids of the session cohort (the same window and page-wide filters as session-facts) that start with the query, the twenty with the most sessions first. kind defaults to viewer ids for the website scope and visitors mode, agent ids otherwise. # V3 session and visitor facts Source: https://zeroclickai.mintlify.dev/docs/api-reference/analytics/v3-session-and-visitor-facts https://api.zeroclick.io/openapi.json get /v1/analytics/sellers/{sellerId}/session-facts Full-population session or visitor metrics for an inclusive UTC date range (totals with the previous window, outcomes, daily outcomes and chart splits, the seven traffic types, regions, top routes, first and last documents, the arrival-lane flow) and one stable ordered page of sessions. Page-wide filters change every number; list filters narrow the rows and their outcome chips only. Daily unique visitors are non-additive across days. Repeat with offset and the first page's asOf to export every row. Returns 503 until the marts behind it exist. # V3 store buyers Source: https://zeroclickai.mintlify.dev/docs/api-reference/analytics/v3-store-buyers https://api.zeroclick.io/openapi.json get /v1/analytics/sellers/{sellerId}/store-buyers The known agents with a transaction for one seller over an inclusive UTC date range: how many, how many were new (first payment or transaction with the seller inside the window), returning, repeat (two or more active UTC days), paid or trial-only; the same tiles for the equal-length previous window; seven-day new vs returning buckets ending on the window's last day; and one paged row per agent, ranked by revenue, with its first activity, transactions, verified payments, active days, paying wallet and whether a transaction came through a storefront journey. Returns 503 until the marts behind it exist. # V3 store demand Source: https://zeroclickai.mintlify.dev/docs/api-reference/analytics/v3-store-demand https://api.zeroclick.io/openapi.json get /v1/analytics/sellers/{sellerId}/store-demand Per-service demand for one seller over an inclusive UTC date range: for each live service (or the one named by serviceId), the eligible storefront sessions that opened its page (a floor: an agent that reads the whole catalog at once opens none), the 402 quotes minted on it (one per challenged payment, read from the raw event stream, which the bot and internal switches cannot reach), its verified per-call payments and their sum, the requests and dollars its calls drew on plan credit, the completed free-trial and free-mode calls it served, and where that puts it on the demand ladder. Returns 503 until the marts behind it exist. # V3 store metrics Source: https://zeroclickai.mintlify.dev/docs/api-reference/analytics/v3-store-metrics https://api.zeroclick.io/openapi.json get /v1/analytics/sellers/{sellerId}/store-metrics Revenue, credit used, transactions, transacting agents and call delivery for one seller over an inclusive UTC date range, each with its total, the equal-length previous window, sparse daily points and its breakdowns (service, named plan, plan type, attribution, new vs returning, payment lane, kind, paid vs trial). Money is counted by payment creation, calls and credit by request time. Breakdowns are alternate views of one metric, never amounts to add together. Returns 503 until the marts behind it exist. # V3 transaction or payment facts Source: https://zeroclickai.mintlify.dev/docs/api-reference/analytics/v3-transaction-or-payment-facts https://api.zeroclick.io/openapi.json get /v1/analytics/sellers/{sellerId}/activity-facts One row per charged or completed funded, trial or free call, or per verified payment when kind=payments, with the totals, attribution and payment-lane splits, top buyers and exclusive paid/trial-only agent counts of every matching fact. view=grouped pages completed and failed calls by UTC day, service, buyer, funding and status with the credit they drew. Transaction dates use request creation; payment dates use payment creation. Repeat with offset and the first page's asOf for a complete export. Returns 503 until the marts behind it exist. # V3 visitors Source: https://zeroclickai.mintlify.dev/docs/api-reference/analytics/v3-visitors https://api.zeroclick.io/openapi.json get /v1/analytics/sellers/{sellerId}/session-visitors One row per estimated visitor of the session cohort (the same window and page-wide filters as session-facts), most recently seen first, with its session count, first arrival, best outcome and first and last seen times. Sessions with no single visitor id never form a visitor. Pages independently of the session rows. # Create an API key Source: https://zeroclickai.mintlify.dev/docs/api-reference/api-keys/create-an-api-key https://api.zeroclick.io/openapi.json post /v1/api-keys/ Creates an organization API key and returns the secret once. # List API keys Source: https://zeroclickai.mintlify.dev/docs/api-reference/api-keys/list-api-keys https://api.zeroclick.io/openapi.json get /v1/api-keys/ Lists active API keys for the authenticated organization. # Revoke an API key Source: https://zeroclickai.mintlify.dev/docs/api-reference/api-keys/revoke-an-api-key https://api.zeroclick.io/openapi.json delete /v1/api-keys/{apiKeyId} Revokes an active API key for the organization. # API reference Source: https://zeroclickai.mintlify.dev/docs/api-reference/introduction Base URL, authentication, scopes, conventions, and errors for the ZeroClick REST API. The ZeroClick REST API manages your catalog (sellers, services, meters, plans, and prices) and handles usage checks, usage reports, and analytics. The endpoint pages that follow are generated from the live OpenAPI document the API serves, so they always match production. The interactive playground on each page sends real requests; authenticate it with your API key. ## Base URL ```text theme={null} https://api.zeroclick.io ``` All endpoints live under `/v1/` and speak JSON over HTTPS. ## Authentication Authenticate with an API key as a bearer token. Keys start with `zc_` and are shown once. Create them in the [dashboard](https://dashboard.zeroclick.io) under Settings → API keys. See [keys and secrets](/docs/integrate/keys-and-secrets). ```sh theme={null} curl https://api.zeroclick.io/v1/sellers \ -H "Authorization: Bearer $ZEROCLICK_API_KEY" ``` Every key is scoped to your organization and carries one or more scopes: | Scope | Grants | | - | - | | `admin:read` | Read catalog, analytics, and sandbox endpoints. | | `admin:write` | Create, update, and delete catalog and sandbox resources; create the Stripe onboarding link. | | `usage:read` | `POST /v1/usage/check` (allowance checks). | | `usage:write` | `POST /v1/usage` (usage reports). | | `agentify:convert` | `GET /v1/agentify/markdown` ([Agentify](/docs/agentify/overview) page conversion). | Auth requirements differ by route group: * **Usage** endpoints accept API keys only, with the split read and write scopes above. A dashboard session cannot call them. * **Agentify** accepts API keys only, with the `agentify:convert` scope. * **Sellers** (including signing secrets), **Services**, **Meters**, **Plans**, **Plan meter prices**, **Analytics**, and **Sandbox** accept an API key (`admin:read` for reads, `admin:write` for writes) or a dashboard session. * **API keys**, **Organizations**, **Users**, and **Stripe Connect** (except `POST /v1/stripe-connect/account-link`, which accepts `admin:write`) are dashboard-session-only. An API key gets `403 {"error":"auth_type_not_allowed"}`. This is why API keys cannot mint more API keys. A key missing a required scope gets `403 {"error":"insufficient_scope"}`. ## Conventions **Ids are prefixed strings**, returned in the `id` field and used in path and query parameters: | Prefix | Resource | | - | - | | `sel_` | Seller | | `svc_` | Service | | `mtr_` | Meter | | `pln_` | Plan | | `pmp_` | Plan meter price | | `ak_` | API key | | `hsec_` | Signing secret (the `kid` in `zc-signature`) | | `agt_` | Buyer agent | | `zcreq_` | Forwarded request (`zc-request-id`) | | `use_` | Usage event | **Lists are parent-scoped and unpaginated.** List endpoints filter by a required parent id (`GET /v1/services?sellerId=sel_…`, `GET /v1/meters?serviceId=svc_…`, `GET /v1/plan-meter-prices?planId=pln_…`) and return the full set in one response. There are no cursors or page parameters. **Timestamps** are ISO 8601 strings in UTC. **There are no webhooks**; poll the analytics endpoints instead. ## Errors Errors return a machine-readable envelope, with an optional human-readable `reason`: ```json theme={null} { "error": "insufficient_scope" } ``` | Status | Meaning | | - | - | | `400` | Request validation failed. | | `401` | Missing, invalid, or revoked credentials. | | `402` | Usage denial: `access_inactive`, `plan_expired`, `usage_exhausted`. | | `403` | `organization_required`, `insufficient_scope`, `auth_type_not_allowed`, `organization_permission_required`. | | `404` | Resource missing, or owned by another organization; the two are deliberately indistinguishable. | | `409` | Conflict, such as `duplicate_slug` on create or `meter_not_priced` on a usage report. | | `422` | Semantic rejection, such as `payg_price_not_whole_cents`. | The [errors reference](/docs/resources/errors) catalogs every code. # Create a meter Source: https://zeroclickai.mintlify.dev/docs/api-reference/meters/create-a-meter https://api.zeroclick.io/openapi.json post /v1/meters/ Creates one measurable usage dimension for a service. # Delete a meter Source: https://zeroclickai.mintlify.dev/docs/api-reference/meters/delete-a-meter https://api.zeroclick.io/openapi.json delete /v1/meters/{meterId} Soft-deletes a meter and active prices that reference it. # Get a meter Source: https://zeroclickai.mintlify.dev/docs/api-reference/meters/get-a-meter https://api.zeroclick.io/openapi.json get /v1/meters/{meterId} # List meters Source: https://zeroclickai.mintlify.dev/docs/api-reference/meters/list-meters https://api.zeroclick.io/openapi.json get /v1/meters/ Lists usage meters for a service. # Update a meter Source: https://zeroclickai.mintlify.dev/docs/api-reference/meters/update-a-meter https://api.zeroclick.io/openapi.json patch /v1/meters/{meterId} # Accept a terms document for the current organization Source: https://zeroclickai.mintlify.dev/docs/api-reference/organizations/accept-a-terms-document-for-the-current-organization https://api.zeroclick.io/openapi.json post /v1/organizations/current/terms Records that the signed-in member accepted the current version of the Order Form on behalf of their organization: the signer's name, role and the legal entity they bind, the exact text they saw and its hash, the acceptance wording, and the address and browser the click came from. The signer is emailed the agreement as a PDF. Dashboard sessions only. Accepting the same version again returns the existing acceptance. # Accept the Agent Simulation Terms for the current organization Source: https://zeroclickai.mintlify.dev/docs/api-reference/organizations/accept-the-agent-simulation-terms-for-the-current-organization https://api.zeroclick.io/openapi.json post /v1/organizations/current/agent-simulation-terms/accept Records the acceptance, by an owner or admin of the organization, of the current Agent Simulation Terms outside a plan start: an organization on a plan accepting a new version on its next visit. The exact text and its hash, the consent wording shown, and the address, browser and country the click came from are kept. version and sha256 are the ones the page showed; an older version answers 409 terms_stale. Accepting the current version again returns the acceptance on record. Other members get 403 forbidden; staff working in the organization through the switcher get 403 membership_required and nothing is recorded. # Buy credits Source: https://zeroclickai.mintlify.dev/docs/api-reference/organizations/buy-credits https://api.zeroclick.io/openapi.json post /v1/organizations/current/credits/purchases Charges the organization's card for credits (10 credits = $1): a pack, or any whole-dollar amount from $1 to $10,000 (credits a multiple of 10, 10 to 100,000). The credits are added once the payment succeeds and last a year from then, past the end of the plan. A requires_action result carries a client secret for Stripe.js to finish card authentication, after which POST /current/credits/purchases/{paymentIntentId}/confirm adds the credits. Replaying the same Idempotency-Key returns the original purchase. Needs an active Agent Simulations plan (402 plan_required otherwise); staff in the organization are exempt. Organization admins only. # Cancel the Agent Simulations plan Source: https://zeroclickai.mintlify.dev/docs/api-reference/organizations/cancel-the-agent-simulations-plan https://api.zeroclick.io/openapi.json post /v1/organizations/current/plan/cancel A paid plan stays usable until currentPeriodEnd and then ends; no further credits are added, its plan credits expire then, and credits added earlier stay until their own expiry. Cancelling the free month (status trialing) ends it now, uncharged, and removes every credit at once, added ones too. Either way auto top-up turns off. Organization admins only. # Change the organization's auto top-up setting Source: https://zeroclickai.mintlify.dev/docs/api-reference/organizations/change-the-organizations-auto-top-up-setting https://api.zeroclick.io/openapi.json put /v1/organizations/current/credits/auto-top-up Turning it on needs an active Agent Simulations plan (402 plan_required) and a saved card (409 card_required). Saving clears any recorded failure. Organization admins only. # Create the caller's organization Source: https://zeroclickai.mintlify.dev/docs/api-reference/organizations/create-the-callers-organization https://api.zeroclick.io/openapi.json post /v1/organizations/ Creates the organization a partner signs up with. Through a partner invite (the link, or an open invite for the caller's email domain): the first person at the domain gets a new organization bound to the invite, later ones join it as admins until the agreement is signed. On their own: any address creates its own organization; a caller who belongs to one already is refused. The product decides what the organization owes next: a storefront sign-up (the default) owes the seller agreement; an Agent Simulations sign-up names the website the simulations run against (required, kept as its host), which becomes the organization's first site (`site`; null for a storefront sign-up), and accepts the Agent Simulation Terms when it starts its plan instead. Where the sign-up came from is kept with it. A sign-up without an invite must say how the person heard about us (`heardAbout`), or is refused with `heard_about_required`; an invited sign-up's answer is not kept. # Finish a credit purchase after card authentication Source: https://zeroclickai.mintlify.dev/docs/api-reference/organizations/finish-a-credit-purchase-after-card-authentication https://api.zeroclick.io/openapi.json post /v1/organizations/current/credits/purchases/{paymentIntentId}/confirm # Finish starting the plan after card authentication Source: https://zeroclickai.mintlify.dev/docs/api-reference/organizations/finish-starting-the-plan-after-card-authentication https://api.zeroclick.io/openapi.json post /v1/organizations/current/plan/confirm # Finish starting the plan after Stripe Checkout Source: https://zeroclickai.mintlify.dev/docs/api-reference/organizations/finish-starting-the-plan-after-stripe-checkout https://api.zeroclick.io/openapi.json post /v1/organizations/current/plan/checkout/{sessionId}/confirm Activates the plan the Checkout session created and adds its credits; safe to repeat. 409 checkout_incomplete while the session is not complete. Organization admins only. # Get the card credits are charged to Source: https://zeroclickai.mintlify.dev/docs/api-reference/organizations/get-the-card-credits-are-charged-to https://api.zeroclick.io/openapi.json get /v1/organizations/current/credits/card # Get the current organization Source: https://zeroclickai.mintlify.dev/docs/api-reference/organizations/get-the-current-organization https://api.zeroclick.io/openapi.json get /v1/organizations/current Returns the caller's current organization, and the products it uses: agent_storefront once it has a live storefront; agent_simulations when it signed up for Agent Simulations, holds a plan, or has a site it opened Simulations on. # Get the current organization's Agent Simulations plan Source: https://zeroclickai.mintlify.dev/docs/api-reference/organizations/get-the-current-organizations-agent-simulations-plan https://api.zeroclick.io/openapi.json get /v1/organizations/current/plan The organization's current plan subscription, or null when it has none (never started, canceled or expired). status is Stripe's subscription status: active and trialing are paid up; past_due and unpaid mean a renewal is failing. trialAvailable is true when starting now would begin with a free first month: an organization's first plan gets one, and staff can offer one to an organization that has had a plan before. trialEnd is when billing would start if the plan were started now, null when there is no free month. access says what the plan allows: active (trialing, active or past_due) runs studies and buys credits; none allows neither, and every credit left when a plan ends expires with it. terms is what a new start by the caller has to accept: the current Agent Simulation Terms (version, sha256, legalUrl) while the organization has not accepted them, null once it has, and null for staff working in the organization, who are never asked. # Get the current organization's credit balance Source: https://zeroclickai.mintlify.dev/docs/api-reference/organizations/get-the-current-organizations-credit-balance https://api.zeroclick.io/openapi.json get /v1/organizations/current/credits The organization's credit balance in USD (10 credits = $1): settled is everything granted, bought, captured, refunded or adjusted; held is reserved by open holds; available is settled minus held. A capture never exceeds its hold, so spending alone cannot take available below zero; a refund or adjustment can. kinds splits what is available: planUsd is this period's plan credits, spent first and gone when the period or the plan ends; topUpUsd is credits added (bought, or granted by staff), spent after plan credits and gone a year after purchase or when the plan ends, whichever is first; topUpExpiresAt is when the soonest of those expires, null when none do. # Get the organization's auto top-up setting Source: https://zeroclickai.mintlify.dev/docs/api-reference/organizations/get-the-organizations-auto-top-up-setting https://api.zeroclick.io/openapi.json get /v1/organizations/current/credits/auto-top-up When enabled, a study run settling with the available balance below thresholdCredits charges the saved card for packCredits. failure says why auto top-up last turned itself off (card_declined, authentication_required or card_required), until the setting is saved again. # Get the receipt for a paid credit history entry Source: https://zeroclickai.mintlify.dev/docs/api-reference/organizations/get-the-receipt-for-a-paid-credit-history-entry https://api.zeroclick.io/openapi.json get /v1/organizations/current/credits/history/{entryId}/receipt A fresh link to the payment's receipt, for entries with paid true: the charge receipt for a credit pack, the invoice for a plan payment. Links expire, so fetch one each time it is opened. # Grant free credits to an organization Source: https://zeroclickai.mintlify.dev/docs/api-reference/organizations/grant-free-credits-to-an-organization https://api.zeroclick.io/openapi.json post /v1/organizations/current/credits/grants Adds free credits, in USD, to the organization selected through the staff organization switcher. Staff only. Replaying the same Idempotency-Key returns the original grant. # Invite a member Source: https://zeroclickai.mintlify.dev/docs/api-reference/organizations/invite-a-member https://api.zeroclick.io/openapi.json post /v1/organization-members/invitations Sends an invitation email so the recipient can join an organization with the given role. # List members Source: https://zeroclickai.mintlify.dev/docs/api-reference/organizations/list-members https://api.zeroclick.io/openapi.json get /v1/organization-members/ Lists the active members of an organization. # List pending invitations Source: https://zeroclickai.mintlify.dev/docs/api-reference/organizations/list-pending-invitations https://api.zeroclick.io/openapi.json get /v1/organization-members/invitations Lists the pending invitations for an organization. # List the current organization's credit history Source: https://zeroclickai.mintlify.dev/docs/api-reference/organizations/list-the-current-organizations-credit-history https://api.zeroclick.io/openapi.json get /v1/organizations/current/credits/history Ledger entries, newest first. availableDeltaUsd is each entry's effect on the available balance (closing a hold returns what it reserved, less any capture) and availableAfterUsd is the available balance right after it. study names the study run a hold or its settlement belongs to. paid marks a card payment, whose receipt is at GET /current/credits/history/{entryId}/receipt. # Offer a free first month of the plan Source: https://zeroclickai.mintlify.dev/docs/api-reference/organizations/offer-a-free-first-month-of-the-plan https://api.zeroclick.io/openapi.json put /v1/organizations/current/plan/trial Lets the organization selected through the staff organization switcher start the plan with 30 days free, even if it has had a plan before. A card is still required and billing starts when the free month ends. One offer per organization. Staff only. # Open Stripe's billing portal Source: https://zeroclickai.mintlify.dev/docs/api-reference/organizations/open-stripes-billing-portal https://api.zeroclick.io/openapi.json post /v1/organizations/current/billing-portal Returns a short-lived Stripe billing portal url where the organization's card is added or changed; leaving it returns to returnPath on the dashboard. Organization admins only. # Read how the current organization came to be Source: https://zeroclickai.mintlify.dev/docs/api-reference/organizations/read-how-the-current-organization-came-to-be https://api.zeroclick.io/openapi.json get /v1/organizations/current/signup The sign-up behind the caller's organization, as far as the partner needs it: whether it came through the website or a partner invite, the product they signed up for, the company website as a host, and whether the partner builds their own storefront once they have signed; otherwise the team builds it. A partner who signed up from the website builds their own; one who came through an invite follows the invite's setting. Null for an organization the team created directly. # Read where the current organization stands with a terms document Source: https://zeroclickai.mintlify.dev/docs/api-reference/organizations/read-where-the-current-organization-stands-with-a-terms-document https://api.zeroclick.io/openapi.json get /v1/organizations/current/terms/{document} The latest acceptance of the named terms document by a member of the caller's organization, or null when no version was accepted yet, and whether one is owed: an organization created from a partner invite must accept before it uses the dashboard. # Read whether the current organization accepted the Agent Simulation Terms Source: https://zeroclickai.mintlify.dev/docs/api-reference/organizations/read-whether-the-current-organization-accepted-the-agent-simulation-terms https://api.zeroclick.io/openapi.json get /v1/organizations/current/agent-simulation-terms Whether a member of the caller's organization accepted the current version of the Agent Simulation Terms (GET /v1/terms/agent-simulation-terms), and when. The terms are accepted as the organization starts its Agent Simulations plan (POST /current/plan, terms); a new version is not accepted until someone accepts it, and until then the organization's own study runs are refused with 409 terms_required. canAccept is true for whoever can manage the organization (its owners and admins); staff working in the organization through the switcher see the terms as a preview, accept nothing and are never refused (staff: true). Any member may read it. # Remove a member Source: https://zeroclickai.mintlify.dev/docs/api-reference/organizations/remove-a-member https://api.zeroclick.io/openapi.json delete /v1/organization-members/{membershipId} Removes a member from an organization. Their access is revoked immediately. # Resend an invitation Source: https://zeroclickai.mintlify.dev/docs/api-reference/organizations/resend-an-invitation https://api.zeroclick.io/openapi.json post /v1/organization-members/invitations/{invitationId}/resend Resends the invitation email for a pending invitation and refreshes its expiry. # Revoke an invitation Source: https://zeroclickai.mintlify.dev/docs/api-reference/organizations/revoke-an-invitation https://api.zeroclick.io/openapi.json delete /v1/organization-members/invitations/{invitationId} Revokes a pending invitation so it can no longer be used. # Save the card credits are charged to Source: https://zeroclickai.mintlify.dev/docs/api-reference/organizations/save-the-card-credits-are-charged-to https://api.zeroclick.io/openapi.json put /v1/organizations/current/credits/card Makes the card from a succeeded SetupIntent the organization's card, replacing any previous one. Organization admins only. # Start saving a card for credit purchases Source: https://zeroclickai.mintlify.dev/docs/api-reference/organizations/start-saving-a-card-for-credit-purchases https://api.zeroclick.io/openapi.json post /v1/organizations/current/credits/card/setup-intents Creates a Stripe SetupIntent on the ZeroClick platform account. Confirm it in the browser with Stripe.js and the returned publishable key, then save it with PUT /current/credits/card. Organization admins only. # Start the Agent Simulations plan on Stripe Checkout Source: https://zeroclickai.mintlify.dev/docs/api-reference/organizations/start-the-agent-simulations-plan-on-stripe-checkout https://api.zeroclick.io/openapi.json post /v1/organizations/current/plan/checkout Creates a Stripe Checkout session for the monthly plan and returns its url. Checkout takes the card, also for a free first month (trialAvailable), and returns to returnPath on the dashboard with plan_checkout={sessionId} added; POST /current/plan/checkout/{sessionId}/confirm then activates the plan and adds its credits (the subscription webhooks do the same if the buyer never comes back). Leaving Checkout returns to returnPath unchanged. A current plan answers 409 plan_active: resume a cancelled one with POST /current/plan. The terms and renewal are required as on POST /current/plan, and both are recorded before the session is created (409 terms_required, terms_stale, disclosure_required). Organization admins only. # Start the Agent Simulations plan on the saved card Source: https://zeroclickai.mintlify.dev/docs/api-reference/organizations/start-the-agent-simulations-plan-on-the-saved-card https://api.zeroclick.io/openapi.json post /v1/organizations/current/plan Subscribes the organization to the monthly Agent Simulations plan on its saved card, adding 1,000 credits once the first invoice is paid. When trialAvailable, the first month is free: a $0 invoice still adds the credits and the card is first charged at trialEnd. Starting a plan that is set to cancel at period end resumes it instead. A requires_action result carries a client secret for Stripe.js to finish card authentication, after which POST /current/plan/confirm activates the plan. A new plan starts under the current Agent Simulation Terms: while the organization has not accepted them (GET /current/plan says, in terms), the start carries terms (version, sha256 and the consent sentence shown), recorded as the caller's acceptance, else 409 terms_required (409 terms_stale when the page showed an older version); and it carries renewal, the renewal disclosure shown above the button, recorded as the caller's consent before the plan starts (409 disclosure_required without it). Staff working in an organization through the switcher are never asked and nothing is recorded for them. Organization admins only. # Update a member's role Source: https://zeroclickai.mintlify.dev/docs/api-reference/organizations/update-a-members-role https://api.zeroclick.io/openapi.json patch /v1/organization-members/{membershipId} # Update the current organization Source: https://zeroclickai.mintlify.dev/docs/api-reference/organizations/update-the-current-organization https://api.zeroclick.io/openapi.json patch /v1/organizations/current Updates the name of the caller's current organization. # Withdraw an unused free-month offer Source: https://zeroclickai.mintlify.dev/docs/api-reference/organizations/withdraw-an-unused-free-month-offer https://api.zeroclick.io/openapi.json delete /v1/organizations/current/plan/trial Staff only. A free month already in use stays. # Create a plan meter price Source: https://zeroclickai.mintlify.dev/docs/api-reference/plan-meter-prices/create-a-plan-meter-price https://api.zeroclick.io/openapi.json post /v1/plan-meter-prices/ Adds usage pricing for a meter on a buyer-facing plan. # Delete a plan meter price Source: https://zeroclickai.mintlify.dev/docs/api-reference/plan-meter-prices/delete-a-plan-meter-price https://api.zeroclick.io/openapi.json delete /v1/plan-meter-prices/{planMeterPriceId} # Get a plan meter price Source: https://zeroclickai.mintlify.dev/docs/api-reference/plan-meter-prices/get-a-plan-meter-price https://api.zeroclick.io/openapi.json get /v1/plan-meter-prices/{planMeterPriceId} # List plan meter prices Source: https://zeroclickai.mintlify.dev/docs/api-reference/plan-meter-prices/list-plan-meter-prices https://api.zeroclick.io/openapi.json get /v1/plan-meter-prices/ Lists usage prices configured on a plan. # Update a plan meter price Source: https://zeroclickai.mintlify.dev/docs/api-reference/plan-meter-prices/update-a-plan-meter-price https://api.zeroclick.io/openapi.json patch /v1/plan-meter-prices/{planMeterPriceId} # Create a plan Source: https://zeroclickai.mintlify.dev/docs/api-reference/plans/create-a-plan https://api.zeroclick.io/openapi.json post /v1/plans/ Creates a buyer-facing billing plan for a seller. # Delete a plan Source: https://zeroclickai.mintlify.dev/docs/api-reference/plans/delete-a-plan https://api.zeroclick.io/openapi.json delete /v1/plans/{planId} Soft-deletes a plan and its active prices. # Get a plan Source: https://zeroclickai.mintlify.dev/docs/api-reference/plans/get-a-plan https://api.zeroclick.io/openapi.json get /v1/plans/{planId} # List plans Source: https://zeroclickai.mintlify.dev/docs/api-reference/plans/list-plans https://api.zeroclick.io/openapi.json get /v1/plans/ Lists buyer-facing plans for a seller. # Update a plan Source: https://zeroclickai.mintlify.dev/docs/api-reference/plans/update-a-plan https://api.zeroclick.io/openapi.json patch /v1/plans/{planId} # Fund the sandbox test wallet Source: https://zeroclickai.mintlify.dev/docs/api-reference/sandbox/fund-the-sandbox-test-wallet https://api.zeroclick.io/openapi.json post /v1/sandbox/sellers/{sellerId}/wallet/fund Requests a testnet funding drip for the organization's sandbox test wallet. # Get seller sandbox status Source: https://zeroclickai.mintlify.dev/docs/api-reference/sandbox/get-seller-sandbox-status https://api.zeroclick.io/openapi.json get /v1/sandbox/sellers/{sellerId}/status Returns the organization's sandbox test wallet, the seller's sandbox readiness checks, the sandbox spend limits, and the available buyer-agent profiles. # Get the seller's OpenAPI document Source: https://zeroclickai.mintlify.dev/docs/api-reference/sandbox/get-the-sellers-openapi-document https://api.zeroclick.io/openapi.json get /v1/sandbox/sellers/{sellerId}/openapi Fetches the seller's configured OpenAPI document so the sandbox can offer ready-made example requests. Returns the raw document text, or the reason it is unavailable - an unreachable document is not an error, the caller simply gets no examples. # Run a sandbox buyer-agent chat session Source: https://zeroclickai.mintlify.dev/docs/api-reference/sandbox/run-a-sandbox-buyer-agent-chat-session https://api.zeroclick.io/openapi.json post /v1/sandbox/sellers/{sellerId}/chat Runs the sandbox buyer agent against the seller's pay host and streams the conversation, protocol trace events, and wallet snapshots as a UI message stream over server-sent events. # Run one direct sandbox request against the seller's API Source: https://zeroclickai.mintlify.dev/docs/api-reference/sandbox/run-one-direct-sandbox-request-against-the-sellers-api https://api.zeroclick.io/openapi.json post /v1/sandbox/sellers/{sellerId}/direct Sends a single request to the seller's pay host from the sandbox test wallet, with no agent in the loop, and returns the full protocol trace as JSON. With autoPay (the default), 402 challenges along the way are paid automatically, subject to the sandbox spend caps. # Add a seller custom domain Source: https://zeroclickai.mintlify.dev/docs/api-reference/sellers/add-a-seller-custom-domain https://api.zeroclick.io/openapi.json post /v1/sellers/{sellerId}/domains Registers a custom domain for the seller and returns the DNS records the seller must add to verify ownership and serve TLS. # Cancel a website links run Source: https://zeroclickai.mintlify.dev/docs/api-reference/sellers/cancel-a-website-links-run https://api.zeroclick.io/openapi.json post /v1/sellers/{sellerId}/links/runs/{runId}/cancel A queued run is removed and closed at once; a running one is asked to stop and closes itself after the page in hand (`stopping`). The pages and suggestions written so far stay. # Clear seller body encryption keys Source: https://zeroclickai.mintlify.dev/docs/api-reference/sellers/clear-seller-body-encryption-keys https://api.zeroclick.io/openapi.json delete /v1/sellers/{sellerId}/body-encryption Removes the seller's body encryption configuration; buyers can no longer discover encryption keys for this seller. # Configure the seller's stateful access endpoint Source: https://zeroclickai.mintlify.dev/docs/api-reference/sellers/configure-the-sellers-stateful-access-endpoint https://api.zeroclick.io/openapi.json patch /v1/sellers/{sellerId}/stateful-access Sets the desired-state upsert base URL. Null uses /zeroclick/access under upstreamBaseUrl. # Create a seller Source: https://zeroclickai.mintlify.dev/docs/api-reference/sellers/create-a-seller https://api.zeroclick.io/openapi.json post /v1/sellers/ Creates a seller profile and upstream API base URL for payment proxying. # Create a seller signing secret Source: https://zeroclickai.mintlify.dev/docs/api-reference/sellers/create-a-seller-signing-secret https://api.zeroclick.io/openapi.json post /v1/sellers/{sellerId}/signing-secrets # Delete a seller Source: https://zeroclickai.mintlify.dev/docs/api-reference/sellers/delete-a-seller https://api.zeroclick.io/openapi.json delete /v1/sellers/{sellerId} Soft-deletes a seller and its active billing setup records. Sellers that have issued stateful accounts must remain available for servicing and cannot be deleted. # Enable or disable Buy with AI for the seller Source: https://zeroclickai.mintlify.dev/docs/api-reference/sellers/enable-or-disable-buy-with-ai-for-the-seller https://api.zeroclick.io/openapi.json patch /v1/sellers/{sellerId}/buy-with-ai # Ensure a site integration's API key Source: https://zeroclickai.mintlify.dev/docs/api-reference/sellers/ensure-a-site-integrations-api-key https://api.zeroclick.io/openapi.json post /v1/sellers/{sellerId}/discovery/integrations/{integration}/key Mints or re-serves the single-scope key the integration's snippets embed (page-views:write for Page views, agentify:convert for Agentify). Idempotent within the reveal window: repeated calls return the same value. A key that authenticated real traffic and aged out of the window is returned name-only. # Ensure the implementation wizard key set Source: https://zeroclickai.mintlify.dev/docs/api-reference/sellers/ensure-the-implementation-wizard-key-set https://api.zeroclick.io/openapi.json post /v1/sellers/{sellerId}/onboarding/keys Mints or re-serves the credentials the wizard's setup prompts embed: the signing secret, scoped usage keys, and a setup-only admin key. Idempotent within the display window: repeated calls return identical values. A usage key whose value has aged out after real use is returned name-only. # Get a seller Source: https://zeroclickai.mintlify.dev/docs/api-reference/sellers/get-a-seller https://api.zeroclick.io/openapi.json get /v1/sellers/{sellerId} # Get seller implementation onboarding progress Source: https://zeroclickai.mintlify.dev/docs/api-reference/sellers/get-seller-implementation-onboarding-progress https://api.zeroclick.io/openapi.json get /v1/sellers/{sellerId}/onboarding Lists the implementation wizard's steps with each one's status and verification evidence. Derived steps (catalog, custom domain, payout readiness) are re-checked on every read, so a regressed integration is reflected immediately. # List seller custom domains Source: https://zeroclickai.mintlify.dev/docs/api-reference/sellers/list-seller-custom-domains https://api.zeroclick.io/openapi.json get /v1/sellers/{sellerId}/domains # List seller discovery checks Source: https://zeroclickai.mintlify.dev/docs/api-reference/sellers/list-seller-discovery-checks https://api.zeroclick.io/openapi.json get /v1/sellers/{sellerId}/discovery/checks Returns the persisted result of every discovery validation check that has run for this seller. Checks run on demand through the validate endpoint; a check that has never run has no entry yet. # List seller discovery listings Source: https://zeroclickai.mintlify.dev/docs/api-reference/sellers/list-seller-discovery-listings https://api.zeroclick.io/openapi.json get /v1/sellers/{sellerId}/discovery Returns where this seller is listed across discovery services. Read-only: registering and refreshing listings stays a staff operation. # List seller signing secrets Source: https://zeroclickai.mintlify.dev/docs/api-reference/sellers/list-seller-signing-secrets https://api.zeroclick.io/openapi.json get /v1/sellers/{sellerId}/signing-secrets # List sellers Source: https://zeroclickai.mintlify.dev/docs/api-reference/sellers/list-sellers https://api.zeroclick.io/openapi.json get /v1/sellers/ Lists the seller records owned by the authenticated organization. # List website link suggestions Source: https://zeroclickai.mintlify.dev/docs/api-reference/sellers/list-website-link-suggestions https://api.zeroclick.io/openapi.json get /v1/sellers/{sellerId}/links/suggestions One run's suggestions (the latest run's unless `run` names another), optionally of one status: `open`, `done` (the seller's mark, which survives runs) or `applied` (a run found the link on the page). # Mark a website link suggestion done, or open again Source: https://zeroclickai.mintlify.dev/docs/api-reference/sellers/mark-a-website-link-suggestion-done-or-open-again https://api.zeroclick.io/openapi.json patch /v1/sellers/{sellerId}/links/suggestions/{suggestionId} `done` is the seller's mark and survives runs: the next run carries it forward while the page is unchanged, and marks it applied once the page links the destination. An applied suggestion cannot be changed (409). # Prepare the seller's Buy with AI preview prompt Source: https://zeroclickai.mintlify.dev/docs/api-reference/sellers/prepare-the-sellers-buy-with-ai-preview-prompt https://api.zeroclick.io/openapi.json post /v1/sellers/{sellerId}/buy-with-ai/preview Starts walkthrough-prompt generation for the current storefront when no up-to-date prompt exists; an up-to-date prompt is returned immediately. Never enables Buy with AI. # Re-check a seller custom domain Source: https://zeroclickai.mintlify.dev/docs/api-reference/sellers/re-check-a-seller-custom-domain https://api.zeroclick.io/openapi.json post /v1/sellers/{sellerId}/domains/{domainId}/verify Refreshes the domain's verification and certificate status from the edge provider. # Read stateful access configuration Source: https://zeroclickai.mintlify.dev/docs/api-reference/sellers/read-stateful-access-configuration https://api.zeroclick.io/openapi.json get /v1/sellers/{sellerId}/stateful-access # Read the latest website links run Source: https://zeroclickai.mintlify.dev/docs/api-reference/sellers/read-the-latest-website-links-run https://api.zeroclick.io/openapi.json get /v1/sellers/{sellerId}/links/runs/latest The seller's latest link suggestions run with the queue's live view of it (state and progress while it runs), the page outcomes written so far and its suggestions, each an exact edit to one of the seller's pages. Poll it while a run is in flight; suggestions appear as pages settle. `run` is null before the first run. # Read the seller's agent guides setting Source: https://zeroclickai.mintlify.dev/docs/api-reference/sellers/read-the-sellers-agent-guides-setting https://api.zeroclick.io/openapi.json get /v1/sellers/{sellerId}/guides Reports whether the seller's storefront serves its agent guides, whether any guides are published for it, and where they live. # Read the seller's Buy with AI preview status Source: https://zeroclickai.mintlify.dev/docs/api-reference/sellers/read-the-sellers-buy-with-ai-preview-status https://api.zeroclick.io/openapi.json get /v1/sellers/{sellerId}/buy-with-ai/preview Reports whether a walkthrough prompt tailored to the current storefront is ready, still generating, or failed, and returns the prompt when ready. Reading the preview never enables Buy with AI. With journey=1, a ready prompt uses the widget's valid zcj or mints one, then marks it as preview traffic. # Read the seller's Buy with AI setting Source: https://zeroclickai.mintlify.dev/docs/api-reference/sellers/read-the-sellers-buy-with-ai-setting https://api.zeroclick.io/openapi.json get /v1/sellers/{sellerId}/buy-with-ai # Read the seller's site integrations Source: https://zeroclickai.mintlify.dev/docs/api-reference/sellers/read-the-sellers-site-integrations https://api.zeroclick.io/openapi.json get /v1/sellers/{sellerId}/discovery/integrations Whether Page views and Agentify are enabled for this seller (a live key with the scope exists in the organization), the key the Discovery page minted for each (its value while inside the reveal window), and when each was last seen working: the last page-view beacon received, the last Agentify conversion served. # Remove a seller custom domain Source: https://zeroclickai.mintlify.dev/docs/api-reference/sellers/remove-a-seller-custom-domain https://api.zeroclick.io/openapi.json delete /v1/sellers/{sellerId}/domains/{domainId} # Request a walkthrough from the ZeroClick team Source: https://zeroclickai.mintlify.dev/docs/api-reference/sellers/request-a-walkthrough-from-the-zeroclick-team https://api.zeroclick.io/openapi.json post /v1/sellers/{sellerId}/walkthrough-requests Emails the ZeroClick team asking for a walkthrough of the seller's agent discovery setup, with the caller as the reply-to and their optional note. Accepted once the email is handed off; 503 when email delivery is not configured or fails. # Revoke a seller signing secret Source: https://zeroclickai.mintlify.dev/docs/api-reference/sellers/revoke-a-seller-signing-secret https://api.zeroclick.io/openapi.json delete /v1/sellers/{sellerId}/signing-secrets/{secretId} # Run a discovery validation check Source: https://zeroclickai.mintlify.dev/docs/api-reference/sellers/run-a-discovery-validation-check https://api.zeroclick.io/openapi.json post /v1/sellers/{sellerId}/discovery/checks/{check}/validate Fetches the supplied pages server-side and persists a pass/fail verdict per URL for the named check, returning the fresh result. Re-running a currently passing check within five minutes is refused with a retry window; a failing check re-validates immediately - except the launch blogpost check, which keeps its retry window after every run and accepts exactly one URL. # Set seller body encryption keys Source: https://zeroclickai.mintlify.dev/docs/api-reference/sellers/set-seller-body-encryption-keys https://api.zeroclick.io/openapi.json put /v1/sellers/{sellerId}/body-encryption Stores the seller's public-only P-256 JSON Web Key Set and active key id used by buyers to encrypt request bodies end to end. Replaces any existing configuration. # Skip the custom domain step Source: https://zeroclickai.mintlify.dev/docs/api-reference/sellers/skip-the-custom-domain-step https://api.zeroclick.io/openapi.json post /v1/sellers/{sellerId}/onboarding/custom-domain/skip Marks the custom domain step completed without a domain and records the choice in the step ledger. Available only to sellers whose custom domain requirement is waived; everyone else must verify a domain. # Start a website links run Source: https://zeroclickai.mintlify.dev/docs/api-reference/sellers/start-a-website-links-run https://api.zeroclick.io/openapi.json post /v1/sellers/{sellerId}/links/runs Starts a link suggestions run over the seller's own pages: it finds them (the pages declared here or last time, the Discovery page's checked pages, sitemaps on every content host, the usual blog places, a bounded crawl), reads up to 60, articles first, and proposes at most one exact edit per page linking it to the seller's agent storefront. One run at a time per seller, ten minutes between starts and six a day: a refused start answers 429 with Retry-After. `pages` declares up to ten pages that are always read; a run without them reuses the last run's. # Turn the seller's agent guides on or off Source: https://zeroclickai.mintlify.dev/docs/api-reference/sellers/turn-the-sellers-agent-guides-on-or-off https://api.zeroclick.io/openapi.json patch /v1/sellers/{sellerId}/guides Switched off, the storefront stops serving its agent guides, however many are published; switched back on, it serves them again. # Update a seller Source: https://zeroclickai.mintlify.dev/docs/api-reference/sellers/update-a-seller https://api.zeroclick.io/openapi.json patch /v1/sellers/{sellerId} # Verify the seller's API setup Source: https://zeroclickai.mintlify.dev/docs/api-reference/sellers/verify-the-sellers-api-setup https://api.zeroclick.io/openapi.json post /v1/sellers/{sellerId}/onboarding/verify/api-setup Probes the supplied endpoints unpaid against the seller's upstream. Each passes only when the billing guard answers with the payment-required contract. Stateful storefronts ignore the endpoints: verification instead runs structural conformance checks against the seller's access endpoint (unsigned and mis-signed writes rejected, a signed synthetic write applied twice, a key minted and discarded). The collected set becomes the step's evidence; all passing marks the step completed, any failure demotes it to in progress. # Verify the seller's storefront pointers Source: https://zeroclickai.mintlify.dev/docs/api-reference/sellers/verify-the-sellers-storefront-pointers https://api.zeroclick.io/openapi.json post /v1/sellers/{sellerId}/onboarding/verify/agent-traffic Fetches the supplied pages and checks each one references the seller's storefront origin, carries at least one agent pointer (the llms.txt link or the badge), and serves markdown that references the storefront when a request asks for it. Each unique page origin must also serve an llms.txt that references the storefront. The llms.txt Link header and the agent callout are recorded without gating. All checks passing marks the step completed, any failure demotes it to in progress. Re-verifying a step that completed within the last five minutes is refused with a retry window; a not-yet-completed step always verifies immediately. # Create a service Source: https://zeroclickai.mintlify.dev/docs/api-reference/services/create-a-service https://api.zeroclick.io/openapi.json post /v1/services/ Creates one sellable API capability for a seller. # Delete a service Source: https://zeroclickai.mintlify.dev/docs/api-reference/services/delete-a-service https://api.zeroclick.io/openapi.json delete /v1/services/{serviceId} Soft-deletes a service and its active meter pricing records. # Get a service Source: https://zeroclickai.mintlify.dev/docs/api-reference/services/get-a-service https://api.zeroclick.io/openapi.json get /v1/services/{serviceId} # List services Source: https://zeroclickai.mintlify.dev/docs/api-reference/services/list-services https://api.zeroclick.io/openapi.json get /v1/services/ Lists services for a seller. # Update a service Source: https://zeroclickai.mintlify.dev/docs/api-reference/services/update-a-service https://api.zeroclick.io/openapi.json patch /v1/services/{serviceId} # Create a connected account login link Source: https://zeroclickai.mintlify.dev/docs/api-reference/stripe-connect/create-a-connected-account-login-link https://api.zeroclick.io/openapi.json post /v1/stripe-connect/login-link Returns a hosted dashboard URL for the authenticated organization's connected payout account. # Create an onboarding link Source: https://zeroclickai.mintlify.dev/docs/api-reference/stripe-connect/create-an-onboarding-link https://api.zeroclick.io/openapi.json post /v1/stripe-connect/account-link Creates or reuses the authenticated organization's hosted onboarding account and returns a single-use onboarding URL. The optional country sets where a newly created payout account is based (ISO 3166-1 alpha-2, default US); it cannot be changed after creation and is ignored when an account already exists. # Designate the branding seller Source: https://zeroclickai.mintlify.dev/docs/api-reference/stripe-connect/designate-the-branding-seller https://api.zeroclick.io/openapi.json put /v1/stripe-connect/branding-seller Chooses which of the organization's sellers the connected payout account's public branding and billing statement descriptor are synced from. Null reverts to the organization's oldest seller. # Disconnect a payout account Source: https://zeroclickai.mintlify.dev/docs/api-reference/stripe-connect/disconnect-a-payout-account https://api.zeroclick.io/openapi.json delete /v1/stripe-connect/account Deletes the connected payout account before soft-deleting the local organization connection. # Get connected payout account status Source: https://zeroclickai.mintlify.dev/docs/api-reference/stripe-connect/get-connected-payout-account-status https://api.zeroclick.io/openapi.json get /v1/stripe-connect/account Returns the hosted onboarding and payout readiness state for the authenticated organization. # Check usage allowance Source: https://zeroclickai.mintlify.dev/docs/api-reference/usage/check-usage-allowance https://api.zeroclick.io/openapi.json post /v1/usage/check Checks whether an access grant can perform an action without recording usage. Items may declare maxQuantity instead of quantity to gate an unknown amount at its ceiling, or declare neither to gate against the meter's configured default cap. # Report usage Source: https://zeroclickai.mintlify.dev/docs/api-reference/usage/report-usage https://api.zeroclick.io/openapi.json post /v1/usage/ Records an idempotent usage report for an access grant. # Get user settings Source: https://zeroclickai.mintlify.dev/docs/api-reference/users/get-user-settings https://api.zeroclick.io/openapi.json get /v1/users/{userId} # Agents and access Source: https://zeroclickai.mintlify.dev/docs/concepts/agents-and-access How ZeroClick identifies buying agents, what zcAgentId and zcBuyerId mean to sellers, which forwards carry no agent id, and how access grants work. An agent's identity on ZeroClick is a credential it registers for. Sellers see one opaque, stable id per buyer and handle nothing else: no buyer accounts or API keys to issue, no payment details. ## Identity is a registered credential An agent registers once and exchanges an assertion for an access token, then presents that token as `Authorization: Bearer …` (or `ZC-Agent-Authorization: Bearer …` when `Authorization` already carries an MPP payment credential). Every call needs a registered agent credential, sent as a bearer: registering is one free API call, with no human step. An agent can register anonymously, sign in with its user's Zero identity, or be claimed by a human with a verified email. A call without a credential gets `401 bearer_required` before it reaches your API. Pay-as-you-go is no exception, and a plan purchase or top-up binds to the credential, so the buyer keeps its plan however it chooses to pay. The `zcAgentId` on every call is the agent behind the bearer, so it stays the same across calls, sessions, and payment rails, card included. ## What sellers see: `zcAgentId` Sellers only ever see a buyer as `zcAgentId`, an id shaped like `agt_x7f2kq93bh0d`. It is stable per buyer and appears consistently across the product: the `zc-agent-id` request header on forwarded requests, the `zcAgentId` field in 402 challenge bodies, [usage reports and usage events](/docs/concepts/usage-and-allowances), and transaction analytics. Use it as your foreign key for per-buyer state: rate limits, tenancy, audit logs. ## Agents belong to buyers: `zcBuyerId` An agent is one credential. A **buyer** is the person or company behind it, and one buyer can hold several agents: a replacement for a rotated credential, a second agent for a different workload, a recovered identity from an earlier registration. Entitlements live on the buyer, so every agent a buyer holds can draw on every plan the buyer bought, no matter which agent made the purchase. When ZeroClick knows the owner, forwarded requests carry `zc-buyer-id` (`byr_3n8v1c6t5j2w`) alongside `zc-agent-id`: ```http Agent whose owner is known theme={null} zc-request-id: zcreq_8h2m4x0q9k1f zc-agent-id: agt_x7f2kq93bh0d zc-buyer-id: byr_3n8v1c6t5j2w zc-signature: t=1785196800,kid=hsec_k5nq0v7m3d8p,v1=… ``` `zc-agent-id` is always the agent that made **this** call. It never switches to the agent that originally bought the plan being drawn down, so a request from a buyer's second agent looks like exactly what it is. The buyer id is what stays stable across all of them. No `zc-buyer-id` means an anonymous agent: identified, billable, and fine to serve, but not yet attached to an owner you should key durable records to. Prefer `zc-buyer-id` for anything a human should still see after the agent that created it is gone, and `zc-agent-id` for per-caller concerns like rate limits. The [headers reference](/docs/resources/headers) has the full matrix, including what the signature does and does not cover. ## Agent ids on unpaid and paid calls Every buyer call arrives with its agent id, including the unpaid one. When a pay-as-you-go request needs pricing, ZeroClick forwards it upstream with the caller's `zc-agent-id` so your API can state its price as a `402 payment_required` refusal. ZeroClick re-prices that refusal into the buyer's challenge (see [how ZeroClick works](/docs/concepts/how-zeroclick-works)), and the paid retry carries the same request id and the same agent: ```http Unpaid call: priced by your 402 refusal theme={null} zc-request-id: zcreq_8h2m4x0q9k1f zc-agent-id: agt_x7f2kq93bh0d zc-signature: t=1785196800,kid=hsec_k5nq0v7m3d8p,v1=… ``` ```http Paid retry: same request id, same agent theme={null} zc-request-id: zcreq_8h2m4x0q9k1f zc-agent-id: agt_x7f2kq93bh0d zc-signature: t=1785196819,kid=hsec_k5nq0v7m3d8p,v1=… ``` A signed request with no `zc-agent-id` is still valid: ZeroClick probes your endpoints that way when it builds your catalog, and the signature's agent segment is then the empty string. The [seller SDKs](/docs/sdks/overview) and the [verification guide](/docs/integrate/verify-requests) treat it as a first-class case, so you rarely branch on it yourself. ## Access grants A purchase creates a buyer **access**: the grant that ties one buyer to one plan at one seller, and the thing every allowance check evaluates. Each buyer holds at most one active access per seller. Buying again or switching plans replaces the grant in place rather than stacking a second one. Any remaining credit carries forward onto the new purchase, so an unspent balance survives a plan switch. An access carries: * `status`: `active` or `inactive`. Checks against an inactive access are denied `access_inactive`. * `periodStartsAt` / `periodEndsAt`: the current period for subscription-style plans. A check after `periodEndsAt` is denied `plan_expired`. * `remainingCreditUsd`: the prepaid balance on credit plans, or the included usage credit on `subscription_usage` plans. Usage draws it down; an amount it cannot cover is denied `usage_exhausted`. Pay-as-you-go needs no access at all: a registered agent pays per call and goes. The [plans and pricing](/docs/concepts/plans-and-pricing) page covers what each billing mode means for these fields, and [usage and allowances](/docs/concepts/usage-and-allowances) covers the checks that consume them. For most sellers the access grant is the whole story of a purchase. A seller can also opt into something more: the purchase creates a real account on the seller's side, with a durable `accessId` handle and an API key the buyer then uses with the seller directly — see [sell accounts and API keys](/docs/integrate/stateful-sellers). Identity stays verified per call. Even on a purchased plan, every request carries the buyer's credential, and ZeroClick resolves it to the same `agt_…` before it forwards, so your API needs no buyer authentication of its own. The `zc-signature` header is the trust boundary. # End-to-end body encryption Source: https://zeroclickai.mintlify.dev/docs/concepts/end-to-end-encryption How buyers and sellers encrypt request and response bodies so ZeroClick relays ciphertext without access to either private key. > [!TIP] > > End-to-end body encryption is available in production now. ZeroClick relays Compact JWE ciphertext and never receives the private keys that decrypt either body. ZeroClick terminates TLS at the pay URL to handle routing, identity, and payment. Without body encryption, the proxy receives the application body plaintext. Encrypted calls add a Compact JWE envelope inside TLS. The buyer creates this envelope before the request reaches ZeroClick. The seller opens it after the proxy forwards it. The response follows the reverse path. The seller encrypts the response body for a one-time buyer key. ZeroClick returns the ciphertext, and the buyer decrypts it. ## The data path ```mermaid theme={null} sequenceDiagram participant B as Buyer participant Z as ZeroClick proxy participant S as Seller API S->>Z: Publish public P-256 JWK Note right of S: Seller private key stays here B->>Z: Fetch encryption guide and public JWKS Z-->>B: Active kid and public JWK Note left of B: Create one-time reply key pair
Encrypt request body for seller B->>Z: Compact JWE request body Note over Z: Validate protected header
Hash and sign ciphertext Z->>S: Same ciphertext bytes + zc-signature Note right of S: Verify and check allowance
Then decrypt and serve S-->>Z: Response body encrypted for buyer Z-->>B: Same response ciphertext bytes Note left of B: Decrypt with reply private key ``` **1. The seller publishes a public key** The seller generates a P-256 key pair in its own infrastructure. It publishes only the public JWK through ZeroClick. ZeroClick rejects JWKs that contain private parameters. The seller private key stays in the seller's key manager or application environment. **2. The buyer encrypts the request body** The buyer reads the active `kid` and public JWKS from the storefront. It also creates a fresh P-256 reply key pair. The buyer encrypts the body as Compact JWE. The protected header carries the seller `kid`, original content type, and public reply JWK. **3. ZeroClick processes ciphertext** The proxy can read the protected header without a private key. It validates the fixed cipher suite, seller `kid`, and public reply key. ZeroClick hashes the original ciphertext for payment binding and `zc-signature`. It forwards those ciphertext bytes without modification. **4. The seller verifies and decrypts** The seller verifies `zc-signature` against the ciphertext before decryption. It also checks the buyer's allowance before it does application work. After an allow decision, the seller selects its private key by `kid` and decrypts the body inside its own infrastructure. **5. The seller encrypts the response body** The seller encrypts the application response for the public reply key. Only the buyer has the matching private key. ZeroClick relays the response ciphertext. The buyer uses its one-time private key to decrypt the body. ## What ZeroClick can and cannot see The proxy still needs transaction metadata to route the call and settle payment. Body encryption changes the body trust boundary, not the entire HTTP exchange. | Data | Available to ZeroClick? | Why | | - | - | - | | Request body plaintext | No | The seller holds the only private key that opens the request JWE. | | Response body plaintext | No, when the buyer requests an encrypted reply | The buyer keeps the private reply key. | | Seller private key | No | The seller publishes a strict public-only JWKS. | | Buyer reply private key | No | The buyer sends only the public half in the JWE protected header. | | Request and response ciphertext | Yes | The proxy must relay these bytes. Ciphertext length is also visible. | | Method, host, path, query, HTTP headers, and status | Yes | These values remain outside the JWE body envelope. | | JWE protected header | Yes | It exposes the suite, `kid`, original content type, and public reply JWK. It does not expose body plaintext. | | Identity, payment, allowance, and usage data | Yes | ZeroClick needs this control data to authenticate and settle the transaction. | The proxy request record stores the method, path and query, status, identifiers, and a SHA-256 body digest. It has no request or response body field. The proxy cannot log or persist body plaintext that it never receives. It can log or persist visible metadata and ciphertext. Without an endpoint's private key, retained ciphertext remains unreadable. This is a cryptographic limit, not a logging policy. ## Wire contract ZeroClick accepts one body-encryption profile: | Field | Required value | | - | - | | Request and encrypted-response media type | `application/jose` | | JWE serialization | Compact JWE with five base64url segments | | Seller and reply keys | EC P-256 public JWKs | | Key management | `ECDH-ES+A256KW` | | Content encryption | `A256GCM` | | Seller key selection | `kid` in the protected header | | Original body media type | `cty` in the protected header | | Buyer reply key | `https://zeroclick.io/jwe/reply-jwk` in the protected header | The fixed suite prevents algorithm negotiation. The protected header is authenticated, so a relay cannot replace the reply key without invalidating the request JWE. The payment challenge binds to a SHA-256 digest of the ciphertext. After a `402`, the buyer must retry with the identical JWE bytes. > [!WARNING] > > Do not encrypt the same plaintext again for the paid retry. JWE uses random values, so a new envelope has a different digest. ZeroClick protocol responses remain plaintext. These include payment challenges and errors produced before the seller decrypts the request. ## Scope and trust boundaries * Body encryption is opt-in for each request. A plaintext request remains plaintext at the proxy. * Response encryption is a separate opt-in. The buyer must include a public reply JWK, and the seller must use it. * The JWE protects bodies only. It does not hide routes, headers, status codes, timing, length, billing data, or usage quantities. * This design protects body confidentiality from the ZeroClick data plane. It does not protect a compromised buyer or seller endpoint. * Storefront key discovery trusts the public key that ZeroClick serves for the seller. Buyers can pin a seller key through a seller-controlled channel. * The response JWE provides confidentiality, but it is not a seller signature. If the buyer must prove response origin, add an application-level signature. ## Configure a seller **1. Generate a P-256 encryption key pair** Generate the key pair in the seller's infrastructure. Give the public JWK a unique `kid`. Keep the private JWK secret. **2. Publish the public JWKS** In the dashboard, open **Stores → your seller → Store settings → Upstream security → Body encryption**. Paste the public JWKS. You can also call `PUT /v1/sellers/{sellerId}/body-encryption` with an `admin:write` API key. **3. Add the seller-side helpers** Verify the encrypted request before decryption. Check the allowance before decryption. Attach `zc-usage` before you encrypt the response. > [card] [TypeScript](/docs/sdks/typescript/api#encryption) > > Use `decryptRequest` and `encryptResponse`. > [card] [Python](/docs/sdks/python/api#encryption) > > Use `decrypt_request` and `encrypt_response`. > [card] [Go](/docs/sdks/go/api#encrypted-request-bodies) > > Use the separate `jwe` package. > [card] [Ruby](/docs/sdks/ruby/api#encrypted-request-bodies) > > Require `zeroclick/sellers/encryption`. **4. Give buyers the generated guide** Each configured pay URL publishes `/encryption.md` and `/.well-known/jwks.json`. The guide contains a working buyer example for that seller. During key rotation, publish the old and new public keys together. Keep both private keys available until all requests and payment retries drain. # How ZeroClick works Source: https://zeroclickai.mintlify.dev/docs/concepts/how-zeroclick-works The life of one paid agent request: transparent proxying, the single priced 402 challenge, the signed forward, the allowance check, and settlement. ZeroClick is a transparent paid proxy in front of your API. An agent calls your pay URL, `https://acme.pay.zeroclick.io/`, with exactly the request it would send your API directly: the same method, the same path and query, the same body. ZeroClick prices the call, collects payment over [x402 or MPP](/docs/concepts/payment-protocols), and forwards the request to your upstream base URL. It signs the forward so your backend can trust it. This page follows one pay-as-you-go request through that lifecycle at the protocol level; the [quickstart](/docs/quickstart) covers the integration itself. The full flow is two round trips from the agent's side, after a one-time credential registration. The agent talks only to your pay URL, and your API talks only to ZeroClick: ```mermaid theme={null} sequenceDiagram autonumber participant A as Buying agent participant Z as ZeroClick
(acme.pay.zeroclick.io) participant S as Your API
(upstream base URL) rect rgba(25, 25, 255, 0.06) note over A,S: Round trip 1: price the request A->>Z: POST /v1/product-watch
Authorization: Bearer token Z->>S: same request, signed
zc-request-id + zc-agent-id + zc-signature S-->>Z: 402 refusal with declared usage Z-->>A: one priced 402 challenge
payment-required and www-authenticate end rect rgba(25, 25, 255, 0.06) note over A,S: Round trip 2: pay and get served A->>Z: identical request + bearer + payment proof
x-payment or authorization Z->>S: same request, signed
zc-request-id + zc-agent-id + zc-signature S->>Z: POST /v1/usage/check Z-->>S: allowed S-->>Z: 200 + zc-usage header Z-->>A: 200 response + zc-billing header end ``` The two arrows in the middle of round trip 2 are your backend calling ZeroClick's REST API at `api.zeroclick.io`; every other arrow carries the agent's own request and response. ZeroClick strips the `zc-usage` header before the response reaches the agent. > [!NOTE] > > For an [end-to-end encrypted call](/docs/concepts/end-to-end-encryption), each “same request” arrow carries identical Compact JWE ciphertext. ZeroClick signs and forwards those bytes without a decryption key. After the allowance check, your API decrypts the request and encrypts the application response for the buyer. **1. An agent calls the pay URL** The agent sends its normal request to `https://acme.pay.zeroclick.io/v1/product-watch` with its agent credential as `Authorization: Bearer `: no API key from you, no other ZeroClick-specific headers. The pay URL host names the seller; the method, path, query, and body are your API's own. Every call needs a registered agent credential, sent as a bearer: registering is one free API call, with no human step, following the storefront's `/auth.md`. A call without one gets `401 bearer_required` before any price is quoted. On a catalog sold only on credit or subscription plans, the agent also has to buy a plan first ([plans and pricing](/docs/concepts/plans-and-pricing)). **2. ZeroClick answers with one priced 402** An unpaid request needs a price before ZeroClick can charge for it. For pay-as-you-go, ZeroClick forwards it upstream signed, carrying `zc-request-id`, the caller's `zc-agent-id`, and `zc-signature`. Your API refuses the unpaid call with the exact body `{"error":"payment_required","serviceSlug":"product-watch","usage":[{"meterSlug":"requests","quantity":1}]}`. ZeroClick prices that declared usage against your catalog and answers the agent with a single `402 payment_required` challenge. The challenge arrives in one response, several ways at once: the body carries the exact amount (`payment.amountUsd`) and a block per protocol. The full signable challenges ride in the `payment-required` (x402) and `www-authenticate` (MPP) response headers. The total is one priced 402, so a stock single-payment x402 or MPP client completes the flow, as long as it sends the agent's bearer on both requests. The Zero CLI (`zero fetch`, 1.37.0 or later) registers, stores, and sends the credential for you. **3. The agent pays and retries byte-identically** The agent pays the challenge with its wallet and retries the identical request with the proof attached and its bearer still on it: the signed x402 payload in the `x-payment` header next to `Authorization: Bearer `, or an MPP credential in `Authorization: Payment …` with the token moved to `ZC-Agent-Authorization: Bearer `. The payment binds to the challenged request's body digest, so the retry must carry the same bytes. ZeroClick refuses a different body with `409 payment_request_mismatch`. **4. ZeroClick verifies, signs, and forwards** ZeroClick verifies the payment, resolves the bearer to the caller's [buyer agent](/docs/concepts/agents-and-access) (`agt_…`), and forwards the request to your `upstreamBaseUrl`. It strips inbound `zc-*` and payment headers, then sets its own three: `zc-request-id`, `zc-agent-id`, and `zc-signature`. The signature is an HMAC over the method, path, body digest, and both ids (see the [signature spec](/docs/integrate/signature-spec)). **5. Your API verifies, checks the allowance, and serves** Your backend [verifies the signature](/docs/integrate/verify-requests) first, then asks `POST /v1/usage/check` whether the buyer's plan covers the declared usage. The check is a pure decision: it [records nothing and burns nothing](/docs/concepts/usage-and-allowances). If the check allows, your API does the work. If it denies, your API returns the 402 refusal body. ZeroClick turns that refusal into the buyer's next challenge. **6. Usage settles and the response returns** Your API settles actual usage synchronously, in a `zc-usage` response header on the 2xx response (preferred), or reports it asynchronously via `POST /v1/usage`. ZeroClick records the usage and settles the payment, at actual usage when the challenge priced a [ceiling](/docs/integrate/charge-up-to-a-maximum). It strips `zc-usage` so the agent never sees it, then returns your response to the agent with a `zc-billing` header. ## Who does what | Actor | Responsibility | | - | - | | Agent | Discovers the storefront, registers a credential once, sends normal API requests with its bearer, signs and pays 402 challenges, retries with the proof attached. | | ZeroClick | Checks the agent credential, prices the challenge, verifies the payment, signs and forwards the request, records usage, settles the money. | | Your API | Verifies `zc-signature`, checks the allowance, does the work, returns the exact 402 refusal on denial, settles usage. | The seller side of this table is the whole integration: verify, check, serve, settle. The [integration overview](/docs/integrate/overview) states that contract on one page, and the [seller SDKs](/docs/sdks/overview) implement it. ## One id ties it together `zc-request-id` (`zcreq_…`) is the correlation spine. ZeroClick mints it when a request first arrives and reuses it end to end. The pricing forward, the challenge body (as `zcRequestId`), the paid retry, your allowance check, and the recorded usage events all carry the same id. Log it on every guarded request, and you can trace any transaction across your systems and the dashboard. The agent's side closes the loop with `zc-billing`, a response header on every per-call paid response that reconciles the authorized amount against the charged amount: ```json theme={null} { "status": "settled", "authorizedUsd": "0.016384", "chargedUsd": "0.009046", "remainderUsd": "0.007338", "remainderHandling": "escrow_returned", "settleTransactionHash": "0x…" } ``` For a fixed-quantity request, the authorized and charged amounts match. For a ceiling-priced request, the authorized amount is the most the agent could have paid, and the remainder went back to its wallet. `"status": "settling"` means on-chain settlement has not finished, so the final amounts are not stamped yet. > [!NOTE] > > Agents on purchased plans follow the same lifecycle with one difference: a credit or subscription purchase happens once, up front, through the storefront. After that, each call carries the same bearer without a fresh payment, and covered calls forward without a new 402. See [plans and pricing](/docs/concepts/plans-and-pricing). The [headers reference](/docs/resources/headers) catalogs every header in this flow. # Payment protocols Source: https://zeroclickai.mintlify.dev/docs/concepts/payment-protocols How ZeroClick uses x402 and MPP: challenge and proof headers, minted deposit addresses, reserve rails for ceiling charges, and settlement. ZeroClick accepts two agent payment protocols: [x402](https://www.x402.org) and MPP, the [Machine Payments Protocol](https://mpp.dev). Both settle USDC. This page explains how ZeroClick uses them, not how they work internally; as a seller you never implement either. Your API sees only signed, already-paid requests, and the billing guard is identical whichever rail the buyer chose. ## The two rails Both protocols follow the same loop: ZeroClick answers an unpaid request with the [single priced 402](/docs/concepts/how-zeroclick-works), the agent signs the challenge with its wallet, and the retry carries the proof in a standard header. Every call, paid retry included, also carries the agent's registered credential as a bearer. A request with no payment proof yet is offered both protocols and the buyer picks by paying; a request that already carries a proof on one rail is challenged on that rail. | | x402 | MPP | | - | - | - | | Challenge rides in | `payment-required` response header (and the standard x402 document in the 402 body) | `www-authenticate` response header | | Proof rides in | `x-payment` request header (signed payment payload) | `authorization: Payment ` request header | | Agent credential rides in | `Authorization: Bearer ` | `ZC-Agent-Authorization: Bearer ` | | Settles | USDC on Base (`eip155:8453`) | USDC on Tempo | | Fixed-quantity charges | `exact` scheme | one-shot charge | | Ceiling charges | `upto` scheme (reserve, settle at actual) | session escrow channel | | Receipt header on paid responses | `payment-response` | `payment-receipt` | Inside the 402 body, each offered rail appears as a block under `protocols`, alongside ZeroClick's own `payment` block with the exact USD amount: ```json theme={null} { "error": "payment_required", "zcRequestId": "zcreq_8h2m4x0q9k1f", "payment": { "id": "apay_…", "amountUsd": "0.010000" }, "protocols": { "x402": { "x402Version": 2, "network": "eip155:8453", "scheme": "exact", "amount": "10000", "asset": "0x…" }, "mpp": { "challengeId": "…", "method": "tempo", "intent": "charge" } } } ``` The challenge an agent signs embeds ZeroClick's payment metadata (the `payment.id` and `zcRequestId` above), so a retry needs only the signed proof and the agent's credential. ## Fixed charges settle after delivery on x402 An x402 `exact` payment is verified before ZeroClick forwards the request, but it settles on-chain only after your API returns a 2xx, and before ZeroClick releases your response to the agent. If the delivery fails, the buyer's signed authorization expires unused and no USDC moves. If the settlement cannot happen and nothing has moved (the wallet no longer covers it, the agent cancelled its authorization, or the authorization expired first), the agent gets a `402 payment_settlement_failed` instead of your response, and nothing is charged. An authorization that expires too soon to hold is settled before forwarding instead. A 2xx with an empty body is a failed delivery too; see [empty responses](/docs/integrate/settle-usage#empty-responses-do-not-bill) for what counts as empty. An MPP one-shot charge transfers when the agent pays, so a failed delivery on that rail is not returned; the `zc-billing` header records it either way. ## ZeroClick mints the deposit address Every priced challenge pays into a deposit (`payTo`) address that ZeroClick minted for that specific payment. Buyers pay exactly the address the challenge specifies. Sellers never publish, rotate, or even see these addresses. ## Ceiling charges need a reserve rail A [ceiling-priced request](/docs/integrate/charge-up-to-a-maximum), one whose usage item declares a `maxQuantity`, authorizes the most the call could cost, but must charge only actual usage. That is possible only on the reserve-and-pay-actual rails, so a ceiling challenge offers exactly these: * **x402 `upto`**: the wallet reserves the ceiling; ZeroClick settles the actual amount after delivery, and the reserved remainder never leaves the buyer's wallet. * **MPP session escrow**: the buyer funds a channel to the ceiling and signs one voucher; ZeroClick closes the channel at actual usage, and the escrow refunds the rest. If the close ever fails, the buyer can force-close after the on-chain grace period, so escrowed funds are never stranded. ZeroClick never offers one-shot prepay (`exact`, or the MPP charge) for a ceiling: that is what guarantees an unspent ceiling cannot get stuck as seller credit. If neither reserve rail is available for a capped price, ZeroClick refuses to mint an unpayable challenge and returns `503 capped_pricing_unavailable` instead. A failed delivery debits nothing on either rail, and every per-call paid response reconciles authorized versus charged in the `zc-billing` header. Stateful sellers' plan purchases and top-ups settle the same way. A standing-account purchase only charges once the seller confirms the account is provisioned, so the purchase 402 offers the reserve rails at the plan price (and the card lane authorizes without capturing). Capture happens when provisioning is acknowledged; a failed provisioning releases the wallet reservation or voids the card authorization, and the buyer is never charged. ## Automatic Tempo payments for standing accounts When a plan advertises `tempoAutomaticPayments` in its storefront manifest, a buyer can approve recurring charges separately from ordinary one-time purchases. The buyer reviews the seller's receiving address, price, billing interval, spending limits, and end date before signing an MPP `subscription` permission. The first subscription charge is part of that approval and funds the first service period; a buyer who already paid for a period waits until renewal is due. Later charges run from ZeroClick's hosted worker without the buyer's computer being online. A confirmed charge advances the existing account and sends the seller a new signed account write. Tempo's native billing windows are fixed lengths: a daily plan is 1 day, a monthly plan is **every 30 days**, and a yearly plan is **every 365 days** from the first charge. They are not calendar-month or calendar-year dates. A buyer may choose an end date or leave the permission set to “until cancelled.” The latter uses a distant technical expiry, so the buyer should still cancel when they want billing to stop. Automatic credit top-ups use a **second** standard Tempo `subscription` permission for the fixed refill amount, charged **at most once per day**. Buyers request it in the same signup as the plan by adding an `autoTopUp` block (`amountUsd`, `thresholdUsd`, `cooldownSeconds` of at least 86400, `dailyLimitUsd`, `monthlyLimitUsd`). Refills never charge at signup: they start after the first plan charge, when ZeroClick reads a fresh low balance and the buyer's cooldown and monthly limit allow it. An existing account can add refills later with a separate `kind: "top_up"` request. Every signup step is an ordinary MPP `402`, so any MPP client can complete it. First, pay the plan's challenge and repeat the identical request with `Authorization: Payment `, keeping the agent's bearer in `ZC-Agent-Authorization`; the plan is then active. If refills were requested, send the identical request once more and pay the second challenge the same way. Each response includes `nextAction` describing what is left, and skipping the second step only skips refills. Clients that can sign two challenges at once may instead sign `topUp.challenge` from the first response and send it in the `ZC-Tempo-Top-Up` header alongside the plan credential. A failed top-up approval never blocks the plan. Either permission can be cancelled independently at ZeroClick, which stops its worker from submitting new charges. An “until cancelled” permission has an on-chain technical expiry in 2100. Tempo enforces the exact amount, recipient, one charge per window, and expiry; ZeroClick also enforces the buyer's cooldown and monthly limits. Once a permission's first charge has installed its key on-chain, a buyer who wants to remove the wallet permission should also revoke that key on-chain. Before then there is no installed key to revoke, and cancelling at ZeroClick stops its worker from using the saved approval. ## Amounts and settlement Two money rules shape what the rails carry: * Amounts that settle on-chain as a single charge are **whole cents**: plan purchases, top-ups, subscription base prices, and pay-as-you-go rates. Catalog prices on credit and subscription plans keep 6-decimal precision, because they only burn prepaid balance. [Plans and pricing](/docs/concepts/plans-and-pricing) covers both rules. * Buyers pay USDC, but your revenue settles to your connected Stripe account (in fiat or USDC, your choice). You never operate a wallet to sell through ZeroClick. Rail availability depends on the country where your business is established; see [supported countries](/docs/resources/supported-countries). ## Sellers stay protocol-agnostic Nothing protocol-specific ever reaches your API. ZeroClick strips payment headers before forwarding, and your integration is the same four steps on every rail: verify the [signature](/docs/integrate/verify-requests), [check the allowance](/docs/integrate/check-allowances), serve, and [settle usage](/docs/integrate/settle-usage). When ZeroClick adds a new payment protocol, sellers ship nothing. For the protocols themselves, see [x402.org](https://www.x402.org) and [mpp.dev](https://mpp.dev). Every call also needs the agent's credential. On x402 it stays in `Authorization: Bearer `, because the payment rides `x-payment`. On MPP, send it in `ZC-Agent-Authorization: Bearer ` and keep `Authorization` for the MPP `Payment` credential; never combine credentials in one header. # Plans and pricing Source: https://zeroclickai.mintlify.dev/docs/concepts/plans-and-pricing The five billing modes, the per-plan verified-email gate, plan meter prices with unitSize and includedUnits, and the whole-cent and six-decimal precision rules. A plan defines how agents pay a seller. Each plan has a billing mode, a few plan-level money fields, and a set of **plan meter prices** that put a price on each [meter](/docs/concepts/stores-services-meters). Together they determine what a 402 challenge costs and what an [allowance check](/docs/concepts/usage-and-allowances) draws against. ## The five billing modes | Mode | For the buyer | For allowance checks | | - | - | - | | `payg` | No purchase. Each call returns one priced 402 with the exact cost; pay and retry. | Covered by the verified per-call payment, by included units in free mode (claimed agents with a verified email only), or by a prepaid balance the buyer still holds. | | `credit` | Prepay a balance of at least `minimumPurchaseUsd`, call until it runs out, top up any time. | Passes while `remainingCreditUsd` covers the declared usage at the plan's prices; otherwise denied `usage_exhausted`. | | `subscription` | Purchase once at `basePriceUsd` for the period (day, month, or year). Calls are allowed while the period runs. The plan's meter prices are its inclusion list: price a meter at `0` to include it, and leave it unpriced to exclude it. The storefront shows each meter as Included or Not included per plan, and a call on an excluded meter is refused; when another plan includes it, the `plan_required` refusal names that plan. | Passes while the access period is current; a lapsed period is denied `plan_expired`. No usage balance is burned. | | `subscription_usage` | A subscription whose purchase also grants `includedCreditUsd` of usage; usage beyond it is metered and charged per call. Its meter prices are also its coverage list: a meter with no price row is refused; when another plan covers it, the `plan_required` refusal names that plan. | Passes while the period is current and the included credit covers the declared usage; beyond it, per-call charges take over. | | `free_trial` | A one-time free grant: claimed with the agent's bearer and no payment, one per human, optionally granting `includedCreditUsd` of trial credit — as proxy-burnable usage credit on an ordinary storefront, or a free standing account on a [stateful one](/docs/integrate/stateful-sellers). `basePriceUsd` must be 0, `interval` must be `none`, and a storefront can hold one active free trial plan. | Like `subscription_usage`: passes while the trial credit covers the declared usage. | Plans carry an `interval` (`none`, `day`, `month`, or `year`) that sets the access period a purchase grants, and three money fields: * `basePriceUsd`: what a subscription purchase charges; a whole-cent amount. * `includedCreditUsd`: the usage credit a `subscription_usage` or `free_trial` purchase grants; up to 6 decimals. * `minimumPurchaseUsd`: the smallest credit purchase a buyer may make; whole cents, default \$0.01. A daily period lasts 24 hours. A daily renewal starts a fresh 24 hours when applied, including after a payment failure; missed days are not charged. A purchase creates the buyer's [access grant](/docs/concepts/agents-and-access), which later checks evaluate. Sellers that hand out accounts and API keys build on the same purchase and the same billing modes — see [sell accounts and API keys](/docs/integrate/stateful-sellers). ## The verified email policy Every plan carries a `verifiedEmailPolicy` — `off`, `requested`, or `required` — controlling whether the buyer's verified email is shared with you and whether it gates the sale: * **`off`**: nothing is ever disclosed. Purchases stay anonymous. * **`requested`**: never blocks a purchase. You receive the buyer's verified email whenever one exists — immediately when the buying agent is already claimed, or **later, the moment their human claims**: stateful storefronts get a fresh [account write](/docs/integrate/stateful-sellers#tying-the-account-to-a-user-account) carrying `buyerEmail`, and proxied calls simply start carrying the [`zc-buyer-email` header](/docs/resources/headers) on the next request. **Recommended whenever you keep user accounts**: fully autonomous agents can still buy, and when the human registers or signs in with that same email they find the entitlements their agents bought and can manage them like any other purchase. * **`required`**: purchases and top-ups are refused with a terminal `403 verified_email_required` until the buying agent is claimed by a human whose email is verified — the same claim that unlocks free included usage. On a `payg` plan the gate applies to the calls themselves: every pay-as-you-go request needs the claimed credential before any 402 is offered, which adds real friction. Use `required` only when you cannot deliver without an email; `requested` shares it without blocking anyone. Left unset the policy defaults by mode: **`required`** for `free_trial` (which is what keeps one person from farming unlimited free accounts), **`off`** for everything else. The catalog advertises `verifiedEmailPolicy` on each plan (with `requiresVerifiedEmail: true` echoed in the `purchase` block when the policy is `required`), so agents know to complete the claim before buying rather than discovering a refusal at purchase time — and know when a purchase will share their human's email. ## Plan meter prices A plan meter price attaches a price to one meter on one plan, with one price per meter per plan: * `priceUsd`: the price, up to 6 decimal places. * `unitSize`: how many units `priceUsd` buys (default 1). `priceUsd: "0.002"` with `unitSize: 1000` reads "\$0.002 per 1,000 units". * `includedUnits`: free units per billing period before `priceUsd` applies (default 0). * `defaultMaxQuantity`: an optional per-request ceiling, applied when a request declares neither a `quantity` nor a `maxQuantity` for the meter. Without a default, such an item is denied `meter_not_priced`. Cost is quantity × `priceUsd` ÷ `unitSize`, rounded to six decimal places. ## A worked example Acme prices the `output_tokens` meter of its `product-watch` service on a credit plan at \$0.002 per 1,000 tokens: ```json theme={null} { "priceUsd": "0.002", "unitSize": 1000, "includedUnits": 0, "defaultMaxQuantity": 8192 } ``` A request that settles 4,523 output tokens costs 4,523 × $0.002 ÷ 1,000 = **$0.009046\*\*, deducted from the buyer's `remainingCreditUsd`. A request that declares no token count up front is gated and authorized at the 8,192-token default ceiling (at most \$0.016384). It settles at the actual count, and the remainder returns to the buyer. [Charge up to a maximum](/docs/integrate/charge-up-to-a-maximum) covers ceiling billing from the seller's side. If the price also carried `includedUnits: 100000`, the buyer's first 100,000 tokens each period would be free, and `priceUsd` would apply only beyond them. ## Two precision rules 1. **Money that settles on-chain is whole cents.** Buyer-chosen amounts (credit purchases and top-ups) must be whole-cent values of at least `minimumPurchaseUsd`, and `basePriceUsd` is whole cents. Because ZeroClick charges a pay-as-you-go rate call by call, a payg plan's `priceUsd` must itself be a whole-cent amount. The API rejects anything else with `422 payg_price_not_whole_cents` (see [errors](/docs/resources/errors)). 2. **Catalog prices carry 6 decimals.** Prices on credit and subscription plans only burn prepaid allowance, so they keep full 6-decimal precision: sub-cent rates like `0.000250` are normal there. `unitSize` is how pay-as-you-go expresses sub-cent rates within the whole-cent rule: the credit-plan rate above becomes `priceUsd: "2.00"` with `unitSize: 1000000` on payg. That is the same \$0.002 per 1,000 tokens, stated as a whole-cent price per million. ## Managing plans ZeroClick sets up plans and prices with you during onboarding; you manage them afterward in the [dashboard](https://dashboard.zeroclick.io) or with the [REST API](/docs/api-reference/introduction). Agents always read live prices from the storefront's `manifest.json`, so a price change takes effect on their next call. # Sellers, services, and meters Source: https://zeroclickai.mintlify.dev/docs/concepts/stores-services-meters The ZeroClick catalog model: how sellers, services, and meters are identified, where each slug surfaces, and the uniqueness rules that apply. Your catalog on ZeroClick has three levels. A **seller** is one storefront. It contains **services**, the purchasable things, and each service contains **meters**, the billable measurements within it. Every identifier an agent sees on the storefront, and every identifier your guard sends to ZeroClick, resolves through these three levels. Catalog pricing is a separate concern; [plans and pricing](/docs/concepts/plans-and-pricing) covers it. ## Sellers A seller is one agent-facing storefront; the dashboard presents it as your store. Its slug names the hosted pay URL: slug `acme` gives `https://acme.pay.zeroclick.io`, and a custom domain such as `agents.acme.com` can front the same storefront. Seller slugs are unique across all of ZeroClick. Two seller fields do the heavy lifting: * `upstreamBaseUrl`: the origin ZeroClick forwards paid requests to, such as `https://api.acme.internal`. Agents never see it: they call the pay URL, and ZeroClick maps the path onto your upstream on the signed forward. * Storefront metadata: name, description, tagline, tags, logo, docs and OpenAPI URLs, contact email. Agents read this metadata when they discover you, both on the storefront and in the machine-readable catalog it serves at `/manifest.json`. The pay URL is a transparent proxy over the upstream, so the mapping is mechanical. An agent sends the request it would have sent you directly: ```http theme={null} POST /v1/product-watch HTTP/1.1 Host: acme.pay.zeroclick.io { "url": "https://example.com/product/42" } ``` and, once paid, ZeroClick forwards the same method, path, query, and body to `https://api.acme.internal/v1/product-watch` with the `zc-request-id`, `zc-agent-id`, and `zc-signature` headers attached. The full lifecycle is in [how ZeroClick works](/docs/concepts/how-zeroclick-works). ## Services A service is one purchasable thing: an API, a model, a workflow, or a feature. It has a name, an optional description, and a slug that is unique per seller: two sellers can both have a `product-watch`, but one seller cannot have two. The service slug is the identifier your integration speaks. Your guard passes it as `serviceSlug` in [allowance checks](/docs/integrate/check-allowances) and [usage reports](/docs/integrate/settle-usage). Your API names it in the `402 payment_required` refusal body that ZeroClick re-prices into a challenge. ## Meters A meter is one billable measurement within a service: `requests` with unit "request", or `output_tokens` with unit "token". A meter is only a key and a unit: prices attach to meters through plans, so the same meter can cost different amounts on different plans. Meter keys must match `^[a-z][a-z0-9_]*$` (up to 80 characters) and are unique per service. The key appears as `meterSlug` everywhere usage is named: allowance checks, usage reports, the `zc-usage` response header, and the `usage` items in 402 challenges. ## Where each identifier surfaces | Level | Example | Unique within | Surfaces as | | - | - | - | - | | Seller slug | `acme` | all of ZeroClick | the pay URL host, `acme.pay.zeroclick.io` | | Service slug | `product-watch` | its seller | `serviceSlug` in guard calls, 402 refusals, and the catalog | | Meter key | `output_tokens` | its service | `meterSlug` in allowance checks, usage reports, and `zc-usage` | Seller and service slugs are lowercase kebab-case (`^[a-z0-9]+(?:-[a-z0-9]+)*$`, up to 80 characters); meter keys use underscores instead of hyphens. ## What agents read The pay URL doubles as the seller's machine-readable surface. Alongside the storefront itself, it serves: * `/manifest.json`: the live catalog as JSON: services with their meters and the plans that price each, and plans with their prices plus what each `includes` and `excludes`. Agents read it at call time, so catalog changes reach buyers without a republish step. * `/llms.txt` and `/llms-full.txt`: an agent-facing index and full guide for calling your API through ZeroClick, generated from the same catalog. ZeroClick generates all three from your catalog; none of them is something you author or host. ## Managing the catalog ZeroClick sets up your catalog with you during onboarding. After that, you manage it in the [dashboard](https://dashboard.zeroclick.io), or with the [REST API](/docs/api-reference/introduction) when you want to automate changes. Sellers, services, and meters are plain resources scoped to your organization. Changing a slug changes the identifier your guard must send, so coordinate slug changes with a deploy of your integration. # Usage and allowances Source: https://zeroclickai.mintlify.dev/docs/concepts/usage-and-allowances What an allowance check decides, the three usage-item forms, the seven denial reasons, free mode, and how sync and async settlement stay idempotent. An allowance is the answer to one question, asked before billable work runs: does this buyer's plan cover this usage? Your API asks it with `POST https://api.zeroclick.io/v1/usage/check` (API key scope `usage:read`). The body carries the request's `zcRequestId`, the `serviceSlug`, and 1 to 20 usage items: one per meter, no duplicates. The response is a pure decision: ```json Request theme={null} { "zcRequestId": "zcreq_8h2m4x0q9k1f", "serviceSlug": "product-watch", "usage": [{ "meterSlug": "output_tokens", "maxQuantity": 8192 }] } ``` ```json Response theme={null} { "allowed": true, "reason": null } ``` A check records nothing and burns nothing: no usage event, no credit deduction, no included units consumed. It exists so you can refuse before doing the work; billing happens only when you settle. The [check allowances](/docs/integrate/check-allowances) guide covers calling it; this page covers what the answers mean. ## The three usage-item forms Each usage item names a meter and sizes the usage one of three ways. An item may not declare both a quantity and a ceiling. * `quantity`: the exact amount, known up front ("this call is 1 request"). * `maxQuantity`: a ceiling for work you cannot size in advance ("at most 8,192 output tokens"). The check gates at the ceiling: could the largest allowed call go through? * Neither: the item falls back to the meter's `defaultMaxQuantity` from the [plan meter price](/docs/concepts/plans-and-pricing) and gates at that ceiling. If the meter has no default, there is nothing to gate against, and the check denies `meter_not_priced`. Quantities are integers from 1 to 2,147,483,647. ## The seven denial reasons `allowed: false` always comes with exactly one machine-readable reason: | Reason | Meaning | | - | - | | `service_not_found` | The `serviceSlug` does not name a service in your catalog. | | `access_not_found` | Nothing stands behind the request: no active access, no verified payment, no free-mode coverage. This is the normal first-touch denial that becomes a priced 402. | | `access_inactive` | The buyer's access exists but is not active, or its period has not started. | | `plan_expired` | The access period has ended (`periodEndsAt` is in the past). | | `meter_not_found` | The `meterSlug` does not name a meter on this service. | | `meter_not_priced` | The buyer's plan has no price for this meter, or the item declared neither quantity nor ceiling and the meter has no `defaultMaxQuantity`. | | `usage_exhausted` | The plan prices the usage, but the remaining balance or allowance cannot cover the declared amount. | Your API turns a denial into the `402 payment_required` refusal body, and ZeroClick re-prices it into the buyer's next challenge. A denial is a payment prompt, not a dead end. The [errors reference](/docs/resources/errors) lists the response shapes. ## Free mode Prices can carry `includedUnits`: free units per period before the price applies. On pay-as-you-go, consuming them is an explicit opt-in: the agent sends the `zc-mode: free` request header on each call. A missing or unrecognized header means paid; ZeroClick never rejects a call over it. Like every call, a free-mode call without an agent credential gets `401 bearer_required`. Unclaimed agents are never served free either: the allowance is reserved for agent identities claimed by a human with a verified email, and it is scoped to that buyer - consumption aggregates across every agent the same human owns, so claiming more agents never grants more free usage. Every credentialed call gets the real coverage check, including the claimed-and-verified requirement. ZeroClick records the mode on the request, so your allowance check and the usage recorder honor the same decision ZeroClick made. See [free and identity endpoints](/docs/integrate/free-and-identity-endpoints). ## Settling usage: sync and async A check gates; a settlement records. There are two ways to settle, and both write the same usage events: * **Sync (preferred):** put a `zc-usage` header on your 2xx response. ZeroClick records it while returning the response and strips the header before the agent sees it. A request can never settle the same meter twice. ```http theme={null} zc-usage: [{"serviceSlug":"product-watch","meterSlug":"output_tokens","quantity":4523}] ``` * **Async:** call `POST https://api.zeroclick.io/v1/usage` (scope `usage:write`) with `zcAgentId`, `serviceSlug`, `meterSlug`, `quantity`, an optional `occurredAt`, and an `idempotencyKey`. Async events are unique per `(service, idempotencyKey)`. Keys are yours and must be derived, never random (`zcreq_8h2m4x0q9k1f_output_tokens`), so a retry reproduces the same key. A replay answers `"recorded": true, "duplicate": true` with the originally stored event: a success, not an error. Every recorded usage event carries `source: "sync"` or `"async"`, along with the `zcAgentId`, `zcRequestId`, `meterSlug`, `quantity`, and the computed `totalCostUsd`. This is the same record you see in the dashboard and the [REST API](/docs/api-reference/introduction). ZeroClick can also refuse a report after the fact: `402` for `access_inactive`, `plan_expired`, or `usage_exhausted`, `409` for `meter_not_priced`, and `404` otherwise. That is one more reason to check before you serve. The [settle usage](/docs/integrate/settle-usage) guide covers both paths in code. # Free actions Source: https://zeroclickai.mintlify.dev/docs/examples/free-actions Shared setup for free agent actions, with independent choices for ZeroClick email policy and your endpoint inputs. A free action lets an agent complete a task for its user without paying: book a demo, submit a lead, download a white paper, or register for a webinar. Your API collects the inputs, performs the action, and returns a useful result. You can think of these as \$0 transactions: the agent completes an action without a payment. The reference examples below use unmetered endpoints: they serve the action without checking a billable allowance or reporting usage. No card or wallet charge, payment record, or trial credit is needed. ## Choose an example These are reference designs to adapt, not prescribed seller APIs. The endpoint paths, input fields, and response shapes illustrate possible workflows. Your product decides what to collect and how to fulfill the action; the shared ZeroClick integration below applies across them. | Reference example | What it demonstrates | | - | - | | [Book a demo](/docs/examples/free-actions/book-a-demo) | Check availability, collect attendee details, and confirm a booking. | | [Capture a lead](/docs/examples/free-actions/capture-a-lead) | Submit requirements to a CRM and return a request reference. | | [Deliver a white paper](/docs/examples/free-actions/deliver-a-white-paper) | Select a document and return a download URL, with or without contact collection. | | [Register for a webinar](/docs/examples/free-actions/register-for-a-webinar) | Select an event, register an attendee, and return joining instructions. | You can also adapt these patterns for a waitlist, a quote request, or another free action your API can fulfill. ## Before you start You need a store configured in the [dashboard](https://dashboard.zeroclick.io), an upstream API ZeroClick can reach, and a [signing secret and key id](/docs/integrate/keys-and-secrets). ZeroClick configures your store and catalog with you during onboarding. Configure this shared integration once, then implement the endpoints for your chosen example. The API behind each action—your calendar, CRM, document service, or event platform—is your responsibility. ## Set up ZeroClick ### 1. Choose your email requirements Make two independent choices: | Choice | Who defines it? | | - | - | | Whether the agent owner's verified email is shared or required | **ZeroClick**, through the plan's `verifiedEmailPolicy`. | | Whether a request includes a contact, attendee, or recipient email | **You**, through your endpoint's input schema and validation. | > [!NOTE] > > A plan's email requirement is a ZeroClick concept. It has no effect on which fields your endpoint asks for. **Off** does not prohibit an email input, **Request** does not prompt for one, and **Require** does not verify an address supplied in the request body. If you need to enforce limits per verified email, set ZeroClick's email policy to **Require**. After verifying the request, use `zc-buyer-email` as the key for limits enforced by your application—for example, one demo booking per email per day. ZeroClick verifies the email; your API enforces the limit. In your store's **Pricing & Plans**, create or edit a **Pay as you go** plan and set **Verified email**: | Setting and API value | ZeroClick behavior | | - | - | | **Off** (`off`) | Does not share the agent owner's email or require email verification. | | **Request** (`requested`) | Shares the agent owner's verified email when available. Its absence does not block the call. | | **Require** (`required`) | Requires the agent's human to claim it with a verified email before the call proceeds. Otherwise returns `403 verified_email_required`. | You can also set `verifiedEmailPolicy` on an existing plan through the API. For example, to require verification: ```sh theme={null} curl --request PATCH "https://api.zeroclick.io/v1/plans/$PLAN_ID" \ --header "Authorization: Bearer $ZEROCLICK_ADMIN_KEY" \ --header "Content-Type: application/json" \ --data '{"verifiedEmailPolicy":"required"}' ``` Use an API key with `admin:write`. Set the value to `off` or `requested` for the other choices. For the unmetered reference examples, the plan supplies the email policy and the endpoint remains unbilled. Leave these endpoints without meter links, and do not add a paid allowance check to their handlers. ZeroClick advertises endpoints without meter links at \$0 in its discovery spec. > [!NOTE] > > This policy is per plan, not per endpoint. Without an existing access grant, a pay-as-you-go plan with **Require** gates calls across the storefront, including availability checks. Calls using an existing access grant follow the funding plan's policy. Align the policies of every plan that can fund this workflow; use separate storefronts if you need different entry requirements for different public flows. **Request** does not ask the agent to fill in an email field. It shares an already verified email through `zc-buyer-email` when available. If the human claims the agent later, subsequent proxied calls can carry the email; your earlier lead record is not automatically updated. Separately, choose what your endpoint accepts. You can require an attendee email with **Off**, offer an optional contact email with **Request**, or accept no email input at all with **Require**. An address submitted by an agent remains unverified unless your own verification process proves ownership. For example, a demo booking may accept `attendeeEmail` for a colleague while ZeroClick shares the agent owner's email. Preserve both meanings. If your product only allows users to book for themselves, explicitly enforce that rule in your handler; ZeroClick does not match these addresses for you. See [the verified email policy](/docs/concepts/plans-and-pricing#the-verified-email-policy) for the full contract. ### 2. Describe your action in the catalog Add a service with a name and slug that describe the action. Register its endpoints and request and response schemas, leaving the free endpoints without meter links. Document the action's outcome, its \$0 cost, and the inputs your API needs. Explain the ZeroClick email policy separately from input requirements. For example: “ZeroClick email verification is optional. Booking requires an attendee email for the calendar invitation.” Use the endpoint suggestions on each example page as a starting point. ### 3. Verify the request and identify the agent Install the seller SDK: ```sh theme={null} pnpm add @zeroclickai/sellers ``` Use `guardIdentity` before parsing the body or performing the action. It verifies the ZeroClick signature and requires an agent credential without making an allowance call. This is the guard ZeroClick uses for its demo endpoints. ```ts theme={null} import { guardIdentity } from "@zeroclickai/sellers"; export async function verifyFreeActionRequest( request: Request, serviceSlug: string, ) { return guardIdentity( request, { serviceSlug }, { signingSecrets: { [process.env.ZEROCLICK_SIGNING_SECRET_KID!]: process.env.ZEROCLICK_SIGNING_SECRET!, }, }, ); } ``` Pass the original request, including its unchanged path, query, and body. The standalone guard needs only your signing configuration; there is no usage API key to configure for this flow. An agent without a credential receives `401 bearer_required` from the pay URL and follows that storefront's `/auth.md` registration recipe. It retries with `Authorization: Bearer `. Registration alone is enough for **Off** and **Request**. For **Require**, the human also completes the claim and email verification described in `/auth.md` before retrying. `guardIdentity` establishes an agent id; the plan policy enforces email verification. These are separate checks. If your handler does not need an agent id, you can use [`verifyRequest`](/docs/integrate/verify-requests) instead. This changes the handler's identity check, not the plan's email policy. ### 4. Handle seller inputs and the verified buyer email Once the guard allows a request, parse and validate your input schema. A required input missing from the body is an application validation error, even when ZeroClick's email policy is **Off**. A valid contact email in the body cannot satisfy ZeroClick's **Require** policy. If your plan shares a verified email, read it after request verification: ```ts theme={null} const verifiedBuyerEmail = request.headers.get("zc-buyer-email"); ``` Under **Request**, allow this value to be absent. If your application needs it to fulfill an action, configure **Require** and reject the action if the header is unexpectedly absent. Keep `verifiedBuyerEmail` separate from contact or attendee fields; decide explicitly which address each downstream operation uses. Follow the [header trust rules](/docs/resources/headers): `zc-buyer-email` is asserted by ZeroClick over the authenticated channel, but is not itself covered by the request signature. It must not by itself authorize access to existing customer records. Call your fulfillment system only after validation. Return its result directly, without `withUsage`, `reportUsage`, or a `zc-usage` header. There is no charge to settle. ## Reduce abuse of free actions For per-email limits, use **Require** and key your application's counters by `zc-buyer-email` after request verification. Check the limit before performing the action, and update the counter atomically so simultaneous requests cannot bypass it. A submitted contact or attendee email remains a separate input and does not establish a verified identity. Email verification does not itself rate-limit requests or prove that each email belongs to a different person. Keep retry deduplication and request rate limits appropriate to your API. For metered free allowances enforced by ZeroClick, see [pay-as-you-go included units](/docs/integrate/free-and-identity-endpoints#included-free-units). That approach uses the billing guard and usage reporting instead of the unmetered flow in these examples. ## Test the integration Use a staging integration for actions that create records or send invitations. Fetch your storefront's `/auth.md` and follow its instructions to obtain an agent access token. Call your pay URL with `Authorization: Bearer `. Test ZeroClick policy and seller validation independently: | Check | Expected result | | - | - | | **Off**, with an unclaimed agent | The policy allows the call; no verified buyer email is shared. | | **Request**, with and without a verified human claim | Both calls proceed; only the verified one carries `zc-buyer-email`. | | **Require**, before and after a verified human claim | Before claiming, `403 verified_email_required`; after claiming, the call proceeds with the header. | | Required seller email omitted, with **Off** | Your handler rejects the input, such as with `400 invalid_request`. | | Valid seller email supplied, with **Require** and no verified claim | ZeroClick still returns `403 verified_email_required`. | | Different attendee and verified buyer addresses | Your handler applies your own rule for acting on behalf of someone else. | Also check that unsigned requests to your upstream fail, invalid inputs cause no side effects, and retries do not duplicate the action. A new request may have a new `zcRequestId`; use your own stable operation key when you need deduplication across separate agent requests. A successful free call should not ask for a payment credential or consume a paid allowance. ## Help agents discover the action Add [agent discovery signals](/docs/website/enable-agent-traffic) or the [Buy with AI widget](/docs/website/buy-with-ai-widget) to your website. Describe the sequence in your service instructions: collect inputs, confirm the user's intent, submit the action, and report the result. Each example page supplies a suggested sequence to adapt. # Book a demo Source: https://zeroclickai.mintlify.dev/docs/examples/free-actions/book-a-demo A reference flow for finding availability, collecting attendee details, and confirming a free demo booking. Let an agent check availability, collect the attendee's details, book a time, and return confirmation. This example is loosely based on [ZeroClick's own demo booking flow](https://agents.zeroclick.ai). > [!NOTE] > > This is a reference example, not a required API design or a drop-in implementation. Adapt the endpoints, fields, responses, and fulfillment steps to your product. Only the linked ZeroClick integration requirements are platform contracts. Start with [Overview and setup](/docs/examples/free-actions) for the shared ZeroClick configuration, email policy, request guard, and testing guidance. ## Example choices * **ZeroClick policy:** `off` is enough if you do not need the agent owner's verified email. Use `requested` to receive it when available, or `required` if identifying the owner is essential to your product. * **Seller input:** require an attendee `email` to send the calendar invitation, regardless of the ZeroClick policy. A user can book for a colleague, so this address may differ from the agent owner's verified email. * **Fulfillment:** your calendar integration creates the booking. ZeroClick forwards the request to your API. You need a calendar integration that can list availability and create bookings. Use a test calendar while implementing the flow. The commands use the placeholder pay URL `https://acme.pay.zeroclick.io`; replace it with yours. ## Build the example ### 1. Describe the action in your catalog Add a service named **Book a demo**, with slug `demo-booking`. Describe who the demo is for, what it covers, how long it takes, and that it costs \$0. Include the email requirement you chose. Register the endpoints and their request and response schemas so agents can discover how to complete the action. The core booking flow needs two: | Endpoint | Purpose | | - | - | | `GET /demo/availability` | Return available times for a date range and time zone. | | `POST /demo/bookings` | Book a selected time using the attendee's details. | ZeroClick's own flow also supports `GET /demo/bookings/{bookingId}`, `POST /demo/bookings/{bookingId}/reschedule` and `POST /demo/bookings/{bookingId}/cancel` for follow-up actions. It needs the attendee's time zone (an IANA name, an offset or a common abbreviation such as EST), returns each time in UTC and local time with a readable label, and answers a taken time with the nearest open ones. For the booking body, document these fields: | Field | Required | Meaning | | - | - | - | | `start` | Yes | A `start` value from the availability response, echoed unchanged. | | `firstName`, `lastName` | Yes | The attendee's name. | | `email` | Yes | The attendee's contact email. In a verified-only adaptation, derive this from the verified buyer email instead. | | `company` | Yes | The attendee's company. | | `timeZone` | Yes | The attendee's time zone: an IANA name (`America/New_York`), an offset (`UTC-5`) or a common abbreviation (`EST`). ZeroClick's demo answers 400 without it, with a message asking the agent to ask the person. | | `heardAbout` | Yes | How the attendee heard about you, in a few words (2 to 200 characters). ZeroClick's demo answers 400 without it, with a message asking the agent to ask the person. | | `notes` | No | Questions or context for the demo. | These fields describe the reference booking flow. Choose the inputs your own scheduling integration needs. ### 2. Validate the inputs and complete the action After the guard allows the request, validate the fields, call your calendar provider, and return its confirmed result. The following handler outline uses the `verifyFreeActionRequest` helper from [shared setup](/docs/examples/free-actions#verify-the-request-and-identify-the-agent). `parseBookingInput` and `calendar.createBooking` are application functions you supply, not SDK methods. ```ts theme={null} export async function POST(request: Request): Promise { const decision = await verifyFreeActionRequest(request, "demo-booking"); if (decision.action === "deny") return decision.response; // Validate required fields, email format, timestamp, and time zone. // Return a 400 response for malformed JSON or invalid fields. const input = await parseBookingInput(request); if (input instanceof Response) return input; const booking = await calendar.createBooking({ ...input, idempotencyKey: decision.context.zcRequestId, }); return Response.json(booking, { status: 201 }); } ``` The `email` in this example is the attendee address supplied to your endpoint. The ZeroClick plan policy neither requires this field nor verifies it. Keep a verified buyer email separate if you also receive one; see [the two email choices](/docs/examples/free-actions#choose-your-email-requirements). ZeroClick's demo passes `zcRequestId` to its calendar integration as an idempotency key so a replay of the same forwarded request does not create a duplicate booking. A new agent request can have a new request id; add your own stable operation key if you need deduplication across those requests too. Return a clear error if the slot is no longer available or the provider cannot complete the booking. Confirm success only after the provider confirms it. Keep calendar credentials server-side. Return the successful response directly, without `withUsage`, `reportUsage`, or a `zc-usage` header. There is no charge to settle. ### 3. Test through your pay URL Use a test calendar or a staging integration for booking tests. Fetch your storefront's `/auth.md` and follow its instructions to obtain an agent access token. Then request availability: ```sh theme={null} curl "https://acme.pay.zeroclick.io/demo/availability?timeZone=America%2FNew_York" \ --header "Authorization: Bearer $AGENT_ACCESS_TOKEN" ``` Choose a returned start time and save a request as `booking.json`. This illustrates the body; replace `start` with a currently available slot and use your test attendee's details: ```json theme={null} { "start": "2026-10-15T18:00:00.000Z", "timeZone": "America/New_York", "firstName": "Casey", "lastName": "Reed", "email": "casey@example.com", "company": "Example Co", "heardAbout": "A colleague recommended it", "notes": "We want agents to request quotes through our API." } ``` ```sh theme={null} curl --request POST "https://acme.pay.zeroclick.io/demo/bookings" \ --header "Authorization: Bearer $AGENT_ACCESS_TOKEN" \ --header "Content-Type: application/json" \ --data-binary @booking.json ``` A booking confirmation should include a booking id, status, the scheduled time in UTC and in the attendee's zone, a label the agent can show the person, and a message. For example, these are fields returned by ZeroClick's calendar integration: ```json theme={null} { "outcome": "booked", "booking_id": "11111111-1111-4111-8111-111111111111", "status": "confirmed", "scheduled_start": "2026-10-15T18:00:00.000Z", "scheduled_end": "2026-10-15T18:30:00.000Z", "time_zone": "America/New_York", "local_start": "2026-10-15T14:00:00-04:00", "label": "Thu, Oct 15, 2:00 PM EDT", "host": { "name": "Jamie" }, "message": "You're booked with Jamie on Thu, Oct 15 at 2:00 PM EDT." } ``` Run the [shared integration checks](/docs/examples/free-actions#test-the-integration). For this example, also test an unavailable slot, invalid attendee details, and a replay of the same booking request. Each refusal should leave the calendar unchanged, and the replay should return the original booking. ### 4. Help agents find and finish the flow Add [agent discovery signals](/docs/website/enable-agent-traffic) to your website, or use the [Buy with AI widget](/docs/website/buy-with-ai-widget) with booking copy such as **Book a demo with your AI** and `data-verb="Book"`. Describe the sequence in your service instructions: check availability, ask the user to choose a time, collect the required details, confirm the user's intent to book, submit the booking, and report the confirmed time. Include the email policy so the agent knows whether human verification is needed. You can inspect [ZeroClick's agent storefront](https://agents.zeroclick.ai) as a reference. For another free action, keep the same discovery, identity, and email choices, then replace the calendar call with your CRM submission, document delivery, or event registration. # Capture a lead Source: https://zeroclickai.mintlify.dev/docs/examples/free-actions/capture-a-lead A reference flow for collecting a sales inquiry, saving it to a CRM, and returning next steps. Let an agent submit a sales inquiry on behalf of its user. Your API records the requirements and contact details, then returns a reference the agent can report to the user. > [!NOTE] > > This is a reference example, not a required API design or a drop-in implementation. Adapt the endpoints, fields, responses, and fulfillment steps to your product. Only the linked ZeroClick integration requirements are platform contracts. Start with [Overview and setup](/docs/examples/free-actions) for the shared ZeroClick configuration, email policy, request guard, and testing guidance. ## Example choices * **ZeroClick policy:** choose `requested` if the agent owner's verified email is useful for attribution but should not block an inquiry. * **Seller input:** require `contactEmail` because this example promises a sales follow-up. Your schema enforces that requirement even when ZeroClick has no verified email to share. * **Fulfillment:** create an inquiry in your CRM or support system. Acknowledging the inquiry does not mean a quote has been prepared. The [two email choices](/docs/examples/free-actions#choose-your-email-requirements) remain independent in every variant. Changing a ZeroClick plan policy does not add, remove, or verify an email field in your endpoint. ## Build the example ### 1. Describe the action and endpoints Add a service such as `sales-inquiry` and describe its outcome and \$0 cost. Register your endpoint schemas without meter links, following [shared setup](/docs/examples/free-actions). These paths are suggestions for your API: | Suggested endpoint | Purpose | | - | - | | `POST /sales/inquiries` | Record an inquiry and return its reference. | | `GET /sales/inquiries/{inquiryId}` | Optionally let the originating agent check its status. | These endpoints belong to your upstream API and are called through your pay URL. They are not built-in ZeroClick API operations. ### 2. Define the seller inputs This reference design uses the following inputs. Adapt their names and required status to your product: | Input | Required in this example | Purpose | | - | - | - | | `name` | Yes | The contact person's name. | | `contactEmail` | Yes | Where the sales team should follow up; user-supplied and unverified. | | `company` | No | Company context, if relevant to qualification. | | `requirements` | Yes | What the user wants to discuss or buy. | | `operationId` | Yes | A caller-generated identifier reused when retrying this inquiry. | For example, the request body could be: ```json theme={null} { "name": "Casey Reed", "contactEmail": "casey@example.com", "company": "Example Co", "requirements": "We need a quote for 50 seats and SSO.", "operationId": "inquiry-casey-001" } ``` ### 3. Validate and fulfill the request Use the `verifyFreeActionRequest` helper from [shared setup](/docs/examples/free-actions#verify-the-request-and-identify-the-agent) with service slug `sales-inquiry`. Return a guard denial immediately, then parse and validate your input. Return `400` for malformed or missing fields before creating any records or sending messages. Validate the required contact details and requirements before writing to your CRM. Save `contactEmail` as the follow-up address. If ZeroClick supplies `zc-buyer-email`, store it separately as the verified agent-owner email; do not silently replace the requested contact. Deduplicate by the verified agent id and `operationId`. Persist the operation key with the inquiry so a repeated submission returns the same record. If your CRM writes asynchronously, return an accepted status with a reference only after you have durably queued the work. For an optional status endpoint, verify the caller and enforce ownership of the inquiry before returning its details. Use `201 Created` once the inquiry is saved, or `202 Accepted` when it has been durably queued. Promise a response time only if your team can meet it. ```json theme={null} { "inquiryId": "inq_001", "status": "received", "nextStep": "Our sales team will email the contact address within two business days." } ``` Return the response without reporting billable usage. Your application supplies the fulfillment logic and error handling; the seller SDK supplies request verification. ### 4. Test through your pay URL Use a staging integration. Save the example body as `request.json`, replace its values and the placeholder pay URL below, and get an agent token through your storefront's `/auth.md` recipe. ```sh theme={null} curl --request POST "https://acme.pay.zeroclick.io/sales/inquiries" \ --header "Authorization: Bearer $AGENT_ACCESS_TOKEN" \ --header "Content-Type: application/json" \ --data-binary @request.json ``` Run the [shared integration checks](/docs/examples/free-actions#test-the-integration), then test the cases specific to this action: * Omit `contactEmail`: your API rejects the body even with ZeroClick policy **Off** or **Request**. * Submit through an unclaimed agent with **Request**: the inquiry succeeds without a verified buyer email. * Repeat the same `operationId`: the CRM has one inquiry and the response has the same reference. * Simulate a CRM outage: return an error or a durable queued state, never claim the inquiry was saved when it was lost. ### 5. Describe the agent's workflow Ask the user what they need and where sales should respond. Confirm that they want to submit the inquiry, send it once, then report the reference and next step. Adapt this flow for a quote request or a waitlist by changing the fields and fulfillment. Publish these instructions with your service and add [discovery signals](/docs/website/enable-agent-traffic) on the relevant website page. # Deliver a white paper Source: https://zeroclickai.mintlify.dev/docs/examples/free-actions/deliver-a-white-paper A reference flow for selecting a document and returning a free download, with optional contact collection. Let an agent find a relevant white paper and retrieve a download URL for its user. The reference flow delivers the document directly, so an email address is optional. > [!NOTE] > > This is a reference example, not a required API design or a drop-in implementation. Adapt the endpoints, fields, responses, and fulfillment steps to your product. Only the linked ZeroClick integration requirements are platform contracts. Start with [Overview and setup](/docs/examples/free-actions) for the shared ZeroClick configuration, email policy, request guard, and testing guidance. ## Example choices * **ZeroClick policy:** choose `off` when document delivery needs no verified agent-owner email. * **Seller input:** accept optional `contactEmail` only if you have a defined use for it, such as sending a copy when requested. Omit the field entirely if you do not need it. * **Fulfillment:** return a download URL from your document service. A direct download works without any email address. The [two email choices](/docs/examples/free-actions#choose-your-email-requirements) remain independent in every variant. Changing a ZeroClick plan policy does not add, remove, or verify an email field in your endpoint. For a finite free allowance, such as five downloads per verified buyer, adapt this flow using [pay-as-you-go included units](/docs/integrate/free-and-identity-endpoints#included-free-units). That variant uses the billing guard and usage reporting instead of the unmetered guard below. ## Build the example ### 1. Describe the action and endpoints Add a service such as `white-paper` and describe its outcome and \$0 cost. Register your endpoint schemas without meter links, following [shared setup](/docs/examples/free-actions). These paths are suggestions for your API: | Suggested endpoint | Purpose | | - | - | | `GET /white-papers` | List document ids, titles, descriptions, and formats. | | `POST /white-papers/{documentId}/downloads` | Return a download URL for the selected document. | These endpoints belong to your upstream API and are called through your pay URL. They are not built-in ZeroClick API operations. ### 2. Define the seller inputs This reference design uses the following inputs. Adapt their names and required status to your product: | Input | Required in this example | Purpose | | - | - | - | | `documentId` | Yes, in path | The document selected from your listing. | | `contactEmail` | No | A user-supplied address, if your workflow offers email delivery. | | `sendCopy` | No | Whether the user wants an emailed copy; defaults to `false` in this example. | | `operationId` | Yes | A caller-generated identifier reused for retries, especially email delivery. | For example, the request body could be: ```json theme={null} { "sendCopy": false, "operationId": "download-guide-001" } ``` ### 3. Validate and fulfill the request Use the `verifyFreeActionRequest` helper from [shared setup](/docs/examples/free-actions#verify-the-request-and-identify-the-agent) with service slug `white-paper`. Return a guard denial immediately, then parse and validate your input. Return `400` for malformed or missing fields before creating any records or sending messages. Look up the document by id and check that it is available. For direct delivery, return a URL your user can actually open. If it expires, include the expiration in the response and document how to obtain a new one. If `sendCopy` is `true`, require `contactEmail` in your input validation before requesting email delivery. This conditional requirement is your application rule and is independent of ZeroClick's **Off** setting. Accepting that address does not verify it. Deduplicate email delivery by the verified agent id and `operationId` so retries do not send repeated copies. Report whether the email was queued separately from the download result. Keep storage credentials on your server. Return `200 OK` with the download result. If you use signed URLs, include an `expiresAt` timestamp. Do not claim that a queued email was delivered. ```json theme={null} { "documentId": "agent-commerce-guide", "title": "A guide to agent commerce", "downloadUrl": "https://downloads.example.com/agent-commerce-guide.pdf", "contentType": "application/pdf", "emailStatus": "not_requested" } ``` Return the response without reporting billable usage. Your application supplies the fulfillment logic and error handling; the seller SDK supplies request verification. ### 4. Test through your pay URL Use a staging integration. Save the example body as `request.json`, replace its values and the placeholder pay URL below, and get an agent token through your storefront's `/auth.md` recipe. ```sh theme={null} curl --request POST "https://acme.pay.zeroclick.io/white-papers/agent-commerce-guide/downloads" \ --header "Authorization: Bearer $AGENT_ACCESS_TOKEN" \ --header "Content-Type: application/json" \ --data-binary @request.json ``` Run the [shared integration checks](/docs/examples/free-actions#test-the-integration), then test the cases specific to this action: * Request the direct download without `contactEmail`: the result includes a usable URL. * Set `sendCopy` to `true` without an address: your API rejects the input even though ZeroClick policy is **Off**. * Request an unknown document: return `404` rather than a broken download URL. * Repeat an email request with the same `operationId`: only one copy is queued. * Open the returned URL from the intended recipient's environment; check expiration behavior if applicable. ### 5. Describe the agent's workflow List the available documents, choose one relevant to the user's request, retrieve its URL, and return the title and link. Ask for an email only if the user wants email delivery. If you choose to gate downloads on contact collection, document that as a seller input requirement; requiring the ZeroClick owner's verified email is a separate decision. Publish these instructions with your service and add [discovery signals](/docs/website/enable-agent-traffic) on the relevant website page. # Register for a webinar Source: https://zeroclickai.mintlify.dev/docs/examples/free-actions/register-for-a-webinar A reference flow for discovering an event, collecting attendee details, and confirming a free registration. Let an agent select an upcoming webinar, register an attendee, and return joining instructions. Your event platform owns the registration and confirmation. > [!NOTE] > > This is a reference example, not a required API design or a drop-in implementation. Adapt the endpoints, fields, responses, and fulfillment steps to your product. Only the linked ZeroClick integration requirements are platform contracts. Start with [Overview and setup](/docs/examples/free-actions) for the shared ZeroClick configuration, email policy, request guard, and testing guidance. ## Example choices * **ZeroClick policy:** this example uses `required` to illustrate a seller that wants a verified agent owner before accepting registrations. Use `off` or `requested` instead if that verification serves no purpose for your event. * **Seller input:** require `attendeeEmail` for the event invitation. The verified owner can register a colleague in this example; the attendee address is a separate, unverified input. * **Fulfillment:** create the attendee registration in your event platform and return its confirmation. ZeroClick does not register the attendee for you. The [two email choices](/docs/examples/free-actions#choose-your-email-requirements) remain independent in every variant. Changing a ZeroClick plan policy does not add, remove, or verify an email field in your endpoint. ## Build the example ### 1. Describe the action and endpoints Add a service such as `webinar-registration` and describe its outcome and \$0 cost. Register your endpoint schemas without meter links, following [shared setup](/docs/examples/free-actions). These paths are suggestions for your API: | Suggested endpoint | Purpose | | - | - | | `GET /webinars` | List upcoming events, ids, start times, time zones, and availability. | | `POST /webinars/{webinarId}/registrations` | Register an attendee for the selected event. | | `POST /webinar-registrations/{registrationId}/cancel` | Optionally cancel an existing registration. | These endpoints belong to your upstream API and are called through your pay URL. They are not built-in ZeroClick API operations. ### 2. Define the seller inputs This reference design uses the following inputs. Adapt their names and required status to your product: | Input | Required in this example | Purpose | | - | - | - | | `webinarId` | Yes, in path | The event selected from your listing. | | `attendeeName` | Yes | The person attending. | | `attendeeEmail` | Yes | The invitation address; it may differ from the verified owner. | | `company` | No | Context for the event organizer. | | `operationId` | Yes | A caller-generated identifier reused for retries. | For example, the request body could be: ```json theme={null} { "attendeeName": "Jordan Lee", "attendeeEmail": "jordan@example.com", "company": "Example Co", "operationId": "webinar-jordan-001" } ``` ### 3. Validate and fulfill the request Use the `verifyFreeActionRequest` helper from [shared setup](/docs/examples/free-actions#verify-the-request-and-identify-the-agent) with service slug `webinar-registration`. Return a guard denial immediately, then parse and validate your input. Return `400` for malformed or missing fields before creating any records or sending messages. After request verification, validate the attendee fields and check that registration is open. The **Require** policy establishes the agent owner's verified email; it does not verify `attendeeEmail` or ensure that the addresses match. Keep the verified owner and attendee address as separate values. This example permits registration for another person. If your event requires self-registration, define and enforce that rule explicitly, including how to handle an address mismatch. Deduplicate by the verified agent id and `operationId`, then create the registration in your event platform. Return confirmation only after the platform confirms it. If the event is full or closed, return a clear refusal, such as `409 registration_closed`. If you offer cancellation, enforce ownership of the registration and make repeated cancellations safe. Return `201 Created` with the registration reference and event time. Include a join URL only if your event platform permits sharing it this way. State whether joining instructions are already available or will arrive separately. ```json theme={null} { "registrationId": "reg_001", "status": "confirmed", "webinarId": "agent-commerce-intro", "startsAt": "2026-10-15T18:00:00.000Z", "timeZone": "America/New_York", "joiningInstructions": "The event platform will send joining instructions to the attendee email." } ``` Return the response without reporting billable usage. Your application supplies the fulfillment logic and error handling; the seller SDK supplies request verification. ### 4. Test through your pay URL Use a staging integration. Save the example body as `request.json`, replace its values and the placeholder pay URL below, and get an agent token through your storefront's `/auth.md` recipe. ```sh theme={null} curl --request POST "https://acme.pay.zeroclick.io/webinars/agent-commerce-intro/registrations" \ --header "Authorization: Bearer $AGENT_ACCESS_TOKEN" \ --header "Content-Type: application/json" \ --data-binary @request.json ``` Run the [shared integration checks](/docs/examples/free-actions#test-the-integration), then test the cases specific to this action: * Submit a valid attendee email through an unclaimed agent: ZeroClick still rejects the call under **Require**. * Use an agent claimed with a verified email but omit `attendeeEmail`: your API rejects the input. * Supply a different attendee address: this reference design allows it; test your own rule if you change that behavior. * Repeat the same `operationId`: one registration exists and the same reference is returned. * Try a full or closed event: no registration or invitation is created. ### 5. Describe the agent's workflow Find an event that fits the user's interests and schedule. Follow the storefront's `/auth.md` claim instructions when the ZeroClick policy requires verification. Separately collect the attendee details, confirm the user's intent, register, and report the confirmed time and joining instructions. Publish these instructions with your service and add [discovery signals](/docs/website/enable-agent-traffic) on the relevant website page. # What is ZeroClick? Source: https://zeroclickai.mintlify.dev/docs/index ZeroClick turns any API or offering into an agent-purchasable service, with x402 and MPP support, a machine-readable storefront, and agent transaction analytics. ![A dotted globe with agent activity lights converging on ZeroClick storefronts](https://mintcdn.com/zeroclickai/-ZjfEQ9Js9R6tXdO/images/hero.png?fit=max\&auto=format\&n=-ZjfEQ9Js9R6tXdO\&q=85\&s=c7d3cd2453ff38cd7cdc51e481e389bb) ZeroClick is the storefront and transaction layer for selling to AI agents. Connect an existing API or product, and agents can discover it, pay for it with [x402](https://www.x402.org) or [MPP](https://mpp.dev), and use it. You keep the API and the product experience; ZeroClick operates the agent-facing payment, identity, and proxy layer in front of it. Revenue settles to your connected Stripe account, in fiat or USDC. > [!TIP] > > On encrypted calls, ZeroClick processes payment and routing without body plaintext. The proxy holds no private key for the [request or response body](/docs/concepts/end-to-end-encryption). ## How it works Every seller gets a hosted pay URL, such as `https://acme.pay.zeroclick.io`. The pay URL is a machine-readable storefront: agents read it to find your services, plans, and prices, then transact with your API through it. **1. An agent calls your pay URL** A shopping assistant, coding agent, or procurement agent discovers your storefront, picks a plan, and calls your service through the pay URL with its agent credential, paying with x402 or MPP. **2. ZeroClick authenticates and charges** ZeroClick checks the agent's credential, handles the payment challenge, then signs the request and forwards it to your API. Every call needs a registered agent credential, sent as a bearer: registering is one free API call, with no human step. If an agent shows up without a wallet, ZeroClick creates one on the spot. **3. Your API serves the request** Your API verifies the request signature, checks the agent's allowance, and returns the result. **4. You get paid** Funds settle to your Stripe account. ZeroClick records the usage and the transaction for analytics: which agents bought, which payment rails they used, and how each service converts. Availability by country is listed under [supported countries](/docs/resources/supported-countries). The [how ZeroClick works](/docs/concepts/how-zeroclick-works) page walks the same lifecycle at the protocol level. ## What ZeroClick handles, and what you build ZeroClick operates the agent-facing side: the storefront, payment challenges, agent credentials and identity resolution, payment verification and settlement, request signing, usage recording, and transaction analytics. You add one thing to your API: a billing guard. On each forwarded request, your backend verifies ZeroClick's signature, checks the agent's allowance, does the work, and reports what was used. The [seller SDKs](/docs/sdks/overview) for TypeScript, Python, Go, and Ruby implement the guard; the [REST walkthrough](/docs/integrate/rest-walkthrough) covers doing it without an SDK. ## Core concepts | Concept | Meaning | | - | - | | Seller | Your storefront on ZeroClick. Each seller gets a pay URL that agents call and pay through. | | Service | One thing agents can buy: an API, a model, a workflow, or a feature. | | Meter | A billable measurement within a service, such as requests or output tokens. | | Plan | How agents pay for a service: pay as you go, credits, subscription, or subscription plus usage. | | Agent | The buyer. Every agent is identified and verified, and every call is logged. | | Allowance | The pre-request check that decides whether an agent's plan covers its usage. | ## Explore > [card] [Quickstart](/docs/quickstart) > > Serve your first paid agent request in about ten minutes. > [card] [Integrate your API](/docs/integrate/overview) > > The integration contract: verify, check allowance, serve, settle usage. > [card] [Enable agent traffic](/docs/website/enable-agent-traffic) > > The website changes that point agents at your storefront. > [card] [Buy with AI widget](/docs/website/buy-with-ai-widget) > > Give shoppers an on-page handoff to the AI agent they already use. > [card] [SDKs](/docs/sdks/overview) > > Seller SDKs for TypeScript, Python, Go, and Ruby. > [card] [API reference](/docs/api-reference/introduction) > > Manage sellers, services, meters, plans, usage, and analytics with the REST API. Questions? Email [help@zeroclick.ai](mailto:help@zeroclick.ai). # Charge up to a maximum Source: https://zeroclickai.mintlify.dev/docs/integrate/charge-up-to-a-maximum Bill work you can't size up front (output tokens, pages, seconds of processing) by declaring a ceiling and settling at the actual amount used. You can't price some work until it is done: tokens generated, pages extracted, seconds of processing. Charging a flat worst-case rate overcharges everyone else; metering after the fact leaves the buyer unauthorized. ZeroClick's answer is a ceiling: declare the most the request could use, let the buyer authorize that maximum, and settle at what the request actually used. ## Charging up to a maximum Declare the ceiling with `maxQuantity` instead of `quantity`: ```ts TypeScript theme={null} const decision = await zeroClick.guard(request, { serviceSlug: "product-watch", usage: [ { meterSlug: "requests", quantity: 1 }, { meterSlug: "output_tokens", maxQuantity: 100_000 }, ], }); ``` ```python Python theme={null} decision = await zeroclick.guard( zc_request, service_slug="product-watch", usage=[ UsageItem(meter_slug="requests", quantity=1), UsageItem(meter_slug="output_tokens", max_quantity=100_000), ], ) ``` ```go Go theme={null} result, err := seller.Guard(r.Context(), sellers.FromHTTP(r, body), "product-watch", []sellers.UsageItem{ sellers.PerRequest("requests", 1), sellers.UpTo("output_tokens", 100_000), }, "") ``` The buyer authorizes up to the ceiling, and the payment settles at the actual usage you report: a ceiling never overcharges. The SDK rejects a usage item that declares both `quantity` and `maxQuantity` before any network call. You can also declare **neither**: the item then defers to the meter's configured **Max usage per request** (`defaultMaxQuantity` on the plan's meter price). That keeps the ceiling in your catalog instead of your code. If the meter has no configured maximum, the allowance check denies with `meter_not_priced`. On the buyer's side, a ceiling is payable only on the reserve payment rails: the agent authorizes the maximum and pays the actual amount you settle. An exact `quantity` lets ZeroClick offer the immediate-settle scheme more clients can pay today, so when you know the size, prefer fixed charges. See [payment protocols](/docs/concepts/payment-protocols). ## Settle at the actual amount A ceiling has no settled quantity until you report one. Settle it like any other usage: on the response for amounts you know by the end of the handler, or [asynchronously](/docs/integrate/settle-usage#report-usage) for work that finishes later. ```ts TypeScript theme={null} // 4,200 tokens actually produced, against the 100,000 ceiling. return zeroClick.withUsage(response, [ { serviceSlug: "product-watch", meterSlug: "requests", quantity: 1 }, { serviceSlug: "product-watch", meterSlug: "output_tokens", quantity: 4200 }, ]); ``` ```python Python theme={null} return to_fastapi( zeroclick.with_usage( ZcResponse.json({"tokens": 4200}), [ SyncUsageItem(service_slug="product-watch", meter_slug="requests", quantity=1), SyncUsageItem(service_slug="product-watch", meter_slug="output_tokens", quantity=4200), ], ) ) ``` ```go Go theme={null} value, err := sellers.UsageHeader([]sellers.SyncUsageItem{ {ServiceSlug: "product-watch", MeterSlug: "requests", Quantity: 1}, {ServiceSlug: "product-watch", MeterSlug: "output_tokens", Quantity: 4200}, }) if err == nil { w.Header().Set("zc-usage", value) // before writing the body; 2xx only } ``` The settled quantity can be anywhere from zero up to the declared ceiling. An unreported ceiling on a paid, delivered response settles at zero (safe for the buyer, unbilled for you), so the report is what turns the work into revenue. See [settle usage](/docs/integrate/settle-usage) for the header rules (2xx only, stripped by ZeroClick). ## Go: Meter takes fixed quantities only Go's `Meter` middleware settles exactly what it declares, so it accepts fixed quantities only. Handed an `UpTo` item, it **panics at wire-up**: a ceiling has no settled quantity, and the middleware would otherwise bill zero, silently, on a delivered 200. You have two working shapes: call `Guard` yourself and settle explicitly, or keep `Meter` for a fixed per-request charge and report the variable part after responding. ```go theme={null} mux.Handle("/v1/product-watch", seller.Meter(sellers.PerRequest("requests", 1))( http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { zc, _ := sellers.FromContext(r.Context()) tokens := doTheWork() // discovered by doing the work w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{"tokens":%d}`, tokens) // Reported after the response, on BackgroundContext (r.Context() is // already cancelled) with a derived idempotency key. _, err := seller.ReportUsage(sellers.BackgroundContext(r), sellers.ReportUsageInput{ AgentID: zc.AgentID, ServiceSlug: "product-watch", MeterSlug: "output_tokens", Quantity: tokens, IdempotencyKey: zc.RequestID + "_output_tokens", }) if err != nil { log.Printf("output_tokens not reported: %v", err) } }))) ``` The fixed charge keeps the immediate-settle scheme available to buyers; the report settles the variable part. The same fixed-plus-reported split works in any language when you know the variable amount only after the response. See [settle usage](/docs/integrate/settle-usage#report-usage) for the reporting rules. # Check allowances Source: https://zeroclickai.mintlify.dev/docs/integrate/check-allowances Guard before work: declare what a request will use, let ZeroClick decide whether the buyer's plan covers it, and handle denials and allowance-API outages. After a signature verifies, and before your API does any work, ask ZeroClick whether the buyer's plan covers what this request will use. That is the allowance check: `POST /v1/usage/check` with the request's `zcRequestId` and the declared usage. Checking records nothing and burns no credit; it is a pre-gate, not a charge. For the model behind it, see [usage and allowances](/docs/concepts/usage-and-allowances). The SDK `guard` runs the check for you, immediately after verification: ```ts TypeScript theme={null} const decision = await zeroClick.guard(request, { serviceSlug: "product-watch", usage: [{ meterSlug: "requests", quantity: 1 }], }); if (decision.action === "deny") return decision.response; // decision.context.zcRequestId, decision.context.zcAgentId // decision.allowance.status === "allowed" | "unavailable" ``` ```python Python theme={null} decision = await zeroclick.guard( zc_request, service_slug="product-watch", usage=[UsageItem(meter_slug="requests", quantity=1)], ) if decision.action == "deny": return to_fastapi(decision.response) # decision.context.zc_request_id, decision.context.zc_agent_id # decision.allowance == "allowed" | "unavailable" ``` ```go Go theme={null} result, err := seller.Guard(r.Context(), sellers.FromHTTP(r, body), "product-watch", []sellers.UsageItem{{MeterSlug: "requests", Quantity: 1}}, "") if err != nil { // The usage list is malformed, or the outage policy is Throw. http.Error(w, `{"error":"internal_error"}`, http.StatusInternalServerError) return } if !result.OK { result.Response.WriteTo(w) return } // result.Context.RequestID, result.Context.AgentID // result.Outcome == sellers.OutcomeAllowed | sellers.OutcomeUnavailable ``` In Go, the [`Meter` middleware](/docs/sdks/go/middleware) wraps `Guard` and the usage settlement in one. When you need the decision in your own handler, call `Guard` directly. ## Declare what the request will use Each usage item names a meter and takes one of three forms: | Form | Meaning | | - | - | | `quantity` | An exact amount, known up front. | | `maxQuantity` | A ceiling for work you can't size yet; the payment settles at what you [report](/docs/integrate/settle-usage). See [charge up to a maximum](/docs/integrate/charge-up-to-a-maximum). | | Neither | Defer to the meter's configured **Max usage per request** (`defaultMaxQuantity`). If the meter has none, the check denies with `meter_not_priced`. | Before any network call, the SDK rejects an item that declares both `quantity` and `maxQuantity`. A check takes 1 to 20 items, one per meter. The SDK rejects duplicate meters too. ## Read the decision `guard` returns a decision, not an exception. A buyer who can't pay is an expected event: * **Deny** carries a ready-to-return response: the `401` for a failed signature, the exact `402 payment_required` body for a business denial, or the `503` under a fail-closed outage policy. Return it unchanged (`decision.response` in TypeScript, Python, and Ruby, `result.Response` in Go). Do no work. The `reason` field carries one of the seven denial reasons, listed at [errors](/docs/resources/errors). * **Allow** carries the verified context (`zcRequestId`, `zcAgentId`) and an allowance status: | Status | Meaning | | - | - | | `allowed` | The buyer's plan covers the declared usage. | | `unavailable` | The allowance API gave no answer and your policy chose to serve anyway: possibly unbilled work. | | `not_required` | Identity was proven and no allowance was needed. Only `guardIdentity` produces this. See [free and identity endpoints](/docs/integrate/free-and-identity-endpoints). | ## When the allowance API gives no answer The check sits in front of every billable request, so its timeout is short: 1.5 seconds by default (`checkTimeoutMs` / `check_timeout_seconds` / `CheckTimeout`). When it expires, or the API is unreachable or failing, your configured policy decides: | Policy | Behavior | | - | - | | `allow` (default) | Serve the request with allowance status `unavailable`. A ZeroClick outage should not take your API down with it. | | `deny` | Refuse with the `503`. When unbilled work costs more than a failed request, choose this policy. | | `throw` | Surface the typed error and decide in application code. | The policy applies only after a signature has verified: a fail-open allowance policy never becomes a fail-open signature policy. The Go SDK further restricts the policy to genuine no-answers: | Condition | Go SDK behavior | | - | - | | Timeout, DNS failure, connection refused, 5xx, 429, 408 | The policy applies. | | Any other 4xx (revoked or wrong API key, unknown service) | Always an error, never fail-open: it is permanent and would give your product away indefinitely. | | `allowed: false` with a reason the SDK does not recognize | Always a `402`. The SDK honors the denial and passes the unfamiliar reason through for you to log. | | The caller's context was cancelled | Not an outage. The check runs anyway on its own timeout, and its real answer stands. | > [!NOTE] > > The TypeScript and Python SDKs route every allowance API error through the policy, including 4xx responses and unrecognized denial reasons. Under the default `allow` policy, monitor `onAllowanceUnavailable` for repeated incidents: a persistent 4xx such as a revoked key means you are serving every request unbilled. Each SDK's errors page documents its exact classification. Set `onAllowanceUnavailable` (and, in Go, `Logger`) to record every incident the policy absorbs. A fail-open that is also silent is invisible unbilled traffic: ```ts TypeScript theme={null} const zeroClick = createSeller({ signingSecrets: { [kid]: secret }, apiKey: process.env.ZEROCLICK_API_KEY!, allowanceUnavailable: "allow", onAllowanceUnavailable: (error) => logger.warn("allowance outage", error.context), }); ``` ```python Python theme={null} zeroclick = create_async_seller( signing_secrets={kid: secret}, api_key=os.environ["ZEROCLICK_API_KEY"], allowance_unavailable_policy="allow", on_allowance_unavailable=lambda error: logger.warning("allowance outage: %s", error), ) ``` ```go Go theme={null} seller, err := sellers.New(sellers.Config{ APIKey: os.Getenv("ZEROCLICK_API_KEY"), ServiceSlug: "product-watch", SigningSecrets: secrets, Policy: sellers.PolicyAllow, Logger: log.Default(), OnAllowanceUnavailable: func(err error) { alert("allowance outage", err) }, }) ``` ## Call the allowance API directly For flows where verification and the check live in different layers, call the check yourself with a `zcRequestId` from an already-verified context. The response is `{ "allowed": boolean, "reason": }`. Building the `402` from a denial is then on you (`paymentRequired` / `payment_required` / `PaymentRequired` construct the exact body). ```ts TypeScript theme={null} const decision = await zeroClick.checkAllowance({ zcRequestId: context.zcRequestId, serviceSlug: "product-watch", usage: [{ meterSlug: "output_tokens", maxQuantity: 100_000 }], }); ``` ```python Python theme={null} decision = await zeroclick.check_allowance( zc_request_id=context.zc_request_id, service_slug="product-watch", usage=[UsageItem(meter_slug="output_tokens", max_quantity=100_000)], ) ``` ```go Go theme={null} decision, err := seller.CheckAllowance(r.Context(), zc.RequestID, "product-watch", []sellers.UsageItem{{MeterSlug: "output_tokens", MaxQuantity: 100_000}}) ``` Unlike `guard`, the direct check surfaces outages as errors instead of applying the policy. It runs under your own cancellation (an optional `{ signal }` in TypeScript, the caller's context in Go). Once a request is allowed, serve it. Then [settle the usage](/docs/integrate/settle-usage). # Firewalls and bot protection Source: https://zeroclickai.mintlify.dev/docs/integrate/firewalls-and-bot-protection Let ZeroClick's signed forwards through a WAF, CDN, or bot-protection layer in front of your API without weakening the guard. ZeroClick forwards every paid request, and every unpaid probe, from its own servers to your upstream base URL. A firewall, CDN, or bot-protection layer in front of that URL sees automated traffic from a cloud provider's address space with no browser behind it, which is what bot protection exists to challenge. This page covers what a challenge does to a purchase and how to exempt ZeroClick's forwards without opening those paths to anyone else. ## What a challenge does to a purchase Bot protection answers a request it distrusts with a challenge in place of your response: usually a `403` carrying an HTML page (Vercel's Security Checkpoint, Cloudflare's "Just a moment" interstitial) that a browser passes by running JavaScript. ZeroClick does not solve challenges. It returns your upstream's status and body to the buyer unchanged, so the agent receives an HTML checkpoint where it expected a `402` or your JSON, and reports the purchase as failed. Nothing on your side records an error, because the request never reached your handler. Signs that this is happening: * An agent reports a security checkpoint, a bot check, or a `403` from your pay URL on a route that answers JSON. * The failures are intermittent. One probe passes, the next is challenged. * Your own logs show no request for the failed call. Volume makes it more likely. ZeroClick forwards every unpaid pay-as-you-go call to be priced, then the paid retry, and it probes each endpoint when it builds your catalog. To a bot detector, a busy storefront looks like a scripted flood from one place. ## What to key the exemption on | Property of a forward | Usable | Why | | - | - | - | | `zc-signature` header | Yes | Present on every forward: unpaid calls, paid retries, catalog probes, and account endpoint calls. ZeroClick strips inbound `zc-*` headers, so only ZeroClick sets it on requests that arrive through the pay URL. | | Source IP | No | ZeroClick publishes no fixed egress range. Its addresses are shared cloud addresses that can change without notice. | | `User-Agent` | No | ZeroClick passes the buyer's own `User-Agent` through unchanged, so there is no ZeroClick user agent to allow. | Match on the presence of `zc-signature`, and scope the rule to the paths ZeroClick calls: the endpoint paths in your catalog, which are the paths agents request on your pay URL and which ZeroClick forwards to the origin of your upstream base URL, plus `/zeroclick/access` and everything under it if you [sell accounts and API keys](/docs/integrate/stateful-sellers). The rest of your site keeps its protection. One fetch carries no signature: the OpenAPI document ZeroClick downloads from your store's OpenAPI URL when it imports your catalog. If that document sits behind the same challenge, exempt its path on its own. It is public by design. ## Why the exemption is safe Anyone can put a `zc-signature` header on a request, so the rule lets unverified traffic past the bot check on the exempted paths. That traffic then meets your guard, which recomputes the HMAC with your signing secret and answers `401 {"error":"invalid_zeroclick_signature"}` before your handler runs. A forged header trades a challenge page for a 401 and nothing more. The guard was always the gate. The exemption stops a second gate from refusing the traffic the first one was built to check. See [verify requests](/docs/integrate/verify-requests). Rate limits are a different control. One sized for real buyer volume can stay in place. A challenge action cannot, because no forward can pass it. ## Platform recipes > [tab] Vercel > > Vercel's Bot Protection managed ruleset challenges non-browser traffic, and Vercel notes that direct API calls cannot pass the challenge. Its documented exemption for trusted automation is a WAF custom rule with the **Bypass** action. > > 1. In the project, open **Firewall**, then **Configure**, then **Add New** and **Rule**. > 2. Add the condition **Header** `zc-signature` **Exists**. Add a second condition with **AND**: **Request Path** **Starts with** the path ZeroClick calls, for example `/api/`. > 3. Set the action to **Bypass**, save the rule, and publish the change. If you have Challenge rules of your own, place this rule above them. Custom rules run in order, and the managed rulesets run after them. > > Bypass skips the remaining custom rules and the managed rulesets, including Bot Protection. It does not skip system-level DDoS mitigation. **Attack Mode** is separate: it challenges every request that is not a verified bot or a call from your own Vercel Functions and Cron Jobs, and Vercel does not list custom Bypass rules among its exemptions. Leave Attack Mode off while you sell through ZeroClick. > [tab] Cloudflare > > Create a WAF custom rule with the **Skip** action, placed above any rule that challenges: > > ```text Expression theme={null} > any(http.request.headers.names[*] == "zc-signature") and starts_with(http.request.uri.path, "/api/") > ``` > > Under **Then**, choose **Skip** and select **All Super Bot Fight Mode rules**. Select **Browser Integrity Check** as well if the zone has it enabled, and **All remaining custom rules** if you have challenge rules of your own below this one. > > A Skip rule cannot exempt traffic from Bot Fight Mode, the Free plan's version. If the zone runs Bot Fight Mode, turn it off under **Security**, then **Settings**, filtered to **Bot traffic**, or move to a plan with Super Bot Fight Mode so the Skip rule applies. Under Attack mode is separate too. It challenges every visitor, so scope it with a Configuration Rule that sets a lower Security Level on the paths ZeroClick calls. > [tab] Other layers > > Any WAF that can allow a request on a header condition works the same way: AWS WAF (an allow rule on the `zc-signature` header, ordered above Bot Control), Google Cloud Armor, Fastly, or a challenge module in nginx. Match on the header's presence, scope to the ZeroClick paths, and keep the guard as the gate. A layer that can only allow by IP address cannot exempt ZeroClick. Take the challenge off the API paths instead. ## Confirm the rule From outside your network, send a request with a made-up signature to a guarded route: ```sh theme={null} curl -i https://api.acme.com/v1/product-watch \ -H "zc-signature: t=0,kid=hsec_probe,v1=0" ``` The right answer is the guard's `401 {"error":"invalid_zeroclick_signature"}`: the request passed the firewall and verification refused it. A `403` or an HTML body means the challenge still applies. Then send an unpaid request to the same route on your pay URL. A `402` with a payment challenge confirms the probe reached your guard. # Free and identity endpoints Source: https://zeroclickai.mintlify.dev/docs/integrate/free-and-identity-endpoints Serve free endpoints that need an agent identity, and understand how included free units reach your API. Some endpoints cost nothing but still must know who is asking: polling a job the buyer created, reading account limits, any read or write served only to the buyer that owns the underlying records. Guarding them with `guard` would demand payment for free work; skipping the guard entirely would serve them to anyone. The identity guard is the middle path: it verifies the signature exactly like `guard`, requires a registered agent credential, and makes no allowance call. For shared setup and reference examples covering demo booking, lead capture, document delivery, and webinar registration, see [Free actions](/docs/examples/free-actions). ## Guard identity, not allowance ```ts TypeScript theme={null} export async function GET(request: Request) { const decision = await zeroClick.guardIdentity(request, { serviceSlug: "product-watch", }); if (decision.action === "deny") return decision.response; const jobId = new URL(request.url).pathname.split("/").pop(); const job = await findJob(jobId, { owner: decision.context.zcAgentId }); if (!job) return Response.json({ error: "not_found" }, { status: 404 }); return Response.json(job); } ``` ```python Python theme={null} @app.get("/v1/jobs/{job_id}") async def job_status(request: Request, job_id: str) -> Response: zc_request = zc_request_from_asgi_scope(request.scope, await request.body()) # Synchronous even on the async client: no network call, nothing to await. decision = zeroclick.guard_identity(zc_request, service_slug="product-watch") if decision.action == "deny": return to_fastapi(decision.response) return to_fastapi( ZcResponse.json({"jobId": job_id, "owner": decision.context.zc_agent_id}) ) ``` ```go Go theme={null} mux.Handle("/v1/limits", seller.Identify()(http.HandlerFunc(limits))) func limits(w http.ResponseWriter, r *http.Request) { zc, _ := sellers.FromContext(r.Context()) w.Header().Set("content-type", "application/json") json.NewEncoder(w).Encode(map[string]any{"zcAgentId": zc.AgentID}) } ``` The decision works like `guard`'s: * A failed signature is the usual `401` deny: unverified traffic never reaches free endpoints either. * A verified request **with** `zc-agent-id` allows, with allowance status `not_required` and the buyer in `context`. Scope your reads and writes to that id. * A verified request **without** a buyer, a [signed anonymous probe](/docs/integrate/verify-requests#signed-anonymous-probes-are-valid), denies with reason `identity_required` and this exact body: ```json theme={null} { "error": "payment_required", "serviceSlug": "product-watch", "usage": [] } ``` The empty usage list tells ZeroClick the call costs nothing and needs an agent credential. ZeroClick answers with `401 bearer_required` and a pointer to its registration recipe. The retry carries a pseudonymous `zc-agent-id`; the identity guard alone does not require a human claim or verified email. Configure the [verified email policy](/docs/examples/free-actions#choose-your-email-requirements) separately when your workflow needs it. No payment is involved. ## Identity and access are separate A buyer that has registered holds an identity; billing needs an access grant on top of it. A purchase creates access, and allowance checks and usage reports draw against it (see [agents and access](/docs/concepts/agents-and-access)). Reporting usage against an identity-only buyer fails with `access_not_found`. Keep the division clean: `guardIdentity` for free identity-scoped calls, `guard` for anything billable. The same division applies to settlement: no `zc-usage` belongs on a free response. There is nothing to settle. Free means free. ## Included free units There is a second kind of free: a plan's meter price can grant `includedUnits`, an allowance of free units configured in your catalog (see [plans and pricing](/docs/concepts/plans-and-pricing)). These are billable meters whose first units cost nothing, not identity-scoped endpoints, and they reach your API through the normal guard path: * **The buyer opts in per call** by sending `zc-mode: free` to the pay URL. ZeroClick operates paid-by-default: a missing or unrecognized mode means paid. The proxy consumes the header and never forwards it to you. * **The free allowance needs no funding, but it does need a claimed agent.** Free units are served only to an agent identity that a human has claimed with a verified email. An unclaimed agent, or one whose claim carries no verified email, gets no free units - its free-mode calls are refused like any unpaid call. A claim with a verified email, rather than a payment, is what stands between a new agent and its free units. * **Free calls require an identified caller.** Included-units coverage is per buyer - aggregated across every agent that human has claimed - so ZeroClick answers an unidentified free-mode call with `401 bearer_required` and its registration-and-claim recipe. The identified retry re-runs the real coverage check, including the claimed-and-verified requirement. * **Pay-as-you-go included units do not reset on a schedule.** Consumption is tracked across the buyer's agents for the service and meter, including deleted agents. Use your own counters for daily or monthly application quotas. * **Your integration does not change.** Guard the route and settle usage exactly as for paid traffic. For a covered free-mode call, the allowance check answers `allowed`, and the usage you settle draws down the buyer's included allowance instead of charging. For unmetered actions with application-enforced per-email limits, see [reduce abuse of free actions](/docs/examples/free-actions#reduce-abuse-of-free-actions). That symmetry is the point of the guard: paid, ceiling, included-free, and identity-only traffic all arrive as signed requests. The same four obligations (verify, check, serve, settle) handle every one. Back to the [integration overview](/docs/integrate/overview) for the full contract, or on to [settle usage](/docs/integrate/settle-usage) if you came here mid-integration. # Keys and secrets Source: https://zeroclickai.mintlify.dev/docs/integrate/keys-and-secrets The credentials a ZeroClick integration runs on: the signing secret and its kid, scoped usage keys, admin keys, rotation, and vault-backed resolution. Your integration runs on three runtime credentials, all minted in the [dashboard](https://dashboard.zeroclick.io) under your store's **Implementation** tab (or **Settings** for individual keys): | Credential | Format | Used for | | - | - | - | | Signing secret | Value `zcsec_` + 48 chars, key id (`kid`) `hsec_…` | Verifying the `zc-signature` on every forwarded request. | | Usage read key | `zc_` + 48 chars, scope `usage:read` | Allowance checks (`POST /v1/usage/check`). | | Usage write key | `zc_` + 48 chars, scope `usage:write` | Usage reports (`POST /v1/usage`). | A single API key carrying both usage scopes works in place of the two scoped keys. Every SDK accepts either form and falls back to the combined key when a scoped key is unset. > [!NOTE] > > [End-to-end body encryption](/docs/concepts/end-to-end-encryption) adds a seller-owned P-256 key pair. It is not a ZeroClick credential. ZeroClick receives only the public JWK. ZeroClick shows every secret once, at creation, and cannot show it again. The dashboard displays the first characters of each API key for recognition. Put them in your secret manager immediately: ```sh theme={null} ZEROCLICK_SIGNING_SECRET_KID=hsec_k5nq0v7m3d8p ZEROCLICK_SIGNING_SECRET=zcsec_… ZEROCLICK_API_KEY=zc_… ``` ## The kid must match exactly The dashboard shows the signing secret's key id, the `kid` (format `hsec_…`), next to the secret. The kid arrives in every `zc-signature` header (`t=…,kid=hsec_k5nq0v7m3d8p,v1=…`). The SDKs use the kid to select which secret verifies each request. The key in your secrets map must match the dashboard's key id character for character. A mismatched kid fails every request with `unknown_kid` and the `401` refusal. ## Scopes Send API keys as `Authorization: Bearer zc_…` to `https://api.zeroclick.io`. Each key carries one or more of five scopes: | Scope | Grants | | - | - | | `usage:read` | Allowance checks: `POST /v1/usage/check`. | | `usage:write` | Usage reports: `POST /v1/usage`. | | `admin:read` | Reading your catalog: sellers, services, meters, plans. | | `admin:write` | Managing the catalog over the [REST API](/docs/api-reference/introduction), including minting signing secrets. That is enough for an agent to automate seller setup end to end. | | `agentify:convert` | Converting marketing pages to agent markdown with [Agentify](/docs/agentify/overview): `GET /v1/agentify/markdown`. | Manage keys in the dashboard under **Settings → API keys**, in a signed-in session only: API keys cannot create or revoke API keys. Requests with a missing scope get `403 {"error":"insufficient_scope"}`. See [errors](/docs/resources/errors). ## Split read and write keys The process that guards requests only needs to read allowances; the process that reports usage only needs to write. Splitting the keys follows least privilege and matches a common deployment shape. The read key lives in the service that serves requests; the write key lives in the worker that reports usage asynchronously. ```ts TypeScript theme={null} const zeroClick = createSeller({ signingSecrets: { [process.env.ZEROCLICK_SIGNING_SECRET_KID!]: process.env.ZEROCLICK_SIGNING_SECRET!, }, usageReadKey: process.env.ZEROCLICK_USAGE_READ_KEY!, usageWriteKey: process.env.ZEROCLICK_USAGE_WRITE_KEY!, }); ``` ```python Python theme={null} zeroclick = create_async_seller( signing_secrets={ os.environ["ZEROCLICK_SIGNING_SECRET_KID"]: os.environ[ "ZEROCLICK_SIGNING_SECRET" ] }, usage_read_key=os.environ["ZEROCLICK_USAGE_READ_KEY"], usage_write_key=os.environ["ZEROCLICK_USAGE_WRITE_KEY"], ) ``` ```go Go theme={null} seller, err := sellers.New(sellers.Config{ UsageReadKey: os.Getenv("ZEROCLICK_USAGE_READ_KEY"), UsageWriteKey: os.Getenv("ZEROCLICK_USAGE_WRITE_KEY"), ServiceSlug: "product-watch", SigningSecrets: secrets, }) ``` The read key covers `guard` and the direct allowance check; the write key covers usage reporting. When you pass both scoped keys, omit the combined `apiKey`. ## Rotate a signing secret ZeroClick signs each forwarded request with your newest active secret and names it by kid, so rotation is a three-step overlap, not a cutover: **1. Create the new secret in the dashboard** ZeroClick starts signing new requests with it. The signature's `kid` changes to the new secret's id. **2. Hold both kids in your SDK configuration** Requests signed with either secret verify while both are configured: ```ts TypeScript theme={null} const zeroClick = createSeller({ signingSecrets: { hsec_k5nq0v7m3d8p: process.env.ZEROCLICK_SIGNING_SECRET_PREVIOUS!, hsec_2b9fj6wt5xr0: process.env.ZEROCLICK_SIGNING_SECRET_CURRENT!, }, apiKey: process.env.ZEROCLICK_API_KEY!, }); ``` ```python Python theme={null} zeroclick = create_async_seller( signing_secrets={ "hsec_k5nq0v7m3d8p": os.environ["ZEROCLICK_SIGNING_SECRET_PREVIOUS"], "hsec_2b9fj6wt5xr0": os.environ["ZEROCLICK_SIGNING_SECRET_CURRENT"], }, api_key=os.environ["ZEROCLICK_API_KEY"], ) ``` ```go Go theme={null} // ZEROCLICK_SIGNING_SECRETS="hsec_k5nq0v7m3d8p:,hsec_2b9fj6wt5xr0:" secrets, err := sellers.SecretsFromEnv() if err != nil { log.Fatal(err) } ``` **3. Revoke the old secret, then drop it** Once requests signed with the old secret can no longer be in flight, revoke it in the dashboard. Verification rejects signatures older than the 300-second tolerance anyway, so a few minutes of overlap is enough. Then remove the old kid from your configuration. Never log or return a signing secret, and never send it anywhere. It exists only to verify signatures inside your backend. ## Resolve secrets from a vault If your secrets live in a secret manager rather than the environment, resolve them by kid instead of passing a static map: ```ts TypeScript theme={null} const zeroClick = createSeller({ resolveSigningSecret: async ({ kid }) => secretStore.get(kid), apiKey: process.env.ZEROCLICK_API_KEY!, }); ``` ```python Python theme={null} zeroclick = create_async_seller( resolve_signing_secret=lambda kid: secret_store.get(kid), api_key=os.environ["ZEROCLICK_API_KEY"], ) ``` ```go Go theme={null} seller, err := sellers.New(sellers.Config{ APIKey: os.Getenv("ZEROCLICK_API_KEY"), ServiceSlug: "product-watch", Resolve: func(kid string) (string, bool, error) { return secretStore.Get(kid) }, }) ``` The SDK calls the resolver with each request's kid. Signal "unknown kid" by returning `null` (TypeScript), `None` (Python), `nil` (Ruby), or `ok=false` (Go). That request gets the `401` refusal. An unreachable vault is a different case: raise or return an error so it surfaces loudly instead of refusing valid traffic. Rotation works the same way as the static map: keep the vault serving both kids until the old one ages out. With keys in place, the first obligation is [verifying requests](/docs/integrate/verify-requests). # Integration overview Source: https://zeroclickai.mintlify.dev/docs/integrate/overview The contract between ZeroClick and your API: what arrives on every forwarded request, your backend's four obligations, and the three refusals it must produce. Agents buy and pay at your pay URL (`https://acme.pay.zeroclick.io`). ZeroClick verifies the payment, signs the request, and forwards it to your API at your configured upstream base URL. This page is the whole contract between ZeroClick and your backend. The [seller SDKs](/docs/sdks/overview) implement it; the [REST walkthrough](/docs/integrate/rest-walkthrough) shows how to implement it without one. If a purchase should leave something durable behind — an account, a subscription, an API key the buyer then uses with you directly — that is a separate, additive integration: [sell accounts and API keys](/docs/integrate/stateful-sellers). ## What arrives on every forwarded request ZeroClick sets three headers on each request it forwards: | Header | Value | Purpose | | - | - | - | | `zc-request-id` | `zcreq_8h2m4x0q9k1f` | Correlation id. The same id flows through the unpaid forward, the challenge, the paid retry, the allowance check, and the usage record. | | `zc-agent-id` | `agt_x7f2kq93bh0d` | The buyer. Every buyer call carries it, unpaid ones included. Absent or empty only on ZeroClick's signed anonymous probes, which are valid. See [verify requests](/docs/integrate/verify-requests). | | `zc-signature` | `t=,kid=hsec_…,v1=<64 hex>` | HMAC-SHA256 proof that the request came through ZeroClick unmodified. Sandbox traffic appends `,sb=1` and adds a `zc-sandbox: 1` header. | Before forwarding, ZeroClick strips all inbound `zc-*`, `x-payment`, and `payment*` headers and sets its own, so a caller can never inject them. Other request headers pass through untouched. Your API's own authentication remains whatever you configured between yourself and ZeroClick. One more header matters to the contract without ever reaching you: `zc-mode`. A buyer sends `zc-mode: free` to the pay URL to opt a call into included-units coverage. ZeroClick consumes it there, and a missing or unrecognized value means paid. See [free and identity endpoints](/docs/integrate/free-and-identity-endpoints). The full header reference is at [headers](/docs/resources/headers). ## Optional end-to-end body encryption An encrypted request arrives with `Content-Type: application/jose`. ZeroClick forwards the Compact JWE bytes but has no seller private key. Verify the signature and check the allowance against the encrypted request. After an allow decision, decrypt the body inside your infrastructure. Attach `zc-usage` to the application response before you encrypt its body for the buyer. The header remains visible for settlement. See [end-to-end body encryption](/docs/concepts/end-to-end-encryption) for the data path, key ownership, visible metadata, and fixed cipher suite. ## The four obligations On every forwarded request, your backend must: 1. **Verify** the `zc-signature` against your signing secret, before anything else. Only ZeroClick-signed traffic reaches your handlers. See [verify requests](/docs/integrate/verify-requests). 2. **Check the allowance** with `POST /v1/usage/check`: does the buyer's plan cover what this request will use? See [check allowances](/docs/integrate/check-allowances). 3. **Serve** the request as your API normally would. 4. **Settle** what the request used: a `zc-usage` header on the successful response, or an asynchronous usage report. See [settle usage](/docs/integrate/settle-usage). With an SDK, the first two obligations are one `guard` call and the fourth is one helper: ```ts TypeScript theme={null} const decision = await zeroClick.guard(request, { serviceSlug: "product-watch", usage: [{ meterSlug: "requests", quantity: 1 }], }); if (decision.action === "deny") return decision.response; const response = Response.json({ watching: true }); return zeroClick.withUsage(response, [ { serviceSlug: "product-watch", meterSlug: "requests", quantity: 1 }, ]); ``` ```python Python theme={null} zc_request = zc_request_from_asgi_scope(request.scope, await request.body()) decision = await zeroclick.guard( zc_request, service_slug="product-watch", usage=[UsageItem(meter_slug="requests", quantity=1)], ) if decision.action == "deny": return to_fastapi(decision.response) return to_fastapi( zeroclick.with_usage( ZcResponse.json({"watching": True}), [SyncUsageItem(service_slug="product-watch", meter_slug="requests", quantity=1)], ) ) ``` ```go Go theme={null} // Meter verifies the signature, checks the allowance, refuses before the // handler runs, and settles the zc-usage header on a delivered 2xx. mux.Handle("/v1/product-watch", seller.Meter(sellers.PerRequest("requests", 1))( http.HandlerFunc(productWatch))) ``` ## The three refusals When your API cannot serve, it must answer ZeroClick with one of exactly three responses. The SDKs build all of them. A deny decision carries the response ready to return. | Status | When | Exact body | | - | - | - | | `401` | The signature is missing, malformed, stale, or invalid. | `{"error":"invalid_zeroclick_signature"}` | | `402` | The allowance check denies, or an unpaid request needs payment. | `{"error":"payment_required","serviceSlug":"product-watch","usage":[{"meterSlug":"requests","quantity":1}]}` | | `503` | The allowance API is unreachable and your outage policy is fail-closed. | `{"error":"allowance_unavailable"}` | The `402` body is not an error page. It is data. ZeroClick reads the usage list, prices it from your catalog, and issues the buyer a signable payment challenge. The buyer never sees your body. A `402` with `usage: []` means "free, but identity-scoped", which ZeroClick answers with `401 bearer_required` and its registration recipe, never a charge. The [errors](/docs/resources/errors) page lists error codes across the platform. ## What never to do * **Never serve unverified traffic.** Your upstream URL is reachable; the signature is the gate. A request with no ZeroClick headers must get the `401`, not your handler. * **Never bill on a non-2xx.** `zc-usage` belongs on 2xx responses only: a 4xx is the buyer's bad input and a 5xx is your failure. Neither delivered anything worth charging for. * **Never price or cache challenges yourself.** Your `402` declares usage quantities, not prices. ZeroClick prices each refusal from your catalog per request and binds each challenge to that exact request. A cached price or replayed challenge cannot settle. ## Let the forwards reach your API ZeroClick forwards from its own servers, with no fixed IP range, and the `User-Agent` on a forward is the buyer's. A firewall or bot-protection layer in front of your upstream base URL (Vercel Firewall, Cloudflare, and similar) can answer a forward with an HTML challenge, which ZeroClick relays to the buyer as a failed purchase. Exempt requests that carry `zc-signature` on the paths ZeroClick calls. The guard still verifies every one of them. See [firewalls and bot protection](/docs/integrate/firewalls-and-bot-protection). ## SDK or REST If your backend is TypeScript, Python, Go, or Ruby, use the SDK. It implements the contract, including the denial bodies and the signature edge cases: * [TypeScript quickstart](/docs/sdks/typescript/quickstart): `@zeroclickai/sellers` on npm * [Python quickstart](/docs/sdks/python/quickstart): `zeroclick-sellers` on PyPI * [Go quickstart](/docs/sdks/go/quickstart): `cdn.zeroclick.io/sdks/sellers-go` Otherwise the contract is small enough to implement over REST: two API calls, one signature check, three fixed response bodies. Start at the [REST walkthrough](/docs/integrate/rest-walkthrough) and the byte-level [signature spec](/docs/integrate/signature-spec). ## Work through the contract > [card] [Keys and secrets](/docs/integrate/keys-and-secrets) > > The three runtime keys, scopes, split read/write keys, and rotation. > [card] [Verify requests](/docs/integrate/verify-requests) > > What verification proves, anonymous probes, and the raw-path rule. > [card] [Firewalls and bot protection](/docs/integrate/firewalls-and-bot-protection) > > Exempt signed forwards from bot challenges without weakening the guard. > [card] [Check allowances](/docs/integrate/check-allowances) > > Guard semantics, usage items, denials, and the outage policy. > [card] [Settle usage](/docs/integrate/settle-usage) > > The `zc-usage` header and asynchronous usage reports. > [card] [Charge up to a maximum](/docs/integrate/charge-up-to-a-maximum) > > Use ceilings to bill work you can't size up front. > [card] [Free and identity endpoints](/docs/integrate/free-and-identity-endpoints) > > Endpoints that cost nothing but must know the buyer. > [card] [Sell accounts and API keys](/docs/integrate/stateful-sellers) > > Turn a purchase into a durable account, credit balance, and API key. # REST walkthrough Source: https://zeroclickai.mintlify.dev/docs/integrate/rest-walkthrough Implement the ZeroClick seller contract with plain HTTP in any language: verify the signature, check the allowance, serve, and settle usage. The [seller SDKs](/docs/sdks/overview) implement the billing guard for TypeScript, Python, Go, and Ruby, and a [community SDK](/docs/sdks/overview#community-sdks) covers PHP. If your backend runs on anything else, or you want zero dependencies, the contract is small enough to implement directly: verify one request header, call one HTTPS endpoint before the work, and settle usage after it. This page walks the whole contract with your language's standard library and `curl`. > [!NOTE] > > You need your seller's signing secret (`zcsec_…`) with its key id (`hsec_…`), a usage read key (`zc_…`, scope `usage:read`), and a usage write key (`zc_…`, scope `usage:write`). One API key with both usage scopes also works. See [keys and secrets](/docs/integrate/keys-and-secrets). The examples use the seller Acme with service `product-watch` and meters `requests` and `output_tokens`. **1. Read the three request headers** Every request ZeroClick forwards to your API carries three headers: | Header | Example | Meaning | | - | - | - | | `zc-request-id` | `zcreq_8h2m4x0q9k1f` | Correlation id for this request. Echo it in the allowance check. | | `zc-agent-id` | `agt_x7f2kq93bh0d` | The buying agent. Absent on signed anonymous probes, which ZeroClick sends when it checks your endpoints. This state is expected and valid. | | `zc-signature` | `t=1785258000,kid=hsec_k5nq0v7m3d8p,v1=…` | Proves the request came from ZeroClick and was not altered. | ZeroClick strips any `zc-*` headers the agent sent before forwarding and sets its own. Once the signature verifies, these values are ZeroClick's. Capture the raw body bytes and the raw request target (path plus query, still percent-encoded) before your framework decodes them; both feed verification. The [headers reference](/docs/resources/headers) lists every header on the wire. **2. Verify the signature** `zc-signature` is an HMAC-SHA256 over six newline-joined fields, keyed by the signing secret whose id matches the header's `kid`. The fields are the timestamp, the uppercased method, the raw path and query, the SHA-256 of the body bytes, the request id, and the agent id (or empty string). Verify the timestamp is within 300 seconds of your clock. Compare the digest in constant time. The [zc-signature specification](/docs/integrate/signature-spec) defines every rule byte by byte, with test vectors. A compact verifier in standard-library Python: ```python theme={null} import hashlib, hmac, os, re, time SIGNING_SECRETS = {"hsec_k5nq0v7m3d8p": os.environ["ZEROCLICK_SIGNING_SECRET"]} TOLERANCE_SECONDS = 300 def verify(method, raw_path_and_query, raw_body, headers): """Returns the verified context, or None -> respond 401.""" header = headers.get("zc-signature") if header is None: return None members = {} for entry in header.split(","): key, sep, value = entry.partition("=") key = key.strip() if not sep or not key or key in members: # malformed or duplicate member return None members[key] = value.strip() # unknown members are ignored t, kid, v1 = members.get("t"), members.get("kid"), members.get("v1") if not (t and kid and v1): return None if not re.fullmatch(r"\d{1,20}", t) or not re.fullmatch(r"[0-9a-f]{64}", v1): return None if abs(int(time.time()) - int(t)) > TOLERANCE_SECONDS: return None request_id = headers.get("zc-request-id") if not request_id: return None agent_id = headers.get("zc-agent-id") or "" secret = SIGNING_SECRETS.get(kid) if secret is None: return None canonical = "\n".join([ t, method.upper(), raw_path_and_query, # as sent, never URL-decoded hashlib.sha256(raw_body).hexdigest(), request_id, agent_id, ]) expected = hmac.new(secret.encode(), canonical.encode(), hashlib.sha256).hexdigest() if not hmac.compare_digest(expected, v1): return None return {"zc_request_id": request_id, "zc_agent_id": agent_id or None} ``` > [!WARNING] > > Sign over the request target exactly as it arrived. Most frameworks hand you a decoded path (`%2F` becomes `/`), and the decoded form hashes to a different string. Read the raw request line. Hash the exact body bytes, not re-serialized JSON. **3. Check the allowance** Before you do the work, ask ZeroClick whether this agent's plan covers it. The check is bound to that request, so send the `zc-request-id` you received: ```sh theme={null} curl -sS https://api.zeroclick.io/v1/usage/check \ -H "Authorization: Bearer $ZEROCLICK_USAGE_READ_KEY" \ -H "Content-Type: application/json" \ -d '{ "zcRequestId": "zcreq_8h2m4x0q9k1f", "serviceSlug": "product-watch", "usage": [{ "meterSlug": "requests", "quantity": 1 }] }' ``` `usage` takes 1 to 20 items, one per meter, no duplicates. Each item declares `quantity` when the amount is known, or `maxQuantity` as a ceiling when it is not (see [charge up to a maximum](/docs/integrate/charge-up-to-a-maximum)). An item that declares neither gates against the meter's configured default ceiling. An item may not declare both. The response is one of two shapes: ```json theme={null} { "allowed": true, "reason": null } ``` ```json theme={null} { "allowed": false, "reason": "usage_exhausted" } ``` `reason` is one of `service_not_found`, `access_not_found`, `access_inactive`, `plan_expired`, `meter_not_found`, `meter_not_priced`, or `usage_exhausted`. See [check allowances](/docs/integrate/check-allowances). Checking records nothing and burns no credit, so repeating a check is harmless. Two failure modes need different handling. No answer at all (a timeout, a connection failure, a 5xx) means you choose a policy: fail open and serve, or fail closed with the `503` below. The SDKs default to fail open, with a 1.5 second timeout. A 4xx from the API (a revoked key, a key missing `usage:read`) is a configuration error on your side. Fix it. Never fail open on it. **4. Return the right refusal** Your API returns three refusals, each with an exact body ZeroClick recognizes. A missing, malformed, stale, or invalid signature gets a `401`. The body is the same for every signature failure. Keep the specific reason in your logs: ```json theme={null} { "error": "invalid_zeroclick_signature" } ``` `"allowed": false` gets a `402` naming what the request would cost. ZeroClick prices it and answers the agent with a payment challenge, so return the refusal before you do the work: ```json theme={null} { "error": "payment_required", "serviceSlug": "product-watch", "usage": [{ "meterSlug": "requests", "quantity": 1 }] } ``` An empty `"usage": []` marks a free, buyer-scoped endpoint that needs to know its caller. See [free and identity endpoints](/docs/integrate/free-and-identity-endpoints). An unreachable allowance API under a fail-closed policy gets a `503`: ```json theme={null} { "error": "allowance_unavailable" } ``` **5. Serve and settle** On success, do the work. Settle usage synchronously by setting the `zc-usage` response header: a JSON array of what the response actually consumed. ```text theme={null} zc-usage: [{"serviceSlug":"product-watch","meterSlug":"requests","quantity":1}] ``` Set it on 2xx responses only. A refusal must never carry usage. ZeroClick reads the header, records the usage, settles payment, and strips the header before the agent sees the response. This is the preferred settlement path; see [settle usage](/docs/integrate/settle-usage). **6. Report async usage** When you know the amount only after the response has gone out (a background job, a stream's final token count), report it to the usage API with the write key: ```sh theme={null} curl -sS https://api.zeroclick.io/v1/usage \ -H "Authorization: Bearer $ZEROCLICK_USAGE_WRITE_KEY" \ -H "Content-Type: application/json" \ -d '{ "zcAgentId": "agt_x7f2kq93bh0d", "idempotencyKey": "zcreq_8h2m4x0q9k1f_output_tokens", "serviceSlug": "product-watch", "meterSlug": "output_tokens", "quantity": 1834 }' ``` `quantity` is an integer from 1 to 2,147,483,647. `occurredAt` (ISO 8601) is optional; when omitted, the server sets it to now. ```json theme={null} { "recorded": true, "duplicate": false, "usageEvent": { "id": "use_2q9d5k7x0mfb", "zcAgentId": "agt_x7f2kq93bh0d", "zcRequestId": null, "idempotencyKey": "zcreq_8h2m4x0q9k1f_output_tokens", "meterSlug": "output_tokens", "quantity": 1834, "totalCostUsd": "0.001834", "source": "async", "occurredAt": "2026-07-28T17:03:41.512Z" } } ``` Reports are idempotent per service on `idempotencyKey`. Derive the key from what it bills (`_`, as above). Never generate it randomly: a random key turns a retried report into a second charge, while a derived key makes the retry a replay. A replay returns `"duplicate": true` with the stored event; that is a success, not an error. Denials use the [error envelope](/docs/resources/errors): `402` for `access_inactive`, `plan_expired`, and `usage_exhausted`; `409` for `meter_not_priced`; `404` for `service_not_found`, `access_not_found`, and `meter_not_found`. ## Ordering rules Three rules hold the contract together: 1. **Verify before everything.** Nothing runs on an unverified request: not the allowance check, not your handler. The signature is the only thing that makes `zc-request-id` and `zc-agent-id` trustworthy. 2. **Never bill a non-2xx.** `zc-usage` belongs on successful responses only. The `402` refusal comes before the work, not after it. 3. **Echo the received `zc-request-id` into the check.** The id ties the challenge, the payment, and the usage record to one request; an invented id fails the check. > [card] [zc-signature specification](/docs/integrate/signature-spec) > > The byte-level spec: grammar, canonical string, and test vectors. > [card] [Errors](/docs/resources/errors) > > Every error code the platform returns, with statuses. # Settle usage Source: https://zeroclickai.mintlify.dev/docs/integrate/settle-usage Tell ZeroClick what a served request actually used: the zc-usage header for synchronous settlement, and asynchronous reports for work that finishes later. An allowed request still has to settle: the payment finalizes against what the request actually used. Your revenue, credit burn, and analytics are computed from usage. The primary path is synchronous: stamp a `zc-usage` header on the successful response. ZeroClick records the usage as it returns the response to the agent. Reserve the [asynchronous report](#report-usage) for work that finishes after the response is gone. ## Settle on the response `zc-usage` is a response header carrying a JSON array of what the request used: ```json theme={null} [{ "serviceSlug": "product-watch", "meterSlug": "requests", "quantity": 1 }] ``` The SDK helpers build and validate it: ```ts TypeScript theme={null} const response = Response.json({ watching: true }); return zeroClick.withUsage(response, [ { serviceSlug: "product-watch", meterSlug: "requests", quantity: 1 }, ]); ``` ```python Python theme={null} return to_fastapi( zeroclick.with_usage( ZcResponse.json({"watching": True}), [SyncUsageItem(service_slug="product-watch", meter_slug="requests", quantity=1)], ) ) ``` ```go Go theme={null} // The Meter middleware attaches zc-usage for the quantities it declared, // and only on a 2xx; nothing to write in the handler. mux.Handle("/v1/product-watch", seller.Meter(sellers.PerRequest("requests", 1))( http.HandlerFunc(productWatch))) ``` Three rules govern the header: * **2xx only.** A 4xx is the buyer's bad input and a 5xx is your failure; neither delivered anything, so neither bills. The Go middleware enforces this. In TypeScript and Python, call `withUsage` only on the success path. * **ZeroClick strips it.** The agent never sees `zc-usage`: the proxy consumes it and removes it from the response. * **Settle the actual quantity.** For a fixed `quantity`, that is what you declared. For a `maxQuantity` ceiling, it is anywhere from zero up to the ceiling. See [charge up to a maximum](/docs/integrate/charge-up-to-a-maximum). The platform accepts `0` (a delivered response that produced nothing settles the ceiling at \$0). The TypeScript and Python helpers validate quantities as at least 1, so settle a zero-output ceiling by omitting that item. A paid, delivered response always settles, even if your header is missing or malformed: fixed items settle at the authorized quantity, ceilings settle at zero. That guarantee protects the buyer's payment from a garbage header. It does not excuse the report: an unreported ceiling settles as if nothing was produced. "Delivered" means a 2xx with a body, as the next section explains. ## Empty responses do not bill A 2xx that carries nothing counts as a failed delivery. ZeroClick settles it exactly like a 4xx or 5xx, even if you attached a `zc-usage` header, and passes your response through to the agent unchanged. A response is empty when its body is: * missing, or only whitespace * JSON that is exactly `null`, `{}`, `[]`, or `""` Everything else bills as usual, including: * any other JSON, even `{"results": []}` or an object whose fields are all `null` * plain text * `204 No Content`, which declares a successful action with nothing to return * a response to a `HEAD` request * a compressed body (any `content-encoding` other than `identity`), which ZeroClick does not decode to inspect What this means for your API: * **An action with nothing to return** (send a message, start a job): respond `204`, or describe what happened, such as `{"sent": true, "id": "msg_123"}`. A bare `200 {}` does not bill. * **A lookup that finds nothing**: a shaped answer like `{"results": []}` bills, because your API did the work. If the agent should not pay for a miss, return a 4xx such as `404` instead. * **An error**: return the error status, not a `200` with an error body. A `200` with an error message in it is not empty, so it bills. This applies to settlement on the response. An [asynchronous report](#report-usage) you send later bills as reported. What a failed delivery costs on each payment rail is covered in [payment protocols](/docs/concepts/payment-protocols). ## Report usage Some work outlives the response: a job that keeps extracting after you return `202`, tokens streamed over a connection that has already closed, a worker that settles from a queue. Report that usage asynchronously with `POST /v1/usage`, through `reportUsage`, `report_usage`, or `ReportUsage`, using the `usage:write` key ([split keys](/docs/integrate/keys-and-secrets#split-read-and-write-keys) put it in the worker): ```ts TypeScript theme={null} const result = await zeroClick.reportUsage({ zcAgentId: "agt_x7f2kq93bh0d", idempotencyKey: "zcreq_8h2m4x0q9k1f_output_tokens", // derived, never random serviceSlug: "product-watch", meterSlug: "output_tokens", quantity: 4200, }); console.log(result.recorded, result.duplicate); ``` ```python Python theme={null} result = await zeroclick.report_usage( zc_agent_id="agt_x7f2kq93bh0d", idempotency_key="zcreq_8h2m4x0q9k1f_output_tokens", # derived, never random service_slug="product-watch", meter_slug="output_tokens", quantity=4200, ) ``` ```go Go theme={null} _, err := seller.ReportUsage(sellers.BackgroundContext(r), sellers.ReportUsageInput{ AgentID: zc.AgentID, ServiceSlug: "product-watch", MeterSlug: "output_tokens", Quantity: 4200, IdempotencyKey: zc.RequestID + "_output_tokens", // derived, never random }) if err != nil { // Delivered but unbilled. Log it; do not fail a request the buyer already has. log.Printf("usage not reported: %v", err) } ``` > [!WARNING] > > In Go, report with `sellers.BackgroundContext(r)`, not `r.Context()`. Go cancels the request context the moment your handler returns, so a report on it is silently dropped. The work goes unbilled, with nothing in the logs. **Derive the idempotency key.** Reports are idempotent per service on `idempotencyKey`, and the key is yours to construct: the SDKs never generate one. Derive it from stable facts, such as the request id plus the meter (`zcreq_8h2m4x0q9k1f_output_tokens`). A random key turns every retry into a double bill. `duplicate: true` means the key already landed and the stored event was replayed: a success, not an error. There are no automatic retries. Retry yourself with the same key. On the wire, the call and its response: ```http Request theme={null} POST /v1/usage HTTP/1.1 Host: api.zeroclick.io Authorization: Bearer zc_… Content-Type: application/json { "zcAgentId": "agt_x7f2kq93bh0d", "idempotencyKey": "zcreq_8h2m4x0q9k1f_output_tokens", "serviceSlug": "product-watch", "meterSlug": "output_tokens", "quantity": 4200, "occurredAt": "2026-07-28T17:04:05.000Z" } ``` ```json Response theme={null} { "recorded": true, "duplicate": false, "usageEvent": { "id": "use_2j8fq0w7xk4m", "zcAgentId": "agt_x7f2kq93bh0d", "zcRequestId": null, "idempotencyKey": "zcreq_8h2m4x0q9k1f_output_tokens", "meterSlug": "output_tokens", "quantity": 4200, "totalCostUsd": "0.042000", "source": "async", "occurredAt": "2026-07-28T17:04:05.000Z" } } ``` `quantity` is an integer of at least 1 (maximum 2,147,483,647); `occurredAt` is an optional ISO timestamp for when the usage happened. A report can fail with `402` (`access_inactive`, `plan_expired`, `usage_exhausted`), `409` (`meter_not_priced`), or otherwise `404` for a missing resource. The SDKs surface these as typed errors carrying the status and reason. See [errors](/docs/resources/errors). A failed report after delivery means work went unbilled. Log it with the reason rather than failing a request the buyer already received. ## Choose a path * **Settle on the response** when you know the quantity before you respond: most requests, including ceilings whose actual you know by the end of the handler. * **Report asynchronously** when the work finishes after the response, when settlement happens in a separate worker, or when there is no HTTP response to stamp (a connection upgraded away from HTTP, a queue consumer). * **Combine them** for work you can't size up front: a fixed part settled on the response, the variable part reported when you know it. That is the pattern in [charge up to a maximum](/docs/integrate/charge-up-to-a-maximum). # zc-signature specification Source: https://zeroclickai.mintlify.dev/docs/integrate/signature-spec The byte-level specification of the zc-signature request header: grammar, canonical string, verification algorithm, failure taxonomy, and a worked test vector. Every request ZeroClick forwards to a seller's API carries a `zc-signature` header: an HMAC-SHA256 over the request, keyed by the seller's signing secret. This page is the normative specification for implementers writing their own verifier. If you use a [seller SDK](/docs/sdks/overview), it already implements every rule here. See [verify requests](/docs/integrate/verify-requests). For the surrounding flow, see the [REST walkthrough](/docs/integrate/rest-walkthrough). ## Header grammar The value is a comma-separated list of `key=value` members: ```text theme={null} zc-signature: t=,kid=,v1=<64 lowercase hex> ``` Sandbox traffic appends `sb=1`: ```text theme={null} zc-signature: t=1760000000,kid=hsec_k5nq0v7m3d8p,v1=25e2005f3229a60c8accc0d92576fc89f590533de7cd0ba880e820777ee6faa7,sb=1 ``` | Member | Value | Validation | | - | - | - | | `t` | Signing timestamp in unix seconds. | 1 to 20 ASCII digits. | | `kid` | Id of the signing secret that keyed the HMAC (`hsec_…`). Selects the right secret during [rotation](/docs/integrate/keys-and-secrets). | Non-empty, no surrounding whitespace. | | `v1` | The hex-encoded HMAC-SHA256 signature. | Exactly 64 lowercase hex characters. | | `sb` | `1` on sandbox traffic. | Informational; the canonical string is byte-identical either way. | Parsing rules: * Split the value on `,`. Each member is `key=value`. Trim whitespace around a key or value. * Reject a member with no `=` or an empty key as malformed. * **Reject duplicate member keys as malformed.** Do not skip this rule. * **Ignore unrecognized member keys.** ZeroClick extends this header additively (`sb=1` is one such member), so a parser that demands exactly three members fails all sandbox traffic. * After parsing, `t`, `kid`, and `v1` must all be present and pass their validations; anything else is malformed. ## Canonical string The signed bytes are six fields joined by `\n` (LF, `0x0A`), with no trailing newline: ```text theme={null} \n\n\n\n\n ``` 1. **Timestamp**: the header's `t` value byte-for-byte as received. Never re-parse and re-format it. 2. **Method**: the HTTP method, uppercased. 3. **Request target**: the raw percent-encoded path plus query exactly as sent, with no scheme or host. `/v1/items/a%2Fb%20c` stays `/v1/items/a%2Fb%20c`. Never the decoded path: frameworks commonly hand you one, and it hashes to a different string. Preserve query order and repeated keys verbatim. 4. **Body digest**: lowercase hex SHA-256 of the exact body bytes as received. An empty body hashes to `e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855`. Re-serialized JSON will not match: the digest covers bytes, not meaning. Hash an encrypted body as the ciphertext it arrived as. Verify before you decrypt. 5. **Request id**: the `zc-request-id` header value. 6. **Agent id**: the `zc-agent-id` header value, or the empty string when the header is absent. An absent header and a present-but-empty one sign identically; both mean a signed anonymous probe, which is valid. The signature is `HMAC-SHA256(secret, canonical string)`, lowercase hex, with the secret and canonical string both UTF-8 encoded. The secret is the one whose id equals `kid`. ## Verification algorithm 1. Read `zc-signature`. Absent → `missing_signature`. 2. Parse it per the grammar above. Any violation → `malformed_signature`. 3. Parse `t` as an integer. If `|now − t|` exceeds the tolerance (300 seconds by default, applied in both directions) → `stale_timestamp`. 4. Read `zc-request-id`. Absent or empty → `missing_request_id`. 5. Read `zc-agent-id`; treat absent as the empty string. 6. Resolve the secret for `kid`. No secret with that id → `unknown_kid`. Run steps 1 to 5 first so an unauthenticated request never reaches your key store. A lookup that *fails* (a vault being unreachable) is an operational error, not a refusal. 7. Compute the expected HMAC over the canonical string. Compare it to `v1` **in constant time** (`hmac.compare_digest`, `crypto.timingSafeEqual`, `hmac.Equal`). Mismatch → `invalid_signature`. 8. Otherwise the request is verified: trust `zc-request-id` and `zc-agent-id`. ## Failure taxonomy | Reason | Trigger | | - | - | | `missing_signature` | No `zc-signature` header. | | `malformed_signature` | Grammar violation: missing or duplicate member, non-numeric or over-long timestamp, `v1` not 64 lowercase hex. | | `stale_timestamp` | `t` outside the clock tolerance, past or future. | | `missing_request_id` | No `zc-request-id` header. | | `unknown_kid` | No configured signing secret with the header's `kid`. | | `invalid_signature` | The HMAC comparison failed: wrong secret, tampered body, altered target or headers. | Every reason maps to the same seller response, one `401`: ```json theme={null} { "error": "invalid_zeroclick_signature" } ``` The body never says which check failed. Keep the reason in your own logs. ## Worked test vector This vector comes from the cross-SDK vector suite (the `identified_buyer` case), which every seller SDK executes. The full suite ships with the SDKs as `signing-vectors.json`. The ids and secret below are test fixtures. Production values look like `hsec_…`, `zcreq_…`, and `agt_…`. Signing secret: ```text theme={null} kid: zcsec_vector_1 secret: zcsec_vector_secret_do_not_use_in_production ``` Request: ```text theme={null} POST /v1/product-watch zc-request-id: zcreq_vector zc-agent-id: zcagent_vector zc-signature: t=1760000000,kid=zcsec_vector_1,v1=25e2005f3229a60c8accc0d92576fc89f590533de7cd0ba880e820777ee6faa7 ``` Body (exactly these 36 bytes, no trailing newline): ```json theme={null} {"productId":"sku_42","window":"7d"} ``` Its SHA-256 is `b07172b06310bf8dc76e9427aa33af6c61894b2a2abc1524a980c2b6bb7bd35e`, giving the canonical string: ```text theme={null} 1760000000 POST /v1/product-watch b07172b06310bf8dc76e9427aa33af6c61894b2a2abc1524a980c2b6bb7bd35e zcreq_vector zcagent_vector ``` Expected result: with the verifier's clock pinned to `1760000000` and tolerance `300`, the HMAC-SHA256 of the canonical string with the secret equals the header's `v1`. Verification succeeds with request id `zcreq_vector` and agent id `zcagent_vector`. Your implementation must also pass two checks. With `zc-agent-id` absent, the same request verifies only against `v1=326b303be6b1ca89598b3b572961bce3b999c00cbf8333a71cc1c7f9f3d6566c` (the empty-string sixth field). Your verifier must reject a header that carries `v1` twice as malformed, even when both copies are correct. # Sell accounts and API keys Source: https://zeroclickai.mintlify.dev/docs/integrate/stateful-sellers Turn a ZeroClick purchase into a real account on your side, with a subscription, a credit balance, and an API key the buyer then uses with you directly. Most ZeroClick integrations are stateless: a request arrives, you serve it, you report usage, and nothing is left behind. This page is for the other kind, where a purchase creates something that lasts — an account, a subscription, a credit balance, an API key. Say you sell a \$20/month research API. A buyer purchases your plan through ZeroClick, and you want them to end up with an account in your database, a current billing period, and an API key they can put in their own code. That is what this integration does. ZeroClick handles buyer identity, payment, refunds, and letting a buyer recover their purchase later; your service stays the source of truth for the account. ## How it works You build **one HTTPS endpoint**. ZeroClick makes two kinds of call to it. **1. ZeroClick tells you what the account should look like** After a purchase or a top-up, `POST /zeroclick/access` arrives with a complete picture of the account: which customer, which plan, what period it runs for, how much credit has been granted in total. You create or update the account and answer `200`. **2. ZeroClick asks you for an API key** When the buyer requests a key after the account is ready and the payment has gone through, `POST /zeroclick/access/{accessId}/keys` arrives. You generate a key, store its hash, and return the key once in plaintext. **3. The buyer calls you directly** ZeroClick hands the key to the buyer. From then on they talk to your API with your key, on your terms. ZeroClick does not sit in the middle of those calls and never stores the key. Two calls in, one key out. ## Before you start > [!NOTE] > > Selling accounts is a storefront-level designation made when the storefront is created — today we set that up with you, so email [help@zeroclick.ai](mailto:help@zeroclick.ai). You can build and test the endpoint before that. * **A plan that is not pay-as-you-go** — a `subscription`, `subscription_usage`, `credit`, or `free_trial` plan ([plans and pricing](/docs/concepts/plans-and-pricing#the-five-billing-modes)). Pay-as-you-go buyers pay per call and leave nothing behind, so there is no account to create. * **A signing secret.** ZeroClick signs every call with it and you verify that signature. Create one in the dashboard and keep its id (the `kid`) and value in your secret manager ([keys and secrets](/docs/integrate/keys-and-secrets)). * **An HTTPS endpoint.** By default it is `/zeroclick/access` on the origin of your upstream base URL; you can [point it somewhere else](/docs/resources/stateful-access-reference#configuring-the-endpoint). * **Durable storage** for accounts, the last version you applied, the credit you have granted in total, and your API key hashes. ```sh TypeScript theme={null} pnpm add @zeroclickai/sellers ``` ```sh Python theme={null} pip install zeroclick-sellers ``` ```sh Go theme={null} go get cdn.zeroclick.io/sdks/sellers-go ``` ```sh Ruby theme={null} bundle add zeroclick-sellers ``` > [!NOTE] > > The stateful helpers ship in all four SDKs: `@zeroclickai/sellers/stateful`, `zeroclick_sellers.stateful`, the Go module's `stateful` sub-package, and Ruby's `zeroclick/sellers/stateful`. This guide's examples are TypeScript; the other three mirror them name for name. On any other stack, implement the same two routes by hand — the [reference](/docs/resources/stateful-access-reference) has the full wire contract, the signature with worked verifiers, and a test vector to check yours against. ## The three ids, and which one to key on **Key your accounts on `accessId`** (`zacc_…`). It is the durable account handle ZeroClick mints for the customer at this seller: stable across renewals, top-ups, plan switches, and payment methods, present on every call, and never reused. One customer normally holds one per seller — a repeat purchase or plan switch updates the same account rather than opening a second one. The other two ids describe **who is calling**, not the account: * `agentId` (`agt_…`) is the per-call caller identity — the same id your stateless endpoints see as `zc-agent-id`. A customer's human can hold several agents, and any of them may act on the account, so **different calls to one account may carry different agent ids**. Verify it, log it, but never key on it. * `buyerId` (`byr_…`) appears once the caller's credential has been claimed by its human — the same value proxied traffic carries as `zc-buyer-id`. Not a key either, but worth an ordinary column if you also keep [buyer-keyed customer records](/docs/resources/headers#zc-agent-id-and-zc-buyer-id): it is what joins this account to them. The remaining choice is your remint policy. `"rotating"` replaces the previous key on every mint — the one-live-key shape most APIs want; `"additive"` mints another: ```ts theme={null} { remintPolicy: "rotating" } ``` Whether the customer paid by card or from a crypto wallet is invisible to you, and so is anything else about how they paid. Key everything on `accessId`; never try to infer a customer from a payment. ## Tying the account to a user account The ids above identify agents and buyers inside ZeroClick — none of them tells you which account on **your** side the customer is. **We strongly recommend making that link**: run your plans with the `requested` verified-email policy (or `required`, when your product cannot work without an email) and link on `buyerEmail`. It costs the buyer nothing under `requested`, and it means a human who later registers or signs in with the same email finds the entitlements their agents bought — able to see them, manage settings, and treat the purchase like any they made by hand. Without it, the resource stays reachable only through the agent that bought it. Set the policy per plan ([plans and pricing](/docs/concepts/plans-and-pricing#the-verified-email-policy)): * **`requested`** — the recommended default when you want the email. Purchases are never blocked. When the buying agent is already claimed by a human with a verified email, the account write carries it immediately; when the agent is still anonymous, the purchase goes through without it, and **ZeroClick calls your endpoint again the moment the human claims** — a fresh account write, one `stateVersion` higher, identical except that `buyerEmail` is now set. Your existing write handler needs nothing new: apply the newest picture as always, and treat a `buyerEmail` appearing partway through an account's life as your cue to link. * **`required`** — ZeroClick refuses the purchase (`403 verified_email_required`) until the claim exists, so every write for the account carries the email from the first version. Use it only when you cannot deliver anything without an email; it costs you the fully autonomous purchase. Either way the email arrives as `buyerEmail` in the signed body, mirrored as the `zc-buyer-email` header (the SDKs hand it to your write handler as `buyerEmail` and reject a header/body disagreement for you). It is verified before it ever reaches you, so it is safe to key on. In your write handler: * **The email matches an existing user** — attach the ZeroClick account (and the key you later mint) to that user, so the purchase shows up in the account they already have with you. * **The email is new** — create a fresh user account for it, exactly as if they had signed up on your site, and provision the ZeroClick purchase into it. * **You would rather wait** — store the email against the `accessId` and link the resource when the human registers or signs in with that address later; until then the agent still uses the minted key normally. Any of the three keeps one truth: the human who verified that email owns the resource, whichever of their agents bought it. Plans with the policy `off` never carry `buyerEmail`, so those purchases stay anonymous, agent-held resources keyed only on `accessId`. ## Build the endpoint `handleAccessRequest` routes, verifies, and validates both calls, then hands off to your two functions. It returns `null` for anything that is not one of its routes, so you can mount it inside an existing handler. > [!WARNING] > > Give the SDK the **raw request bytes** and the **original path and query**, before any framework parses or rewrites them. The signature covers those exact bytes, so a body parsed to JSON and re-serialized will not verify — the same rule as [verifying ordinary requests](/docs/integrate/verify-requests#verify-the-raw-body-bytes). ```ts theme={null} import { type AccessOperation, handleAccessRequest, } from "@zeroclickai/sellers/stateful"; const options = { basePath: "/zeroclick/access", remintPolicy: "rotating" as const, secrets: { [process.env.ZEROCLICK_SIGNING_SECRET_KID!]: process.env.ZEROCLICK_SIGNING_SECRET!, }, // `AccessOperation` ("write" | "mint" | "read") is exported by the SDK; typing // the union by hand breaks when a route is added. onHandlerError: (error: unknown, operation: AccessOperation) => { logger.error({ error, operation }, "ZeroClick access handler failed"); }, }; export async function handle(request: Request): Promise { const rawBody = new Uint8Array(await request.clone().arrayBuffer()); const url = new URL(request.url); const result = await handleAccessRequest( { method: request.method, pathAndQuery: `${url.pathname}${url.search}`, rawBody, headers: Object.fromEntries(request.headers), }, { onWrite, onMint }, options, ); // Not one of ZeroClick's two routes: let your own router handle it. if (result === null) return new Response("Not found", { status: 404 }); return new Response( result.body === undefined ? null : JSON.stringify(result.body), { status: result.status, headers: { ...(result.body === undefined ? {} : { "content-type": "application/json" }), ...result.headers, }, }, ); } ``` > [!WARNING] > > Do not guard this endpoint with `guard`, `guardIdentity`, or `verifyRequest`. Those verify the signature on ordinary paid traffic, which is a *different* signature. Account calls carry an extra purpose, so a signature captured from normal proxied traffic can never be replayed against your account routes — but only if you keep the two verifiers apart. ## Create the account The write is a complete description of how the account should look, not a list of changes — which makes duplicates and late arrivals harmless, as long as you follow two rules inside **one database transaction**: 1. **Ignore anything you have already applied.** `shouldApply` compares the incoming `stateVersion` against the one you stored. 2. **Never grant the same credit twice.** `lifetimeCreditGrantedUsd` is a running total, not the size of this top-up, so you add the *difference*. `deriveCreditDelta` computes it and tells you which of [three cases](/docs/resources/stateful-access-reference#why-the-write-is-a-complete-picture) you are in. ```ts theme={null} import { deriveCreditDelta, shouldApply } from "@zeroclickai/sellers/stateful"; import type { WriteInput } from "@zeroclickai/sellers/stateful"; async function onWrite({ accessId, entitlement }: WriteInput) { await database.transaction(async (tx) => { const account = await tx.lockAccount(accessId); if (!shouldApply(account?.stateVersion, entitlement.stateVersion)) return; const delta = deriveCreditDelta( account ? { stateVersion: account.stateVersion, lifetimeCreditGrantedUsdMicros: account.lifetimeCreditGrantedUsdMicros, lifetimeCreditReversedUsdMicros: account.lifetimeCreditReversedUsdMicros, } : null, entitlement, ); if (delta.outcome === "credit") { await tx.addCredit(accessId, delta.deltaUsdMicros); await tx.storeGrant(accessId, delta.next); } else if (delta.outcome === "debit") { // A refund or dispute clawed money back; clamp the balance at zero. await tx.subtractCredit(accessId, delta.deltaUsdMicros); await tx.storeGrant(accessId, delta.next); } else if (delta.outcome === "no_credit_dimension") { await tx.storeGrant(accessId, delta.next); } await tx.applyPlanAndPeriod(accessId, entitlement); // Recommended: link the account to your own user account whenever the // verified email is present — it can arrive on a later write than the // first (see "Tying the account to a user account" above). if (entitlement.buyerEmail) { await tx.linkAccountToUser(accessId, entitlement.buyerEmail); } }); return { lifecycle: "active" as const }; } ``` The row lock, the balance change, and the stored version must commit together — if they can commit separately, a retry landing between them grants credit twice. Never lower a total you have already recorded. **Answer `active` only when the account really works.** If setup is slow — provisioning a tenant, warming an index — answer `{ lifecycle: "provisioning", retryAfterSeconds: 5 }` and ZeroClick sends the same write again until you say `active`. Hint the time you actually need: the hint only ever pushes the next attempt later, and the buyer waits out whatever you name. Every field in the request body is documented in the [reference](/docs/resources/stateful-access-reference#the-account-write). ## Mint the key ```ts theme={null} import type { MintInput } from "@zeroclickai/sellers/stateful"; async function onMint({ accessId }: MintInput) { const plaintext = generateApiKey(); const digest = hashApiKey(plaintext); const created = await database.transaction(async (tx) => { const account = await tx.lockActiveAccount(accessId); if (!account) return false; // Required when remintPolicy is "rotating"; skip it for additive keys. await tx.revokeLiveKeys(account.id); await tx.insertKeyHash(account.id, digest); return true; }); return created ? { apiKey: plaintext } : { unknown: true as const }; } ``` * **Return the plaintext exactly once** and store only a hash. ZeroClick passes the key to the buyer and keeps no copy, so nobody can look it up again. * **Hash it appropriately.** For a random key with real entropy — 32 bytes from a CSPRNG or better — a plain SHA-256 is right: fast enough to check on every request, with nothing to brute-force. Reach for a slow KDF like Argon2 only if your keys are short or human-chosen. * **Never log it**, and keep it out of error messages. The SDK already sets `cache-control: no-store`. * **Revoke and insert in one transaction** when rotating, or a retry can leave the customer with two live keys or none. If the account is not ready yet, return `{ notProvisioned: true, retryAfterSeconds: 5 }` rather than an error. `{ unknown: true }` is only for an account that genuinely does not exist, and `{ conflict: { code } }` is for refusing with a reason of your own — a key cap reached, say. Every return value, and the status each becomes, is in the [reference](/docs/resources/stateful-access-reference#what-your-handlers-can-return); the [inputs your handlers receive](/docs/resources/stateful-access-reference#what-your-handlers-receive) are there too. ## Decide whether to serve Once the key is out, every authenticated request to your API carries a serving decision, and it should be **one derived check** against the state you stored: ```ts theme={null} import { isServiceable } from "@zeroclickai/sellers/stateful"; if (!isServiceable(account.state)) { return refuseInYourOwnErrorShape(account); } ``` `isServiceable` answers `true` only while `status` is `active` **and** the period, when its `end` is non-`null`, has not lapsed. Do not hand-combine the two conditions: checking `status` alone misses period-based revocation on interval plans, and checking the period alone misses suspension and closure. Period expiry has no push — nothing arrives at period end — so the check must be local and time-based, on every request. The two statuses that turn the gate off ask for different follow-through: * **`suspended` is recoverable.** Suspend service and delete nothing; a later write may return the account to `active`. * **`closed` is terminal.** ZeroClick sends it when the account is torn down on the ZeroClick side: revoke live API keys, stop serving, and keep your own records. No higher `stateVersion` will ever follow. ## When a customer runs out of credit Once you have minted a key, the customer calls your API directly. ZeroClick is not in that path, so it never sees the moment a subscription lapses or a credit balance hits zero — **the refusal is yours, in your own error shape.** ZeroClick does not define an envelope for it, and you should not invent one that changes what your directly-signed-up customers already see. Same status, same body, same as ever. What you can usefully add, *only* on the branch where you already know this account came from ZeroClick, is where to go to fix it. Every purchase has a top-up URL on your pay URL: ``` https://acme.pay.zeroclick.io/extend?accessId=zacc_8h2m4x0q9k1f ``` Putting that in your refusal is the difference between an agent retrying blindly and an agent topping up and carrying on. The URL works as handed out — an agent can `POST` to it verbatim, and the query string names the account — and your account key is exactly the id it needs. If you would rather add nothing, an agent can still find its own way: `GET /purchases/receipt` on your pay URL, with the agent's own bearer token, lists every purchase it holds with you and includes both a `topUpUrl` and a `redeemUrl` for each. See [buyer-facing routes](/docs/resources/stateful-access-reference#buyer-facing-routes-on-your-pay-url). Note that a top-up does not go through your error path at all. It arrives as another account write, with a higher `stateVersion` and a larger `lifetimeCreditGrantedUsd` — which your existing `onWrite` already handles. Card refunds and chargebacks arrive the same way: an account write with a larger `lifetimeCreditReversedUsd` (and, for a fully reversed purchase, an ended period or `status: "suspended"`). `deriveCreditDelta` answers `debit` for the difference; subtract it and clamp the balance at zero. Both revocation signals fall inside [`isServiceable`](#decide-whether-to-serve), so if you gate requests on it, applying the debit is the only reversal handling you need. ## Automatic top-ups: reporting the balance Automatic top-ups require a signed usage endpoint that returns the remaining credit. Renewal-only subscriptions do not need it. If your plan offers Tempo automatic payments, buyers approve the recurring plan charge and, optionally, automatic credit top-ups in one signup. Native Tempo subscriptions charge on fixed 1-, 30-, or 365-day windows, even when your plan is named daily, monthly, or yearly. Use the period dates in each signed account write; do not assume a calendar-month boundary. The first plan charge funds the first period when the buyer approves it. Top-ups approved at signup never charge then: they start after that first charge, without another buyer signature, only when ZeroClick reads a fresh low balance and the buyer's limits and cooldown permit another charge. You receive ordinary account writes for both kinds of payment, so the same `onWrite` logic handles them. Add an `onRead` handler with the TypeScript SDK 0.10+, or implement the [usage-read contract](/docs/resources/stateful-access-reference#the-usage-read-required-for-automatic-top-ups) directly. ZeroClick sends `GET /:accessId/usage` with signature purpose `access.read` when a buyer enrolls and roughly every two minutes while top-ups are active. Read from your existing balance store; do not mint keys or change state. You can also push updates to `POST /v1/stateful/accounts/:accessId/balance` with an organization API key carrying `stateful:write`. Pushes supplement polling; they do not replace the usage endpoint. ```ts theme={null} onRead: async ({ accessId }) => { const account = await accounts.read(accessId); // balance and version from one row if (!account) return { unknown: true }; return { accessId, stateVersion: account.stateVersion, // the last write you applied remainingCreditUsd: account.remainingUsd.toFixed(6), observedAt: new Date().toISOString(), // when you read it: now }; }, ``` `observedAt` is the time you read the balance, not when it last changed. ZeroClick discards a reading that is more than five minutes old or more than thirty seconds ahead of its clock, and a reading whose `stateVersion` is not the account's latest acknowledged version, so an idle account must still answer with the current time. ## Retries and failures Account writes are **at-least-once**, so expect duplicates and expect a retry after a network timeout that happened *after* you committed. Three things to design around: * **You have 7 seconds to respond.** Commit, then answer. Anything slower belongs behind `lifecycle: "provisioning"`. * **Return `503` — or just throw — for anything temporary.** ZeroClick retries network errors, `429`, and any `5xx`, backing off for up to 24 hours. It does **not** retry other 4xx responses, so a bug that returns `400` permanently fails the delivery. * **A permanent failure refunds the buyer automatically.** A reserved payment is released, a captured one refunded. You never owe a refund for an account you did not create. Exact backoff, attempt limits, and retry-hint handling are in the [reference](/docs/resources/stateful-access-reference#retries-timeouts-and-failures). ## Customers with more than one agent **The short version: you do nothing, and your account key never changes.** A ZeroClick buyer can hold several agent identities — a replacement for a rotated credential, a second agent for another workload ([agents belong to buyers](/docs/concepts/agents-and-access#agents-belong-to-buyers-zcbuyerid)). Any of them can come back later and ask for a key to a purchase the buyer already owns, or top the account up. When that happens, the call carries the same `accessId` — ZeroClick resolves which account the caller may act on before anything is signed toward you — with the acting agent's own id in `agentId` and, once claimed, the shared `buyerId`. So a second agent minting a key looks like a new `agentId` value against a familiar `accessId`: expected, not suspicious. You never enumerate the buyer's identities and do not need to model them. ## Before you go live * Serve the endpoint over HTTPS, with no redirects. * Verify signatures against the raw body bytes and the original path and query. * Look up secrets by `kid` and keep the previous one through a rotation. * Never route these requests through `guard`, `guardIdentity`, or `verifyRequest`. * Apply `stateVersion` and credit in one locked transaction, and never lower a recorded total. * Store key hashes only, return plaintext once, keep keys out of logs. * Make rotation revoke-and-insert atomic. * Gate every authenticated request on `isServiceable` — period expiry has no push. * Return `503` for anything temporary; remember other 4xx responses are permanent. * Alert on handler errors and on repeated retries for the same account. * Test a duplicate write, an out-of-order write, a handler timeout, a repeated key request, and a signing-secret rotation. * Accept the verification's test account: the check run from the dashboard writes an account whose id starts with `zacc_verify_` and whose plan slug is `zeroclick-verification` (a \$0 subscription for 24 hours), then mints a key for it. A handler that rejects unknown plan slugs fails the check; ignore or delete the account afterwards. ## Next steps > [card] [Account and key reference](/docs/resources/stateful-access-reference) > > Every field, status code, retry rule, and the signature for stacks without an SDK. > [card] [Keys and secrets](/docs/integrate/keys-and-secrets) > > Create, scope, and rotate the signing secret this endpoint verifies against. > [card] [Agents and access](/docs/concepts/agents-and-access) > > What an agent id is, and how one buyer can hold several. > [card] [The integration contract](/docs/integrate/overview) > > The stateless side: verify, check, serve, settle. # Verify requests Source: https://zeroclickai.mintlify.dev/docs/integrate/verify-requests Prove each forwarded request came from ZeroClick: what the SDKs check, why anonymous probes are valid, and the raw-path rule that trips up reverse proxies. Your upstream URL is reachable from the internet; the `zc-signature` header is the gate. Verification proves a request came through ZeroClick (payment handled, buyer resolved) and that nothing changed in transit. Every SDK guard verifies before it does anything else. A request that fails must get `401 {"error":"invalid_zeroclick_signature"}`, never your handler. ## What the SDKs check Verification runs entirely inside your process, with no network call: 1. Parse `zc-signature` (`t=,kid=,v1=<64 lowercase hex>`). Ignore unknown fields: ZeroClick appends fields additively, such as `,sb=1` on sandbox traffic. 2. Reject timestamps outside the clock tolerance: 300 seconds by default, in either direction. 3. Look up the signing secret by the signature's `kid`. An unknown kid is a refusal, so [rotation](/docs/integrate/keys-and-secrets#rotate-a-signing-secret) means holding both kids. 4. Recompute the HMAC-SHA256 over the canonical string and compare in constant time. The canonical string is the timestamp, the uppercased method, the raw path and query, the SHA-256 of the raw body bytes, `zc-request-id`, and `zc-agent-id` (empty string when absent). The [signature spec](/docs/integrate/signature-spec) specifies the exact bytes. Failures are decisions, not exceptions: the guard returns a deny carrying the `401`, with a machine-readable reason (`missing_signature`, `malformed_signature`, `stale_timestamp`, `missing_request_id`, `unknown_kid`, or `invalid_signature`) for your logs. The `401` body itself says nothing about why the request failed. ## Signed anonymous probes are valid A verified request with no `zc-agent-id` (or an empty one) is a **signed anonymous probe**. ZeroClick sends them when it checks your endpoints, to build your catalog or run the setup check. Buyer calls always carry the agent id, unpaid ones included: for an unpaid pay-as-you-go call, ZeroClick forwards the request with the caller's `zc-agent-id`, your guard denies it with the `402 payment_required` usage body, and ZeroClick re-prices that refusal into the one priced challenge the agent pays. Probes are expected traffic, not an attack. ```ts TypeScript theme={null} if (!decision.context.zcAgentId) { // Anonymous probe: zcAgentId is null. } ``` ```python Python theme={null} # Test with truthiness, not `is None`: an absent zc-agent-id header gives # None, but a present-but-empty one gives ""; both mean anonymous. if not decision.context.zc_agent_id: ... ``` ```go Go theme={null} if zc.AgentID == "" { // Anonymous probe. Absent and empty headers sign identically. } ``` ## The signature covers the raw path The canonical string contains the **raw, percent-encoded** path and query exactly as ZeroClick sent it. Every web framework hands you a decoded path, and a decoded path hashes differently. For `GET /v1/items/a%2Fb%20c`: | Source | Value | Verifies | | - | - | - | | ASGI `scope["path"]`, WSGI `PATH_INFO`, Go `r.URL.Path` | `/v1/items/a/b c` | No | | ASGI `scope["raw_path"]`, WSGI `RAW_URI`, Go `r.RequestURI` | `/v1/items/a%2Fb%20c` | Yes | The SDKs handle this at the boundary. The TypeScript SDK reads the web-standard `Request` URL, which preserves encoding. The Python adapters (`zc_request_from_asgi_scope`, `zc_request_from_wsgi_environ`) read the raw target and handle the difference: ASGI's `raw_path` excludes the query string, while WSGI's `RAW_URI` includes it. Go's `FromHTTP` reads `r.RequestURI`, which Go leaves untouched. Ruby's `Middleware.request_from_env` prefers the server's raw target (`REQUEST_URI` under Puma, `ORIGINAL_FULLPATH` under Rails) over the decoded `PATH_INFO`. > [!WARNING] > > A reverse proxy, ingress controller, or managed load balancer in front of your server may normalize the path (`%2F` becoming `/`) before your server sees it. If that happens, every request with an encoded path segment fails verification. If you route through nginx, an ingress, or a load balancer, confirm it passes the request target through unmodified. The same layer may run bot protection that challenges ZeroClick's forwards before they reach your guard. See [firewalls and bot protection](/docs/integrate/firewalls-and-bot-protection). On WSGI, if the server sets neither `RAW_URI` nor `REQUEST_URI`, an encoded separator cannot be recovered: the server decodes `%2F` before the SDK runs. gunicorn, werkzeug, uWSGI, and nginx all set one of them. ## Verify the raw body bytes The body digest covers the bytes exactly as they arrived, before any parsing or transformation. Adapt framework requests without re-encoding the body. If your service opts into encrypted bodies, verify first: the signature covers the ciphertext, so decryption comes after the guard. In Go, the `Meter` and `Identify` middleware read the body for verification and then restore `r.Body`, so your handler reads it normally. ## Lower-level verification `guard` is the right entry point for a billable route. When verification and allowance checking live in separate middleware layers (verify once at the edge, check allowances per route), use the verify-only entry point. In TypeScript, it reads a clone of the `Request`, so the body stays available to your handler. In Python, Go, and Ruby, you hand it the raw bytes you already hold. ```ts TypeScript theme={null} const result = await zeroClick.verifyRequest(request); if (!result.ok) return result.response; // the 401; result.reason for logs // result.context: { zcRequestId, zcAgentId, timestamp, kid } console.log(result.context.zcRequestId); ``` ```python Python theme={null} result = zeroclick.verify_request(zc_request) if not result.ok: return to_fastapi(result.response) # the 401; result.reason for logs context = result.context # zc_request_id, zc_agent_id, timestamp, kid ``` ```go Go theme={null} result, err := seller.Verify(sellers.FromHTTP(r, body)) if err != nil { // Secret resolution failed: a vault outage, not a bad request. http.Error(w, `{"error":"internal_error"}`, http.StatusInternalServerError) return } if !result.OK { result.Response.WriteTo(w) // the 401; result.Reason for logs return } // result.Context: RequestID, AgentID, Timestamp, KID ``` The verified context carries `zcRequestId` and `zcAgentId`: everything the [allowance check](/docs/integrate/check-allowances) and [usage settlement](/docs/integrate/settle-usage) need. ## Who called, and who they belong to `zcAgentId` is always the agent that made this call. When ZeroClick knows the owner behind that agent, the request also carries `zc-buyer-id` (`byr_…`), exposed by the TypeScript and Python SDKs as `zcBuyerId` / `zc_buyer_id`. One buyer can hold several agents, and they all share the buyer's entitlements, so the buyer id is what stays stable when a customer rotates or replaces an agent. Key durable per-customer records on the buyer id when it is present and per-caller state on the agent id. An absent buyer id means an anonymous agent: still identified and billable, just not yet attached to an owner. Note that the signature covers `zc-agent-id` and not `zc-buyer-id`; the [headers reference](/docs/resources/headers) has the full matrix. # What is Page views? Source: https://zeroclickai.mintlify.dev/docs/page-views/overview Page views reports every page-content request your marketing site serves so you can see who reads it - agents, crawlers, and people - and how that traffic converts. What it captures, how viewers are classified, the privacy model, and the API key scope. Page views tells you who reads your marketing site and how that top-of-funnel traffic turns into agent purchases. Your site reports each page-content request to ZeroClick, which classifies the visitor against the same agent registry your storefront uses, so a page view of your pricing page and a later purchase through your storefront line up as one journey. It is a separate capability from [Agentify](/docs/agentify/overview), enabled on its own. Agentify changes what an agent *receives* (markdown instead of HTML); Page views only *observes* the request and never changes the response. Turn on either, both, or neither. Report page views one of two ways: mount the [SDK middleware](/docs/page-views/sdk-middleware) in your site so every page request is reported automatically, or send each view to the [REST endpoint](/docs/page-views/rest) from any stack. ## What is reported A page view is one `GET` request to a page-content path. Requests for assets (anything whose final path segment has a file extension, like `/_astro/app.css`, `/favicon.ico`, or `/logo.png`) are skipped, as are redirects. Everything a reader actually loads to view a page is reported: your pages for people, and the same pages for agents and crawlers. There is no user-agent gate at capture. A crawler, an unknown agent, and a browser are all reported and told apart afterward, so a new agent shows up in your numbers without any change on your side. ## How a viewer is classified The visitor's user-agent, `Accept` header, and IP are read to classify the request, then discarded. What is stored is coarse and non-identifying: * **Client kind**: `agent`, `browser`, or `other`. * **The agent**, when one is recognized: its registry slug (`gptbot`, `perplexitybot`, …) and operator (OpenAI, Perplexity, …), plus a coarse agent type. * **A user-agent family** and the registry version that classified it, so history can be re-bucketed when the registry improves. No raw user-agent or IP is ever stored. Each view carries the same anonymous viewer id your storefront traffic already does (a hash of the visitor's IP and user-agent), so a page view, a later storefront visit, and a purchase from the same client line up as one journey, without either side ever holding an address. Two coarse context signals ride along when the edge exposes them: the visitor's **country** (the header your edge sets, whether Cloudflare, CloudFront, Vercel or App Engine, clamped to a 2-letter code; see the [middleware page](/docs/page-views/sdk-middleware#the-visitors-country)) and the **referrer host**, the referring domain only, never the full referrer URL, so a referrer's own path or query never leaves the visitor's site. Both are optional and hold nothing that identifies a person. ZeroClick's own checks are told apart too. When one of our eval runs loads your pages to confirm they render for agents, its request carries a signed tag. The middleware forwards it, the view is labeled on our side once the signature verifies, and the Website scope of your dashboard leaves those sessions out of every number and shows the count as **ZeroClick checks**. A tag no run signed labels nothing. A check that runs inside a browser agent's own cloud cannot sign, so it starts from a URL whose `src` value carries ZeroClick's marker. The middleware forwards that value with the signature beside it and nothing else from the query, and the whole visit is left out even when the agent drops the marker on its next page. ## Journey stitching Beyond the anonymous viewer id, a page view can carry two fields that describe the agent's *read* of the page, not just the client behind it: * **`representation`**: whether this request was served as plain `html` or agentified `markdown`. The [SDK middleware](/docs/page-views/sdk-middleware) reads it from the response content-type, so you can segment journeys by whether the entry actually got the agent experience. * **`journeyId`**: a reading-chain id that stitches this page view to the agentified read it belongs to. When [Agentify](/docs/agentify/overview) serves an agent markdown, it attaches a journey id to that response; if Page views is mounted as the outer layer, it forwards that id on the view. The marketing view and the agentified read then line up on one journey. Both are optional and present only when the machinery that produces them is running. `representation` is filled whenever the middleware can see the response. `journeyId` appears only when Agentify attached one: Page views without Agentify simply reports no journey id, and Agentify without Page views attaches a journey id that nothing reads. They come together only when Page views wraps Agentify, so the outer view observes both the agent's request and the journey id on its response. The [SDK middleware](/docs/page-views/sdk-middleware#combining-with-agentify) shows that wrap in each language. ## Two timestamps Each view carries two clocks, so you can measure delivery lag and trust the right one: * **`captured_at`**: when your edge observed the request. Present only when your reporter sends it; it is never invented. * **`received_at`**: when ZeroClick received the beacon. This is the authoritative time. ## The Page views key scope Reporting authenticates with an API key carrying the `page-views:write` scope. Mint one in the [dashboard](https://dashboard.zeroclick.io) under **Settings → API keys**: create a key and enable the **Page views** group's **Write** toggle. The scope grants `POST /v1/page-views` and nothing else, so the key can live on your marketing site's edge without exposing your catalog, usage, or Agentify APIs. A key can carry both `page-views:write` and `agentify:convert` when you run both from the same edge, or just one. ## Next steps > [card] [SDK middleware](/docs/page-views/sdk-middleware) > > Report every page view from your TypeScript, Python, Go, or Ruby site, fire-and-forget. > [card] [REST endpoint](/docs/page-views/rest) > > Send a page view from any stack with one POST. # Report a page view over REST Source: https://zeroclickai.mintlify.dev/docs/page-views/rest Send one page-content request to POST /v1/page-views from any stack: the key scope, the request body, the fire-and-forget 204, and the errors. `POST /v1/page-views` records one page view. Use it from any language or framework that has no [SDK middleware](/docs/page-views/sdk-middleware): call it once per page-content `GET` your site serves, from the request that serves it. It answers `204` without waiting for anything downstream, so a report never sits on your response. ## Mint a key Reporting authenticates with a `zc_` key carrying the [`page-views:write` scope](/docs/page-views/overview#the-page-views-key-scope). In the [dashboard](https://dashboard.zeroclick.io) under **Settings → API keys**, create a key with the **Page views** group's **Write** toggle enabled, and keep it on your marketing site's server. ## Report a view ```sh theme={null} curl -sS -X POST https://api.zeroclick.io/v1/page-views \ -H "Authorization: Bearer $ZEROCLICK_PAGE_VIEWS_KEY" \ -H "Content-Type: application/json" \ -d '{ "seller": "sel_your_seller_id", "path": "/pricing", "status": 200, "capturedAt": "2026-08-26T17:00:00.000Z", "userAgent": "Mozilla/5.0 (compatible; GPTBot/1.1; +https://openai.com/gptbot)", "accept": "text/markdown, text/html", "clientIp": "203.0.113.7", "country": "US", "referrerHost": "www.google.com" }' ``` A success is an empty `204`. ## Request body Report only page-content `GET` requests (the same thing a reader loads to view a page), so there is no method field; the method is always `GET`. | Field | Type | Required | Notes | | - | - | - | - | | `seller` | string | yes | The seller whose site served the page (its public `sel_…` id). | | `path` | string | yes | The request path, starting with `/`. Send the path only; any query string or fragment is dropped on our side. | | `status` | number | no | The response status you served (100–599). | | `durationMs` | number | no | How long the request took, in milliseconds. | | `capturedAt` | string | no | When your edge observed the request (ISO 8601). Omit it rather than guessing; it is never invented on our side. | | `journeyId` | string | no | A [reading-chain id](/docs/page-views/overview#journey-stitching) that ties this view to an agentified read, when the request carried one. | | `representation` | string | no | What your site served for this request: `html` or `markdown`. The [SDK middleware](/docs/page-views/sdk-middleware) derives it from the response content-type; set it yourself when you report by hand. Lets analytics segment journeys by whether the entry got the agent experience. | | `userAgent` | string | no | The visitor's `User-Agent`. Read to derive the viewer id and classify the viewer, then discarded, never stored raw. | | `accept` | string | no | The visitor's `Accept` header, which sharpens agent detection. | | `clientIp` | string | no | The visitor's IP. Combined with the user-agent into the anonymous viewer id and never stored raw. | | `country` | string | no | The visitor's country as your edge resolved it, forwarded raw: Cloudflare's `cf-ipcountry`, CloudFront's `cloudfront-viewer-country`, Vercel's `x-vercel-ip-country` or App Engine's `x-appengine-country`. Clamped to a 2-letter ISO code on our side; the vendors' unknown sentinels (`XX`, `ZZ`) are dropped. Never your server's own location. | | `referrerHost` | string | no | The referrer's host, e.g. `www.google.com`. Send the host only; if you send a full URL we reduce it to the host, but the referrer's path and query should never leave your site. | | `evalTag` | string | no | The request's `x-zeroclick-eval` header, as received, when one of ZeroClick's own eval runs loaded the page (1 to 512 characters). | | `evalSignature` | string | no | The request's `x-zeroclick-eval-signature` header, as received (1 to 1024 characters). Sent with `evalTag`. | | `evalSignatureInput` | string | no | The request's `x-zeroclick-eval-signature-input` header, as received (1 to 1024 characters). Sent with `evalTag`. | | `evalSignatureAgent` | string | no | The request's `x-zeroclick-eval-signature-agent` header, as received (1 to 512 characters). Sent with `evalTag`. | | `host` | string | no | The host the page was requested on, as the JS `URL.host` reads it: the hostname and any non-default port (1 to 300 characters). Sent with `evalTag`; the signature is verified against it. | | `source` | string | no | The request's `src` query value when it is ZeroClick's own check marker: `ze-` followed by the run, a slug of up to 32 characters. How a check that runs inside a browser agent's cloud, which cannot sign, is told apart. Sent with `host`. Send no other query value. | | `sourceSignature` | string | no | The request's `signature` query value beside a `source` marker, as received (1 to 256 characters). Accepted and not checked yet; ZeroClick is adding signed markers. | Forward the visitor's `userAgent`, `accept`, and `clientIp` from the original request, not your server's: the request reaches ZeroClick from your backend, so its own headers describe your server, not the reader. Report only what a reader loads to view a page; skip assets and redirects, exactly as the [middleware does](/docs/page-views/sdk-middleware). The last seven fields describe ZeroClick's own checks, and the middleware forwards them for you. A value past its limit fails validation for the whole report, so leave a field out rather than truncate it. A tagged view is labeled as one of ZeroClick's checks, and kept out of your numbers, only when the signature verifies over `host`; a forged tag changes nothing. The marker is unsigned, so a forged one only keeps that visit out of your own numbers. ## Response and errors | Status | Meaning | | - | - | | `204` | Recorded. The body is empty. | | `400` | The body failed validation (for example a `path` that does not start with `/`). | | `403` | The key is missing the `page-views:write` scope, or resolves to no organization. | | `404` | `seller` does not name a seller in the key's organization. | | `429` | Per-organization rate limit exceeded. | Reporting is fire-and-forget by design: send the beacon without blocking your response, and treat any failure as a no-op so a reporting problem never affects the page. The [SDK middleware](/docs/page-views/sdk-middleware) does exactly this for you. ## Next steps > [card] [SDK middleware](/docs/page-views/sdk-middleware) > > Report automatically from your own site (TypeScript, Python, Go, or Ruby), fail-open. > [card] [Overview](/docs/page-views/overview) > > What is captured, how viewers are classified, and the privacy model. # Page views SDK middleware Source: https://zeroclickai.mintlify.dev/docs/page-views/sdk-middleware Report every page-content request your site serves with drop-in middleware for TypeScript, Python, Go, and Ruby: what it forwards, how it composes with Agentify, and the fail-open guarantee that a beacon never delays or breaks a page. Every [seller SDK](/docs/sdks/overview) ships Page views middleware for its language's dominant boundary: a fetch-handler wrapper in TypeScript, ASGI and WSGI adapters in Python, `net/http` middleware in Go, and Rack middleware in Ruby. Mount it around the handler that serves your marketing site, and each page load is reported to [Page views](/docs/page-views/overview) in the background. Agents, crawlers, and people all get your site exactly as before. All four implement one contract: * Only `GET` requests to non-asset paths are reported; assets and every other method pass through unobserved. * The handler runs first, so the beacon carries the real response status and the request duration. The visitor's `User-Agent`, `Accept`, and connecting IP are forwarded for [server-side classification](/docs/page-views/overview#how-a-viewer-is-classified). * The visitor's **country** rides along when your edge resolved it. The middleware reads the header Cloudflare, CloudFront, Vercel or App Engine sets and sends nothing when none is present; see [The visitor's country](#the-visitors-country). * It records the response's **representation** (`html` or `markdown`, read from the response's content-type) and, when [Agentify](/docs/agentify/overview) attached one, the **journey id** that stitches this view to the agentified read. Both are captured automatically; you set nothing. * A page load by one of ZeroClick's own eval runs carries a signed tag. The middleware forwards the tag, its signature and the page's host with the beacon, so the run is labeled as ZeroClick's and never counts as your traffic. You set nothing here either; a tag no run signed labels nothing. A check that runs inside a browser agent's own cloud cannot sign, so it starts from a URL whose `src` value carries ZeroClick's marker, and the middleware forwards that value with the page's host and the `signature` beside it. * **The beacon is fire-and-forget and fails open.** A missing key, a network error, a non-204, a timeout, or a malformed report is handed to `onError` and swallowed. The middleware never delays or breaks the page. Only the request's **path** is reported, never its query string, so tracking parameters never reach ZeroClick. The one exception is a `src` value that carries ZeroClick's own check marker (`ze-`), and the `signature` next to it; any other query value stays on your site. ## Configure the key Reporting uses a `zc_` key with the [`page-views:write` scope](/docs/page-views/overview#the-page-views-key-scope). TypeScript is standalone: the key rides inline on the middleware as `apiKey`, with no `createSeller` and no signing secrets. The other three SDKs read it from a `page_views_key` / `PageViewsKey` field on the client you already build for the guard; when that field is unset, they fall back to the combined API key. ```ts TypeScript theme={null} import { withPageViews } from "@zeroclickai/sellers"; // Standalone: no createSeller, no signing secrets. The key rides inline // on the middleware. See "Mount the middleware" below. const handler = withPageViews(renderPage, { seller: process.env.ZEROCLICK_SELLER_ID!, apiKey: process.env.ZEROCLICK_PAGE_VIEWS_KEY!, }); ``` ```python Python theme={null} # Set page_views_key on the client (create_seller or create_async_seller); # the middleware reads it from there. zeroclick = create_async_seller( api_key=os.environ["ZEROCLICK_API_KEY"], page_views_key=os.environ["ZEROCLICK_PAGE_VIEWS_KEY"], ) ``` ```go Go theme={null} seller, err := sellers.New(sellers.Config{ APIKey: os.Getenv("ZEROCLICK_API_KEY"), PageViewsKey: os.Getenv("ZEROCLICK_PAGE_VIEWS_KEY"), }) ``` ```ruby Ruby theme={null} config.zeroclick.api_key = ENV.fetch("ZEROCLICK_API_KEY") config.zeroclick.page_views_key = ENV.fetch("ZEROCLICK_PAGE_VIEWS_KEY") ``` Delivery is fire-and-forget on a short timeout: Go's `PageViewsTimeout` defaults to `DefaultPageViewTimeout` (2 seconds), and the other SDKs use an equally short page-view default (`timeoutMs` in TypeScript, `page_view_timeout_seconds` in Ruby), long enough to send the beacon, short enough never to sit on a page. ## Mount the middleware ```ts TypeScript theme={null} import { withPageViews } from "@zeroclickai/sellers"; // Wrap the fetch handler that serves your site. Works anywhere the SDK // works: Node.js servers, Hono, Next.js route handlers, edge runtimes. const handler = withPageViews(renderPage, { seller: process.env.ZEROCLICK_SELLER_ID!, apiKey: process.env.ZEROCLICK_PAGE_VIEWS_KEY!, }); export default { fetch: handler }; ``` ```python Python theme={null} # ASGI (Starlette, FastAPI). Pass the async client and your seller id: from zeroclick_sellers.adapters import PageViewsAsgiMiddleware app.add_middleware(PageViewsAsgiMiddleware, seller=zeroclick, seller_id="sel_x") # WSGI (Flask, Django). Pass the blocking client from create_seller: from zeroclick_sellers.adapters import PageViewsWsgiMiddleware app.wsgi_app = PageViewsWsgiMiddleware(app.wsgi_app, zeroclick, "sel_x") ``` ```go Go theme={null} // A plain func(http.Handler) http.Handler, like Meter and Agentify: it // composes with net/http, chi, gorilla/mux, and gin's WrapH. mux.Handle("/", seller.PageViews(sellers.PageViewsOptions{})(site)) ``` ```ruby Ruby theme={null} # Rails: mount it in config/application.rb. Omit `seller:` and the # middleware resolves the process-wide client on the first request. config.middleware.use ZeroClick::Sellers::Middleware::PageViews, seller_id: "sel_x" # Outside Rails, pass the client explicitly: use ZeroClick::Sellers::Middleware::PageViews, seller: SELLER, seller_id: "sel_x" ``` Mount it in front of the pages people and agents read (your marketing routes), not in front of your billed API, which already reports usage through the guard. If your marketing site runs as its own process, configure a client there the same way; Page views only ever needs the seller id and the `page-views:write` key. ## Combining with Agentify [Page views](/docs/page-views/overview) and [Agentify](/docs/agentify/sdk-middleware) are independent opt-ins: run either alone or both. When you run both, **Page views must be the outer middleware, wrapping Agentify**, and this ordering is load-bearing, not cosmetic. * **It is the only way Page views sees agent traffic at all.** The Agentify middleware short-circuits agent requests: on a match it returns markdown and never calls the inner handler. A Page views beacon mounted *inside* Agentify would therefore never fire for those requests, silently dropping exactly the agent page views you most want to measure. Only the outer layer observes them. * **It stitches the journey.** Being outside is also how the page view picks up the journey id Agentify attaches to its response, tying the marketing view to the agentified read on one journey. Wrap Agentify with Page views in each language's idiom: ```ts TypeScript theme={null} // withPageViews on the outside, wrapping withAgentify. const handler = withPageViews(withAgentify(zeroClick, renderPage), { seller: process.env.ZEROCLICK_SELLER_ID!, apiKey: process.env.ZEROCLICK_PAGE_VIEWS_KEY!, }); export default { fetch: handler }; ``` ```python Python theme={null} # WSGI: the LAST wrap is the outermost, so apply Agentify first and # Page views second. Page views ends up outside Agentify. app.wsgi_app = AgentifyWsgiMiddleware(app.wsgi_app, seller=zeroclick) app.wsgi_app = PageViewsWsgiMiddleware(app.wsgi_app, zeroclick, "sel_x") # ASGI: add Agentify first and Page views last, so Page views is outermost. ``` ```go Go theme={null} // PageViews wraps Agentify wraps your site. mux.Handle("/", seller.PageViews(sellers.PageViewsOptions{})( seller.Agentify(sellers.AgentifyOptions{})(site))) ``` ```ruby Ruby theme={null} # In Rack the FIRST `use` is the OUTERMOST layer, so mount Page views # before Agentify to keep Page views on the outside. use ZeroClick::Sellers::Middleware::PageViews, seller_id: "sel_x" use ZeroClick::Sellers::Middleware::Agentify ``` The direction differs by framework because the composition primitives do. TypeScript and Go nest explicitly, so the outer call is Page views. Python's WSGI wrapping and Rack's `use` build a stack instead: in WSGI the **last** wrap is outermost, so Page views is applied second; in Rack the **first** `use` is outermost, so Page views is mounted first. In every case the result is the same: Page views sits on the outside of Agentify. ## Options Each middleware takes the same options, named in its language's idiom: | Option | TypeScript | Python | Go | Ruby | | - | - | - | - | - | | The seller whose site this is (`sel_…`); required | `seller` | `seller_id` | `Seller` | `seller_id` | | Override the public URL whose path is reported | `resolveUrl` | `resolve_url` | `ResolveURL` | `resolve_url` | | Override where the visitor's country is read | `resolveCountry` | `resolve_country` | `ResolveCountry` | `resolve_country` | | Observe the fail-open path; never re-raised | `onError` | `on_error` | `OnError` | `on_error` | The key itself is not an option here: TypeScript passes `apiKey` inline on the middleware, while Python, Go, and Ruby configure it once on the client as `page_views_key` / `PageViewsKey`. Behind a proxy that rewrites the scheme or host, set the URL override so the reported path, ZeroClick's `src` marker, and the page's host that travels with an eval tag come from the public URL rather than the one your process sees. The rest of the query is never reported. Without the override, a rewritten host keeps an eval run's signature from verifying, and the run counts as your traffic. ## The visitor's country The middleware never geolocates anyone itself. It forwards the country your edge already resolved, read from the first present of these request headers, outermost layer first: | Edge | Header | Notes | | - | - | - | | Cloudflare | `cf-ipcountry` | Sent when IP Geolocation is on for the zone, or the "Add visitor location headers" transform is. | | AWS CloudFront | `cloudfront-viewer-country` | Sent only when your cache policy or origin request policy adds it. | | Vercel | `x-vercel-ip-country` | Sent to every deployment; never in local development. | | Google App Engine | `x-appengine-country` | Sent on every request; `ZZ` means unknown and is dropped on our side. | The order matters when a CDN sits in front of a platform: the CDN sees the true client, while the platform behind it geolocates the CDN's edge, so the outer header wins. A site whose edge sets none of these sends no country at all, never a guess, and its sessions show as unknown. Set the country override to read exactly one source instead. Do this when your edge is not in the table (Netlify, for example, exposes the country on its edge context rather than a request header), or to make sure a header a visitor sends themselves is never taken for your edge's. It takes the request and returns the raw value, or nothing for unknown: ```ts theme={null} const handler = withPageViews(renderPage, { seller: process.env.ZEROCLICK_SELLER_ID!, apiKey: process.env.ZEROCLICK_PAGE_VIEWS_KEY!, resolveCountry: (request) => request.headers.get("x-appengine-country") ?? undefined, }); ``` The value is forwarded as sent and clamped to a 2-letter ISO code on our side. Your server's own location is never used. ## Report without the middleware Any language or framework can report by calling the [REST endpoint](/docs/page-views/rest) directly, once per page-content `GET`. Each SDK also exposes a one-shot reporter for when the middleware boundary does not fit (a background job, a custom router, a hand-rolled handler): | SDK | Reporter | | - | - | | TypeScript | `reportPageView(input, { apiKey })` | | Python | `client.report_page_view(ReportPageViewInput(...))` (`await` it on the async client) | | Go | `seller.ReportPageView(ctx, sellers.ReportPageViewInput{...})` | | Ruby | `client.report_page_view(seller:, path:, ...)` | A direct reporter carries the same body the middleware sends, and can set `representation` and the journey id explicitly rather than deriving them from a response it never saw. ## Failing open, observably The middleware exists to add a measurement, never an outage or a delay: any error on the reporting path leaves the response untouched. That silence is deliberate, and it means a misconfigured key looks exactly like a working page, so wire the error hook to your logger: ```ts theme={null} const handler = withPageViews(renderPage, { seller: process.env.ZEROCLICK_SELLER_ID!, apiKey: process.env.ZEROCLICK_PAGE_VIEWS_KEY!, onError: (error, request) => logger.warn({ error, url: request.url }, "page-view beacon failed"), }); ``` In Go, a nil `OnError` falls back to the client's configured `Logger`. ## Next steps > [card] [REST endpoint](/docs/page-views/rest) > > The underlying request: body, response, and errors. > [card] [Overview](/docs/page-views/overview) > > What is captured, how viewers are classified, and the key scope. # Quickstart Source: https://zeroclickai.mintlify.dev/docs/quickstart Add the ZeroClick billing guard to an existing API and serve your first paid agent request. This guide adds the ZeroClick billing guard to one route of an existing API. When you finish, an unpaid agent request to that route gets a priced `402` challenge, a paid request gets served, and the usage and transaction appear in your dashboard. > [!NOTE] > > You need a store that is set up in the [dashboard](https://dashboard.zeroclick.io). ZeroClick configures your store, services, and plans with you during onboarding. You also need an API that ZeroClick can reach at your store's upstream base URL. If a firewall or bot-protection layer sits in front of it, [let ZeroClick's forwards through](/docs/integrate/firewalls-and-bot-protection) first. This guide uses a service `product-watch` with a meter `requests`; substitute your own slugs. **1. Get your keys** Your integration runs on three keys, minted in the dashboard under your store's **Implementation** tab (or **Settings** for individual keys): * A **signing secret** (`zcsec_…`) and its key id (`hsec_…`), used to verify that requests really came from ZeroClick. The key id, or `kid`, appears alongside the secret in the dashboard. * A **usage read key** (`zc_…`, scope `usage:read`) for allowance checks. * A **usage write key** (`zc_…`, scope `usage:write`) for usage reporting. A single API key carrying both usage scopes works in place of the two scoped keys. Each secret is shown once when it is created, so store it in your secret manager right away: ```sh theme={null} ZEROCLICK_SIGNING_SECRET_KID=hsec_k5nq0v7m3d8p ZEROCLICK_SIGNING_SECRET=zcsec_… ZEROCLICK_API_KEY=zc_… ``` See [keys and secrets](/docs/integrate/keys-and-secrets) for scopes, rotation, and split read/write keys. **2. Install the SDK** ```sh TypeScript theme={null} pnpm add @zeroclickai/sellers ``` ```sh Python theme={null} pip install zeroclick-sellers ``` ```sh Go theme={null} go get cdn.zeroclick.io/sdks/sellers-go ``` ```sh Ruby theme={null} bundle add zeroclick-sellers ``` The TypeScript SDK is ESM and runs anywhere the web-standard `Request`, `Response`, and `fetch` exist, including current Node.js and edge runtimes. The Python SDK supports Python 3.10 and later, with sync and async clients. The Go SDK requires Go 1.24 and imports only the standard library. The Ruby gem requires Ruby 3.1 and later, has no runtime dependencies, and ships Rack middleware that covers Rails, Sinatra, Hanami, and Roda. **3. Guard a route** Configure the client once, then guard the route: verify the signature, check the allowance, do the work, and settle usage on the successful response. ```ts TypeScript theme={null} import { createSeller } from "@zeroclickai/sellers"; const zeroClick = createSeller({ signingSecrets: { [process.env.ZEROCLICK_SIGNING_SECRET_KID!]: process.env.ZEROCLICK_SIGNING_SECRET!, }, apiKey: process.env.ZEROCLICK_API_KEY!, }); export async function handle(request: Request): Promise { const decision = await zeroClick.guard(request, { serviceSlug: "product-watch", usage: [{ meterSlug: "requests", quantity: 1 }], }); if (decision.action === "deny") return decision.response; const response = Response.json({ message: "Hello from the seller", zcRequestId: decision.context.zcRequestId, }); return zeroClick.withUsage(response, [ { serviceSlug: "product-watch", meterSlug: "requests", quantity: 1 }, ]); } ``` ```python Python theme={null} import os from fastapi import FastAPI, Request from fastapi.responses import Response from zeroclick_sellers import ( SyncUsageItem, UsageItem, ZcResponse, create_async_seller, ) from zeroclick_sellers.adapters import zc_request_from_asgi_scope zeroclick = create_async_seller( signing_secrets={ os.environ["ZEROCLICK_SIGNING_SECRET_KID"]: os.environ[ "ZEROCLICK_SIGNING_SECRET" ] }, api_key=os.environ["ZEROCLICK_API_KEY"], ) app = FastAPI() def to_fastapi(response: ZcResponse) -> Response: return Response( content=response.body, status_code=response.status, headers=dict(response.headers), ) @app.post("/v1/product-watch") async def product_watch(request: Request) -> Response: zc_request = zc_request_from_asgi_scope(request.scope, await request.body()) decision = await zeroclick.guard( zc_request, service_slug="product-watch", usage=[UsageItem(meter_slug="requests", quantity=1)], ) if decision.action == "deny": return to_fastapi(decision.response) result = do_the_work(owner=decision.context.zc_agent_id) return to_fastapi( zeroclick.with_usage( ZcResponse.json(result), [ SyncUsageItem( service_slug="product-watch", meter_slug="requests", quantity=1, ) ], ) ) ``` ```go Go theme={null} package main import ( "encoding/json" "log" "net/http" "os" sellers "cdn.zeroclick.io/sdks/sellers-go" ) func main() { secrets, err := sellers.SecretsFromEnv() // ZEROCLICK_SIGNING_SECRETS if err != nil { log.Fatal(err) } seller, err := sellers.New(sellers.Config{ APIKey: os.Getenv("ZEROCLICK_API_KEY"), ServiceSlug: "product-watch", SigningSecrets: secrets, Logger: log.Default(), }) if err != nil { log.Fatal(err) } mux := http.NewServeMux() mux.Handle("/v1/product-watch", seller.Meter(sellers.PerRequest("requests", 1))( http.HandlerFunc(productWatch))) log.Fatal(http.ListenAndServe(":8080", mux)) } func productWatch(w http.ResponseWriter, r *http.Request) { zc, _ := sellers.FromContext(r.Context()) // zc.AgentID, zc.RequestID w.Header().Set("content-type", "application/json") json.NewEncoder(w).Encode(map[string]any{"ok": true, "agent": zc.AgentID}) } ``` ```ruby Ruby theme={null} # config.ru require "json" require "zeroclick/sellers" SELLER = ZeroClick::Sellers.create( api_key: ENV.fetch("ZEROCLICK_API_KEY"), signing_secrets: ZeroClick::Sellers.secrets_from_env # ZEROCLICK_SIGNING_SECRETS ) product_watch = lambda do |env| zc = env["zeroclick.context"] # zc.zc_agent_id, zc.zc_request_id [200, { "content-type" => "application/json" }, [JSON.generate({ ok: true, agent: zc.zc_agent_id })]] end map "/v1/product-watch" do use ZeroClick::Sellers::Middleware::Meter, seller: SELLER, service_slug: "product-watch", usage: [ZeroClick::Sellers::UsageItem.new(meter_slug: "requests", quantity: 1)] run product_watch end ``` The guard verifies the signature before it calls the allowance API. Its result is a decision, not an exception. A denial carries the exact response to return: `401` for a bad signature, the `402 payment_required` refusal for a business denial, or `503` under a fail-closed outage policy. In Go and Ruby, the `Meter` middleware returns the denial and sets the `zc-usage` header for you. In TypeScript and Python, you return `decision.response` and settle usage with `withUsage`. **4. Verify the integration** Deploy the guarded route where ZeroClick can reach it, then open your store's **Implementation** tab in the dashboard and run the API setup verification. ZeroClick sends an unpaid probe to your endpoint and confirms it answers with the priced `402` refusal and reports usage correctly. You can also test the guard locally: a plain request with no ZeroClick headers must get `401 {"error":"invalid_zeroclick_signature"}`. Only signed requests from ZeroClick reach your handler. **5. Serve paid traffic** That's the whole integration. Agents now transact with the guarded route through your pay URL: every call carries the agent's registered credential, an unpaid call gets one priced `402` challenge, the agent pays with x402 or MPP and retries, and ZeroClick forwards the signed request to your API. > [!TIP] > > Each paid request appears under **Transactions** in the dashboard, with the agent, service, meter quantities, and settled amount. ## Next steps > [card] [The integration contract](/docs/integrate/overview) > > Everything your API must verify, check, and return, on one page. > [card] [How ZeroClick works](/docs/concepts/how-zeroclick-works) > > The full request lifecycle: challenge, payment, signed forward, settlement. > [card] [Charge up to a maximum](/docs/integrate/charge-up-to-a-maximum) > > Bill work you can't size up front, like output tokens. > [card] [SDK reference](/docs/sdks/overview) > > Configuration and full API surface for each SDK. # Errors Source: https://zeroclickai.mintlify.dev/docs/resources/errors Every machine error code ZeroClick returns, by surface: the REST API, the usage endpoints, the responses your API must return, and the agent-facing pay URL. ZeroClick returns errors on four surfaces: the REST API at `https://api.zeroclick.io`, the usage endpoints under `/v1/usage`, your own API (which returns three fixed bodies to ZeroClick), and the agent-facing pay URL (`https://acme.pay.zeroclick.io`). This page lists every machine code per surface. ## The error envelope Every error body is JSON with a machine code in `error`: ```json theme={null} { "error": "usage_exhausted" } ``` Some errors carry additional fields: pay URL errors may add a `reason` (and `settlementReason`), and `amount_below_minimum` adds `minimumPurchaseUsd`. Two cases fall outside the machine-code convention: * Request validation failures return `400` with a human-readable message in `error` describing the invalid field. * Server errors return `500 { "error": "Internal server error" }`. The body never carries internals. ## REST API errors Management endpoints (sellers, services, meters, plans, prices, signing secrets, API keys, analytics) authenticate with `Authorization: Bearer zc_…` and share these codes: | Code | Status | Meaning | | - | - | - | | `missing_bearer_token` | 401 | The request has no `Authorization: Bearer` header. | | `invalid_token` | 401 | The API key or session token did not verify. | | `auth_type_not_allowed` | 403 | The endpoint does not accept this credential type. For example, API keys cannot manage API keys (session-only), and the usage endpoints accept API keys only. | | `insufficient_scope` | 403 | The API key lacks a scope the endpoint requires. See [keys and secrets](/docs/integrate/keys-and-secrets). | | `organization_required` | 403 | The caller has no current organization. | | `organization_permission_required` | 403 | The caller may not act on the selected organization. | | `seller_not_found` | 404 | No such seller in your organization. | | `service_not_found` | 404 | No such service. | | `meter_not_found` | 404 | No such meter. | | `plan_not_found` | 404 | No such plan. | | `plan_meter_price_not_found` | 404 | No such plan meter price. | | `signing_secret_not_found` | 404 | No such signing secret. | | `duplicate_slug` | 409 | A seller, service, or plan with this slug already exists in that scope. | | `duplicate_key` | 409 | A meter with this key already exists on the service. | | `duplicate_plan_meter_price` | 409 | The plan already prices this meter. | | `payg_price_not_whole_cents` | 422 | Pay-as-you-go rates are charged per call, so `priceUsd` must be a whole-cent amount. Rates on credit and subscription plans keep full 6-decimal precision. | > [!NOTE] > > 404 is the default for anything that does not resolve. A resource that exists but belongs to another organization is also a 404, never a 403. ### Agentify errors (`GET /v1/agentify/markdown`) The [Agentify](/docs/agentify/overview) endpoint requires an API key with the `agentify:convert` scope; a wrong scope is `403 insufficient_scope`, a non-API-key credential is `403 auth_type_not_allowed`, and requests beyond 60 per minute per organization answer `429`. Its own codes: | Code | Status | Meaning | | - | - | - | | `invalid_url` | 400 | The `url` is not a public `http(s)` page: IP literals, credentials, non-standard ports, and non-public hostnames are rejected. | | `seller_required` | 400 | The organization has zero or several active sellers, or the `seller` parameter matched none of them. Pass `?seller=sel_…`. | | `page_not_found` | 404 | The page answered `404` or `410`. The SDK middleware falls through, so your site serves its own not-found page. | | `content_too_thin` | 422 | The page converted to too little readable content, usually a JavaScript app serving an empty shell. See [SPA setup](/docs/agentify/spa-setup). | | `fetch_failed` | 502 | The page could not be fetched: DNS, TLS, a network failure, too many redirects, or an oversized body. | ## Usage endpoint errors Both usage endpoints live at `https://api.zeroclick.io` and require an API key: `POST /v1/usage/check` needs scope `usage:read`, `POST /v1/usage` needs `usage:write`. A wrong scope is `403 insufficient_scope`; a non-API-key credential is `403 auth_type_not_allowed`. ### Allowance denials (`POST /v1/usage/check`) A denial is not an HTTP error. The check returns `200` with the decision, and checking records nothing and burns no credit: ```json theme={null} { "allowed": false, "reason": "usage_exhausted" } ``` `reason` is `null` when `allowed` is `true`, and exactly one of these seven codes otherwise: | Reason | Meaning | Fix | | - | - | - | | `service_not_found` | No service with this slug under the organization your API key belongs to. | Send the service slug as configured in the dashboard, with a key from the owning organization. | | `access_not_found` | The `zcRequestId` does not match a live ZeroClick request for this service, or the request has no purchase or payment behind it. | Pass the `zc-request-id` header value through unchanged. For unpaid traffic, this is the expected denial: return the `402 payment_required` body, and ZeroClick prices the challenge. | | `access_inactive` | The buyer's access is not active: canceled, or its period has not started. | Deny with the `402` body; the agent must purchase again. | | `plan_expired` | The access period has ended. | Deny with the `402` body; the agent re-purchases. | | `meter_not_found` | No meter with this slug exists on the service. | Use the meter key exactly as configured on the service. | | `meter_not_priced` | The buyer's plan does not price this meter. Also returned when an item declares neither `quantity` nor `maxQuantity` and the price has no `defaultMaxQuantity` to gate against. | Price the meter on the plan, or set the price's `defaultMaxQuantity` (or declare an explicit `maxQuantity` per request). | | `usage_exhausted` | The plan cannot cover this usage: credit or included allowance has run out. | Deny with the `402` body; ZeroClick challenges the agent to pay or top up. | See [check allowances](/docs/integrate/check-allowances) for the request shape and [usage and allowances](/docs/concepts/usage-and-allowances) for how ZeroClick decides coverage. ### Report errors (`POST /v1/usage`) A replayed `idempotencyKey` is a success (`200` with `duplicate: true`), not an error. Failures map to: | Status | Codes | Meaning | | - | - | - | | 402 | `access_inactive`, `plan_expired`, `usage_exhausted` | The access exists but can no longer be billed. | | 409 | `meter_not_priced` | The buyer's plan does not price this meter. | | 404 | `service_not_found`, `access_not_found`, `meter_not_found` | The slug or agent does not resolve (the default for anything missing). | ## Errors your API returns to ZeroClick Your API answers ZeroClick with exactly three non-2xx bodies. The [seller SDKs](/docs/sdks/overview) build all of them; if you integrate over [REST](/docs/integrate/rest-walkthrough), return them byte-for-byte. An invalid, missing, or stale `zc-signature`, before any other work: ```json 401 theme={null} { "error": "invalid_zeroclick_signature" } ``` A business denial (no allowance, unpaid call). ZeroClick reads the `usage` list, prices it, and issues the buyer a payment challenge. The buyer never sees this body. `planSlug` is optional; `usage: []` marks a [free identity-scoped endpoint](/docs/integrate/free-and-identity-endpoints), which ZeroClick never charges for: ```json 402 theme={null} { "error": "payment_required", "serviceSlug": "product-watch", "usage": [{ "meterSlug": "requests", "quantity": 1 }] } ``` The allowance API unreachable under a fail-closed outage policy: ```json 503 theme={null} { "error": "allowance_unavailable" } ``` ## Errors agents see at your pay URL Buyers transact at your pay URL (`https://acme.pay.zeroclick.io`). Once ZeroClick forwards a paid request, agents receive your API's own status codes and bodies unchanged. The codes below are ZeroClick's own, issued before or instead of the forward: | Code | Status | Meaning | | - | - | - | | `invalid_request` | 400 | Malformed purchase or top-up body. | | `amount_required` | 400 | A credit plan purchase without `amountUsd`. | | `payg_not_purchasable` | 400 | Purchase attempt on a pay-as-you-go plan: payg is called, never purchased. | | `amount_not_cent_increment` | 400 | The `amountUsd` is not a whole-cent value; buyer-chosen amounts settle on-chain in whole cents. | | `amount_below_minimum` | 400 | The `amountUsd` is under the plan's minimum purchase; the body carries `minimumPurchaseUsd`. | | `encryption_not_configured` | 400 | An `application/jose` body was sent but the seller publishes no encryption keys. | | `invalid_compact_jwe` | 400 | The body is not a five-segment Compact JWE. | | `unsupported_jwe_suite` | 400 | The JWE does not use the seller's fixed `alg`/`enc` suite. | | `jwe_kid_required` | 400 | The JWE protected header names no `kid`. | | `unknown_jwe_kid` | 400 | The `kid` is not in the seller's published JWKS. | | `private_reply_jwk` | 400 | The reply JWK carries private key material. | | `invalid_reply_jwk` | 400 | The reply JWK is not a public P-256 key. | | `bearer_required` | 401 | The call carries no registered agent credential. Every call needs one, pay-as-you-go included, so ZeroClick refuses before quoting any price. The body carries an `auth` block pointing at the storefront's `/auth.md` registration recipe, and the `WWW-Authenticate` header carries `resource_metadata`. | | `payment_required` | 402 | The payment challenge: the one 402 an agent pays. A `reason` field distinguishes the cases below. | | `plan_required` | 403 | A registered agent's plan does not include a meter the call uses (`reason: not_included_in_plan`, with the meters named), or the agent holds no plan and the call has no per-request price (`reason: access_not_found`). The body's `plans` lists only the plans that cover the call, each with its `purchase.url`. Buy one with the bearer, then retry. | | `seller_not_found` | 404 | The host does not map to a seller. | | `plan_not_found` | 404 | Unknown plan id; agents use ids from `GET /manifest.json`. | | `signing_secret_required` | 409 | The seller has no active signing secret: setup is incomplete. | | `payment_request_mismatch` | 409 | The paid retry differs from the challenged request: method, path, or body bytes changed. The payment is bound to the request's body digest, so the retry must be byte-identical. | | `payment_request_already_completed` | 409 | A retry of a request that already delivered. Each payment forwards its request once. | | `payment_request_in_flight` | 409 | A concurrent retry while another attempt for the same request is still running. | | `payment_amount_mismatch` | 409 | A purchase or top-up retry carried a different `amountUsd` than the challenge that was paid. | | `payment_rail_unavailable` | 409 | No payment method the seller accepts can settle this charge. The usual case is a card-only seller (no stablecoin payments) and a per-call charge or top-up below the seller's card minimum (\$0.50, or a little more for a seller paid out in another currency): buy credits or a plan by card, then retry with the bearer. | | `usage_not_priced` | 409 | The upstream's refusal names usage no plan can price, so ZeroClick cannot mint a per-call challenge. When the gap is the calling agent's own plan, it receives `plan_required` instead. | | `entitlements_not_available` | 501 | This storefront does not sell plans or top-ups. Pay-as-you-go per call still works. | | `capped_pricing_unavailable` | 503 | The request needs ceiling pricing but no reserve-and-pay-actual rail is currently available. | The seven `400` JWE codes apply only to requests sent with `Content-Type: application/jose` (end-to-end encrypted bodies). ZeroClick returns them before it asks for any payment. > [!NOTE] > > A billing failure detected after your API already delivered a 2xx does not become an error status. ZeroClick returns the delivered response and surfaces the failure in the `zc-usage-error` response header. See [headers](/docs/resources/headers). ### `402 payment_required` reasons | Reason | Meaning | | - | - | | *absent* | The normal per-call charge: the body carries a `payment` block with the exact `amountUsd` and a signable challenge per protocol. The agent pays and retries. | | `identity_invalid` | The identity proof did not verify. The agent signs a fresh challenge. | | `access_not_found` | The agent has no active plan to draw from or extend. It purchases one first. | | `usage_exhausted` | The plan's credit ran out. The agent tops up or purchases again. | | `settlement_failed` | The signed payment did not settle; `settlementReason` says why (for example `insufficient_funds`). The agent fixes its wallet and restarts for a fresh challenge. | A priced challenge looks like this (the same challenge also rides in the `payment-required` and `www-authenticate` response headers): ```json 402 theme={null} { "error": "payment_required", "zcAgentId": "agt_x7f2kq93bh0d", "zcRequestId": "zcreq_8h2m4x0q9k1f", "serviceSlug": "product-watch", "usage": [{ "meterSlug": "requests", "quantity": 1 }], "plan": { "id": "pln_...", "slug": "metered", "billingMode": "payg" }, "payment": { "id": "apay_...", "amountUsd": "0.010000", "rail": "base_usdc", "network": "base" }, "protocols": { "x402": { "x402Version": 2, "network": "eip155:8453", "scheme": "exact", "amount": "10000", "asset": "0x..." }, "mpp": { "challengeId": "...", "method": "tempo", "intent": "charge" } } } ``` The body also carries the standard x402 document fields (`x402Version`, `resource`, `accepts`) at the top level for body-reading clients. ZeroClick omits `rail` and `network` on a challenge to a request that carries no payment proof yet, where the agent picks a protocol by paying. The full lifecycle around this challenge is on [how ZeroClick works](/docs/concepts/how-zeroclick-works); the protocols themselves are on [payment protocols](/docs/concepts/payment-protocols). # Headers Source: https://zeroclickai.mintlify.dev/docs/resources/headers The zc-* and payment header reference for every direction: ZeroClick to your API, your API to ZeroClick, ZeroClick to the agent, and the agent to ZeroClick. Four parties exchange headers on every paid request: the agent, ZeroClick's proxy, your API, and the response path back. This page lists every header per direction, with formats and realistic values. The `zc-request-id` value (`zcreq_…`) is the correlation spine. The same id flows through the challenge, the paid retry, the allowance check, and the usage record. See [how ZeroClick works](/docs/concepts/how-zeroclick-works) for the lifecycle. ## ZeroClick to your API (request) Headers ZeroClick sets on every request it forwards to your `upstreamBaseUrl`: | Header | Example | Notes | | - | - | - | | `zc-request-id` | `zcreq_8h2m4x0q9k1f` | Correlation id for this request. Echo it in `POST /v1/usage/check` as `zcRequestId`. | | `zc-agent-id` | `agt_x7f2kq93bh0d` | The agent that made this call. Absent on signed anonymous probes, which ZeroClick sends when it checks your endpoints: a valid, expected state. | | `zc-anonymous-id` | `agt_x7f2kq93bh0d` | The same value as `zc-agent-id`, under the name that will eventually replace it. Present and absent in exactly the same cases. | | `zc-buyer-id` | `byr_3n8v1c6t5j2w` | The person or company the agent belongs to. Sent only once that owner is known; absent means an anonymous agent. | | `zc-buyer-email` | `casey@example.com` | The buyer's verified email. Sent only when the funding plan's [verified email policy](/docs/concepts/plans-and-pricing#the-verified-email-policy) is `requested` or `required`, and only once the email exists — under `requested` it can start appearing partway through a customer relationship, on the first call after their human claims. Use it to tie activity to a customer account — it arrives verified, so it is safe to key on. | | `zc-signature` | see below | HMAC proof the request came from ZeroClick. Verify it before anything else. | | `zc-sandbox` | `1` | Sent on sandbox test traffic only; branch to your own test mode on it. | ### `zc-agent-id` and `zc-buyer-id` These answer two different questions, and a request can carry either one or both: * `zc-agent-id` is **who called**. It is always the agent that executed this request, never some other agent that happens to have paid for the plan being drawn down. * `zc-buyer-id` is **who they belong to**. One buyer can hold many agents; every one of them is entitled to everything the buyer owns. | What you see | What it means | | - | - | | Neither | A signed anonymous probe. No identity has been established yet. | | Agent id only | An anonymous agent: identified and billable, but not yet attached to a known owner. | | Both | The agent belongs to that buyer and inherits the buyer's entitlements. | Key per-caller state (rate limits, per-run scratch data) on `zc-agent-id`. Key per-customer state (history, tenancy, saved records, anything a human should still see after their agent is replaced) on `zc-buyer-id` when it is present, since a buyer can retire one agent and call you with the next. Two requests carrying the same `zc-buyer-id` under different agent ids are the same customer. > [!WARNING] > > The signature covers `zc-agent-id`, not `zc-buyer-id` or `zc-buyer-email`. Treat both as facts ZeroClick asserts over the authenticated channel rather than as independently proven ones, and never let either alone unlock records you would not release to the agent id it arrived with. (On stateful account writes the email additionally arrives inside the signed body as `buyerEmail` — key on that one.) > [!NOTE] > > Before forwarding, ZeroClick strips every inbound `zc-*` and `x-zc-*` header plus `x-payment`, `payment`, and `payment-signature`, then sets its own. An agent can never spoof these values. Any upstream auth you configured between ZeroClick and your API passes through unchanged. Because only ZeroClick sets `zc-signature`, its presence is also the right key for a firewall or bot-protection exemption. See [firewalls and bot protection](/docs/integrate/firewalls-and-bot-protection). ### `zc-signature` ```text theme={null} zc-signature: t=1785254400,kid=hsec_k5nq0v7m3d8p,v1=9f2c7d41a8e05b6c3f1d92e47ab08c5d6e1f3a29b47c80d5e2f16a3b4c5d6e7f ``` The grammar is `t=,kid=,v1=<64 lowercase hex>`; sandbox traffic appends `,sb=1`. `t` is the signing time (verify within a tolerance, 300 seconds by default). `kid` names the signing secret so you can select the right one during rotation. `v1` is the HMAC-SHA256 (constant-time compare) over a six-field canonical string: `t`, the uppercased method, the raw path and query, the SHA-256 hex of the raw body bytes, the `zc-request-id` value, and the `zc-agent-id` value or empty string. The signed canonical is identical for sandbox and live traffic; verifiers that parse only `t`/`kid`/`v1` ignore the trailing `sb=1`. Full byte-level rules: [signature spec](/docs/integrate/signature-spec). ## Your API to ZeroClick (response) | Header | Example | Notes | | - | - | - | | `zc-usage` | see below | Settles usage synchronously on a delivered response. 2xx only. | ### `zc-usage` ```text theme={null} zc-usage: [{"serviceSlug":"product-watch","meterSlug":"requests","quantity":1},{"serviceSlug":"product-watch","meterSlug":"output_tokens","quantity":842}] ``` A JSON array of `{ "serviceSlug", "meterSlug", "quantity" }` items; `quantity` is an integer from 0 to 2,147,483,647 (0 settles a capped meter at zero). Set it only on a 2xx response that delivered. A 4xx must not carry it. ZeroClick strips the header before the agent sees the response. This is the preferred way to settle usage; [settle usage](/docs/integrate/settle-usage) covers it against the async `POST /v1/usage` alternative. If billing fails after your API already delivered (a malformed header, a denial, or a settlement exception), ZeroClick does not drop the response. It returns the body to the agent and names the failure in the `zc-usage-error` response header. The payment stays observable rather than silently lost. ## ZeroClick to the agent (response) | Header | When | Carries | | - | - | - | | `payment-required` | 402 challenges | The full signable x402 challenge (the complete PaymentRequired document, header-encoded). | | `www-authenticate` | 402 challenges | The full signable MPP challenge. | | `zc-billing` | Responses to requests paid with a per-request payment | The settlement summary: authorized vs. charged vs. remainder. | | `payment-response` | Paid x402 responses | The x402 settle receipt, base64-encoded: loggable proof of what settled. | | `payment-receipt` | Paid MPP responses | The serialized MPP receipt. | | `zc-usage-error` | Delivered responses whose billing failed | A machine code: an allowance denial reason, `invalid_usage_header`, or `settlement_failed`. | | `zc-usage-adjusted` | Settled quantities differ from reported | JSON array of `{ "meterSlug", "reportedQuantity", "settledQuantity" }`. Reports beyond the authorization settle at the cap or at zero. | Identity-only responses carry no receipt header. Free-mode responses covered by included units carry no `zc-billing`: there was no per-request payment to settle. ### `zc-billing` ```text theme={null} zc-billing: {"status":"settled","authorizedUsd":"1.250000","chargedUsd":"0.421000","remainderUsd":"0.829000","remainderHandling":"escrow_returned","settleTransactionHash":"0x9c2e..."} ``` | Field | Meaning | | - | - | | `status` | `settled` once the settlement committed; `settling` while it is still finishing (the amounts below are withheld until final). | | `authorizedUsd` | What the agent's payment authorized. On [ceiling-priced requests](/docs/integrate/charge-up-to-a-maximum) this is the ceiling, not the charge. | | `chargedUsd` | What the request actually cost, read back from the settlement ledger. | | `remainderUsd` | `authorizedUsd` minus `chargedUsd`. | | `remainderHandling` | Where the remainder went: `credited` (added to the buyer's balance with this seller), `escrow_returned` (it never left the wallet, or was refunded from escrow), or `escrow_expired` (the hold lapsed unsettled; the buyer kept the full ceiling). | | `settleTransactionHash` | The on-chain settle transaction, when one exists. | ## The agent to ZeroClick (request) | Header | Example | Notes | | - | - | - | | `x-payment` | `x-payment: ` | The signed x402 proof answering a `payment-required` challenge. Also accepted under the `payment-signature` name. | | `authorization` | `authorization: Payment ` | The signed MPP credential answering a `www-authenticate` challenge. | | `zc-mode` | `zc-mode: free` | Opt-in to free included-units coverage on pay-as-you-go. Any other value, or no header, is paid mode. | The proof carries everything: the challenge an agent signs embeds ZeroClick's payment metadata, so the paid retry needs no other headers. The retry must be byte-identical to the challenged request, because the payment is bound to the request's body digest. Protocol details: [payment protocols](/docs/concepts/payment-protocols). ### `zc-mode` `free` is the only recognized value; ZeroClick treats anything else as paid rather than rejecting it. The mode applies to the whole request, so your allowance pre-gate (`POST /v1/usage/check`) honors the same decision the proxy made. Agents send it on every call they want covered. ZeroClick tracks the allowance per buyer - every agent claimed by the same human draws from one shared pool - and serves it only to claimed agents with a verified email, so an unidentified free-mode caller is answered with `401 bearer_required` and registers - and gets claimed - before its first covered call. See [free and identity endpoints](/docs/integrate/free-and-identity-endpoints). Every call also needs the agent's credential. On x402 it stays in `Authorization: Bearer `, because the payment rides `x-payment`. On MPP, send it in `ZC-Agent-Authorization: Bearer ` and keep `Authorization` for the MPP `Payment` credential; never combine credentials in one header. # Account and key reference Source: https://zeroclickai.mintlify.dev/docs/resources/stateful-access-reference The complete wire contract for stateful sellers: request and response bodies, field meanings, handler return values, retry and timeout behavior, and the signature for stacks without an SDK. Every detail behind [sell accounts and API keys](/docs/integrate/stateful-sellers). Read that guide first — this page is for looking things up once you are building. ## Configuring the endpoint ZeroClick derives the endpoint from the **origin** of your upstream base URL plus `/zeroclick/access`. Any path on the base URL is dropped: `https://api.example.com/v1` gives `https://api.example.com/zeroclick/access`. To host it elsewhere, set an override: ```sh theme={null} curl -X PATCH https://api.zeroclick.io/v1/sellers/{sellerId}/stateful-access \ -H "authorization: Bearer $ZEROCLICK_API_KEY" \ -H "content-type: application/json" \ -d '{"accessEndpointUrl":"https://accounts.example.com/hooks/zeroclick"}' ``` `GET` the same path returns `stateful` (is this storefront designated to sell accounts) and the current `accessEndpointUrl`. The mint route is always the write route plus `/{accessId}/keys`. ## Request headers Both calls arrive as `POST` with: | Header | Meaning | | - | - | | `zc-signature` | `t=…,kid=…,v1=…`. A `t` more than 5 minutes old or in the future is rejected. | | `zc-agent-id` | The agent making this call — different calls to one account may carry different values. Sent again as `zc-anonymous-id` with the same value. | | `zc-buyer-id` | The person or company behind the agent (`byr_…`), once the credential has been claimed; absent until then. Not covered by the signature — it mirrors the body's `buyerId`, which is, and the SDK rejects a disagreement with `400 buyer_mismatch`. | | `zc-buyer-email` | The buyer's verified email, sent on account writes when the purchased plan's [verified email policy](/docs/concepts/plans-and-pricing#the-verified-email-policy) is `requested` or `required` and the email exists; absent otherwise. Like `zc-buyer-id` it is an unsigned mirror of the body's `buyerEmail`, and the SDK rejects a disagreement with `400 buyer_email_mismatch`. | | `zc-request-id` | Stable across retries of the same call. For account writes it is `{accessId}:{stateVersion}`. | ## The account write ```json POST /zeroclick/access theme={null} { "accessId": "zacc_8h2m4x0q9k1f", "agentId": "agt_x7f2kq93bh0d", "buyerId": "byr_3n8v1c6t5j2w", "buyerEmail": "casey@example.com", "idempotencyKey": "zacc_8h2m4x0q9k1f:3", "stateVersion": 3, "plan": { "slug": "research-pro", "name": "Research Pro", "billingMode": "subscription_usage", "interval": "month", "basePriceUsd": "20.000000" }, "state": { "period": { "start": "2026-08-01T00:00:00Z", "end": "2026-09-01T00:00:00Z" }, "lifetimeCreditGrantedUsd": "45.000000", "lifetimeCreditReversedUsd": "0.000000", "status": "active" } } ``` | Field | What it means | | - | - | | `accessId` | The durable ZeroClick account handle, `zacc_…`. **Your account key**, stable for the life of the account. | | `agentId` | The agent making this call, `agt_…` — may differ between writes to one account, so never key on it. Always equal to the signed `zc-agent-id`; the SDK rejects the request with `400` if they disagree. | | `buyerId` | The person or company behind the agent (`byr_…`), or `null` until the credential is claimed — it can appear partway through an account's life. Covered by the body signature; the same value proxied traffic carries as `zc-buyer-id`, so store it if you keep buyer-keyed customer records. | | `buyerEmail` | The buyer's verified email, or `null` unless the purchased plan's [verified email policy](/docs/concepts/plans-and-pricing#the-verified-email-policy) asks for it and the email exists. Under the `requested` policy it can appear **partway through an account's life**: when the human claims after the purchase, ZeroClick sends a fresh write, one `stateVersion` higher, whose only news is this field — apply it like any other write. Covered by the body signature and mirrored unsigned as `zc-buyer-email`. The recommended key for tying this account to a user account on your side — see [the integration guide](/docs/integrate/stateful-sellers#tying-the-account-to-a-user-account). | | `stateVersion` | A counter that goes up every time ZeroClick sends a newer picture of this account. **Apply a write only if this is higher than the last version you stored.** Equal or lower is a retry you have already handled. | | `idempotencyKey` | `{accessId}:{stateVersion}`, the same value as `zc-request-id`. Keep it for your audit log; `stateVersion` is what you deduplicate on. | | `plan.billingMode` | `subscription`, `subscription_usage`, `credit`, or `free_trial` — see [plans and pricing](/docs/concepts/plans-and-pricing#the-five-billing-modes). Key trial behavior off this mode, never off a slug convention. | | `plan.interval` | `none`, `day`, `month`, or `year`. | | `plan.basePriceUsd` | What the plan charges per period. | | `state.period` | The window this plan is paid for. `end` is `null` for plans with no expiry. | | `state.lifetimeCreditGrantedUsd` | **Not the remaining balance, and not the size of this top-up** — the cumulative total for the account. Each payment mints what its plan's billing mode says: a `subscription_usage` purchase mints its `includedCreditUsd`, not its price, and a `free_trial` claim mints the trial's `includedCreditUsd` with no payment. `null` if the plan has no credit component — on a `subscription` plan both credit totals are `null`. | | `state.lifetimeCreditReversedUsd` | **What card refunds and chargebacks have pulled back** — cumulative like the grant total, not the size of one refund. `null` if the plan has no credit component, exactly as the grant is. | | `state.status` | `active`, `suspended`, or `closed`. `suspended` is recoverable: suspend service, delete nothing — a later write may return the account to `active`. `closed` is terminal, sent when the account is torn down on the ZeroClick side: revoke live API keys, stop serving, keep your own records — no higher `stateVersion` will ever follow. | For an automatically renewed Tempo plan, `plan.interval` remains the plan's `month` or `year` label, while the native payment permission charges every 30 or 365 elapsed days. The `state.period` dates in each write are the authoritative access window. Apply those dates instead of calculating a calendar-month or calendar-year end yourself. A top-up changes the cumulative credit totals in the same account; it does not create a second account. Every declared field is always present in the body — explicitly `null` when unset, never omitted. Every money field is a string with exactly six decimal places. `parseMoneyUsd` converts one to an integer count of millionths of a dollar ("micros") so you never do floating-point math on money; `formatMoneyUsd` converts back. ### Why the write is a complete picture The write describes **how the account should look**, not what changed. Replay it, receive it twice, or receive an old one late: applying the newest version you have seen always leaves the account correct. That is why `lifetimeCreditGrantedUsd` and `lifetimeCreditReversedUsd` are running totals rather than deltas. `deriveCreditDelta` nets the two totals into one purse movement, and returns one of four outcomes: | Outcome | What to do | | - | - | | `credit` | Add `deltaUsdMicros` to the balance, then store `next` as the new recorded totals. | | `debit` | A refund or chargeback clawed money back. Subtract `deltaUsdMicros`, clamping the balance at zero, then store `next`. | | `no_credit_dimension` | This plan has no credit component. Store `next`; leave the balance alone. | | `replay` | You have already applied this version or a newer one. Do nothing. | ### When the period advances A renewal arrives as an ordinary write whose `state.period.start` differs from the one you stored — `periodAdvanced` compares the two. That is your cue to reset any **per-period counters of your own** (a monthly quota, included usage you meter yourself). The credit totals are the asymmetry: they are lifetime running totals and never reset, which is exactly what lets `deriveCreditDelta` stay correct across renewals. Reset quotas on a new period; never reset the recorded grant and reversal totals. ### Deciding whether to serve `isServiceable` (`is_serviceable` in Python, `IsServiceable` in Go, `serviceable?` in Ruby) is the one request-time gate: it answers `true` only while the stored `status` is `active` **and** the period, when its `end` is non-`null`, has not lapsed. Gate every authenticated request on it rather than combining `status` and the period yourself — `status` alone misses period-based revocation on interval plans, and the period alone misses suspension and closure. Period expiry has no push: nothing arrives at period end, so the check must be local and time-based, against the state you stored. ## The key mint ```json POST /zeroclick/access/zacc_8h2m4x0q9k1f/keys theme={null} { "agentId": "agt_x7f2kq93bh0d", "buyerId": "byr_3n8v1c6t5j2w" } ``` A successful response returns the key once. `maxKeys` tells ZeroClick how many live keys this account may hold (the SDK sends `1` automatically when `remintPolicy` is `"rotating"`), and `keyExpiresAt` lets ZeroClick tell the buyer when to come back for a new one. Both are optional. ```json 200 theme={null} { "apiKey": "sk_live_…", "maxKeys": 1, "keyExpiresAt": "2027-08-01T00:00:00Z" } ``` ZeroClick passes the key straight to the buyer and never stores it. If the buyer needs it again, they ask for a new one and you mint again under your `remintPolicy`. ## The usage read (required for automatic top-ups) ```http GET /zeroclick/access/zacc_8h2m4x0q9k1f/usage theme={null} ``` Sent with `zc-signature`, `zc-agent-id` and `zc-request-id` headers, an empty body, and a signature whose purpose is `access.read`, so a write or mint signature can never be replayed as a read. ZeroClick calls it for accounts with an active top-up authorization (about every two minutes) and when a buyer enrolls in top-ups. Renewal-only sellers do not need this route. [Pushed balance reports](/docs/integrate/stateful-sellers#automatic-top-ups-reporting-the-balance) supplement polling. Without an `onRead` handler the TypeScript SDK answers `404 {"error":"balance_read_unavailable"}`. For Tempo automatic top-ups, a low balance alone does not authorize a charge. Tempo allows at most one refill of the approved amount per day; ZeroClick also checks the cooldown, monthly cap, and permission expiry. An immediate first top-up is an explicit choice when adding refills to an existing account and can occur before the balance falls below the threshold; other top-ups require a fresh low-balance reading. ```json 200 theme={null} { "accessId": "zacc_8h2m4x0q9k1f", "stateVersion": 7, "remainingCreditUsd": "3.250000", "observedAt": "2030-02-28T12:00:00.000Z" } ``` | Field | Meaning | | - | - | | `accessId` | Must echo the account in the path. | | `stateVersion` | The last account write you applied, read together with the balance. A reading for an older version is discarded. | | `remainingCreditUsd` | Spendable credit, six decimal places, never negative. | | `observedAt` | When you read the balance (normally now), with a UTC offset. Discarded if more than 5 minutes old or more than 30 seconds in the future. | Answer `404` for an account you do not know. The read must not mint keys or change state. Timeout is 5 seconds; a failing read is retried at a slower pace and never triggers a charge. ## What your handlers receive `WriteInput`, passed to `onWrite`: | Field | Meaning | | - | - | | `accessId` | The durable ZeroClick account handle. Key your account table on this. | | `agentId` | The agent making this call; may differ between calls to one account. Already checked against the signed `zc-agent-id`. | | `buyerId` | The body's `buyerId`: the owner behind the agent, or `null` until the credential is claimed. Already checked against the `zc-buyer-id` header. | | `buyerEmail` | The body's `buyerEmail`: the buyer's verified email, or `null` unless the plan requires one. Already checked against the `zc-buyer-email` header. | | `entitlement` | The parsed request body, plus `basePriceUsdMicros`, `lifetimeCreditGrantedUsdMicros`, and `lifetimeCreditReversedUsdMicros` as integers, and `period`, `status`, `lifetimeCreditGrantedUsd`, and `lifetimeCreditReversedUsd` lifted to the top level for convenience. | | `requestId` | The `zc-request-id` header. | | `dedupeKey` | `write:{requestId}`. A ready-made unique key if you keep a table of processed callbacks; deduplicating on `stateVersion` is still the rule that protects the account state. | | `kid` | Which signing secret verified this request. Useful for logging a rotation. | `MintInput`, passed to `onMint`, is the same minus `entitlement`, with `dedupeKey` of `mint:{requestId}`. Its `accessId` comes from the URL path rather than a body. ## What your handlers can return `onWrite`: | Return | Status | What ZeroClick does | | - | - | - | | `{ lifecycle: "active" }` | `200` | Acknowledges the applied state. ZeroClick finalizes the payment; the buyer may then request a key. | | `{ lifecycle: "provisioning", retryAfterSeconds }` | `200` | Sends the same write again after the hint, capped at 30 minutes. | | *throws* | `503` | Treated as temporary and retried. Your `onHandlerError` callback fires first. | `onMint`: | Return | Status | What ZeroClick does | | - | - | - | | `{ apiKey, keyExpiresAt? }` | `200` | Delivers the key to the buyer, with `cache-control: no-store`. | | `{ notProvisioned: true, retryAfterSeconds }` | `409` | The account exists but is not ready; the buyer is told to retry, default 5 seconds. | | `{ unknown: true }` | `404` | No such account. The mint fails — use this only when the account genuinely does not exist. | | `{ conflict: { code } }` | `409` | Your own refusal, with your code in the body. | | *throws* | `503` | The mint fails and `onHandlerError` fires. | Before either handler runs, the SDK answers `401` on a missing, stale, or invalid signature, and `400` if the body is malformed, its `agentId` does not match the signed `zc-agent-id`, its `buyerId` does not match the `zc-buyer-id` header, or its `buyerEmail` does not match the `zc-buyer-email` header. ## Retries, timeouts, and failures Account writes are **at-least-once**. Expect duplicates, and expect a retry after a network timeout that happened *after* you committed. | | Behavior | | - | - | | Response budget | **7 seconds** for both calls. Anything slower belongs behind `lifecycle: "provisioning"`. | | Retried | Network failure, `429`, any `5xx`, and a `200` whose body cannot be parsed. | | **Not** retried | Any other non-2xx, including `400`, `403`, and `404`. A bug that returns `400` permanently fails the delivery — return `503` when unsure. | | Backoff | Starts at 5 seconds and doubles with jitter, to a 30-minute ceiling. A `retryAfterSeconds` hint moves an attempt later, never sooner. | | Retry hints | A `Retry-After` header on a `429`/`5xx`, or `retryAfterSeconds` in a `200` body. Both are capped at 30 minutes. | | Giving up | After 20 attempts or 24 hours, whichever comes first. | | Redirects | Not followed. Serve the account routes directly. | | Signing-secret rotation | If your endpoint answers `401`, ZeroClick retries once with your newest active secret. See [rotating a signing secret](/docs/integrate/keys-and-secrets#rotate-a-signing-secret). | When a delivery permanently fails, **the buyer is made whole automatically**: a reserved payment is released, a captured one is refunded. You never owe a refund for an account you did not create. If the refund itself fails, ZeroClick flags the account internally and follows up — there is nothing for you to do. Because ZeroClick considers the write applied when you answer `200` with `lifecycle: "active"`, do not start anything irreversible after that point. ## Buyer-facing routes on your pay URL Your customer's agent uses these to manage a purchase, all on your pay URL (`https://acme.pay.zeroclick.io`) and all authenticated with the agent's own bearer token. You do not implement them — ZeroClick does — but you may want to point agents at them. | Route | What it does | | - | - | | `GET /purchases/receipt` | Lists every purchase this buyer holds with you: `accessId`, `provisioningState`, plan, access period, delivery status, plus a `redeemUrl` and a `topUpUrl` for each. | | `POST /keys/redeem` | Asks for an API key, which triggers your mint handler. `accessId` may be omitted when the buyer holds exactly one account with you. | | `POST /extend` | Tops up active access. For expired access, inspect the eligible purchase contract and recover the existing account before purchasing. `accessId` travels in the request body or in the URL's query — POSTing to the `topUpUrl` above as-is works, and a body value wins if both are present. It may be omitted entirely when the buyer holds exactly one account. | ## Free plans A `free_trial` plan creates an account with no payment. By default its [verified email policy](/docs/concepts/plans-and-pricing#the-verified-email-policy) is `required` — that is what stops one person minting unlimited free accounts — so its write arrives with `buyerEmail` set, and each human can claim it once. A seller may relax the policy per plan, accepting that unclaimed agents can then open trial accounts (the email then arrives on a later write once the human claims, under `requested`). Once created, the free account is durable and recoverable across the buyer's agents, just like a paid account. ## Signature, for stacks without an SDK The stateful helpers ship in the TypeScript (`@zeroclickai/sellers/stateful`), Python (`zeroclick_sellers.stateful`), Go (`cdn.zeroclick.io/sdks/sellers-go/stateful`), and Ruby (`zeroclick/sellers/stateful`) SDKs. On any other stack, implement the two routes and verify the signature yourself. It is HMAC-SHA256 over these seven lines joined by `\n` — the [ordinary canonical string](/docs/integrate/signature-spec#canonical-string) plus a trailing purpose: ``` {timestamp} {METHOD} {path and query, unnormalized} {lowercase hex SHA-256 of the raw body} {zc-request-id} {zc-agent-id} {access.write | access.mint} ``` | Route | Purpose | | - | - | | `POST {endpoint}` | `access.write` | | `POST {endpoint}/{accessId}/keys` | `access.mint` | Select the purpose from **the route you matched**, never from anything in the request. That is what stops a signature captured from ordinary proxied traffic from authorizing an account write. Compare against the `v1=` value in constant time, and reject a `t=` more than 5 minutes old or in the future. The header grammar, parsing rules, and raw-bytes rules are exactly those of the [signature spec](/docs/integrate/signature-spec) — only the trailing purpose line is new. Handler results map to the statuses in [what your handlers can return](#what-your-handlers-can-return); refuse a failed verification with a `401` and `{"error":"missing_or_malformed_signature"}`, `{"error":"stale_timestamp"}`, `{"error":"unknown_kid"}`, or `{"error":"invalid_signature"}`. ### Worked verifiers A compact verifier in the standard library — a porting reference for stacks without an SDK. (On Python and Go themselves, prefer the SDK's `verify_access_signature` / `stateful.Verify`.) Pass the purpose from the route you matched: ```python Python theme={null} import hashlib, hmac, os, re, time SIGNING_SECRETS = {"hsec_k5nq0v7m3d8p": os.environ["ZEROCLICK_SIGNING_SECRET"]} TOLERANCE_SECONDS = 300 def verify_access(method, raw_path_and_query, raw_body, headers, purpose): """purpose is "access.write" or "access.mint", from the matched route.""" header = headers.get("zc-signature") if header is None: return None members = {} for entry in header.split(","): key, sep, value = entry.partition("=") key = key.strip() if not sep or not key or key in members: # malformed or duplicate member return None members[key] = value.strip() # unknown members are ignored t, kid, v1 = members.get("t"), members.get("kid"), members.get("v1") if not (t and kid and v1): return None if not re.fullmatch(r"\d{1,20}", t) or not re.fullmatch(r"[0-9a-f]{64}", v1): return None if abs(int(time.time()) - int(t)) > TOLERANCE_SECONDS: return None request_id = headers.get("zc-request-id") if not request_id: return None agent_id = headers.get("zc-agent-id") or "" secret = SIGNING_SECRETS.get(kid) if secret is None: return None canonical = "\n".join([ t, method.upper(), raw_path_and_query, # as sent, never URL-decoded hashlib.sha256(raw_body).hexdigest(), request_id, agent_id, purpose, # the seventh line ]) expected = hmac.new(secret.encode(), canonical.encode(), hashlib.sha256).hexdigest() if not hmac.compare_digest(expected, v1): return None return {"zc_request_id": request_id, "zc_agent_id": agent_id} ``` ```go Go theme={null} var signingSecrets = map[string]string{ "hsec_k5nq0v7m3d8p": os.Getenv("ZEROCLICK_SIGNING_SECRET"), } const toleranceSeconds = 300 // purpose is "access.write" or "access.mint", from the matched route. func verifyAccess(r *http.Request, rawPathAndQuery string, rawBody []byte, purpose string) bool { members := map[string]string{} for _, part := range strings.Split(r.Header.Get("zc-signature"), ",") { key, value, found := strings.Cut(part, "=") key = strings.TrimSpace(key) if !found || key == "" { return false // malformed member } if _, duplicate := members[key]; duplicate { return false // duplicate member; unknown members are ignored } members[key] = strings.TrimSpace(value) } t, kid, v1 := members["t"], members["kid"], members["v1"] if t == "" || len(t) > 20 || kid == "" || len(v1) != 64 { return false } timestamp, err := strconv.ParseUint(t, 10, 64) if err != nil { return false } if delta := time.Now().Unix() - int64(timestamp); delta > toleranceSeconds || delta < -toleranceSeconds { return false } requestID := r.Header.Get("zc-request-id") if requestID == "" { return false } agentID := r.Header.Get("zc-agent-id") secret, ok := signingSecrets[kid] if !ok || secret == "" { return false } bodyDigest := sha256.Sum256(rawBody) canonical := strings.Join([]string{ t, strings.ToUpper(r.Method), rawPathAndQuery, // as sent, never URL-decoded hex.EncodeToString(bodyDigest[:]), requestID, agentID, purpose, // the seventh line }, "\n") mac := hmac.New(sha256.New, []byte(secret)) mac.Write([]byte(canonical)) expected, err := hex.DecodeString(v1) if err != nil { return false } return hmac.Equal(expected, mac.Sum(nil)) } ``` The dedup, never-regress, and credit-delta arithmetic from [the account write](#the-account-write) still apply on these stacks — implement `shouldApply`, `isServiceable`, and `deriveCreditDelta` from their descriptions there, and keep money in integer micros, never floats. ### Worked test vector The ids and secret below are test fixtures in the style of the [signature spec's vector](/docs/integrate/signature-spec#worked-test-vector); production values look the same. Signing secret: ```text theme={null} kid: hsec_k5nq0v7m3d8p secret: zcsec_vector_secret_do_not_use_in_production ``` Request: ```text theme={null} POST /zeroclick/access zc-request-id: zacc_8h2m4x0q9k1f:3 zc-agent-id: agt_x7f2kq93bh0d zc-signature: t=1760000000,kid=hsec_k5nq0v7m3d8p,v1=f988cc7ebd64478e75502297a81d7e85d3c41535d2ed8c88c21024e21eb0c477 ``` Body (exactly these 430 bytes, one line, no trailing newline): ```json theme={null} {"accessId":"zacc_8h2m4x0q9k1f","agentId":"agt_x7f2kq93bh0d","buyerId":null,"buyerEmail":null,"idempotencyKey":"zacc_8h2m4x0q9k1f:3","stateVersion":3,"plan":{"slug":"research-pro","name":"Research Pro","billingMode":"credit","interval":"none","basePriceUsd":"20.000000"},"state":{"period":{"start":"2026-08-01T00:00:00Z","end":null},"lifetimeCreditGrantedUsd":"45.000000","lifetimeCreditReversedUsd":"0.000000","status":"active"}} ``` Its SHA-256 is `19c2447c4bcd377389b0c7f06660b54e33eacb06a39b6c8ffdfed39936b66e3c`, and the matched route is the write route, so the canonical string is: ```text theme={null} 1760000000 POST /zeroclick/access 19c2447c4bcd377389b0c7f06660b54e33eacb06a39b6c8ffdfed39936b66e3c zacc_8h2m4x0q9k1f:3 agt_x7f2kq93bh0d access.write ``` Expected result: with the verifier's clock pinned to `1760000000` and tolerance `300`, the HMAC-SHA256 of the canonical string with the secret equals the header's `v1`. Verification succeeds. Your implementation must also refuse two signatures over the same request. Signed with no purpose line — what ZeroClick sends with ordinary proxied traffic — `v1` is `70969f4352049b371bfd6fcff35eb4409c12cc08c734ad0889a79de1708e54a6`; your access verifier must reject it. Signed for the other purpose (`access.mint`), `v1` is `1c3fb09f2d2983a1f725d5459ea2743c61de2aaf79699e171bfd7d15ce0b196e`; a mint signature must never authorize a write, nor the reverse. # Supported countries Source: https://zeroclickai.mintlify.dev/docs/resources/supported-countries Where your business can be based to accept agent payments and receive payouts, by payment method. Agents pay through ZeroClick with cards or with USDC stablecoins, and your revenue settles to your own connected payout account. Which payment methods are available to you depends on the country where your business is legally established. > [!NOTE] > > You do not need a pre-existing Stripe account to sell through ZeroClick. Payment setup is part of onboarding: you complete it from the dashboard and add a bank account for payouts. A seller needs only one available payment method to go live, and agents see only the methods your storefront supports. ## Availability by country Agents pay in three ways: * **Card checkout**: a checkout page hosted by Stripe, which the agent pays in a browser or hands to its human. * **Shared payment tokens (SPTs)**: a scoped card credential the buyer grants their agent, paid over MPP without a browser. * **Stablecoins**: USDC over x402 and MPP. | Country | Card checkout | SPTs | Stablecoins | | - | - | - | - | | 🇺🇸 United States | Yes | Yes | Yes, except New York | | 🇨🇦 Canada | Yes | Yes | No | | 🇬🇧 United Kingdom | Yes | Yes | No | | 🇦🇺 Australia | Yes | No | No | | 🇦🇹 Austria | Yes | Yes | On request | | 🇧🇪 Belgium | Yes | Yes | On request | | 🇧🇬 Bulgaria | Yes | Yes | On request | | 🇭🇷 Croatia | Yes | Yes | On request | | 🇨🇾 Cyprus | Yes | Yes | On request | | 🇨🇿 Czechia | Yes | Yes | On request | | 🇩🇰 Denmark | Yes | Yes | On request | | 🇪🇪 Estonia | Yes | Yes | On request | | 🇫🇮 Finland | Yes | Yes | On request | | 🇫🇷 France | Yes | Yes | On request | | 🇩🇪 Germany | Yes | Yes | On request | | 🇬🇮 Gibraltar | Yes | Yes | On request | | 🇬🇷 Greece | Yes | Yes | On request | | 🇭🇰 Hong Kong | Yes | No | On request | | 🇭🇺 Hungary | Yes | Yes | On request | | 🇮🇪 Ireland | Yes | Yes | On request | | 🇮🇹 Italy | Yes | Yes | On request | | 🇯🇵 Japan | Yes | No | No | | 🇱🇻 Latvia | Yes | Yes | On request | | 🇱🇮 Liechtenstein | Yes | Yes | On request | | 🇱🇹 Lithuania | Yes | Yes | On request | | 🇱🇺 Luxembourg | Yes | Yes | On request | | 🇲🇹 Malta | Yes | Yes | On request | | 🇲🇽 Mexico | Yes | No | On request | | 🇳🇱 Netherlands | Yes | Yes | On request | | 🇳🇿 New Zealand | Yes | No | No | | 🇳🇴 Norway | Yes | Yes | On request | | 🇵🇱 Poland | Yes | Yes | On request | | 🇵🇹 Portugal | Yes | Yes | On request | | 🇷🇴 Romania | Yes | Yes | On request | | 🇸🇬 Singapore | Yes | No | No | | 🇸🇰 Slovakia | Yes | Yes | No | | 🇸🇮 Slovenia | Yes | Yes | On request | | 🇪🇸 Spain | Yes | Yes | On request | | 🇸🇪 Sweden | Yes | Yes | On request | | 🇨🇭 Switzerland | Yes | Yes | On request | | 🇹🇭 Thailand | Yes | No | No | | 🇦🇪 United Arab Emirates | Yes | No | No | "On request" means we arrange access for your business: contact your account representative or email [help@zeroclick.ai](mailto:help@zeroclick.ai). "No" means that payment method is not offered in that country today. ## Receiving payouts Revenue from agent purchases, card and stablecoin alike, settles in fiat to the bank account you add during onboarding. ## If your country is not listed Country support expands regularly. Reach out to your account representative or email [help@zeroclick.ai](mailto:help@zeroclick.ai) with the country where your business is established, and we will confirm what is available and set it up with you. # Go SDK API reference Source: https://zeroclickai.mintlify.dev/docs/sdks/go/api Every public identifier in the Go seller SDK: Client methods, package helpers, response builders, result types, and the jwe subpackage. Everything in `cdn.zeroclick.io/sdks/sellers-go`, importable as: ```go theme={null} import sellers "cdn.zeroclick.io/sdks/sellers-go" ``` The `Client` is safe for concurrent use: build it once with [`New`](/docs/sdks/go/configuration) and share it. Every decision flows through the framework-neutral [`Request`](#request) and [`Response`](#response) types, so the SDK works outside `net/http` too. `FromHTTP` is only the `net/http` adapter, and the [`Meter` and `Identify` middleware](/docs/sdks/go/middleware) are packaged versions of the same calls. Guards return decisions, not errors: an unsigned or unpayable request is an expected event on a public endpoint, so it comes back as a result carrying the exact `Response` to return. The SDK reserves errors for your own misconfiguration and for ZeroClick API failures. See [Go SDK errors](/docs/sdks/go/errors). ## Client methods ### Guard ```go theme={null} func (c *Client) Guard(ctx context.Context, request *Request, serviceSlug string, usage []UsageItem, planSlug string) (GuardResult, error) ``` The one call a billable endpoint needs: it verifies the signature, then checks that the buyer's allowance covers `usage`, before any work happens. Verification always runs first: a request that fails it never reaches the allowance API. `planSlug` may be empty. ```go theme={null} result, err := seller.Guard(r.Context(), sellers.FromHTTP(r, body), "product-watch", []sellers.UsageItem{{MeterSlug: "requests", Quantity: 1}}, "") if err != nil { // The usage list was malformed, or Policy is PolicyThrow. http.Error(w, `{"error":"internal_error"}`, http.StatusInternalServerError) return } if !result.OK { result.Response.WriteTo(w) return } // Serve the request. result.Context.AgentID is the buyer, // result.Context.RequestID correlates with ZeroClick's logs. ``` `body` must be the raw request bytes, read in full before the call. The middleware bounds that read for you. When you call `Guard` directly, bound the read yourself (for example with `http.MaxBytesReader`). Declaring an exact `Quantity` lets ZeroClick offer the `exact` x402 payment scheme. A `MaxQuantity` forces `upto`, which fewer clients can pay. Prefer a fixed per-request charge, and report variable work afterwards with [`ReportUsage`](#reportusage). See [charge up to a maximum](/docs/integrate/charge-up-to-a-maximum). > [!NOTE] > > `Guard` deliberately severs the caller's cancellation for the allowance check: it wraps `ctx` with `context.WithoutCancel` and applies its own `CheckTimeout`. Inheriting cancellation meant a client disconnect, or any proxy-side timeout, short-circuited the check before it was even sent. Under the `allow` policy the request was served anyway: a buyer who would have been denied got served, and the API was never asked. The check's own timeout still bounds it. [`CheckAllowance`](#checkallowance) keeps the caller's context, because it surfaces the error instead of applying a policy to it. The SDK still honors a denial with a reason it does not recognize: `allowed` is legible on its own, and the unfamiliar reason passes through in `GuardResult.Reason` for you to log. Rejecting the whole response on an unfamiliar reason would turn a denial into an allow the day ZeroClick adds a new one. An additive server change must stay additive. ### GuardIdentity ```go theme={null} func (c *Client) GuardIdentity(request *Request, serviceSlug string) (GuardResult, error) ``` Guards a free endpoint that must still know which buyer is calling, such as a limits or account route. It makes no network call. A signed request with no `zc-agent-id` is an anonymous probe: valid, but it has not established a buyer. `GuardIdentity` answers it with a `402` carrying an empty usage list (`Reason` is `identity_required`). ZeroClick turns that into `401 bearer_required` with its registration recipe, and the agent retries with a credential, so its `zc-agent-id` is attached. No payment is involved. A signed request that does carry a buyer passes with `Outcome` set to `OutcomeNotRequired`. See [free and identity endpoints](/docs/integrate/free-and-identity-endpoints). ### Verify ```go theme={null} func (c *Client) Verify(request *Request) (VerifyResult, error) ``` Verifies the request's signature using the client's secrets, tolerance, and clock; it does nothing else. Use it directly only for endpoints that bill nothing. Anything billable should go through [`Guard`](#guard), which also checks that the buyer can pay. The package-level [`Verify`](#verify-package-function) does the same without a `Client`. ### CheckAllowance ```go theme={null} func (c *Client) CheckAllowance(ctx context.Context, requestID, serviceSlug string, usage []UsageItem) (AllowanceDecision, error) ``` Asks the allowance API directly, without verifying a request and without applying the outage policy. Errors surface for you to handle, classified with [`IsAllowanceUnavailable`](#isallowanceunavailable). It keeps the caller's context, bounded by `CheckTimeout`. Checking records nothing and burns no credit. [`Guard`](#guard) is what an endpoint should use; this is for sellers driving the check themselves. ```go theme={null} decision, err := seller.CheckAllowance(ctx, "zcreq_8h2m4x0q9k1f", "product-watch", []sellers.UsageItem{{MeterSlug: "output_tokens", MaxQuantity: 4096}}) if err != nil { // No usable answer; classify with sellers.IsAllowanceUnavailable(err). } if !decision.Allowed { // decision.Reason, e.g. "usage_exhausted" } ``` ### ReportUsage ```go theme={null} func (c *Client) ReportUsage(ctx context.Context, input ReportUsageInput) (ReportUsageResult, error) ``` Records usage out of band, after the response has gone out. This is how a seller bills for work whose amount is only known once it is done (pages extracted, tokens produced). The seller still declares a fixed per-request charge to the guard, so the `exact` scheme stays available. `CheckTimeout` bounds the call, and the write-scoped key authenticates it. ```go theme={null} _, err := seller.ReportUsage(sellers.BackgroundContext(r), sellers.ReportUsageInput{ AgentID: zc.AgentID, ServiceSlug: "product-watch", MeterSlug: "output_tokens", Quantity: tokens, IdempotencyKey: zc.RequestID + "_output_tokens", // derived, never random }) ``` Reports are idempotent on `IdempotencyKey`: a retried report replays the stored event with `Duplicate: true`, which is a success, not a failure. Derive the key from the request id and the meter: a random key double-bills on retry. A failure here means work was delivered and not billed. Log it with the reason; do not fail the request the buyer already received. ### Meter ```go theme={null} func (c *Client) Meter(usage ...UsageItem) func(http.Handler) http.Handler ``` Middleware that guards a billable endpoint: it verifies the signature, checks that the buyer can pay, and, if the handler responds 2xx, settles the declared usage via the `zc-usage` response header. It takes fixed quantities only. If handed an [`UpTo`](#perrequest-and-upto) item or a non-positive quantity, it panics at wire-up. Covered in depth in [Go SDK middleware](/docs/sdks/go/middleware). ### Identify ```go theme={null} func (c *Client) Identify() func(http.Handler) http.Handler ``` Middleware form of [`GuardIdentity`](#guardidentity), for free identity-scoped endpoints. Also covered in [Go SDK middleware](/docs/sdks/go/middleware). ## Request helpers ### FromHTTP ```go theme={null} func FromHTTP(r *http.Request, body []byte) *Request ``` Builds a [`Request`](#request) from a server-side `*http.Request` and an already-read body. It reads `r.RequestURI`, which is the raw percent-encoded request target exactly as it arrived. `r.URL.Path` is decoded and would break verification for any target containing an encoded character. On a hand-built request (where `RequestURI` is unset), it falls back to the escaped path plus raw query, which is exact unless the path held an encoded slash. ### FromContext ```go theme={null} func FromContext(ctx context.Context) (Context, bool) ``` Returns what a guarded request proved about its caller; `ok` is false on an unguarded route. ```go theme={null} zc, ok := sellers.FromContext(r.Context()) // zc.AgentID: the buyer (agt_…) // zc.RequestID: correlates with ZeroClick's logs; use it for idempotency keys ``` ### BackgroundContext ```go theme={null} func BackgroundContext(r *http.Request) context.Context ``` Returns a context for work that outlives the response, such as reporting usage after the buyer has their result. It is `context.WithoutCancel(r.Context())`: context values survive, cancellation does not. Deriving from `r.Context()` would not work: the server cancels that context the moment the handler returns. The report would be dropped, and the work would go unbilled with nothing in the logs to say so. ## Usage constructors ### PerRequest and UpTo ```go theme={null} func PerRequest(meterSlug string, quantity int) UsageItem func UpTo(meterSlug string, maxQuantity int) UsageItem ``` `PerRequest` declares a fixed charge, which is what lets ZeroClick offer the `exact` x402 scheme. `UpTo` declares a ceiling for work whose cost is unknown until it is done. It settles at the amount actually reported, so a ceiling never overcharges. But it forces the `upto` scheme, which fewer clients can pay, and [`Meter`](#meter) rejects it because a ceiling has no settled quantity. Prefer `PerRequest` plus [`ReportUsage`](#reportusage) for the variable part. ## Signing secret helpers ### SecretsFromEnv and ParseSigningSecrets ```go theme={null} func SecretsFromEnv() (map[string]string, error) func ParseSigningSecrets(raw string) (map[string]string, error) ``` `SecretsFromEnv` parses the `ZEROCLICK_SIGNING_SECRETS` environment variable (the constant `SigningSecretsEnv`), which holds `:` pairs, comma-separated. Listing more than one is how a rotation survives. `ParseSigningSecrets` parses the same format from any source, such as a secret manager. Entries split on the first colon only, so secrets containing colons are safe, and parse errors never echo the value. See [configuration](/docs/sdks/go/configuration) for the format and rotation examples. ### SigningSecrets ```go theme={null} func SigningSecrets(secrets map[string]string) ResolveSigningSecret ``` Adapts a static map to the `ResolveSigningSecret` resolver signature, for use with the package-level [`Verify`](#verify-package-function). `Config.SigningSecrets` applies this adapter for you. ```go theme={null} type ResolveSigningSecret func(kid string) (secret string, ok bool, err error) ``` `ok == false` means the key id is unknown (a refusal); a non-nil error means the lookup itself failed, such as a vault being unreachable (a fault). ## Response builders `Guard` and the middleware build these responses for you; use them directly when you drive the flow yourself. ### PaymentRequired ```go theme={null} func PaymentRequired(serviceSlug string, usage []UsageItem, planSlug string) (*Response, error) ``` The `402` that tells ZeroClick what this request would cost: `{"error":"payment_required","serviceSlug":…,"usage":[…]}`, with `planSlug` included when non-empty. ZeroClick reads the usage list, prices it, and issues the buyer an x402 or MPP challenge; the buyer never sees this body. Return it **before** doing the work: a `402` after the fact means the work is done and unpaid. An empty usage list is meaningful, not a mistake: it is the free identity-scoped refusal, answered with `401 bearer_required` and never a charge. ```go theme={null} response, err := sellers.PaymentRequired("product-watch", []sellers.UsageItem{{MeterSlug: "requests", Quantity: 1}}, "") ``` ### MustPaymentRequired ```go theme={null} func MustPaymentRequired(serviceSlug string, usage []UsageItem, planSlug string) *Response ``` [`PaymentRequired`](#paymentrequired) for a usage list built from constants, where a validation failure is a bug rather than a runtime condition. It panics instead of returning an error. ### InvalidSignature ```go theme={null} func InvalidSignature() *Response ``` The `401 {"error":"invalid_zeroclick_signature"}` for a request that did not prove it came from ZeroClick. The body says nothing about why, deliberately. Your logs carry the [`FailureReason`](/docs/sdks/go/errors). ### AllowanceUnavailable ```go theme={null} func AllowanceUnavailable() *Response ``` The `503 {"error":"allowance_unavailable"}` for "we could not reach the allowance API", as distinct from "the allowance API said no". The SDK returns it only under `PolicyDeny`. ### WithUsage and UsageHeader ```go theme={null} func WithUsage(response *Response, usage []SyncUsageItem) (*Response, error) func UsageHeader(usage []SyncUsageItem) (string, error) ``` `UsageHeader` renders the `zc-usage` header value: what this response actually consumed, settled against whatever was authorized. `WithUsage` attaches it to a response. Set it only on a response that delivered: a `4xx` for input you rejected must not carry it, because that bills the buyer for a refusal. The [`Meter`](#meter) middleware does this for you on 2xx responses. ```go theme={null} response, err := sellers.WithUsage(sellers.JSON(200, result), []sellers.SyncUsageItem{ {ServiceSlug: "product-watch", MeterSlug: "requests", Quantity: 1}, }) ``` ### JSON ```go theme={null} func JSON(status int, payload any) *Response ``` Builds a JSON [`Response`](#response) with the `content-type` header set. It panics only on a payload that cannot be marshalled, which is a programming error rather than a runtime condition. ## Verification primitives ### Verify (package function) ```go theme={null} func Verify(req *Request, opts VerifyOptions) (VerifyResult, error) type VerifyOptions struct { Resolve ResolveSigningSecret // required ToleranceSeconds int // 0 means 300 Now func() time.Time // nil means time.Now } ``` Verifies a ZeroClick signature over an already-read body, without a `Client`; no API key is needed. The body must be the raw bytes as received: re-serialized JSON will not match, because the digest covers bytes, not meaning. The verifier parses the signature header additively: it ignores unknown members (ZeroClick appends fields such as the sandbox marker over time) and rejects duplicate members. The returned error is non-nil only for a resolver fault (wrapped in `ErrSecretResolution`) or a missing resolver; every authentication failure is a `VerifyResult` decision instead. ### CanonicalString ```go theme={null} func CanonicalString(timestamp, method, pathAndQuery string, body []byte, requestID, agentID string) string ``` Builds the exact bytes that get signed, as six newline-joined fields: the timestamp, the uppercased method, the raw percent-encoded path and query, the lowercase hex SHA-256 of the body bytes, the `zc-request-id` value, and the `zc-agent-id` value or empty string. Useful for debugging a verification mismatch or building your own verifier; the full wire format is in the [signature spec](/docs/integrate/signature-spec). ## Error helpers ### IsAllowanceUnavailable ```go theme={null} func IsAllowanceUnavailable(err error) bool ``` Reports whether an error means "the allowance API did not give us an answer", as opposed to "the API said no" or "we are misconfigured". Only that condition is subject to the configured outage policy. The full classification is on the [errors page](/docs/sdks/go/errors). ## Types ### Request ```go theme={null} type Request struct { Method string PathAndQuery string // raw, percent-encoded, exactly as it arrived Headers map[string][]string // an http.Header or any map Body []byte // raw bytes as received, before any parsing } func (r *Request) Header(name string) string ``` The framework-neutral view of an inbound request. `PathAndQuery` must be the raw percent-encoded target: the signature covers those bytes, and the decoded path most frameworks hand you hashes differently. [`FromHTTP`](#fromhttp) takes care of this for `net/http`. `Header` looks up the first value for a name, case-insensitively, whether `Headers` is an `http.Header` or a plain map. ### Response ```go theme={null} type Response struct { Status int Body []byte Headers map[string]string } func (r *Response) WriteTo(w http.ResponseWriter) error ``` The framework-neutral response you return to ZeroClick. `WriteTo` writes it to a `net/http` response writer; outside `net/http`, map the three fields onto your framework's response type. ### Context ```go theme={null} type Context struct { RequestID string // zcreq_…, the correlation id across ZeroClick and your logs AgentID string // agt_…; empty for a signed anonymous probe AnonymousID string // the same value as AgentID, under the name that will replace it BuyerID string // byr_…; the owner behind the agent, empty for an anonymous agent Timestamp int64 // the signature's unix-seconds timestamp KID string // which signing secret verified this request } ``` `AnonymousID` repeats `AgentID` under the name that will eventually replace `zc-agent-id`. `BuyerID` is the buyer that agent belongs to; unlike the fields above it is not covered by the signature. See [agents and access](/docs/concepts/agents-and-access). What a verified request proved. `AgentID` is empty for a signed anonymous probe, which is valid: ZeroClick sends those when it checks your endpoints. Buyer calls always carry it. Test it with `== ""`, never against a sentinel: an absent header and a present-but-empty one both mean "no buyer identity" and both sign identically. ### GuardResult and GuardOutcome ```go theme={null} type GuardResult struct { OK bool Context Context Outcome GuardOutcome Reason string Response *Response // never nil when OK is false } const ( OutcomeAllowed GuardOutcome = "allowed" // the buyer's allowance covers this request OutcomeUnavailable GuardOutcome = "unavailable" // no answer; the policy chose to serve, possibly unbilled OutcomeNotRequired GuardOutcome = "not_required" // identity proven; no allowance was needed ) ``` The guard's decision. Read `OK` first; when it is false, return `Response` verbatim and do no work. `Reason` is the denial code: a verification [`FailureReason`](/docs/sdks/go/errors), an allowance denial such as `usage_exhausted`, `identity_required` from [`GuardIdentity`](#guardidentity), or `allowance_unavailable` under `PolicyDeny`. Watch for `Outcome == OutcomeUnavailable` in logs and metrics: it means work is being done that may not be billed. ### VerifyResult ```go theme={null} type VerifyResult struct { OK bool Context Context Reason FailureReason // why the request was refused, for your logs Response *Response // the 401 to return, ready-built } ``` A decision, not an error. The errors page lists the [`FailureReason`](/docs/sdks/go/errors) values and explains why they are values rather than errors. ### UsageItem ```go theme={null} type UsageItem struct { MeterSlug string Quantity int MaxQuantity int } ``` What a request will be charged for. Set exactly one of `Quantity` or `MaxQuantity`, or neither to defer to the meter's configured per-request ceiling. A usage list must name at least one meter and may not repeat one. See [usage and allowances](/docs/concepts/usage-and-allowances) for how the three forms are priced. ### SyncUsageItem ```go theme={null} type SyncUsageItem struct { ServiceSlug string MeterSlug string Quantity int } ``` Actual usage reported alongside a successful response, in the `zc-usage` header. ### AllowanceDecision ```go theme={null} type AllowanceDecision struct { Allowed bool Reason string // a denial code, or "" when allowed } ``` ZeroClick's answer to an allowance check. The SDK exports the denial codes as constants: ```go theme={null} const ( DenialServiceNotFound = "service_not_found" DenialAccessNotFound = "access_not_found" DenialAccessInactive = "access_inactive" DenialPlanExpired = "plan_expired" DenialMeterNotFound = "meter_not_found" DenialMeterNotPriced = "meter_not_priced" DenialUsageExhausted = "usage_exhausted" ) ``` A reason outside this set passes through unchanged, and the decision still stands. ### ReportUsageInput and ReportUsageResult ```go theme={null} type ReportUsageInput struct { AgentID string // the buyer, from Context.AgentID ServiceSlug string MeterSlug string Quantity int // must be positive IdempotencyKey string // derive from the request id + meter, never random OccurredAt string // RFC 3339; empty means "now", decided server-side } type ReportUsageResult struct { Recorded bool Duplicate bool // the idempotency key had already landed: a success UsageEvent map[string]any // the recorded event, as returned by the API } ``` Input and outcome of [`ReportUsage`](#reportusage). ## Encrypted request bodies A buyer can [encrypt its request body end to end](/docs/concepts/end-to-end-encryption) with your public key. Encryption support lives in the separate `jwe` subpackage. The core package imports only the standard library. Go module pruning keeps `go-jose` out of your project until you import this package: ```go theme={null} import "cdn.zeroclick.io/sdks/sellers-go/jwe" ``` ```go theme={null} envelope, err := jwe.DecryptRequest(body, jwe.PrivateKeys(keys)) // envelope.Plaintext is the original request body; envelope.ReplyJWK is // non-nil when the buyer asked for an encrypted reply. reply, err := jwe.EncryptResponse(response, envelope) // Returns the response unchanged when no reply key was sent. ``` Verify the signature **before** decrypting: the signature covers the ciphertext as it arrived on the wire, not the plaintext. The cipher suite is pinned (ECDH-ES+A256KW key management, A256GCM content encryption), so a sender cannot negotiate something weaker. The [errors page](/docs/sdks/go/errors) lists the subpackage's error codes. > [!WARNING] > > Known limitation: `jwe.DecryptRequest` returns `decryption_failed` for an encrypted request whose plaintext is **empty**; every non-empty body works. This is a limitation of Go's JOSE libraries, not of the platform: ZeroClick permits empty-plaintext encrypted requests, and the TypeScript and Python SDKs decrypt them. If your endpoint accepts encrypted requests and a zero-length body is meaningful to it, handle that case before decrypting. # Go SDK configuration Source: https://zeroclickai.mintlify.dev/docs/sdks/go/configuration Every field of the Go seller SDK's Config: usage keys, signing secrets and rotation, body limits, the allowance outage policy, and timeouts. `sellers.New(sellers.Config{…})` builds the client. The config requires a usage key (or a both-scopes `APIKey`) and exactly one of `SigningSecrets` or `Resolve`. Everything else has a working default. `New` returns an error rather than defaulting past a bad config. A seller booting with no signing secret would accept nothing, and failing at startup is far cheaper than discovering that in traffic. `New` refuses a config that leaves either usage direction uncovered, sets both or neither of `SigningSecrets` and `Resolve`, contains an empty secret, or names an unknown `Policy`. ```go theme={null} seller, err := sellers.New(sellers.Config{ APIKey: os.Getenv("ZEROCLICK_API_KEY"), ServiceSlug: "product-watch", SigningSecrets: map[string]string{ "hsec_k5nq0v7m3d8p": os.Getenv("ZEROCLICK_SIGNING_SECRET"), }, Logger: log.Default(), }) if err != nil { log.Fatal(err) } ``` The client is safe for concurrent use; build it once at startup. ## Usage keys **APIKey** `string` A single API key (`zc_…`) carrying both the `usage:read` and `usage:write` scopes. It backfills whichever scoped key below is not set. **UsageReadKey** `string` A key with the `usage:read` scope, used for allowance checks (`Guard`, `CheckAllowance`). Falls back to `APIKey` when empty. **UsageWriteKey** `string` A key with the `usage:write` scope, used for usage reporting (`ReportUsage`), which often runs in a separate process such as a worker. Falls back to `APIKey` when empty. Provide `APIKey` alone, or provide the scoped keys and omit it. If either direction ends up with no key, `New` returns an error naming the missing side. ```go theme={null} // Least privilege: split keys, no both-scopes credential. seller, err := sellers.New(sellers.Config{ UsageReadKey: os.Getenv("ZEROCLICK_USAGE_READ_KEY"), UsageWriteKey: os.Getenv("ZEROCLICK_USAGE_WRITE_KEY"), ServiceSlug: "product-watch", SigningSecrets: map[string]string{ "hsec_k5nq0v7m3d8p": os.Getenv("ZEROCLICK_SIGNING_SECRET"), }, }) ``` See [keys and secrets](/docs/integrate/keys-and-secrets) for how the scopes map to the ZeroClick API. ## Service and plan **ServiceSlug** `string` The service these endpoints sell, as configured in ZeroClick. Required by the `Meter` and `Identify` middleware, which read it from the client. `Guard` takes a service slug per call instead, so a multi-service backend can share one client. **PlanSlug** `string` Optional. When set, the SDK offers this plan on the `402 payment_required` response, steering the buyer toward it. ## Signing secrets Provide exactly one of `SigningSecrets` or `Resolve`. **SigningSecrets** `map[string]string` A static map from key id (`kid`, format `hsec_…`) to secret value (`zcsec_…`). The kid appears in every request's `zc-signature` header, and the verifier uses it to select the secret. The map keys must match the key ids shown in your dashboard exactly. The client copies the map at construction; a later mutation of your map does not change which requests the client accepts. **Resolve** `ResolveSigningSecret` A per-kid lookup for secrets that live in a vault or database rather than a static map: ```go theme={null} type ResolveSigningSecret func(kid string) (secret string, ok bool, err error) ``` For a kid you do not recognize, return `ok == false`; the SDK refuses the request with a `401`. Return an error only when the lookup itself failed (the vault was unreachable). It surfaces as an error to your code, not as a refusal, so an infrastructure fault is never silently read as a forged request. Because the client consults `Resolve` on each request, rotated secrets take effect without a restart. ### Loading from the environment `SecretsFromEnv()` builds the map from the `ZEROCLICK_SIGNING_SECRETS` environment variable, which holds `:` pairs, comma-separated. The format carries the key id, so there is nothing to hardcode: ```sh theme={null} ZEROCLICK_SIGNING_SECRETS="hsec_k5nq0v7m3d8p:zcsec_…" ``` ```go theme={null} secrets, err := sellers.SecretsFromEnv() if err != nil { log.Fatal(err) } ``` `ParseSigningSecrets(raw string)` parses the same format from any source, for sellers reading the value from a secret manager instead of the environment. Each entry splits on the first colon only, because secrets may contain colons. Error messages never echo the value, so a config mistake does not put a secret in your logs. ### Rotation Hold both secrets while requests signed with either are still in flight, then drop the old one: ```go theme={null} SigningSecrets: map[string]string{ "hsec_k5nq0v7m3d8p": os.Getenv("ZEROCLICK_SIGNING_SECRET_CURRENT"), "hsec_w2j9r4t8b6mx": os.Getenv("ZEROCLICK_SIGNING_SECRET_PREVIOUS"), }, ``` Or, in the one-variable form: ```sh theme={null} ZEROCLICK_SIGNING_SECRETS="hsec_k5nq0v7m3d8p:zcsec_…,hsec_w2j9r4t8b6mx:zcsec_…" ``` Each request names its kid, so the verifier always picks the right secret. Rotation requires no downtime. ## Request body limit **MaxBodyBytes** `int64` (default: 10 MiB) Caps what a guarded endpoint will buffer. Zero means `DefaultMaxBodyBytes` (10 MiB). The signature covers the whole body, so the SDK must hold the whole body in memory to verify it. An attacker does not need a valid signature to make you buffer. This is a memory bound against unauthenticated callers, not a politeness limit. The SDK refuses a request over the cap with `413 {"error":"request_body_too_large"}` before verification. ## Allowance outage policy If the allowance API gives **no answer** (a timeout, a transport failure, a 5xx), `Policy` decides what happens. This is separate from the API answering *no*, which is always a `402`, and from your own misconfiguration, which is always an error. See [Go SDK errors](/docs/sdks/go/errors) for the exact classification. **Policy** `UnavailablePolicy` (default: PolicyAllow) | Policy | Behavior | | - | - | | `PolicyAllow` (default) | Serve the request. A ZeroClick outage should not take your API down with it. | | `PolicyDeny` | Refuse with `503 {"error":"allowance_unavailable"}`. Choose this when unbilled work costs more than a failed request. | | `PolicyThrow` | Surface the error and decide yourself. In the middleware, this becomes a `500`. | The guard consults the policy only after a signature verifies, so a fail-open allowance policy never becomes a fail-open signature policy. But every legitimate buyer request is signed, so `PolicyAllow` bounds free work to real traffic rather than to a small subset. Set `Logger` or `OnAllowanceUnavailable`, because a fail-open that is also silent is invisible unbilled traffic. **CheckTimeout** `time.Duration` (default: 1500ms) Bounds each allowance check (and each `ReportUsage` call). It sits in front of every billable request, so it is deliberately short: under the outage policy, a slow answer is worse than no answer. **OnAllowanceUnavailable** `func(error)` Called with the underlying error before the policy applies, so you can alarm on an outage you are choosing to absorb. ## Logging **Logger** `interface\{ Printf(string, ...any) \}` Receives conditions the SDK absorbs rather than surfaces: an allowance outage served under the allow policy, a guard failure the middleware turns into a `500`, a usage report that failed after the response was delivered. `*log.Logger` satisfies it, so `Logger: log.Default()` works. Nil discards these conditions, which makes unbilled traffic invisible; set it. ## Signature verification **ToleranceSeconds** `int` (default: 300) How far a signature's timestamp may drift from your clock, in either direction, before the SDK refuses the request as stale. See the [signature spec](/docs/integrate/signature-spec) for what the timestamp protects against. ## Plumbing **APIBaseURL** `string` (default: [https://api.zeroclick.io](https://api.zeroclick.io)) Base URL for the allowance and usage endpoints. Leave it unset in production. **HTTPClient** `*http.Client` The client used for ZeroClick API calls. Defaults to a plain `&http.Client{}`; per-call timeouts come from `CheckTimeout`. **Now** `func() time.Time` Clock override so tests can pin time. Defaults to `time.Now`. ## Defaults at a glance | Constant | Value | | - | - | | `DefaultAPIBaseURL` | `https://api.zeroclick.io` | | `DefaultToleranceSeconds` | `300` | | `DefaultCheckTimeout` | `1500 * time.Millisecond` | | `DefaultMaxBodyBytes` | `10 << 20` (10 MiB) | | `SigningSecretsEnv` | `ZEROCLICK_SIGNING_SECRETS` | | Default `Policy` | `PolicyAllow` | # Go SDK errors Source: https://zeroclickai.mintlify.dev/docs/sdks/go/errors How the Go seller SDK separates decisions from errors: the Error type, error codes, verification failure reasons, and outage classification. The Go SDK splits outcomes into decisions and errors, and the split is load-bearing. * **Decisions** are values. An unsigned request, a bad signature, a buyer who cannot pay: these are expected events on a public endpoint, not faults in your program. They come back as results (`VerifyResult`, `GuardResult`, `AllowanceDecision`) carrying the ready-to-return `Response`. Nothing to catch, nothing to recover. * **Errors** are reserved for what you got wrong (malformed input, bad configuration) and what the environment did (the ZeroClick API unreachable or answering nonsense). They are `*sellers.Error` values with a stable machine-readable code. This page covers the error side; the decision flow is on the [API reference](/docs/sdks/go/api). ## The Error type ```go theme={null} type Error struct { Code ErrorCode // stable classification; switch on this, not the message Operation string // the SDK call that failed: "new", "guard", "guard_identity", // "check_allowance", "report_usage" Status int // HTTP status from the ZeroClick API, or 0 if no response arrived Reason string // the API's own denial code, when it gave one Cause error // the underlying transport or decoding failure, if any } func (e *Error) Error() string func (e *Error) Unwrap() error ``` The message renders every populated field, for example: ```text theme={null} zeroclick: api_status_error during report_usage (status 402) (reason usage_exhausted) ``` `Unwrap` returns `Cause`, so `errors.Is` and `errors.As` see through to the underlying failure. ## Error codes The core package defines four codes: | Code | Meaning | | - | - | | `malformed_input` | You handed the SDK something invalid: a config `New` refuses, a usage list with a duplicate meter or with both `Quantity` and `MaxQuantity` set, a missing service slug or idempotency key. `Cause` explains what. | | `api_transport_error` | The call to the ZeroClick API never completed: timeout, DNS failure, connection refused, cancelled context. `Cause` holds the transport error. | | `api_status_error` | The API answered with a 4xx or 5xx. `Status` holds the code. For usage reports refused with `402`, `404`, or `409`, `Reason` carries the API's machine code: `402` for `access_inactive`, `plan_expired`, or `usage_exhausted`; `409` for `meter_not_priced`; otherwise `404`. | | `api_response_invalid` | The API answered, but with a body the SDK could not read as the documented shape: unparseable JSON, a missing field, an unrecognized error code on a typed status. | See [errors](/docs/resources/errors) for the control-plane error envelope these map from. ### jwe error codes The `jwe` subpackage (encrypted request bodies) adds its own codes, on the same `*sellers.Error` type with `Operation` set to `decrypt_request` or `encrypt_response`: | Code | Meaning | | - | - | | `invalid_compact_jwe` | The body is not a well-formed five-segment Compact JWE: wrong segment count, an empty segment, an undecodable protected header, or a parse failure. | | `unsupported_jwe_suite` | The header names an algorithm outside the pinned suite (ECDH-ES+A256KW key management, A256GCM content encryption). | | `jwe_kid_required` | The protected header carries no `kid`, so no private key can be selected. | | `invalid_reply_jwk` | The buyer's reply key is malformed: not an EC P-256 public key, unexpected members, or bad coordinates. | | `private_reply_jwk` | The reply key carries private key material. A protocol violation, refused outright rather than quietly used. | | `private_key_not_found` | Your resolver does not know the header's `kid`. `Reason` carries the kid. | | `private_key_resolution_failed` | The private-key lookup itself failed: a vault error, not a missing key. `Reason` carries the kid. | | `decryption_failed` | The suite and key were right, but decryption failed. `Reason` carries the kid. Also returned for an encrypted request whose plaintext is empty, a known Go JOSE-library limitation; see the [API reference](/docs/sdks/go/api). | | `encryption_failed` | Encrypting the reply to the buyer's key failed. | The SDK reports a nil private-key resolver as the core `malformed_input`. ## Verification refusals are decisions, not errors When a signature does not verify, `Verify` and `Guard` return a deny decision, not an error. `Reason` carries a `FailureReason` value saying why: | Reason | The request was refused because | | - | - | | `missing_signature` | No `zc-signature` header at all, which is typical for traffic that did not come through ZeroClick. | | `malformed_signature` | The header does not parse as `t=…,kid=…,v1=…`: a missing or duplicate member, a malformed timestamp, or a value that is not 64 lowercase hex characters. | | `stale_timestamp` | The signature's timestamp drifted more than `ToleranceSeconds` (default 300) from your clock, in either direction. | | `missing_request_id` | The `zc-request-id` header is absent. | | `unknown_kid` | Your secrets hold no entry for the signature's key id: commonly a secret rotated away too early, or an environment mismatch. | | `invalid_signature` | The HMAC did not match: the body, path, method, or ids differ from what ZeroClick signed, or the secret is wrong. A proxy that rewrites the raw request target is a common cause; see [Go SDK middleware](/docs/sdks/go/middleware). | Every one of these surfaces to the caller as the same `401 {"error":"invalid_zeroclick_signature"}` response. The body deliberately says nothing about why. The specific reason rides on `VerifyResult.Reason` and `GuardResult.Reason` for your logs. One verification path does produce an error rather than a refusal: a signing-secret **resolver fault**. If your `Resolve` function fails (a vault unreachable) or resolves an empty secret, `Verify` returns an error wrapping `ErrSecretResolution`. An infrastructure fault must not be silently read as a forged request: ```go theme={null} var ErrSecretResolution = errors.New("zeroclick: signing secret could not be resolved") ``` Test for it with `errors.Is(err, sellers.ErrSecretResolution)`. An *unknown* kid, by contrast, is an ordinary `unknown_kid` refusal. ## Allowance denials are decisions too `allowed: false` from the allowance API is always a `402` decision, never an error: `Guard` returns a deny result carrying the priced `payment_required` response, with `Reason` set to the denial code. The SDK exports the codes as the `Denial*` constants: `service_not_found`, `access_not_found`, `access_inactive`, `plan_expired`, `meter_not_found`, `meter_not_priced`, `usage_exhausted`. See [usage and allowances](/docs/concepts/usage-and-allowances) for what each means. The SDK still honors a denial whose reason it does not recognize: the decision stands, and the unfamiliar reason passes through for you to log. ## Outage classification `IsAllowanceUnavailable` answers one question: did the allowance API give **no answer**? Only that condition is subject to the configured outage `Policy` (see [configuration](/docs/sdks/go/configuration)). Everything else fails loudly, because conflating the cases all failed in the same direction: serving unbilled work. ```go theme={null} func IsAllowanceUnavailable(err error) bool ``` | Condition | Classification | | - | - | | Timeout, DNS failure, connection refused (`api_transport_error`) | No answer; the policy applies. | | `5xx`, `429`, or `408` from the API (`api_status_error`) | No answer: transient, genuinely worth failing open on. The policy applies. | | A response the SDK cannot read (`api_response_invalid`) | No answer: an answer that cannot be understood is no answer. The policy applies. | | Any other `4xx` (`api_status_error`): a revoked or wrong-environment API key, a suspended account, an unknown service | **Always an error.** Permanent, never self-heals, and every second of failing open makes the loss larger. | | `malformed_input` | **Always an error.** Your bug, not an outage. | | A cancelled context (`errors.Is(err, context.Canceled)`, at any depth) | **Not an outage.** The caller went away; authorizing work because nobody is listening is backwards. `Guard` runs the check on its own timeout regardless, so its real answer stands. | A readable decision with an unfamiliar reason never reaches this classification at all: the SDK honors it as a `402`, per the previous section. The guard consults the policy only after a signature verifies, so a fail-open allowance policy never becomes a fail-open signature policy. ## Patterns Inspect any SDK error by code: ```go theme={null} var zcErr *sellers.Error if errors.As(err, &zcErr) { log.Printf("zeroclick %s failed: code=%s status=%d reason=%s", zcErr.Operation, zcErr.Code, zcErr.Status, zcErr.Reason) } ``` `Unwrap` lets `errors.Is` reach the cause: ```go theme={null} if errors.Is(err, context.DeadlineExceeded) { // The check timeout (default 1.5 s) elapsed. } if errors.Is(err, sellers.ErrSecretResolution) { // The signing-secret lookup failed: alert on infrastructure, not on buyers. } ``` When you drive the check yourself, classify before deciding. This is exactly what `Guard` does internally with `Config.Policy`: ```go theme={null} decision, err := seller.CheckAllowance(ctx, zc.RequestID, "product-watch", []sellers.UsageItem{{MeterSlug: "requests", Quantity: 1}}) switch { case err == nil: // A real answer: decision.Allowed, decision.Reason. case sellers.IsAllowanceUnavailable(err): // No answer. Apply your own outage policy. default: // Misconfiguration or a permanent API refusal. Fix it; do not fail open. log.Printf("allowance check broken: %v", err) } ``` A failed `ReportUsage` deserves the same care in the other direction: the buyer already has their result. Log the error with its `Reason`, and retry later with the **same derived idempotency key** rather than failing the delivered request. A replay is a harmless `Duplicate: true`. See [settle usage](/docs/integrate/settle-usage). # Go SDK middleware Source: https://zeroclickai.mintlify.dev/docs/sdks/go/middleware What the Go SDK's Meter and Identify middleware do on every request: body handling, 2xx-only settlement, streaming support, and failure modes. The Go SDK packages the whole guard flow (verify, check allowance, serve, settle) as `net/http` middleware. `Meter` guards a billable endpoint; `Identify` guards a free endpoint that must still know which buyer is calling. Both return a plain `func(http.Handler) http.Handler`, the standard middleware shape, so they compose with `net/http`, chi, gorilla/mux, and anything else built on `http.Handler`. ```go theme={null} // Billable: one fixed charge per request. mux.Handle("/v1/product-watch", seller.Meter(sellers.PerRequest("requests", 1))( http.HandlerFunc(productWatch))) // Free, but identity-scoped: the caller must prove which buyer they are. mux.Handle("/v1/limits", seller.Identify()(http.HandlerFunc(limits))) ``` `Meter` needs `ServiceSlug` set on the client's [Config](/docs/sdks/go/configuration); it reads the service, plan, and body limit from there. ## What Meter does on every request In order: it reads the request body under the configured cap, verifies the `zc-signature` header over the raw bytes, and checks the buyer's allowance for the declared usage. Only then does it call your handler, with the body restored and the buyer in the request context. When your handler responds 2xx, it attaches the `zc-usage` header so the request settles. | Behavior | Why it matters | | - | - | | Restores `r.Body` after verification | The signature covers the raw bytes, so verifying consumes the body. Without this, your handler reads empty, and does so silently. | | `zc-usage` only on a 2xx | A 4xx is the buyer's bad input and a 5xx is your failure. Neither should bill. | | Bounds the body (`MaxBodyBytes`, default 10 MiB) | Verification needs the whole body in memory, and an attacker does not need a valid signature to make you buffer it. Over the cap, the middleware refuses the request with `413 {"error":"request_body_too_large"}` before verification. | | Puts the buyer in the request context | `sellers.FromContext(r.Context())` returns the verified `AgentID` and `RequestID`. | | Refuses before your handler runs | The middleware refuses an unsigned request before it ever consults the allowance API, and refuses an unpayable one before your code runs. Unpayable traffic never costs you work. | A refusal is the exact response ZeroClick expects: `401 {"error":"invalid_zeroclick_signature"}` for a failed verification, the priced `402 payment_required` body for an allowance denial, or `503 {"error":"allowance_unavailable"}` under a fail-closed outage policy. See [integrate your API](/docs/integrate/overview) for the bodies and when each one is returned. ## Fixed quantities only `Meter` settles exactly what it declares, so it takes fixed quantities only: `sellers.PerRequest(meter, n)` items. If handed an `UpTo` item or a non-positive quantity, it **panics at wire-up**. A ceiling has no settled quantity: it would bill zero, silently, on a delivered 200, which is the exact failure this SDK exists to prevent. The panic happens when you build the middleware, not in production traffic. For work you cannot size up front, declare the fixed part to `Meter` and report the variable part after responding. ## Billing for work you can't size up front Declare a fixed charge to the guard: that is what lets ZeroClick offer the `exact` payment scheme, which is the one clients can pay today. Then report the variable part with `ReportUsage` after the response has gone out. This example charges one `requests` unit per call synchronously and reports `output_tokens` afterwards: ```go theme={null} handler := func(w http.ResponseWriter, r *http.Request) { zc, _ := sellers.FromContext(r.Context()) tokens := 1842 // discovered by doing the work w.WriteHeader(http.StatusOK) fmt.Fprintf(w, `{"outputTokens":%d}`, tokens) // Reported AFTER the response. Two things matter here: // // 1. BackgroundContext, not r.Context(): the request context is // already cancelled, so the report would be silently dropped and // the tokens would go unbilled. // 2. An idempotency key derived from the request id, never random: // a retried report with a fresh key double-bills. _, err := seller.ReportUsage(sellers.BackgroundContext(r), sellers.ReportUsageInput{ AgentID: zc.AgentID, ServiceSlug: "product-watch", MeterSlug: "output_tokens", Quantity: tokens, IdempotencyKey: zc.RequestID + "_output_tokens", }) if err != nil { // Delivered but unbilled. Log it; do not fail a request the // buyer already has. log.Printf("output_tokens not reported: %v", err) } } http.Handle("/v1/product-watch", seller.Meter(sellers.PerRequest("requests", 1))( http.HandlerFunc(handler))) ``` Two things are easy to get wrong: > [!WARNING] > > Use `sellers.BackgroundContext(r)`, not `r.Context()`. The server cancels the request context the moment your handler returns, so a report on it is dropped and the work goes unbilled with nothing in the logs. > [!WARNING] > > Derive the idempotency key: `zc.RequestID + "_output_tokens"`, never a random value. A random key double-bills on retry; a derived key makes the retry a harmless duplicate. To let the buyer authorize a variable amount up front instead, see [charge up to a maximum](/docs/integrate/charge-up-to-a-maximum). That pattern uses `Guard` directly rather than `Meter`. ## Settling on 2xx only The middleware wraps your response writer and defers the `zc-usage` header until the status is known, because only a delivered response should be billed. A 4xx means you rejected the buyer's input, and a 5xx is your own failure. Charging for either bills someone for work they did not receive. Two edge cases the wrapper handles for you: * **A handler that writes nothing** still delivers a 200 (`net/http` emits it at the transport layer, below the wrapper), so the middleware settles it explicitly rather than letting the work ship unbilled. * **A handler that sets its own `zc-usage` header** wins: the middleware attaches the declared usage only when the header is not already present, so you can override the settled quantities for one response when you must. ## Streaming and WebSockets The wrapped writer implements `http.Flusher`, `http.Hijacker`, and `Unwrap` (for `http.ResponseController`), so streaming handlers work unchanged: * **Server-sent events**: a direct `w.(http.Flusher)` assertion, the long-standing streaming idiom, succeeds. `Flush` settles the usage header before the first byte leaves, because headers cannot follow the body. * **WebSocket upgrades**: `Hijack` works, but a hijacked connection leaves HTTP response semantics behind, so no `zc-usage` header can follow it. Meter the connection itself as the fixed charge and report anything per-message with `ReportUsage`. ## Identify `Identify` guards a free endpoint that must still know which buyer is calling, such as a limits or account route. It bounds and restores the body and verifies the signature exactly as `Meter` does, but makes no network call and settles nothing. A signed request with no `zc-agent-id` header is an anonymous probe: valid, but it has not established a buyer. `Identify` answers it with a `402` carrying an empty usage list. ZeroClick turns that into `401 bearer_required` with its registration recipe, and the agent retries with a credential, so its `zc-agent-id` is attached. No payment is involved. Your handler then finds the buyer with `sellers.FromContext`: ```go theme={null} func limits(w http.ResponseWriter, r *http.Request) { zc, _ := sellers.FromContext(r.Context()) w.Header().Set("content-type", "application/json") json.NewEncoder(w).Encode(map[string]any{"zcAgentId": zc.AgentID}) } ``` See [free and identity endpoints](/docs/integrate/free-and-identity-endpoints) for when to use this over an unguarded route. ## Failure modes | Condition | Response | | - | - | | Body exceeds `MaxBodyBytes`, or the client hung up mid-body | `413 {"error":"request_body_too_large"}`. The SDK cannot verify a signature over a body the server does not fully have. | | Signature missing, malformed, stale, or wrong | `401 {"error":"invalid_zeroclick_signature"}` | | Allowance denied | The priced `402 payment_required` body. | | Allowance API unreachable | Governed by `Policy`: served (default), `503 {"error":"allowance_unavailable"}`, or treated as an error. | | Guard returned an error: a malformed usage list, a signing-secret resolver fault, or `PolicyThrow` surfacing an outage | `500 {"error":"internal_error"}`, with the underlying error written to the configured `Logger`. Neither is the buyer's fault, and neither bills. | The full split between decisions and errors is on the [errors page](/docs/sdks/go/errors). ## Deploying behind a proxy > [!WARNING] > > The signature covers the raw, percent-encoded request target. The SDK reads `r.RequestURI`, which Go leaves untouched. But a reverse proxy, ingress, or load balancer in front of you may normalize the path (`%2F` becoming `/`) before your server sees it. If that happens, every request with an encoded path segment fails verification. If you route through nginx, an ingress controller, or a managed load balancer, confirm it passes the request target through unmodified. The [signature spec](/docs/integrate/signature-spec) specifies the exact bytes the signature covers. ## Reporting marketing page views `Meter` and `Identify` guard your billed API. To also measure the marketing pages agents and people read before they buy, the Go SDK ships `PageViews`, a `net/http` middleware in the same `func(http.Handler) http.Handler` shape: > [card] [Page views middleware](/docs/page-views/sdk-middleware) > > Report every page-content request from your site, fail-open. When you also run `Agentify`, wrap it so `PageViews` stays the outer layer and can observe agent reads. # Go SDK quickstart Source: https://zeroclickai.mintlify.dev/docs/sdks/go/quickstart Install the ZeroClick Go seller SDK and guard a net/http route with one middleware: verify the signature, check the allowance, and settle usage. The Go seller SDK ([`cdn.zeroclick.io/sdks/sellers-go`](https://pkg.go.dev/cdn.zeroclick.io/sdks/sellers-go)) implements the ZeroClick billing guard for Go backends. It verifies that a request really came from ZeroClick and checks that the buyer can pay before your handler runs. It returns the refusals ZeroClick expects and reports what was used. The usual integration is one middleware on each billable route. This page takes a `net/http` service from `go get` to guarded. The [quickstart](/docs/quickstart) covers the full setup, including the dashboard side, and [integrate your API](/docs/integrate/overview) describes the contract the SDK implements. ## Install ```sh theme={null} go get cdn.zeroclick.io/sdks/sellers-go ``` Requires Go 1.24 or newer. The core package imports only the standard library. The SDK's one third-party dependency (`go-jose`) belongs to the optional `jwe` subpackage for encrypted request bodies. Unless you import that package, Go's module graph pruning keeps it out of your `go.sum` and your binary. ## What you need first Two credentials from your [dashboard](https://dashboard.zeroclick.io): * A **signing secret**: a secret value (`zcsec_…`) and its key id (`hsec_…`), called the `kid`. The SDK uses it to verify the `zc-signature` header on every forwarded request. * An **API key** (`zc_…`) with the `usage:read` and `usage:write` scopes. The read scope covers allowance checks; the write scope covers usage reporting. `APIKey` carries both scopes. To follow least privilege, pass two scoped keys instead and omit `APIKey`: `UsageReadKey` for allowance checks and `UsageWriteKey` for usage reporting. The split is handy when a separate worker reports usage. A scoped key falls back to `APIKey` when it is not set, so either form works. See [keys and secrets](/docs/integrate/keys-and-secrets) for scopes and rotation. The dashboard shows each secret once, when you create it. `SecretsFromEnv()` reads signing secrets from one environment variable of `:` pairs, comma-separated: ```sh theme={null} export ZEROCLICK_SIGNING_SECRETS="hsec_k5nq0v7m3d8p:zcsec_…" export ZEROCLICK_API_KEY="zc_…" ``` ## The whole integration This example guards `/v1/product-watch` for a service `product-watch` with a meter `requests`, and leaves `/health` open. Substitute your own slugs. ```go main.go theme={null} package main import ( "encoding/json" "io" "log" "net/http" "os" sellers "cdn.zeroclick.io/sdks/sellers-go" ) func main() { secrets, err := sellers.SecretsFromEnv() // ZEROCLICK_SIGNING_SECRETS if err != nil { log.Fatal(err) } seller, err := sellers.New(sellers.Config{ APIKey: os.Getenv("ZEROCLICK_API_KEY"), ServiceSlug: "product-watch", SigningSecrets: secrets, Logger: log.Default(), }) if err != nil { log.Fatal(err) } mux := http.NewServeMux() // Unguarded: the platform's health probe is not a buyer. mux.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte(`{"status":"ok"}`)) }) // Billable. One fixed charge per request. mux.Handle("/v1/product-watch", seller.Meter(sellers.PerRequest("requests", 1))( http.HandlerFunc(productWatch))) log.Fatal(http.ListenAndServe(":8080", mux)) } func productWatch(w http.ResponseWriter, r *http.Request) { zc, _ := sellers.FromContext(r.Context()) // zc.AgentID, zc.RequestID body, _ := io.ReadAll(r.Body) // still readable log.Printf("watching %d bytes for %s", len(body), zc.AgentID) w.Header().Set("content-type", "application/json") json.NewEncoder(w).Encode(map[string]any{"productCount": 3}) } ``` On each request, `Meter` verifies the `zc-signature` header over the raw bytes, checks that the buyer's allowance covers one `requests` unit, and only then calls your handler. When a request fails either step, the middleware refuses it before your code runs, with the exact response ZeroClick expects: a `401` for a bad signature, a priced `402` for a business denial. When the handler responds 2xx, the middleware attaches the `zc-usage` header so the request settles. A 4xx or 5xx bills nothing. Inside the handler, `r.Body` reads normally: verification consumed it, and the middleware put it back. `sellers.FromContext` returns the verified buyer: `AgentID` (`agt_…`) and `RequestID` (`zcreq_…`), the id that correlates this request across ZeroClick's logs and your own. Test the guard locally: it must refuse a plain request with no ZeroClick headers. ```sh theme={null} curl -i localhost:8080/v1/product-watch -d '{}' ``` ```http theme={null} HTTP/1.1 401 Unauthorized Content-Type: application/json {"error":"invalid_zeroclick_signature"} ``` Only signed requests from ZeroClick reach your handler. To see paid traffic end to end (the `402` challenge, the payment, the forwarded request), deploy the route where ZeroClick can reach it and follow the verification step in the [quickstart](/docs/quickstart). ## Framework fit `Meter` (and its free counterpart `Identify`) returns a plain `func(http.Handler) http.Handler`, the standard middleware shape, so it composes with any router built on `net/http`: | Framework | Wire-up | | - | - | | `net/http` | `mux.Handle("/v1/product-watch", seller.Meter(…)(handler))` | | chi | `r.Use(seller.Meter(…))` | | gorilla/mux | `r.Use(seller.Meter(…))` | | Echo | `echo.WrapMiddleware(seller.Meter(…))` | | Gin | Wrap the guarded handler with `gin.WrapH` inside a `gin.HandlerFunc` | | Fiber | Not supported. Fiber runs on fasthttp, which has no `http.Handler` | Apply the middleware per billable route, not globally: health probes and other free endpoints should stay unguarded, and each metered route declares its own charge. For a backend not built on `net/http` at all, every decision also flows through the SDK's framework-neutral `Request` and `Response` types. See the [API reference](/docs/sdks/go/api). ## Next steps > [card] [Middleware](/docs/sdks/go/middleware) > > What Meter and Identify do on every request, streaming support, and variable usage. > [card] [Configuration](/docs/sdks/go/configuration) > > Every Config field: keys, signing secrets, body limits, and the outage policy. > [card] [API reference](/docs/sdks/go/api) > > The full public surface, including Guard and the framework-neutral types. > [card] [Errors](/docs/sdks/go/errors) > > Decisions versus errors, error codes, and outage classification. # Seller SDKs Source: https://zeroclickai.mintlify.dev/docs/sdks/overview ZeroClick seller SDKs for TypeScript, Python, Go, and Ruby, plus a community PHP SDK: install, shared behavior, and how to choose. The seller SDKs implement the ZeroClick billing guard in your backend: they verify that a request really came from ZeroClick, check that the buyer can pay before you do the work, build the refusal responses ZeroClick expects, and report what was used. All four speak the same wire protocol and make the same decisions; they differ only in language idiom. | SDK | Package | Install | Requires | | - | - | - | - | | TypeScript | [`@zeroclickai/sellers`](https://www.npmjs.com/package/@zeroclickai/sellers) | `pnpm add @zeroclickai/sellers` | ESM; web-standard `Request`, `Response`, `fetch`, Web Crypto (current Node.js and compatible edge runtimes) | | Python | [`zeroclick-sellers`](https://pypi.org/project/zeroclick-sellers/) | `pip install zeroclick-sellers` | Python 3.10+ | | Go | [`cdn.zeroclick.io/sdks/sellers-go`](https://pkg.go.dev/cdn.zeroclick.io/sdks/sellers-go) | `go get cdn.zeroclick.io/sdks/sellers-go` | Go 1.24+ | | Ruby | [`zeroclick-sellers`](https://rubygems.org/gems/zeroclick-sellers) | `gem "zeroclick-sellers"` | Ruby 3.1+; Rack middleware, so Rails, Sinatra, Hanami, Roda | All four are Apache-2.0 licensed. ## What every SDK does * **Verify first.** Every entry point verifies the `zc-signature` header before anything else. The signature is an HMAC-SHA256 over the raw request bytes. The SDK never checks an allowance for an unverified request. * **Decisions, not exceptions.** A guard returns an allow decision with the verified buyer context, or a deny decision that carries the exact response to return: `401` for a bad signature, the `402 payment_required` refusal for a business denial, or `503` under a fail-closed outage policy. Malformed configuration and API failures raise typed errors instead. * **Fail open by default.** If the allowance check fails without a usable answer, the configurable outage policy decides: `allow` (default), `deny`, or `throw`. A recognized `allowed: false` is always a `402`. The policy applies only after a signature verifies, so an unverified request is never served because the allowance API was down. The SDKs differ in how strictly they classify failures. The Go SDK treats any 4xx from the allowance API (a revoked key, an unknown service) as a hard error, never an outage. The TypeScript and Python SDKs route API errors through the policy. Each SDK's errors page documents its exact classification. * **Settle on success only.** Synchronous usage rides the `zc-usage` response header on 2xx responses; asynchronous usage goes through `reportUsage` with a seller-owned, derived idempotency key. No SDK retries automatically or invents idempotency keys. * **Split usage keys.** Pass one API key with both usage scopes, or a read key for guards and checks plus a write key for reporting. The split is useful when a separate worker reports usage. * **Encrypt bodies end to end.** Every official SDK can decrypt request JWE inside your backend and encrypt the response for the buyer. [ZeroClick never receives either private key](/docs/concepts/end-to-end-encryption). ## Differences that matter | | TypeScript | Python | Go | Ruby | | - | - | - | - | - | | Integration shape | Web-standard `Request` in, `Response` out; adapt your framework at the boundary | ASGI and WSGI adapters plus sync and async clients | Drop-in `net/http` middleware (`Meter`, `Identify`) | Drop-in Rack middleware (`Middleware::Meter`, `Middleware::Identify`) | | Framework fit | Hono, Next.js route handlers, edge runtimes, anything web-native | FastAPI and Starlette (async); Flask and Django (sync) | `net/http`, chi, gorilla/mux directly; Echo and Gin via adapters; Fiber unsupported | Rails, Sinatra, Hanami, Roda — anything Rack | | Concurrency model | async (Promises) | both: `create_seller` and `create_async_seller` | synchronous, context-aware | synchronous | | Runtime validation schemas | Zod schemas via `@zeroclickai/sellers/contracts` | frozen dataclasses with validation | typed structs | frozen value objects with validation | | Encryption helpers | `@zeroclickai/sellers/encryption` subpath | top-level functions | separate `jwe` subpackage, so the core stays stdlib-only | `zeroclick/sellers/encryption`, stdlib-only | | Secret loading helper | None | None | `SecretsFromEnv()` parses `ZEROCLICK_SIGNING_SECRETS` | `secrets_from_env` parses `ZEROCLICK_SIGNING_SECRETS` | | Stateful account helpers ([sell accounts and API keys](/docs/integrate/stateful-sellers)) | `@zeroclickai/sellers/stateful` subpath | `zeroclick_sellers.stateful` submodule, sync and async dispatchers | separate `stateful` subpackage, stdlib-only | `zeroclick/sellers/stateful`, stdlib-only | | [Agentify middleware](/docs/agentify/sdk-middleware) (serve marketing pages as agent markdown) | `withAgentify` handler wrapper | `AgentifyAsgiMiddleware` and `AgentifyWsgiMiddleware` adapters | `Agentify` net/http middleware | `Middleware::Agentify` Rack middleware | | [Page-views middleware](/docs/page-views/sdk-middleware) (report who reads your marketing pages) | `withPageViews` handler wrapper | `PageViewsAsgiMiddleware` and `PageViewsWsgiMiddleware` adapters | `PageViews` net/http middleware | `Middleware::PageViews` Rack middleware | Pick the SDK that matches your backend language. The core guard flow has the same capabilities in all four. If your backend is in another language entirely, the [REST walkthrough](/docs/integrate/rest-walkthrough) implements the same contract with plain HTTP. ## Community SDKs These are built and maintained by the community, not by ZeroClick. We list them because they work and because they serve languages we do not yet ship for — but they are outside our release process, so treat version upgrades as you would any third-party dependency. | Language | Package | Install | Maintainer | | - | - | - | - | | PHP | [`affiliatecom/zeroclick-sdk-sellers-php`](https://packagist.org/packages/affiliatecom/zeroclick-sdk-sellers-php) | `composer require affiliatecom/zeroclick-sdk-sellers-php` | [affiliatecom](https://github.com/affiliatecom/zeroclick-sdk-sellers-php), Apache-2.0 | ### PHP Requires PHP 8.3+. Ships PSR-15 middleware plus Laravel and Symfony bridges, and covers request verification, allowance checks, usage reporting, and encrypted request bodies. The [PHP quickstart](/docs/sdks/php/quickstart) walks the integration. We ran our shared signing conformance vectors — the same 29 cases every official SDK is checked against, including malformed-header and tampered-body cases — against it, and **all 29 agreed**. That covers the security-critical core: signature verification. Two things to know before you choose it: * **No stateful account helpers.** If you [sell accounts and API keys](/docs/integrate/stateful-sellers) rather than metering per call, you will need to implement those two routes yourself against the [reference](/docs/resources/stateful-access-reference). * **It carries runtime dependencies** (PSR HTTP interfaces, `php-http/discovery`, `psr/clock`), where the official SDKs deliberately carry none. They land in your `composer.json` alongside your own. Building a seller SDK for another language? [Tell us](mailto:help@zeroclick.ai) — we will list it here. ## Get started > [card] [TypeScript](/docs/sdks/typescript/quickstart) > > Web-native guard for Node.js and edge runtimes. > [card] [Python](/docs/sdks/python/quickstart) > > Sync and async clients with ASGI and WSGI adapters. > [card] [Go](/docs/sdks/go/quickstart) > > Standard middleware for net/http and friends. > [card] [Ruby](/docs/sdks/ruby/quickstart) > > Rack middleware for Rails, Sinatra, and Hanami. > [card] [PHP](/docs/sdks/php/quickstart) > > PSR-15 middleware for Laravel, Symfony, and Slim. Community-maintained. # PHP Source: https://zeroclickai.mintlify.dev/docs/sdks/php/quickstart Guard a PHP route with the community ZeroClick seller SDK: install, wire the client, and settle usage. > [!WARNING] > > **Community SDK.** [`affiliatecom/zeroclick-sdk-sellers-php`](https://packagist.org/packages/affiliatecom/zeroclick-sdk-sellers-php) > is built and maintained by [Affiliate.com](https://github.com/affiliatecom/zeroclick-sdk-sellers-php), > not by ZeroClick. We list it because PHP sellers asked for one and this one is > good — we verified its signature handling against our own conformance vectors > (see [below](#what-we-verified)) — but it is outside our release process, and > we do not review its updates. Treat version upgrades as you would any > third-party dependency. > > This page gets you integrated. For the full API, the maintainer's > [documentation](https://github.com/affiliatecom/zeroclick-sdk-sellers-php/tree/main/docs) > is the authority, and issues belong on their tracker. ## Install ```bash theme={null} composer require affiliatecom/zeroclick-sdk-sellers-php ``` Requires PHP 8.3+. It needs a PSR-18 HTTP client and PSR-17 factories; if you have none yet, add a pair: ```bash theme={null} composer require guzzlehttp/guzzle nyholm/psr7 ``` ## Configure Two values, and the first is two values in one. The signing credential is a key id and a secret joined by a colon — pasting in the secret alone is the common setup mistake. ```bash theme={null} ZEROCLICK_SIGNING_SECRETS=: ZEROCLICK_API_KEY=zc_live_... ``` Both come from your seller settings. [Keys and secrets](/docs/integrate/keys-and-secrets) covers rotation, which the format supports: comma-separate the pairs and both verify during the overlap. ## Wire the client, once ```php theme={null} use AffiliateCom\ZeroClick\Sellers\Config\Credentials; use AffiliateCom\ZeroClick\Sellers\Http\RefusalFactory; use AffiliateCom\ZeroClick\Sellers\Http\ServerRequestVerifier; use AffiliateCom\ZeroClick\Sellers\Http\Transport; use AffiliateCom\ZeroClick\Sellers\SellerClient; use AffiliateCom\ZeroClick\Sellers\Signature\SignatureVerifier; use AffiliateCom\ZeroClick\Sellers\Signature\SystemClock; use Nyholm\Psr7\Factory\Psr17Factory; $psr17 = new Psr17Factory(); $credentials = Credentials::fromEnvironment(getenv()); $refusals = new RefusalFactory($psr17, $psr17); $client = new SellerClient( credentials: $credentials, transport: Transport::discover(), verifier: new ServerRequestVerifier( verifier: new SignatureVerifier( secrets: $credentials->signingSecrets, refusals: $refusals, clock: new SystemClock(), ), refusals: $refusals, ), refusals: $refusals, ); ``` On Laravel or Symfony you write none of that — the package ships a service provider and a bundle that assemble it from config. See the maintainer's [middleware guide](https://github.com/affiliatecom/zeroclick-sdk-sellers-php/blob/main/docs/middleware.md). ## Guard a paid route The PSR-15 middleware performs the whole sequence in the order that matters, so no route can get it wrong or forget the last step: ```php theme={null} use AffiliateCom\ZeroClick\Sellers\Http\GuardMiddleware; use AffiliateCom\ZeroClick\Sellers\Usage\UsageItem; $guard = new GuardMiddleware($client, 'product-watch', [UsageItem::of('requests', 1)]); $response = $guard->process($request, $yourHandler); ``` A denied request comes back as the refusal, your handler never runs, and nothing is billed. A served one carries `zc-usage`, which is what turns the work into revenue. ## When the cost is not known upfront Declare a ceiling, then settle the real amount. ZeroClick authorises up to the ceiling and bills what you settle, so a ceiling never overcharges: ```php theme={null} use AffiliateCom\ZeroClick\Sellers\Usage\SyncUsageItem; use AffiliateCom\ZeroClick\Sellers\Usage\UsageItem; $result = $client->guard($request, 'product-watch', [UsageItem::upTo('rows', 500)]); if ($result->isDenied()) { return $result->response(); } $rows = doTheWork($request); return $client->withUsage($yourResponse, [ SyncUsageItem::of('product-watch', 'rows', count($rows)), ]); ``` A ceiling does **gate the buyer's authorisation**, though: the reserve is the ceiling, so a buyer whose per-call cap is below it is refused before any work happens. Keep it near a realistic worst case rather than as high as possible. ## Free endpoints that still need a caller ```php theme={null} $result = $client->guardIdentity($request, 'product-watch'); ``` No allowance call and no `zc-usage`. See [free and identity endpoints](/docs/integrate/free-and-identity-endpoints). ## Three things that cost money quietly The maintainer documents these prominently, and they are worth repeating because each is a silent failure rather than an error in a log: * **The default serves work you may never bill.** When the allowance API gives no usable answer, the package serves the request anyway — matching every official SDK, so a ZeroClick outage does not become your outage. Watch it with `onAllowanceUnavailable`, or choose `OutagePolicy::Deny` if refusing costs you less than serving for free. * **An unreported ceiling settles at zero.** `upTo()` authorises up to a limit and charges what you settle. Deliver without settling and that is zero — free for the buyer, unbilled for you, no error anywhere. * **A normalised request target fails verification.** ZeroClick signs the percent-encoded path and query exactly as sent. A framework or an ingress that decodes or reorders them breaks verification for those URLs only, in production only, as an unexplained `401`. The package faults loudly on the framework case; the proxy case is a deployment concern — nginx and several managed load balancers normalise `%2F` by default. See the maintainer's [raw request target](https://github.com/affiliatecom/zeroclick-sdk-sellers-php/blob/main/docs/raw-request-target.md). ## What we verified We ran our shared signing conformance vectors — the same 29 cases every official SDK is checked against, including malformed-header and tampered-body cases — against this package, and **all 29 agreed**. That covers signature verification: the part where a mistake means serving forged traffic. Two gaps to plan around, neither a defect: * **No stateful account helpers.** If you [sell accounts and API keys](/docs/integrate/stateful-sellers) rather than metering per call, implement those two routes yourself against the [reference](/docs/resources/stateful-access-reference). * **It carries runtime dependencies** — PSR HTTP interfaces, `php-http/discovery`, `psr/clock` — where the official SDKs deliberately carry none. They land in your `composer.json` beside your own. The maintainer also marks their catalog and analytics surfaces as unverified against a live server. Those are additions beyond what any official SDK offers; confirm them against a sandbox before depending on them. ## If you would rather not take a dependency The [REST walkthrough](/docs/integrate/rest-walkthrough) implements the same contract with plain HTTP and your standard library. The whole guard is one HMAC check and one HTTPS call. # Python SDK API reference Source: https://zeroclickai.mintlify.dev/docs/sdks/python/api Every public export of zeroclick-sellers: client methods, decision and data types, response builders, adapters, module defaults, and encryption helpers. Everything on this page imports from `zeroclick_sellers`, except the framework adapters, which live in `zeroclick_sellers.adapters`. See [configuration](/docs/sdks/python/configuration) for constructor options and [errors](/docs/sdks/python/errors) for error codes. `create_seller(**options)` returns a `SellerClient` (blocking, for WSGI); `create_async_seller(**options)` returns an `AsyncSellerClient` (non-blocking, for ASGI). The SDK exports both classes for type annotations. The methods below have identical signatures and semantics on both clients; on `AsyncSellerClient`, `guard`, `check_allowance`, and `report_usage` are coroutines you `await`. `guard_identity` and `verify_request` make no network call, so they are synchronous on both clients. ## Guard methods ### guard ```python theme={null} def guard( request: ZcRequest, *, service_slug: str, usage: Iterable[UsageItem], plan_slug: str | None = None, ) -> GuardResult ``` The whole billing guard in one call. It verifies the `zc-signature` header first, and only then checks the declared usage against the buyer's allowance with `POST /v1/usage/check`. The SDK never consults the allowance API for an unverified request. The result is a decision, not an exception: * **Deny, `401`**: a missing, malformed, stale, or invalid signature. * **Deny, `402`**: the allowance API answered `allowed: false`. The response is the exact `payment_required` body ZeroClick converts into a payment challenge, built from `service_slug`, `usage`, and `plan_slug`. * **Deny, `503`**: the allowance API gave no answer and the client's policy is `"deny"`. * **Allow**: carries the verified `context` and an `allowance` of `"allowed"` or `"unavailable"`. `usage` must contain at least one `UsageItem` and no duplicate meters; the allowance API accepts at most 20 items per check. When set, `plan_slug` appears in a denial's `402` body as `planSlug`. `guard` raises `ZCError` only for malformed input, a failing secret resolver, or an allowance outage under the `"throw"` policy. ```python theme={null} decision = await zeroclick.guard( # no await on the sync client zc_request, service_slug="product-watch", usage=[UsageItem(meter_slug="requests", quantity=1)], ) if decision.action == "deny": return to_fastapi(decision.response) result = do_the_work(owner=decision.context.zc_agent_id) ``` ### guard\_identity ```python theme={null} def guard_identity(request: ZcRequest, *, service_slug: str) -> GuardResult ``` Guards a [free, identity-scoped endpoint](/docs/integrate/free-and-identity-endpoints): one that costs nothing but must know which buyer is calling. It verifies the signature exactly like `guard`, makes no allowance call (so it is synchronous on both clients), and: * denies a bad signature with the `401` response, * denies a verified request without a buyer identity (reason `identity_required`) with the `402 payment_required` body carrying `usage: []`, which ZeroClick answers with `401 bearer_required` and never a charge, * allows an identified buyer with `allowance == "not_required"`, and in that case `decision.context.zc_agent_id` is always non-empty. ```python theme={null} decision = zeroclick.guard_identity(zc_request, service_slug="product-watch") if decision.action == "deny": return to_fastapi(decision.response) owner = decision.context.zc_agent_id ``` ### verify\_request ```python theme={null} def verify_request(request: ZcRequest) -> VerifyResult ``` Signature verification alone, using the client's secrets, tolerance, and clock. This is the first half of `guard`, for when you want to run the allowance check separately or not at all. It returns `VerifyOk` with the proven context, or `VerifyFailure` with a `reason` and the ready-to-return `401` response. The failure reasons are `missing_signature`, `malformed_signature`, `stale_timestamp`, `missing_request_id`, `unknown_kid`, and `invalid_signature`; every one maps to the same `401 {"error":"invalid_zeroclick_signature"}` body, so the reason is for your logs, not the caller. The HMAC comparison is constant-time. ```python theme={null} verification = zeroclick.verify_request(zc_request) if not verification.ok: return to_fastapi(verification.response) context = verification.context # zc_request_id, zc_agent_id, timestamp, kid ``` `verify_request` is also a standalone function for use without a client. It takes the same request plus its own configuration. Provide exactly one of `signing_secrets` or `resolve_signing_secret`, and optional `tolerance_seconds` (default 300) and `clock`: ```python theme={null} from zeroclick_sellers import verify_request verification = verify_request( zc_request, signing_secrets={"hsec_k5nq0v7m3d8p": os.environ["ZEROCLICK_SIGNING_SECRET"]}, ) ``` ## Usage API methods ### check\_allowance ```python theme={null} def check_allowance( *, zc_request_id: str, service_slug: str, usage: Iterable[UsageItem] ) -> AllowanceDecision ``` The [allowance check](/docs/integrate/check-allowances) alone, without verification or response-building. Use it for a second check partway through a multi-stage request, or when you have already verified. `zc_request_id` must be the id from the verified request's context. Checking records nothing and burns no credit. Unlike `guard`, any API failure raises `ZCError`: the outage policy applies only inside `guard`. ```python theme={null} decision = await zeroclick.check_allowance( zc_request_id=context.zc_request_id, service_slug="product-watch", usage=[UsageItem(meter_slug="output_tokens", max_quantity=100_000)], ) if not decision.allowed: ... # decision.reason, for example "usage_exhausted" ``` ### report\_usage ```python theme={null} def report_usage( *, zc_agent_id: str, idempotency_key: str, service_slug: str, meter_slug: str, quantity: int, occurred_at: str | None = None, ) -> ReportUsageResult ``` Reports usage asynchronously with `POST /v1/usage`, for work that finishes after the response has gone out. This is the alternative to [settling with the `zc-usage` header](/docs/integrate/settle-usage). All arguments are keyword-only. `quantity` is an integer of at least 1 (at most 2,147,483,647); `occurred_at` is an optional ISO 8601 timestamp. Reporting is idempotent per service on `idempotency_key`. Derive the key from stable facts (`zcreq_8h2m4x0q9k1f_output_tokens`, not a random value) so a retry of your own job cannot double-bill. `report_usage` does not generate idempotency keys and does not retry. A result with `duplicate=True` means the key already landed and the API returned the stored event. That is a success, not an error. A rejected report raises `ZCError`; see [errors](/docs/sdks/python/errors) for reading the status and reason. ```python theme={null} result = await zeroclick.report_usage( zc_agent_id="agt_x7f2kq93bh0d", idempotency_key="zcreq_8h2m4x0q9k1f_output_tokens", service_slug="product-watch", meter_slug="output_tokens", quantity=4200, ) result.recorded # True result.duplicate # True when this key was already reported: still a success ``` ## Response builders ### payment\_required ```python theme={null} def payment_required( *, service_slug: str, usage: Iterable[UsageItem], plan_slug: str | None = None ) -> ZcResponse ``` Builds the exact `402` refusal ZeroClick converts into a payment challenge, the same response a `guard` denial carries. Use it to deny for business reasons of your own. An empty `usage` is meaningful, not a mistake: it is the free identity-scoped refusal, which ZeroClick answers with `401 bearer_required` and never a charge. It is available as a static method on both clients and as a top-level import. ```python theme={null} response = zeroclick.payment_required( service_slug="product-watch", usage=[UsageItem(meter_slug="requests", quantity=1)], ) response.status # 402 response.json_body() # {"error": "payment_required", "serviceSlug": "product-watch", # "usage": [{"meterSlug": "requests", "quantity": 1}]} ``` ### with\_usage ```python theme={null} def with_usage(response: ZcResponse, usage: Iterable[SyncUsageItem]) -> ZcResponse ``` Returns a copy of the response with the `zc-usage` header attached: the synchronous settlement path. Attach it to `2xx` responses only; ZeroClick records the usage and strips the header before the agent sees the response. It is available as a static method on both clients and as a top-level import. ```python theme={null} stamped = zeroclick.with_usage( ZcResponse.json({"watching": True}), [SyncUsageItem(service_slug="product-watch", meter_slug="requests", quantity=1)], ) stamped.headers["zc-usage"] # '[{"serviceSlug":"product-watch","meterSlug":"requests","quantity":1}]' ``` ### Other builders * `usage_header(usage: Iterable[SyncUsageItem]) -> str`: the `zc-usage` header value alone, for stamping a framework response directly instead of going through `ZcResponse`. * `invalid_zeroclick_signature() -> ZcResponse`: the `401 {"error":"invalid_zeroclick_signature"}` response. Deny decisions already carry it; the export is for manual flows. * `allowance_unavailable() -> ZcResponse`: the `503 {"error":"allowance_unavailable"}` response the fail-closed outage policy uses. ## Request and response types All SDK types are frozen dataclasses: immutable after construction, validated in `__post_init__`, and comparable by value. ### ZcRequest ```python theme={null} @dataclass(frozen=True) class ZcRequest: method: str path_and_query: str headers: Mapping[str, str] = field(default_factory=dict) body: bytes = b"" ``` The framework-neutral view of an inbound request that every verification entry point consumes. Two rules matter: * `body` must be the raw bytes exactly as received. Passing anything else raises `ZCError` (`malformed_input`, "body must be bytes; decode nothing before verifying"). * `path_and_query` must be the raw, percent-encoded request target. Decoded paths fail verification; the [adapters](#framework-adapters) recover the raw target for you. The constructor lowercases header names, and `request.header(name)` looks up case-insensitively: ```python theme={null} zc_request = ZcRequest( method="POST", path_and_query="/v1/product-watch?fast=1", headers={"ZC-Request-Id": "zcreq_8h2m4x0q9k1f"}, body=b'{"productId":"prod_9d4k"}', ) zc_request.header("zc-request-id") # "zcreq_8h2m4x0q9k1f" ``` ### ZcResponse ```python theme={null} @dataclass(frozen=True) class ZcResponse: status: int body: bytes headers: Mapping[str, str] = field(default_factory=dict) ``` The framework-neutral response the SDK hands back; your adapter turns it into a real framework response. `ZcResponse.json(payload, *, status=200, headers=None)` builds one with compact JSON and a `content-type: application/json` header; `response.json_body()` parses the body back. ```python theme={null} response = ZcResponse.json({"watching": True}) response.status # 200 response.body # b'{"watching":true}' ``` ## Decision types ### GuardResult ```python theme={null} @dataclass(frozen=True) class Allow: context: ZeroClickContext allowance: Literal["allowed", "unavailable", "not_required"] action: Literal["allow"] = "allow" @dataclass(frozen=True) class Deny: reason: str response: ZcResponse action: Literal["deny"] = "deny" GuardResult = Allow | Deny ``` Discriminate on `action` (or match on the class). `Allow.allowance` tells you how the guard cleared the request: * `"allowed"`: the allowance API confirmed coverage. * `"unavailable"`: the allowance API gave no answer and the `"allow"` policy let the request through. * `"not_required"`: `guard_identity` allowed the request and made no allowance check. `Deny.reason` is one of the six verification failures (response `401`); one of the seven allowance denial reasons (`service_not_found`, `access_not_found`, `access_inactive`, `plan_expired`, `meter_not_found`, `meter_not_priced`, `usage_exhausted`) or `allowance_denied` when the API denies without a reason (response `402`); `allowance_unavailable` under the fail-closed policy (response `503`); or `identity_required` from `guard_identity` (response `402`). `Deny.response` is always ready to return as-is. ### VerifyResult ```python theme={null} @dataclass(frozen=True) class VerifyOk: context: ZeroClickContext ok: Literal[True] = True @dataclass(frozen=True) class VerifyFailure: reason: VerifyFailureReason response: ZcResponse ok: Literal[False] = False VerifyResult = VerifyOk | VerifyFailure ``` `verify_request` returns this type. Discriminate on `ok`. ### ZeroClickContext ```python theme={null} @dataclass(frozen=True) class ZeroClickContext: zc_request_id: str zc_agent_id: str | None timestamp: int kid: str zc_anonymous_id: str | None = None zc_buyer_id: str | None = None ``` Proven facts about a verified request: the correlation id (`zcreq_…`), the id of the agent that made the call (`agt_…`), the signature's timestamp in Unix seconds, and the key id that signed it. `zc_anonymous_id` repeats `zc_agent_id` under the name that will eventually replace `zc-agent-id`. `zc_buyer_id` (`byr_…`) is the buyer that agent belongs to, and is `None` for an anonymous agent; unlike the fields above it is not covered by the signature. See [agents and access](/docs/concepts/agents-and-access). > [!WARNING] > > A verified request without a buyer identity is a **signed anonymous probe**. ZeroClick sends one when it checks your endpoints, so it is valid, expected traffic; buyer calls always carry the agent id. Test for it with truthiness, not `is None`: an absent `zc-agent-id` header gives `None`, but a present-but-empty one gives `""`, and both mean the same thing. > > ```python theme={null} > if not decision.context.zc_agent_id: > ... # anonymous > ``` > > `guard_identity` already handles both. ### AllowanceDecision ```python theme={null} @dataclass(frozen=True) class AllowanceDecision: allowed: bool reason: str | None ``` `check_allowance` returns this type. `reason` is `None` when allowed, otherwise one of the seven allowance denial reasons. ### ReportUsageResult ```python theme={null} @dataclass(frozen=True) class ReportUsageResult: recorded: bool duplicate: bool usage_event: Mapping[str, Any] ``` `report_usage` returns this type. `usage_event` is the API's recorded event: `id`, `zcAgentId`, `zcRequestId`, `idempotencyKey`, `meterSlug`, `quantity`, `totalCostUsd`, `source`, and `occurredAt`. ## Usage items ### UsageItem ```python theme={null} @dataclass(frozen=True) class UsageItem: meter_slug: str quantity: int | None = None max_quantity: int | None = None ``` What a request will be charged for, used by `guard`, `check_allowance`, and `payment_required`. Declare at most one of `quantity` (a known amount) or `max_quantity` (a [ceiling](/docs/integrate/charge-up-to-a-maximum) for work you cannot size up front). Declaring both raises `ZCError`. Declaring neither defers to the meter's configured per-request ceiling; if the meter has none, the API denies the check with `meter_not_priced`. Quantities must be positive integers. ```python theme={null} usage = [ UsageItem(meter_slug="requests", quantity=1), UsageItem(meter_slug="output_tokens", max_quantity=100_000), ] ``` The buyer authorizes up to a ceiling and settles at the actual amount you report, so a ceiling never overcharges. ### SyncUsageItem ```python theme={null} @dataclass(frozen=True) class SyncUsageItem: service_slug: str meter_slug: str quantity: int ``` Actual usage settled alongside a successful response, used by `with_usage` and `usage_header`. All fields are required; `quantity` must be a positive integer. ## Standalone verification `canonical_string` builds the exact string ZeroClick signs: six fields joined by newlines. You need it only to debug a verification mismatch or implement verification elsewhere; the [signature spec](/docs/integrate/signature-spec) specifies the format. ```python theme={null} def canonical_string( *, timestamp: str, method: str, path_and_query: str, body: bytes, zc_request_id: str, zc_agent_id: str | None, ) -> str ``` ## Framework adapters ```python theme={null} from zeroclick_sellers.adapters import ( asgi_path_and_query, wsgi_path_and_query, zc_request_from_asgi_scope, zc_request_from_wsgi_environ, ) ``` * `zc_request_from_asgi_scope(scope, body) -> ZcRequest`: builds a request from an ASGI scope and the already-read raw body (FastAPI, Starlette). * `zc_request_from_wsgi_environ(environ, body) -> ZcRequest`: the same for a WSGI environ (Flask, Django). * `asgi_path_and_query(scope) -> str` and `wsgi_path_and_query(environ) -> str`: the raw request-target recovery alone, for custom integrations. The adapters' whole job is recovering the raw, percent-encoded request target that the signature covers; see [why the adapters exist](/docs/sdks/python/quickstart#why-the-adapters-exist). In both cases `body` must be the raw bytes, read before any framework parses or re-serializes them. ## Module defaults | Constant | Value | | - | - | | `DEFAULT_API_BASE_URL` | `"https://api.zeroclick.io"` | | `DEFAULT_TOLERANCE_SECONDS` | `300` | | `DEFAULT_CHECK_TIMEOUT_SECONDS` | `1.5` | | `COMPACT_JWE_ALG` | `"ECDH-ES+A256KW"` | | `COMPACT_JWE_ENC` | `"A256GCM"` | | `REPLY_JWK_PARAM` | `"https://zeroclick.io/jwe/reply-jwk"` | ## Encryption For services that opt into [end-to-end body encryption](/docs/concepts/end-to-end-encryption), the request body arrives as a Compact JWE. The encrypted reply follows the reverse path. Run `guard` first because the signature covers the **ciphertext**. Decrypt only after an allow decision. ```python theme={null} def decrypt_request( body: bytes | str, *, resolve_private_key: Callable[[str], Any] ) -> DecryptedEnvelope def encrypt_response(response: ZcResponse, envelope: DecryptedEnvelope) -> ZcResponse ``` `resolve_private_key` receives the `kid` from the JWE protected header and returns that private key (a JWK mapping or a `joserfc` `ECKey`), or `None` if it is unknown. `DecryptedEnvelope` carries the `plaintext` bytes plus what `encrypt_response` needs to encrypt the reply (`protected_header`, `cty`, `reply_jwk`). `encrypt_response` returns the response unchanged when the request carried no reply key, so the same handler serves encrypted and plaintext buyers. ```python theme={null} import json from zeroclick_sellers import decrypt_request, encrypt_response raw_body = await request.body() zc_request = zc_request_from_asgi_scope(request.scope, raw_body) decision = await zeroclick.guard( zc_request, service_slug="product-watch", usage=[UsageItem(meter_slug="requests", quantity=1)], ) if decision.action == "deny": return to_fastapi(decision.response) envelope = decrypt_request(raw_body, resolve_private_key=lookup_private_key) payload = json.loads(envelope.plaintext) # ... do the work, build the response, stamp usage with with_usage ... return to_fastapi(encrypt_response(stamped_response, envelope)) ``` The suite is fixed at `ECDH-ES+A256KW` key management with `A256GCM` content encryption; the SDK rejects anything else. If a reply key arrives with private key material, the SDK rejects it outright rather than using it. Failures raise `ZCError` with JWE-specific string codes. ## Errors `ZCError` and `is_zc_error(error, code=None)` are the last two exports. Guard outcomes are decisions; `ZCError` is reserved for malformed input and ZeroClick API failures. The [errors page](/docs/sdks/python/errors) covers every code and how to handle them. # Python SDK configuration Source: https://zeroclickai.mintlify.dev/docs/sdks/python/configuration Every option create_seller and create_async_seller accept: signing secrets, usage keys, the outage policy, timeouts, HTTP client injection, and lifecycle. `create_seller` returns a blocking `SellerClient` for WSGI apps; `create_async_seller` returns a non-blocking `AsyncSellerClient` for ASGI apps. Both accept the same keyword arguments and make the same decisions. Configure one client at startup and reuse it for every request. The client validates its configuration at construction, not when the first request arrives: any invalid combination raises `ZCError` with code `malformed_input` (see [errors](/docs/sdks/python/errors)). ```python theme={null} import logging import os from zeroclick_sellers import create_async_seller logger = logging.getLogger("zeroclick") zeroclick = create_async_seller( # Signature verification signing_secrets={ os.environ["ZEROCLICK_SIGNING_SECRET_KID"]: os.environ[ "ZEROCLICK_SIGNING_SECRET" ] }, tolerance_seconds=300, # Usage API credentials api_key=os.environ["ZEROCLICK_API_KEY"], # Allowance behavior allowance_unavailable_policy="allow", check_timeout_seconds=1.5, on_allowance_unavailable=lambda error: logger.warning( "allowance check failed: %s", error.code ), ) ``` ## Options **signing\_secrets** `Mapping[str, str]` Signing secrets keyed by key id: `{"hsec_…": "zcsec_…"}`. Every `zc-signature` header names the `kid` it was signed with, and the SDK uses it to pick the matching secret. The mapping must contain at least one entry. Provide exactly one of `signing_secrets` or `resolve_signing_secret`. Passing both, or neither, raises at construction. **resolve\_signing\_secret** `Callable[[str], str | None]` A lookup function in place of the static mapping, for secrets that live in a secret manager. It receives the `kid` from the request's signature header and returns the secret, or `None` for an unknown kid. If it returns `None`, the SDK denies the request with the `401` response rather than raising. If the function raises, or returns anything other than a non-empty string, the SDK raises `ZCError` with code `signing_secret_resolution_failed`. **api\_key** `str` An API key carrying both the `usage:read` and `usage:write` scopes. It backfills whichever of the two scoped keys you leave unset, so a single key is enough for the whole client. **usage\_read\_key** `str` A key with the `usage:read` scope, used for allowance checks (`guard` and `check_allowance`). When unset, it falls back to `api_key`. **usage\_write\_key** `str` A key with the `usage:write` scope, used for usage reporting (`report_usage`). This is handy when a separate worker reports usage. When unset, it falls back to `api_key`. **api\_base\_url** `str` (default: [https://api.zeroclick.io](https://api.zeroclick.io)) Base URL for the ZeroClick usage API. Override it only to point the SDK at a test double. **tolerance\_seconds** `int` (default: 300) Maximum accepted difference, in seconds, between the timestamp in the `zc-signature` header and the current clock. The SDK denies a request outside the window with the `401` response (reason `stale_timestamp`). **allowance\_unavailable\_policy** `str` (default: allow) What `guard` does when the allowance API gives no usable answer after a signature has verified: `"allow"`, `"deny"`, or `"throw"`. Any other value raises at construction. See [outage policy](#outage-policy) below. **check\_timeout\_seconds** `float` (default: 1.5) Timeout, in seconds, for calls to the ZeroClick usage API, passed to `httpx` per request. Despite the name, the client applies it to both allowance checks and usage reports. The SDK never retries a timed-out call. **on\_allowance\_unavailable** `Callable[[ZCError], None]` Called with the `ZCError` whenever the allowance API fails to answer during `guard`. The hook runs before the SDK applies the policy, whatever the policy is. Use it for operational logging and metrics; it does not change the decision. **clock** `Callable[[], float]` (default: time.time) The time source for signature freshness checks. Inject a fixed clock in tests to verify recorded requests without patching `time.time`. **http\_client** `httpx.Client | httpx.AsyncClient` Your own configured `httpx` client (`httpx.Client` for `create_seller`, `httpx.AsyncClient` for `create_async_seller`), for when you need proxies, event hooks, or connection limits. When omitted, the SDK constructs one. Closing the seller client closes whichever `httpx` client it holds, injected or not. ## Keys: one or two `api_key` must carry both usage scopes. To follow least privilege, pass two scoped keys instead and omit `api_key`. The read key covers allowance checks, and the write key covers usage reporting: ```python theme={null} import os from zeroclick_sellers import create_async_seller zeroclick = create_async_seller( signing_secrets={ os.environ["ZEROCLICK_SIGNING_SECRET_KID"]: os.environ[ "ZEROCLICK_SIGNING_SECRET" ] }, usage_read_key=os.environ["ZEROCLICK_USAGE_READ_KEY"], usage_write_key=os.environ["ZEROCLICK_USAGE_WRITE_KEY"], ) ``` The constructor validates coverage. If neither `api_key` nor the scoped key covers a side, it raises `ZCError` with code `malformed_input` naming the missing key: `Provide usage_read_key (or a both-scopes api_key) for allowance checks`, or `Provide usage_write_key (or a both-scopes api_key) for usage reporting`. ## Rotating signing secrets `signing_secrets` takes any number of entries, and the `kid` in each request selects the right one, so rotation is zero-downtime. Create the new secret. Deploy with both entries. Once ZeroClick signs only with the new kid, drop the old entry: ```python theme={null} zeroclick = create_async_seller( signing_secrets={ "hsec_k5nq0v7m3d8p": os.environ["ZEROCLICK_SIGNING_SECRET_CURRENT"], "hsec_2r8w1t6y4b0s": os.environ["ZEROCLICK_SIGNING_SECRET_PREVIOUS"], }, api_key=os.environ["ZEROCLICK_API_KEY"], ) ``` The key ids are not secret: they appear in every `zc-signature` header. See [keys and secrets](/docs/integrate/keys-and-secrets) for the rotation workflow in the dashboard. ## Outage policy `allowance_unavailable_policy` applies only when the allowance API gives no answer (a timeout, a transport failure, an error status, or a malformed response), and only after a signature has verified. It never applies to a missing or invalid signature, and an `allowed: false` answer is a normal `402` denial, not an outage. * `"allow"` (default): serve the request. The decision is an allow with `allowance == "unavailable"`, so you can tell it apart from a confirmed `"allowed"`. * `"deny"`: return the SDK's `503 {"error":"allowance_unavailable"}` response. * `"throw"`: the SDK raises the `ZCError` for your application to handle. Whatever the policy, the SDK calls `on_allowance_unavailable` first with the underlying error. See [errors](/docs/sdks/python/errors) for which error codes the policy covers. ## Lifecycle Both clients hold an `httpx` client, so a long-lived module-level instance is the normal shape. Create the client at import time and reuse it for every request, as the [quickstart](/docs/sdks/python/quickstart) examples do. For short-lived processes (scripts, workers, tests), close the client explicitly with `close()` / `aclose()`, or use it as a context manager: ```python Sync theme={null} import os from zeroclick_sellers import create_seller with create_seller( signing_secrets={ os.environ["ZEROCLICK_SIGNING_SECRET_KID"]: os.environ[ "ZEROCLICK_SIGNING_SECRET" ] }, api_key=os.environ["ZEROCLICK_API_KEY"], ) as zeroclick: zeroclick.report_usage( zc_agent_id="agt_x7f2kq93bh0d", idempotency_key="zcreq_8h2m4x0q9k1f_output_tokens", service_slug="product-watch", meter_slug="output_tokens", quantity=4200, ) ``` ```python Async theme={null} import os from zeroclick_sellers import create_async_seller async with create_async_seller( signing_secrets={ os.environ["ZEROCLICK_SIGNING_SECRET_KID"]: os.environ[ "ZEROCLICK_SIGNING_SECRET" ] }, api_key=os.environ["ZEROCLICK_API_KEY"], ) as zeroclick: await zeroclick.report_usage( zc_agent_id="agt_x7f2kq93bh0d", idempotency_key="zcreq_8h2m4x0q9k1f_output_tokens", service_slug="product-watch", meter_slug="output_tokens", quantity=4200, ) ``` # Python SDK errors Source: https://zeroclickai.mintlify.dev/docs/sdks/python/errors Which operations return decisions and which raise ZCError, every error code and its context, and how to handle usage API failures. The SDK draws a hard line between expected events and errors. A request with a bad signature or an exhausted allowance is an expected event, not a programming mistake. `guard`, `guard_identity`, and `verify_request` return it as a decision that carries the exact response to send back. `ZCError` is reserved for what the caller got wrong (malformed input) or what the environment did (the ZeroClick API being unreachable or answering nonsense). ## Decisions or exceptions, by operation | Operation | Returns a decision for | Raises ZCError for | | - | - | - | | `guard` | Bad signature (`401`), allowance denied (`402`), allowance unavailable under the `"allow"` and `"deny"` policies | Malformed usage input, a failing secret resolver, allowance unavailable under the `"throw"` policy | | `guard_identity` | Bad signature (`401`), missing buyer identity (`402`) | A failing secret resolver | | `verify_request` | Every signature failure (`401`) | Misconfigured secret sources, a non-`ZcRequest` argument, a failing secret resolver | | `check_allowance` | An allowed or denied `AllowanceDecision` | Every API failure (the outage policy applies only inside `guard`) | | `report_usage` | A duplicate replay (`duplicate=True` is a success) | Every API failure, including rejected reports | | `create_seller`, `create_async_seller` | None | Invalid configuration, at construction | | `ZcRequest`, `UsageItem`, `SyncUsageItem` | None | Invalid fields, at construction | | `decrypt_request`, `encrypt_response` | None | Every encryption failure | [GuardResult](/docs/sdks/python/api#guardresult) documents the deny reasons that ride on decisions; this page covers the exceptions. ## ZCError ```python theme={null} class ZCError(Exception): code: ZCErrorCode # stable machine code, for example "api_status_error" operation: str # the operation that raised, for example "check_allowance" context: dict[str, Any] # {"operation": ..., plus code-specific keys} ``` `ZCError(code, message=None, operation=..., **context)` carries a stable machine `code`, the `operation` that raised it, and a `context` dict. The dict holds the operation plus code-specific keys such as `status`, `reason`, `kid`, or `meter_slug`. `str(error)` is a human-readable message; branch on `code` and `context`, never on the message text. `is_zc_error(error, code=None)` returns `True` when `error` is a `ZCError`, optionally of a specific code. It is useful at boundaries that catch broadly: ```python theme={null} from zeroclick_sellers import is_zc_error try: process_job() except Exception as error: if is_zc_error(error, "api_transport_error"): ... # the ZeroClick API was unreachable raise ``` ## Error codes `ZCErrorCode` is a `Literal` of five values: | Code | Meaning | Context keys | | - | - | - | | `api_response_invalid` | The ZeroClick API answered, but the body is not the shape the SDK requires: invalid JSON, missing fields, or an unrecognized denial reason. | `status`, sometimes `reason` | | `api_status_error` | The ZeroClick API returned a status of 400 or above. | `status`; `reason` on rejected usage reports | | `api_transport_error` | The request never completed: timeout, connection failure, DNS. The default check timeout is 1.5 seconds, and the SDK never retries. | None | | `malformed_input` | You passed the SDK something invalid: at construction (missing usage keys, no signing secret, a bad policy value) or at call time (duplicate meters, both `quantity` and `max_quantity`, a non-bytes body). The message names the field. | varies | | `signing_secret_resolution_failed` | Your `resolve_signing_secret` callable raised, or returned something other than a non-empty string. An unknown `kid` does not raise: it denies with the `401` response. | `kid` | ## The allowance outage policy Inside `guard`, after a signature has verified, the codes `api_transport_error`, `api_status_error`, and `api_response_invalid` all mean the same thing: the allowance API gave no usable answer. The SDK routes these three, and only these, to the client's `allowance_unavailable_policy` instead of propagating them: `"allow"` serves the request with `allowance == "unavailable"`, `"deny"` returns the SDK's `503 {"error":"allowance_unavailable"}`, and `"throw"` re-raises the error for your application. The `on_allowance_unavailable` hook sees the error first, whatever the policy. The policy never applies to a missing or invalid signature, and an `allowed: false` answer is not an outage: it is a `402` denial. Outside `guard`, in `check_allowance` and `report_usage`, these codes always raise. See [configuration](/docs/sdks/python/configuration#outage-policy) for choosing a policy. ## Handling api\_status\_error `api_status_error` carries the HTTP status in `error.context["status"]`. When the API rejects a `report_usage` call with a typed status (`402`, `404`, or `409`), its machine reason also rides in `error.context["reason"]`: the report endpoint answers `402` for `access_inactive`, `plan_expired`, and `usage_exhausted`, `409` for `meter_not_priced`, and `404` otherwise. The [errors reference](/docs/resources/errors) covers the platform-wide error model. ```python theme={null} import logging from zeroclick_sellers import ZCError logger = logging.getLogger("zeroclick") try: result = zeroclick.report_usage( zc_agent_id="agt_x7f2kq93bh0d", idempotency_key="zcreq_8h2m4x0q9k1f_output_tokens", service_slug="product-watch", meter_slug="output_tokens", quantity=4200, ) except ZCError as error: if error.code != "api_status_error": raise status = error.context["status"] # for example 402 reason = error.context.get("reason") # for example "usage_exhausted" logger.warning("usage report rejected: %s %s", status, reason) else: if result.duplicate: logger.info("already reported; stored event replayed") ``` Because the SDK never retries, retrying is yours to schedule. It is also safe: reporting is idempotent per service on `idempotency_key`, so replaying the same report can never double-bill. ## Encryption error codes `decrypt_request` and `encrypt_response` raise `ZCError` with JWE-specific string codes that sit outside the five-value `ZCErrorCode` literal. Compare `error.code` directly rather than through `is_zc_error`'s typed `code` parameter: | Code | Meaning | | - | - | | `invalid_compact_jwe` | The request body is not a valid Compact JWE. | | `unsupported_jwe_suite` | The JWE does not use `ECDH-ES+A256KW` with `A256GCM`, the only accepted suite. | | `jwe_kid_required` | The JWE protected header has no key id. | | `invalid_reply_jwk` | The reply key is not a public P-256 key. | | `private_reply_jwk` | The reply key carries private key material. The SDK rejects it outright rather than using it. | | `private_key_not_found` | `resolve_private_key` returned `None` for the JWE's `kid`. | | `private_key_resolution_failed` | `resolve_private_key` raised. | | `decryption_failed` | The SDK could not decrypt the encrypted request. | | `encryption_failed` | The SDK could not encrypt the response to the reply key. | `private_key_not_found`, `private_key_resolution_failed`, and `decryption_failed` carry the JWE's `kid` in `error.context`. # Python SDK quickstart Source: https://zeroclickai.mintlify.dev/docs/sdks/python/quickstart Install zeroclick-sellers, pick the sync or async client, and guard a FastAPI, Flask, or Django route. The [`zeroclick-sellers`](https://pypi.org/project/zeroclick-sellers/) package implements the ZeroClick billing guard for Python backends: it verifies that each request came from ZeroClick, checks the buyer's [allowance](/docs/concepts/usage-and-allowances) before you do the work, returns the refusal responses ZeroClick expects, and settles or reports what was used. This page wires the guard into FastAPI, Flask, and Django. The [integration overview](/docs/integrate/overview) describes the contract it implements. ## Install ```sh theme={null} pip install zeroclick-sellers ``` The package requires Python 3.10 or later and is fully typed (it ships `py.typed`, so type checkers see every signature). Its HTTP calls go through `httpx`. > [!NOTE] > > You need three values from the [dashboard](https://dashboard.zeroclick.io): your signing secret (`zcsec_…`), its key id (`hsec_…`), and an API key (`zc_…`) with the `usage:read` and `usage:write` scopes. See [keys and secrets](/docs/integrate/keys-and-secrets). > > ```sh theme={null} > ZEROCLICK_SIGNING_SECRET_KID=hsec_k5nq0v7m3d8p > ZEROCLICK_SIGNING_SECRET=zcsec_… > ZEROCLICK_API_KEY=zc_… > ``` ## Pick the right client | Your framework | Client | Guard call | | - | - | - | | FastAPI, Starlette (ASGI) | `create_async_seller` | `await zeroclick.guard(...)` | | Flask, Django (WSGI) | `create_seller` | `zeroclick.guard(...)` | Use the async client in ASGI apps. The blocking client would stall the event loop during every allowance check. The two clients accept the same options and make the same decisions; they differ only in how they perform IO. ## Guard a FastAPI route ```python theme={null} import os from fastapi import FastAPI, Request from fastapi.responses import Response from zeroclick_sellers import SyncUsageItem, UsageItem, ZcResponse, create_async_seller from zeroclick_sellers.adapters import zc_request_from_asgi_scope zeroclick = create_async_seller( signing_secrets={ os.environ["ZEROCLICK_SIGNING_SECRET_KID"]: os.environ[ "ZEROCLICK_SIGNING_SECRET" ] }, api_key=os.environ["ZEROCLICK_API_KEY"], ) app = FastAPI() def to_fastapi(response: ZcResponse) -> Response: return Response( content=response.body, status_code=response.status, headers=dict(response.headers), ) @app.post("/v1/product-watch") async def product_watch(request: Request) -> Response: zc_request = zc_request_from_asgi_scope(request.scope, await request.body()) decision = await zeroclick.guard( zc_request, service_slug="product-watch", usage=[UsageItem(meter_slug="requests", quantity=1)], ) if decision.action == "deny": return to_fastapi(decision.response) result = do_the_work(owner=decision.context.zc_agent_id) return to_fastapi( zeroclick.with_usage( ZcResponse.json(result), [ SyncUsageItem( service_slug="product-watch", meter_slug="requests", quantity=1 ) ], ) ) ``` The handler is four moves: 1. **Adapt.** `zc_request_from_asgi_scope` turns the framework request into a `ZcRequest` built from the raw path and raw body bytes. 2. **Guard.** `guard` verifies the `zc-signature` header before it calls the allowance API, and returns a decision, not an exception. 3. **Deny.** A deny decision carries the exact response to return: `401` for a bad signature, the `402 payment_required` body ZeroClick converts into a payment challenge, or `503` under a fail-closed outage policy. An allow decision carries the verified context: `decision.context.zc_agent_id` identifies the buyer. 4. **Settle.** `with_usage` stamps the `zc-usage` response header with the actual usage. ZeroClick records that usage and strips the header before the agent sees the response. ## Flask and Django The handler keeps the same shape: `create_seller`, no `await`, and the WSGI adapter in place of the ASGI one. ```python Flask theme={null} import os from flask import Flask, Response, request from zeroclick_sellers import SyncUsageItem, UsageItem, ZcResponse, create_seller from zeroclick_sellers.adapters import zc_request_from_wsgi_environ zeroclick = create_seller( signing_secrets={ os.environ["ZEROCLICK_SIGNING_SECRET_KID"]: os.environ[ "ZEROCLICK_SIGNING_SECRET" ] }, api_key=os.environ["ZEROCLICK_API_KEY"], ) app = Flask(__name__) def to_flask(response: ZcResponse) -> Response: return Response( response=response.body, status=response.status, headers=dict(response.headers), ) @app.post("/v1/product-watch") def product_watch() -> Response: # request.get_data() returns the raw body without consuming it for later # handlers; never use request.json here, which would re-serialise. zc_request = zc_request_from_wsgi_environ(request.environ, request.get_data()) decision = zeroclick.guard( zc_request, service_slug="product-watch", usage=[UsageItem(meter_slug="requests", quantity=1)], ) if decision.action == "deny": return to_flask(decision.response) result = do_the_work(owner=decision.context.zc_agent_id) return to_flask( zeroclick.with_usage( ZcResponse.json(result), [ SyncUsageItem( service_slug="product-watch", meter_slug="requests", quantity=1 ) ], ) ) ``` ```python Django theme={null} import os from django.http import HttpRequest, HttpResponse from django.urls import path from zeroclick_sellers import SyncUsageItem, UsageItem, ZcResponse, create_seller from zeroclick_sellers.adapters import zc_request_from_wsgi_environ zeroclick = create_seller( signing_secrets={ os.environ["ZEROCLICK_SIGNING_SECRET_KID"]: os.environ[ "ZEROCLICK_SIGNING_SECRET" ] }, api_key=os.environ["ZEROCLICK_API_KEY"], ) def to_django(response: ZcResponse) -> HttpResponse: django_response = HttpResponse( content=response.body, status=response.status, content_type=response.headers.get("content-type", "application/json"), ) for key, value in response.headers.items(): if key.lower() != "content-type": django_response[key] = value return django_response def product_watch(request: HttpRequest) -> HttpResponse: # request.body is the raw bytes. request.META is the WSGI environ, which # is where the raw target lives; request.path is already decoded. zc_request = zc_request_from_wsgi_environ(request.META, request.body) decision = zeroclick.guard( zc_request, service_slug="product-watch", usage=[UsageItem(meter_slug="requests", quantity=1)], ) if decision.action == "deny": return to_django(decision.response) result = do_the_work(owner=decision.context.zc_agent_id) return to_django( zeroclick.with_usage( ZcResponse.json(result), [ SyncUsageItem( service_slug="product-watch", meter_slug="requests", quantity=1 ) ], ) ) urlpatterns = [path("v1/product-watch", product_watch)] ``` ## Why the adapters exist The signature covers the request target exactly as ZeroClick sent it, so `ZcRequest.path_and_query` must be the **raw, percent-encoded** path and query. Every framework hands you a decoded one. These are the observed values for `GET /v1/items/a%2Fb%20c`: | | Decoded (unusable) | Raw (correct) | | - | - | - | | ASGI / uvicorn | `scope["path"]` → `/v1/items/a/b c` | `scope["raw_path"]` → `/v1/items/a%2Fb%20c` | | WSGI / werkzeug | `PATH_INFO` → `/v1/items/a/b c` | `RAW_URI` → `/v1/items/a%2Fb%20c?…` | Using the decoded path produces a different canonical string and fails verification. The adapters handle this. They also cover a spec difference between the two interfaces: ASGI's `raw_path` excludes the query string (the adapter appends `scope["query_string"]`), while WSGI's `RAW_URI` and `REQUEST_URI` already include it. The body has the same rule: pass the raw bytes exactly as received, before any framework parses or re-serializes them. Use `await request.body()` in FastAPI, `request.get_data()` in Flask, and `request.body` in Django. > [!WARNING] > > On WSGI, if the server sets neither `RAW_URI` nor `REQUEST_URI`, the SDK cannot recover an encoded separator. WSGI decodes `%2F` to `/` before the SDK runs, and nothing can tell it from a literal `/`. gunicorn, werkzeug, uWSGI, and nginx all set one of them. ## Test the guard The guard must deny a plain request with no ZeroClick headers. Only signed requests from ZeroClick reach your handler: ```sh theme={null} curl -i -X POST http://localhost:8000/v1/product-watch # HTTP/1.1 401 # {"error":"invalid_zeroclick_signature"} ``` The [quickstart](/docs/quickstart) covers the rest of the loop: deploying the guarded route and running the dashboard's API setup verification against it. ## Next steps > [card] [Configuration](/docs/sdks/python/configuration) > > Every constructor option: secrets, split usage keys, outage policy, timeouts. > [card] [API reference](/docs/sdks/python/api) > > Every public export, from guard to the encryption helpers. > [card] [Errors](/docs/sdks/python/errors) > > Decisions versus exceptions, and every ZCError code. > [card] [Charge up to a maximum](/docs/integrate/charge-up-to-a-maximum) > > Bill work you cannot size up front, like output tokens. # Ruby SDK API Source: https://zeroclickai.mintlify.dev/docs/sdks/ruby/api Every public method and value type in zeroclick-sellers. ## `ZeroClick::Sellers.create` Builds a client. See [configuration](/docs/sdks/ruby/configuration) for every option. ```ruby theme={null} SELLER = ZeroClick::Sellers.create( api_key: ENV.fetch("ZEROCLICK_API_KEY"), signing_secrets: ZeroClick::Sellers.secrets_from_env ) ``` Invalid configuration raises `ZeroClick::Sellers::Error` with code `malformed_input` at construction, not at the first request. ## `#guard` Verifies the request, then checks the buyer can pay before you do the work. ```ruby theme={null} decision = SELLER.guard( request, service_slug: "extractor", usage: [ZeroClick::Sellers::UsageItem.new(meter_slug: "requests", quantity: 1)], plan_slug: nil ) ``` Returns `Allow` or `Deny` — never raises for an unpayable or unsigned request, because both are expected events. ```ruby theme={null} if decision.allow? decision.context # ZeroClickContext decision.allowance # "allowed" or "unavailable" else decision.reason # "usage_exhausted", "invalid_signature", … decision.response # ready to return as-is end ``` ## `#guard_identity` Guards a free endpoint that must still know the caller. Makes no network call. ```ruby theme={null} decision = SELLER.guard_identity(request, service_slug: "extractor") ``` `Allow#allowance` is `"not_required"`. A signed anonymous probe is denied with reason `identity_required` and a `402` carrying empty usage. ## `#verify_request` Signature verification alone, with no allowance check. ```ruby theme={null} result = SELLER.verify_request(request) result.ok? # true or false result.context # on success result.reason # on failure: missing_signature, malformed_signature, # stale_timestamp, missing_request_id, unknown_kid, invalid_signature result.response # on failure: the 401 ``` A verified request whose `zc_agent_id` is `nil` is a signed anonymous probe — valid, not a failure. ## `#check_allowance` The allowance check on its own, without verification. ```ruby theme={null} decision = SELLER.check_allowance( zc_request_id: zc.zc_request_id, service_slug: "extractor", usage: [ZeroClick::Sellers::UsageItem.new(meter_slug: "requests", quantity: 1)] ) decision.allowed? # true or false decision.reason # a usage denial reason, or nil ``` Unlike `guard`, this raises on an API failure rather than applying the outage policy — it has no verified context to fall back to. ## `#report_usage` Reports usage asynchronously, after the work is done. ```ruby theme={null} result = SELLER.report_usage( zc_agent_id: zc.zc_agent_id, idempotency_key: "extract:#{zc.zc_request_id}", service_slug: "extractor", meter_slug: "tokens", quantity: 4_120, occurred_at: nil ) result.recorded? # always true on success result.duplicate? # true when this key was already recorded result.usage_event # the recorded event ``` > [!WARNING] > > The idempotency key is **yours** to derive, and must be stable for the request — derive it from `zc_request_id`. The SDK never invents one and never retries on your behalf, because a retry under a changed key double-bills. A replay of the same key returns `duplicate? == true`. That is a success, not a failure. ## Response helpers ```ruby theme={null} SELLER.payment_required( service_slug: "extractor", usage: [ZeroClick::Sellers::UsageItem.new(meter_slug: "requests", quantity: 1)], plan_slug: "pro" ) SELLER.with_usage(response, [ ZeroClick::Sellers::SyncUsageItem.new(service_slug: "extractor", meter_slug: "requests", quantity: 1) ]) ``` `ZeroClick::Sellers::Responses` exposes the same functions plus `invalid_zeroclick_signature`, `allowance_unavailable` and `usage_header`. ## Value types ### `UsageItem` What a request will be charged for. ```ruby theme={null} ZeroClick::Sellers::UsageItem.new(meter_slug: "requests", quantity: 1) ZeroClick::Sellers::UsageItem.new(meter_slug: "tokens", max_quantity: 10_000) ZeroClick::Sellers::UsageItem.new(meter_slug: "requests") ``` Give at most one of `quantity` or `max_quantity`; neither defers to the meter's configured per-request ceiling. Declaring both raises. A fixed `quantity` lets ZeroClick offer the `exact` x402 scheme. A `max_quantity` forces `upto`, which fewer clients can pay — prefer a fixed charge and report variable work afterwards. The ceiling never overcharges: ZeroClick authorises up to it and bills what you settle. But it does **gate the buyer's authorisation**, which is easy to miss. A ceiling of 50 units at `$0.002` plus a `$0.01` request charge makes every call reserve `$0.11`, and a buyer whose per-call cap is below that is refused before any work happens — a client capped at `$0.10` is simply turned away. The unspent remainder never leaves their wallet, but an ambitious ceiling still prices out small callers, so keep it near a realistic worst case. `Middleware::Meter` accepts **only** items with an explicit `quantity`, because it settles usage automatically. The other two forms are fine for `guard`, which only asks whether the buyer could pay. ### `SyncUsageItem` Actual usage, reported alongside a successful response via the `zc-usage` header. ```ruby theme={null} ZeroClick::Sellers::SyncUsageItem.new(service_slug: "extractor", meter_slug: "requests", quantity: 1) ``` ### `Request` A framework-neutral inbound request. Build one from a Rack env with `Middleware.request_from_env(env)`, or directly: ```ruby theme={null} ZeroClick::Sellers::Request.new( method: "POST", path_and_query: "/v1/extract?format=json", headers: { "zc-signature" => "…" }, body: raw_bytes ) ``` `path_and_query` must be the **raw, percent-encoded** target, and `body` the raw bytes. Decode nothing before verifying — the signature covers exactly what arrived. ### `Response` ```ruby theme={null} response.status # 402 response.headers # { "content-type" => "application/json" } response.body # the JSON string response.json_body ``` ### `ZeroClickContext` ```ruby theme={null} zc.zc_request_id zc.zc_agent_id zc.zc_buyer_id zc.zc_anonymous_id zc.kid zc.timestamp ``` ## Module helpers ```ruby theme={null} ZeroClick::Sellers.secrets_from_env # parses ZEROCLICK_SIGNING_SECRETS ZeroClick::Sellers.configure(**options) # store config for .seller ZeroClick::Sellers.seller # the lazily built process-wide client ZeroClick::Sellers.error?(e, "api_status_error") ZeroClick::Sellers::VERSION ``` ## Encrypted request bodies A buyer can [encrypt its request body end to end](/docs/concepts/end-to-end-encryption) with your public key. The buyer can also request an encrypted reply. The helpers load only after this separate require: ```ruby theme={null} require "zeroclick/sellers/encryption" ``` Nothing new is added to your dependency graph. The gem implements the whole suite on the standard library — OpenSSL supplies P-256 ECDH, AES key wrap and AES-256-GCM, and the one missing piece, the NIST SP 800-56A Concat KDF, is a short SHA-256 loop. ```ruby theme={null} envelope = ZeroClick::Sellers.decrypt_request( raw_body, resolve_private_key: ->(kid) { my_private_jwks[kid] } ) envelope.plaintext # the original request body envelope.reply_jwk # non-nil when the buyer asked for an encrypted reply # Returns the response unchanged when no reply key was sent. ZeroClick::Sellers.encrypt_response(response, envelope) ``` Verify the signature **before** decrypting: the signature covers the ciphertext as it arrived on the wire, not the plaintext. The cipher suite is pinned — `ECDH-ES+A256KW` key management, `A256GCM` content encryption — so a sender cannot negotiate something weaker. Two ordering rules are worth stating outright, because both are silently wrong in a way that still returns 200: * **Attach usage before encrypting.** `zc-usage` is a header, which is what lets an encrypted call settle through a proxy that cannot read the body. * **Encrypt refusals too.** A buyer who asked for confidentiality does not stop wanting it because the answer is a 4xx. > [!NOTE] > > Unlike the Go SDK, there is no empty-plaintext limitation here: an encrypted request whose plaintext is empty decrypts normally, matching the TypeScript and Python SDKs. The [errors page](/docs/sdks/ruby/errors) lists the encryption error codes. ## The stateful helpers `require "zeroclick/sellers/stateful"` implements the account routes for [sellers whose purchases create accounts and API keys](/docs/integrate/stateful-sellers): * `ZeroClick::Sellers::Stateful.handle_access_request(request, on_write:, on_mint:, base_path:, remint_policy:, ...)`: routes, verifies, and validates both account calls, then hands off to your two handlers. Returns `nil` for anything that is not one of its routes. * `Stateful::Entitlement.should_apply?`, `.derive_credit_delta`, `.period_advanced?`, and `.parse`: the dedup and never-regress arithmetic an account write must be applied with. * `Stateful::Entitlement.serviceable?(state, now = Time.now)`: the one request-time gate — `true` only while the account is `active` and its period, when it has an `end`, has not lapsed. * `Stateful::Money.parse_money_usd` and `.format_money_usd`: six-decimal money strings to integer micros and back, so no floating-point math ever touches money. * `Stateful::Verify.verify_access_signature`, `.canonical_access_string`, and `.sign_access_request`: the purpose-carrying access signature on its own, plus a signer for integration tests. * `Stateful::Contracts`: the wire shapes — parsed entitlements expose `lifetime_credit_granted_usd` and `lifetime_credit_reversed_usd` (plus `_micros` variants) alongside the period and status. Do not route these calls through `#guard` or `#verify_request`: account calls carry a different, purpose-separated signature by design. The [account and key reference](/docs/resources/stateful-access-reference) documents every field, status, and retry rule. # Ruby SDK configuration Source: https://zeroclickai.mintlify.dev/docs/sdks/ruby/configuration Keys, signing secrets, the allowance-unavailable policy, and timeouts for zeroclick-sellers. Every option is passed to `ZeroClick::Sellers.create`, or set on `config.zeroclick` under [Rails](/docs/sdks/ruby/quickstart). ```ruby theme={null} SELLER = ZeroClick::Sellers.create( api_key: ENV.fetch("ZEROCLICK_API_KEY"), signing_secrets: ZeroClick::Sellers.secrets_from_env ) ``` ## Options | Option | Default | Purpose | | - | - | - | | `api_key` | — | A both-scopes credential (`usage:read` and `usage:write`). | | `usage_read_key` | falls back to `api_key` | Covers allowance checks: `guard`, `check_allowance`. | | `usage_write_key` | falls back to `api_key` | Covers `report_usage`. | | `signing_secrets` | — | A `kid => secret` Hash. Exactly one of this or `resolve_signing_secret`. | | `resolve_signing_secret` | — | A callable taking a `kid`, returning the secret or `nil`. | | `api_base_url` | `https://api.zeroclick.io` | Point at a mock in tests. | | `tolerance_seconds` | `300` | Accepted clock skew on the signature timestamp. | | `allowance_unavailable_policy` | `"allow"` | `"allow"`, `"deny"` or `"throw"`. See below. | | `check_timeout_seconds` | `1.5` | The allowance check sits in your request path. | | `on_allowance_unavailable` | — | A callable receiving the `Error` on every fail-open event. | | `clock` | `-> { Time.now.to_i }` | Freeze time in tests. | | `http_post` | `Usage.method(:post)` | Inject a transport in tests. | ## Signing secrets ```sh theme={null} ZEROCLICK_SIGNING_SECRETS=hsec_old:zcsec_old,hsec_new:zcsec_new ``` ```ruby theme={null} ZeroClick::Sellers.secrets_from_env # => { "hsec_old" => "zcsec_old", "hsec_new" => "zcsec_new" } ``` A map rather than a single secret, because rotation is the normal case: while ZeroClick is switching, requests arrive signed with either `kid`, and both must verify. Remove the old entry only once no traffic carries it. If your secrets live in a vault rather than the environment, pass a resolver instead: ```ruby theme={null} SELLER = ZeroClick::Sellers.create( api_key: ENV.fetch("ZEROCLICK_API_KEY"), resolve_signing_secret: ->(kid) { Vault.read("zeroclick/#{kid}") } ) ``` Provide exactly one of `signing_secrets` or `resolve_signing_secret` — giving both, or neither, raises at construction rather than at the first request. ## Split usage keys Useful when a separate process reports usage — a Sidekiq worker settling variable work, say. The reporting process then needs no read scope, and the serving process needs no write scope. ```ruby theme={null} SELLER = ZeroClick::Sellers.create( usage_read_key: ENV.fetch("ZEROCLICK_USAGE_READ_KEY"), usage_write_key: ENV.fetch("ZEROCLICK_USAGE_WRITE_KEY"), signing_secrets: ZeroClick::Sellers.secrets_from_env ) ``` ## The allowance-unavailable policy When the allowance API cannot give an answer — a timeout, a 5xx, an unparseable body — this decides what happens. | Policy | Behaviour | Choose it when | | - | - | - | | `"allow"` (default) | Serve the request. `Allow#allowance` is `"unavailable"`. | Serving occasional unbilled work is better than an outage. | | `"deny"` | Refuse with `503 allowance_unavailable`. | Unbilled work is worse than a refusal. | | `"throw"` | Raise the `Error`. | You want to handle it yourself. | > [!WARNING] > > The policy applies **only after a signature verifies**. A fail-open allowance policy never becomes a fail-open signature policy — an unsigned or badly signed request is refused with `401` under every policy. A recognised `allowed: false` is always a `402`, never an outage — the API answered, and the answer was no. An `Allow` reached through the policy reports `allowance == "unavailable"` rather than `"allowed"`, so you can distinguish served-because-we-could-not-check from served-because-they-paid: ```ruby theme={null} SELLER = ZeroClick::Sellers.create( api_key: ENV.fetch("ZEROCLICK_API_KEY"), signing_secrets: ZeroClick::Sellers.secrets_from_env, allowance_unavailable_policy: "allow", on_allowance_unavailable: ->(error) { Sentry.capture_exception(error) } ) ``` ## Timeouts `check_timeout_seconds` bounds the allowance check, which sits in your request path — it applies to connect, read and write. The default of `1.5` seconds trades a slow check for a fast fail-open. Raise it only if your outage policy is `"deny"` and you would rather wait than refuse. ## Body size The middleware buffers the request body to verify it, bounded at 10 MiB by default: ```ruby theme={null} use ZeroClick::Sellers::Middleware::Meter, seller: SELLER, service_slug: "extractor", usage: [...], max_body_bytes: 1024 * 1024 ``` The ceiling is enforced **before** verification, on purpose: an attacker needs no valid signature to make you buffer. An over-size body is refused with `413`. # Ruby SDK errors Source: https://zeroclickai.mintlify.dev/docs/sdks/ruby/errors What raises, what returns a decision, and how zeroclick-sellers classifies allowance-API failures. The Ruby SDK draws one line: **an expected event is a value, a mistake is an exception.** A request with a bad signature, or a buyer who cannot pay, is an expected event — the SDK returns a decision carrying the exact response to send. `ZeroClick::Sellers::Error` is reserved for what you got wrong, or what the environment did. ## Decisions, not exceptions ```ruby theme={null} decision = SELLER.guard(request, service_slug: "extractor", usage: usage) unless decision.allow? decision.reason # why decision.response # what to return end ``` | Reason | Status | | - | - | | `missing_signature`, `malformed_signature`, `stale_timestamp`, `missing_request_id`, `unknown_kid`, `invalid_signature` | `401` | | `identity_required` | `402`, empty usage | | A usage denial reason (below) | `402` with the payment challenge | | `allowance_unavailable` | `503`, only under the `"deny"` policy | ### Usage denial reasons `service_not_found`, `access_not_found`, `access_inactive`, `plan_expired`, `meter_not_found`, `meter_not_priced`, `usage_exhausted`. Any other reason on the wire is treated as a malformed response rather than passed through — a seller matching on an unknown reason would silently take the wrong branch. ## `ZeroClick::Sellers::Error` ```ruby theme={null} begin SELLER.report_usage(...) rescue ZeroClick::Sellers::Error => e e.code # a stable machine code — match on this, never the message e.operation # "report_usage" e.context # { operation: …, status: 402, reason: "usage_exhausted" } end ``` `ZeroClick::Sellers.error?(e, "api_status_error")` is the same check as a predicate. | Code | Meaning | | - | - | | `malformed_input` | You passed something invalid. A bug in your integration. | | `signing_secret_resolution_failed` | Your `resolve_signing_secret` raised, or returned an empty secret. | | `api_transport_error` | The ZeroClick API could not be reached. | | `api_status_error` | The API answered with an unsuccessful status. | | `api_response_invalid` | The API answered with something unparseable or off-contract. | ### Encryption error codes `require "zeroclick/sellers/encryption"` adds its own codes on the same `ZeroClick::Sellers::Error`, with `operation` set to `decrypt_request` or `encrypt_response`: | Code | Meaning | | - | - | | `invalid_compact_jwe` | The body is not a well-formed five-segment Compact JWE: wrong segment count, an undecodable protected header, or a parse failure. | | `unsupported_jwe_suite` | The header names an algorithm outside the pinned suite (`ECDH-ES+A256KW` key management, `A256GCM` content encryption). | | `jwe_kid_required` | The protected header carries no `kid`, so no private key can be selected. | | `private_key_not_found` | Your `resolve_private_key` returned `nil` for the header's kid. | | `private_key_resolution_failed` | Your `resolve_private_key` raised. | | `invalid_reply_jwk` | The buyer's reply key is not a usable public P-256 JWK. | | `private_reply_jwk` | The buyer's reply key carried private parameters, which a reply key must never do. | | `decryption_failed` | The suite and key were right, but decryption failed. | | `encryption_failed` | Encrypting the reply to the buyer's key failed. | These are raised, not returned: an undecryptable body is not a routine refusal the way an unsigned request is, so it surfaces as an exception for you to map to a response. Decide deliberately whether that response is encrypted — if the failure was in reading the header, there is no reply key to encrypt to. ### Stateful refusal codes The stateful rail answers `401` with one of exactly four codes, which are response bodies rather than exceptions: | Code | Meaning | | - | - | | `missing_or_malformed_signature` | No `zc-signature`, or one that does not parse. | | `stale_timestamp` | Outside the skew window (default 300s). | | `unknown_kid` | The kid names no secret you hold. | | `invalid_signature` | The HMAC did not match. | Deliberately fewer codes than the proxy rail: a caller learning *why* its signature failed learns something about the secret. > [!WARNING] > > Match on `code`, never on the message. Messages are written for humans reading logs and will change. ## Which failures the outage policy covers Only these mean *"the allowance API did not give us an answer"*: `api_transport_error`, `api_status_error`, `api_response_invalid`. Only they are subject to [`allowance_unavailable_policy`](/docs/sdks/ruby/configuration#the-allowance-unavailable-policy). Anything else — a `malformed_input` from your own call — propagates under every policy, because a bug in your integration must not be laundered into a fail-open allow. > [!NOTE] > > This is where the SDKs legitimately differ. The Go SDK treats any 4xx from the allowance API (a revoked key, an unknown service) as a hard error, never an outage. The Ruby, TypeScript and Python SDKs route API errors through the policy. A revoked key under a `"allow"` policy therefore serves unbilled work in Ruby, and refuses in Go — set the policy to `"deny"` or `"throw"` if that matters to you. The policy is applied **only after a signature verifies**, so a fail-open allowance policy never becomes a fail-open signature policy. ## Errors raised at construction Invalid configuration raises immediately rather than at the first request: * no credential (neither `api_key` nor the usage keys) * both or neither of `signing_secrets` and `resolve_signing_secret` * an empty `signing_secrets` * an `allowance_unavailable_policy` that is not `"allow"`, `"deny"` or `"throw"` `Middleware::Meter` likewise raises at wire-up when given a `max_quantity` item, because it would otherwise bill zero on a delivered `200`. See [middleware](/docs/sdks/ruby/middleware). ## Errors that are not raised The SDK never retries and never invents an idempotency key. A failed `report_usage` is yours to retry, with the same key — which is exactly why the key must be derived from `zc_request_id` rather than generated. # Ruby SDK middleware Source: https://zeroclickai.mintlify.dev/docs/sdks/ruby/middleware Meter and Identify — mounting the ZeroClick guard as Rack middleware in Rails, Sinatra, Hanami, or Roda. `ZeroClick::Sellers::Middleware` is plain Rack middleware, so it composes with Rails, Sinatra, Hanami and Roda alike. Nothing in it requires the `rack` gem — a Rack middleware is duck-typed — so mounting the guard adds no dependency to your bundle. ## Meter Guards a billable endpoint: verifies the signature, confirms the buyer can pay, and — if your app responds `2xx` — settles the usage. ```ruby theme={null} use ZeroClick::Sellers::Middleware::Meter, seller: SELLER, service_slug: "extractor", usage: [ZeroClick::Sellers::UsageItem.new(meter_slug: "requests", quantity: 1)] ``` | Option | Default | Purpose | | - | - | - | | `seller:` | — | A client from `ZeroClick::Sellers.create`. | | `service_slug:` | — | Which service this route belongs to. Per-route, not per-client. | | `usage:` | — | The `UsageItem`s this route charges for. | | `plan_slug:` | `nil` | Names a plan in the `402` challenge. | | `max_body_bytes:` | 10 MiB | The verification buffer ceiling. | ### Every item needs an explicit quantity `Meter` settles usage from what it declared, so each item must carry a definite `quantity`. Anything else has no settled amount to report, and inventing one would silently mis-bill a delivered `200` — the exact failure this SDK exists to prevent. It therefore raises when you build the middleware, not in production: ```ruby theme={null} # both raise malformed_input immediately # a ceiling has no settled amount usage: [ZeroClick::Sellers::UsageItem.new(meter_slug: "tokens", max_quantity: 1000)] # and neither does an item that defers to the meter's configured default usage: [ZeroClick::Sellers::UsageItem.new(meter_slug: "requests")] ``` Both forms remain valid for [`guard`](/docs/sdks/ruby/api#guard), which only asks whether the buyer *could* pay. It is settlement that needs a definite number. Declare the fixed part in the middleware and report the variable part afterwards with [`report_usage`](/docs/sdks/ruby/api#report_usage). ### Only delivered responses are billed `zc-usage` is attached only when your app answers `2xx`. A `4xx` or `5xx` gets no usage header, because the work was not delivered. ## Identify Guards a free endpoint that must still know which buyer is calling — a limits or account route. It makes **no network call**. ```ruby theme={null} use ZeroClick::Sellers::Middleware::Identify, seller: SELLER, service_slug: "extractor" ``` A signed anonymous probe (no `zc-agent-id`) is refused with a `402` carrying an empty `usage` list. That is the free identity-scoped refusal: the proxy answers it with `401 bearer_required` and never a charge. Buyers rarely reach that refusal. Every call needs a registered agent credential, checked before anything is priced, so an unidentified caller gets `401 bearer_required` from ZeroClick and registers a credential first by following the seller's `/auth.md`. Either way your endpoint's contract is the same: it refused an unidentified caller. ## The verified caller A guarded request carries what it proved on the Rack env: ```ruby theme={null} zc = env["zeroclick.context"] # ZeroClick::Sellers::Middleware::CONTEXT_ENV_KEY zc.zc_agent_id # the buyer, or nil on a signed anonymous probe zc.zc_request_id # correlates with ZeroClick's logs; derive idempotency keys from it zc.zc_buyer_id # the buyer that owns the agent, once claimed zc.kid # which signing secret verified the request zc.timestamp # the signed timestamp, in epoch seconds ``` Under Rails that is `request.env["zeroclick.context"]`. ## The request body Verification covers the whole body, so the middleware must read it. It then replaces `rack.input` with a fresh stream over the same bytes, so your app reads the body normally. It deliberately does **not** call `#rewind`: Rack 3 dropped the requirement that input be rewindable, and against a streaming server `#rewind` either raises or silently does nothing — handing the application an empty body. ## Mounting on a subset of routes Rack middleware runs on every request through the stack. To guard only some paths, mount it on a scoped app rather than globally: ```ruby theme={null} # config.ru map "/v1/extract" do use ZeroClick::Sellers::Middleware::Meter, seller: SELLER, service_slug: "extractor", usage: [ZeroClick::Sellers::UsageItem.new(meter_slug: "requests", quantity: 1)] run ExtractApp end map "/health" do run HealthApp end ``` Under Rails, mount a guarded Rack app in `routes.rb`, or guard inside the controller with [`guard`](/docs/sdks/ruby/api#guard) when routing is more naturally expressed there. ## Ordering Mount the guard **above** anything that reads or rewrites the request body, and above logging you want to carry the buyer id. Mount it **below** anything that must run for unauthenticated traffic too — health checks, and whatever terminates TLS or normalises the host. ## Reporting marketing page views `Meter` and `Identify` guard your billed API. To measure the marketing pages read before a purchase, the Ruby SDK ships `Middleware::PageViews`, mounted the same Rack way: > [card] [Page views middleware](/docs/page-views/sdk-middleware) > > Report every page-content request from your site, fail-open. When you also run Agentify, `use` Page views first so it stays the outer layer: in Rack the first `use` is the outermost. # Ruby SDK quickstart Source: https://zeroclickai.mintlify.dev/docs/sdks/ruby/quickstart Install zeroclick-sellers, mount the Rack middleware, and guard a Rails, Sinatra, or Hanami route. The [`zeroclick-sellers`](https://rubygems.org/gems/zeroclick-sellers) gem implements the ZeroClick billing guard for Ruby backends: it verifies that each request came from ZeroClick, checks the buyer's [allowance](/docs/concepts/usage-and-allowances) before you do the work, returns the refusal responses ZeroClick expects, and settles or reports what was used. The [integration overview](/docs/integrate/overview) describes the contract it implements. It ships **Rack middleware**, so one implementation covers Rails, Sinatra, Hanami and Roda — Rails is a Rack app. ## Install ```ruby theme={null} gem "zeroclick-sellers" ``` The gem requires Ruby 3.1 or later and has **no runtime dependencies**: the core is stdlib-only (`openssl`, `json`, `net/http`), and the middleware is duck-typed rather than requiring `rack`. Adding it cannot change how anything else in your bundle resolves. > [!NOTE] > > You need three values from the [dashboard](https://dashboard.zeroclick.io): your signing secret (`zcsec_…`), its key id (`hsec_…`), and an API key (`zc_…`) with the `usage:read` and `usage:write` scopes. See [keys and secrets](/docs/integrate/keys-and-secrets). > > ```sh theme={null} > ZEROCLICK_SIGNING_SECRETS=hsec_k5nq0v7m3d8p:zcsec_… > ZEROCLICK_API_KEY=zc_… > ``` > > `ZEROCLICK_SIGNING_SECRETS` holds `kid:secret` pairs, comma-separated. It is a map rather than a single secret so that during a rotation both the old and the new `kid` verify — otherwise every in-flight request fails the moment you rotate. ## Guard a Rails route The Railtie is opt-in, so the gem stays usable without Rails on the load path. ```ruby theme={null} # config/application.rb require "zeroclick/sellers/railtie" module MyApp class Application < Rails::Application config.zeroclick.api_key = ENV.fetch("ZEROCLICK_API_KEY") config.zeroclick.signing_secrets = ZeroClick::Sellers.secrets_from_env config.middleware.use ZeroClick::Sellers::Middleware::Meter, service_slug: "extractor", usage: [ZeroClick::Sellers::UsageItem.new(meter_slug: "requests", quantity: 1)] end end ``` > [!WARNING] > > Do not pass `seller: ZeroClick::Sellers.seller` here. `config.middleware.use` > evaluates its arguments in the `Application` class body, which runs **before** > the initializer that reads `config.zeroclick` — so no client exists yet and > boot fails. Omit `seller:` and the middleware resolves the process-wide client > on the first request, by which point configuration exists. Outside Rails, > where you build the client yourself, pass it explicitly. > [!NOTE] > > In **development only**, `ActionDispatch::HostAuthorization` sits at the top of > the Rails stack and answers `403` before the guard is reached, so testing > through a tunnel needs `config.hosts << "my-tunnel.ngrok.app"`. It is not in > the production stack, so a deployed app needs nothing here. Inside a controller, the verified caller is on the request env: ```ruby theme={null} class ExtractController < ApplicationController def create zc = request.env["zeroclick.context"] Rails.logger.info("serving #{zc.zc_agent_id} for #{zc.zc_request_id}") render json: { ok: true } end end ``` `zc_request_id` correlates with ZeroClick's own logs — use it when you derive an idempotency key. ## Guard a Sinatra or Rack route The same middleware, mounted the Rack way: ```ruby theme={null} # config.ru require "zeroclick/sellers" SELLER = ZeroClick::Sellers.create( api_key: ENV.fetch("ZEROCLICK_API_KEY"), signing_secrets: ZeroClick::Sellers.secrets_from_env ) use ZeroClick::Sellers::Middleware::Meter, seller: SELLER, service_slug: "extractor", usage: [ZeroClick::Sellers::UsageItem.new(meter_slug: "requests", quantity: 1)] run MyApp ``` ## What the middleware does 1. Reads the body (bounded at 10 MiB) and **verifies `zc-signature`** before anything else. 2. Asks ZeroClick whether the buyer can pay for the declared usage. 3. On refusal, answers `402` with the payment challenge — your app is never called. 4. On success, calls your app, then attaches `zc-usage` **only if you answered `2xx`**. A non-2xx answer is never billed: the work was not delivered. Your app can still read the request body. Verification has to consume it, so the middleware replaces `rack.input` with a fresh stream over the same bytes. It deliberately does not rely on `#rewind`, which Rack 3 no longer guarantees. ## Guard without the middleware When the charge depends on the request, guard inside the action: ```ruby theme={null} request, = ZeroClick::Sellers::Middleware.request_from_env(env) decision = SELLER.guard( request, service_slug: "extractor", usage: [ZeroClick::Sellers::UsageItem.new(meter_slug: "pages", quantity: pages)] ) unless decision.allow? return [decision.response.status, decision.response.headers, [decision.response.body]] end ``` For a free endpoint that still needs to know who is calling, use `Middleware::Identify` or `SELLER.guard_identity`. Neither makes a network call. ## Deployment note The signature covers the **raw, percent-encoded** request target. The middleware prefers the server's raw target (`REQUEST_URI`, which Puma sets) over the decoded `PATH_INFO`. Behind a server that decodes and exposes no raw target, a route containing an encoded separator such as `%2F` cannot verify — deploy behind Puma if your routes can contain one. ## Next > [card] [Configuration](/docs/sdks/ruby/configuration) > > Keys, the outage policy, and timeouts. > [card] [Middleware](/docs/sdks/ruby/middleware) > > Meter, Identify, and settling variable usage. > [card] [API](/docs/sdks/ruby/api) > > Every public method and value type. > [card] [Errors](/docs/sdks/ruby/errors) > > What raises, what returns a decision. # TypeScript SDK API Source: https://zeroclickai.mintlify.dev/docs/sdks/typescript/api Every public export of @zeroclickai/sellers: client methods, standalone functions, result shapes, and the contracts, encryption, and stateful subpaths. Everything in `@zeroclickai/sellers` comes two ways: as bound methods on the client `createSeller(config)` returns, and as standalone named exports. The standalone exports are for applications that place verification, allowance checking, and response construction in separate middleware layers. All public functions validate their inputs and throw a typed [`ZCError`](/docs/sdks/typescript/errors) for malformed input or API failure. Signature failures and business denials are returned decisions, never exceptions. ## Client methods `createSeller(config)` (see the [configuration reference](/docs/sdks/typescript/configuration)) returns these bound methods: | Method | Purpose | | - | - | | `guard(request, input)` | Verify the request, check the allowance, and return an allow or deny decision. | | `guardIdentity(request, input)` | Verify the request and require a proven buyer for a free, identity-scoped call. No allowance call. | | `verifyRequest(request)` | Verify only the ZeroClick request signature without consuming the original body. | | `checkAllowance(input, options?)` | Call `POST /v1/usage/check` directly. | | `paymentRequired(input)` | Construct the exact seller `402 payment_required` response. | | `withUsage(response, usage)` | Set the validated `zc-usage` header without consuming the response body. | | `reportUsage(input, options?)` | Call `POST /v1/usage` for asynchronous usage. | ### guard ```ts theme={null} guard(request: Request, input: { serviceSlug: string; planSlug?: string; usage: UsageItem[]; // at least one item }): Promise ``` Verifies the signature first, then checks the allowance under the request's own `zcRequestId` and returns a [decision](#guardresult). It never consults the allowance API for an unverified request. Each `UsageItem` names a `meterSlug` and declares the charge one of three ways: an exact `quantity`, a `maxQuantity` ceiling, or neither. A ceiling covers work you cannot size up front; it settles later at actual usage, so it never overcharges. An item with neither defers to the meter's configured max usage per request. The SDK rejects an item that declares both. It also rejects duplicate meters and an empty `usage` array: an accidentally empty computed array must fail rather than silently skip the check. ```ts theme={null} const decision = await zeroClick.guard(request, { serviceSlug: "product-watch", usage: [ { meterSlug: "requests", quantity: 1 }, { meterSlug: "output_tokens", maxQuantity: 100_000 }, ], }); ``` On a business denial, the SDK builds the carried response from your `input`: the exact `402 payment_required` body with the declared usage and, if you passed one, the `planSlug`. See [charge up to a maximum](/docs/integrate/charge-up-to-a-maximum) for the ceiling pattern. ### guardIdentity ```ts theme={null} guardIdentity(request: Request, input: { serviceSlug: string }): Promise ``` The guard for free, identity-scoped endpoints: calls that cost nothing but serve only the buyer that owns the underlying records, such as polling a job the buyer created. It verifies the signature exactly like `guard`. When `zc-agent-id` is present, it allows with `allowance: { status: "not_required" }`. When it is absent, it denies with `reason: "identity_required"` and a `402` whose body carries `usage: []`. ZeroClick answers that with `401 bearer_required` and its registration recipe, and the retry arrives with the buyer's `zc-agent-id` attached. `guardIdentity` makes no allowance call, and no `zc-usage` belongs on the response: free means free. ```ts theme={null} export async function GET(request: Request) { const decision = await zeroClick.guardIdentity(request, { serviceSlug: "product-watch", }); if (decision.action === "deny") return decision.response; const job = await findJob(jobId, { owner: decision.context.zcAgentId }); if (!job) return Response.json({ error: "not_found" }, { status: 404 }); return Response.json(job); } ``` Identity alone is not billability: a buyer that has only proven identity has no active access, so `reportUsage` against it fails with `access_not_found`. Gate billable work with `guard`. See [free and identity endpoints](/docs/integrate/free-and-identity-endpoints). ### verifyRequest ```ts theme={null} verifyRequest(request: Request): Promise ``` Verifies the `zc-signature` header and nothing else: parses `t`, `kid`, and `v1`, enforces the timestamp tolerance, resolves the signing secret by `kid`, recomputes the HMAC-SHA256 over the canonical string, and compares in constant time. It reads a clone, so the original body stays readable. The result is a decision: ```ts theme={null} type VerifyRequestResult = | { ok: true; context: ZeroClickContext } | { ok: false; reason: VerifyFailureReason; response: Response }; ``` `reason` is one of `missing_signature`, `malformed_signature`, `stale_timestamp`, `missing_request_id`, `unknown_kid`, or `invalid_signature`; `response` is the ready-to-return `401 {"error":"invalid_zeroclick_signature"}`. Use it when verification and allowance checking live in different layers: ```ts theme={null} const verification = await zeroClick.verifyRequest(request); if (!verification.ok) return verification.response; // verification.context: zcRequestId, zcAgentId, timestamp, kid ``` The [signature spec](/docs/integrate/signature-spec) specifies the canonical string and header format. ### checkAllowance ```ts theme={null} checkAllowance( input: { zcRequestId: string; serviceSlug: string; usage: UsageItem[] }, options?: { signal?: AbortSignal }, ): Promise<{ allowed: boolean; reason: UsageDenialReason | null }> ``` Calls `POST /v1/usage/check` with the verified request's `zcRequestId`. Checking records nothing and burns no credit: it answers whether the declared usage is covered right now. The SDK rejects an empty or duplicate-metered `usage` array before calling; the API accepts up to 20 items. Unlike `guard`, `checkAllowance` throws on a failed call: no outage policy applies here, so the caller decides. ```ts theme={null} const allowance = await zeroClick.checkAllowance({ zcRequestId: verification.context.zcRequestId, serviceSlug: "product-watch", usage: [{ meterSlug: "requests", quantity: 1 }], }); if (!allowance.allowed) { // allowance.reason: "usage_exhausted", "access_not_found", … } ``` See [check allowances](/docs/integrate/check-allowances) for what each denial reason means. ### paymentRequired ```ts theme={null} paymentRequired(input: { serviceSlug: string; planSlug?: string; usage: UsageItem[]; // [] is the free identity refusal }): Response ``` Constructs the exact `402` refusal ZeroClick expects from a seller: `{"error":"payment_required","serviceSlug":"…","usage":[…]}`. For pay-as-you-go pricing, ZeroClick re-prices the refusal an unpaid call earns into the priced challenge the agent sees. An empty `usage` array is valid here: it is the refusal for a free, identity-scoped endpoint, and ZeroClick answers it with `401 bearer_required` and never a charge. ```ts theme={null} return zeroClick.paymentRequired({ serviceSlug: "product-watch", usage: [{ meterSlug: "output_tokens", maxQuantity: 100_000 }], }); ``` ### withUsage ```ts theme={null} withUsage(response: Response, usage: { serviceSlug: string; meterSlug: string; quantity: number; // positive integer }[]): Response ``` Sets the validated `zc-usage` header for synchronous settlement without consuming the response body: it requires an unread `Response` and rebuilds it around the same body stream. Every item declares an exact quantity: this is where ceilings settle at actual usage. The header belongs on successful (`2xx`) responses only, and ZeroClick strips it before the agent sees the response. ```ts theme={null} return zeroClick.withUsage(response, [ { serviceSlug: "product-watch", meterSlug: "requests", quantity: 1 }, { serviceSlug: "product-watch", meterSlug: "output_tokens", quantity: 4187 }, ]); ``` See [settle usage](/docs/integrate/settle-usage) for choosing between synchronous and asynchronous settlement. ### reportUsage ```ts theme={null} reportUsage( input: { zcAgentId: string; idempotencyKey: string; serviceSlug: string; meterSlug: string; quantity: number; // positive integer occurredAt?: string; // ISO timestamp }, options?: { signal?: AbortSignal }, ): Promise ``` Calls `POST /v1/usage` for work that finishes after the response is gone. The idempotency key is seller-owned: derive it from stable facts (`zcreq_8h2m4x0q9k1f_output_tokens`), never random. Reporting is idempotent per service on that key, and `reportUsage` does not generate keys or retry automatically. ```ts theme={null} const result = await zeroClick.reportUsage({ zcAgentId: "agt_x7f2kq93bh0d", idempotencyKey: "zcreq_8h2m4x0q9k1f_output_tokens", serviceSlug: "product-watch", meterSlug: "output_tokens", quantity: 4200, }); console.log(result.recorded, result.duplicate); ``` The result is `{ recorded: true, duplicate: boolean, usageEvent }`. `duplicate: true` replays the stored event: a success, not an error. A business denial at reporting time throws an `api_status_error` whose `context.reason` carries the denial reason; see [errors](/docs/sdks/typescript/errors). ## Result shapes ### GuardResult `guard` and `guardIdentity` return the same union: ```ts theme={null} type GuardResult = | { action: "allow"; context: ZeroClickContext; allowance: { status: "allowed" | "unavailable" | "not_required" }; } | { action: "deny"; reason: GuardDenyReason; response: Response }; ``` The allow branch's `context` is the verified ZeroClick envelope: | Field | Value | | - | - | | `zcRequestId` | The correlation id (`zcreq_…`) ZeroClick threads through the challenge, the paid retry, and the usage record. | | `zcAgentId` | The id (`agt_…`) of the agent that made this call, or `null` on a signed anonymous probe. | | `zcAnonymousId` | The same value as `zcAgentId`, read from `zc-anonymous-id`: the name that will eventually replace `zc-agent-id`. | | `zcBuyerId` | The buyer (`byr_…`) the agent belongs to, or `null` for an anonymous agent. Not covered by the signature. See [agents and access](/docs/concepts/agents-and-access). | | `timestamp` | The signature timestamp, in Unix seconds. | | `kid` | The id of the signing secret that verified the request. | `allowance.status` is `"allowed"` when the API said yes, `"unavailable"` when the fail-open outage policy admitted a verified request without an answer, and `"not_required"` from `guardIdentity`, which makes no allowance call. ### Deny reasons | `reason` | Response carried | Source | | - | - | - | | `missing_signature`, `malformed_signature`, `stale_timestamp`, `missing_request_id`, `unknown_kid`, `invalid_signature` | `401` with `{"error":"invalid_zeroclick_signature"}` | Signature verification, in every guard | | `service_not_found`, `access_not_found`, `access_inactive`, `plan_expired`, `meter_not_found`, `meter_not_priced`, `usage_exhausted` | `402` with the `payment_required` body | The allowance check in `guard` | | `allowance_denied` | `402` with the `payment_required` body | `guard`, when the API denies without naming a reason | | `identity_required` | `402` with `usage: []` | `guardIdentity`, for a signed request without `zc-agent-id` | | `allowance_unavailable` | `503` with `{"error":"allowance_unavailable"}` | `guard` under the `"deny"` outage policy | ## Standalone exports The same primitives are named exports for applications that spread the flow across middleware layers. The guards take an options argument in place of client configuration; the API calls take [per-call options](/docs/sdks/typescript/configuration#standalone-function-options). * `guard(request, input, options)`: options are a signing-secret source (`signingSecrets` or `resolveSigningSecret`), a required `apiKey`, and the guard settings (`apiBaseUrl`, `fetch`, `clock`, `toleranceSeconds`, `allowanceUnavailable`, `checkTimeoutMs`, `onAllowanceUnavailable`). * `guardIdentity(request, input, options)` and `verifyRequest(request, options)`: options are a signing-secret source plus optional `clock` and `toleranceSeconds`. * `checkAllowance(input, options)` and `reportUsage(input, options)`: options are `{ apiKey, apiBaseUrl?, fetch?, signal?, timeoutMs? }`. * `paymentRequired(input)` and `withUsage(response, usage)`: identical to the bound methods. * `invalidZeroClickSignature()` and `allowanceUnavailable()`: construct the bare `401` and `503` refusal responses. * `ZCError` and `isZCError`: the typed error and its narrowing helper; see [errors](/docs/sdks/typescript/errors). ```ts theme={null} import { verifyRequest } from "@zeroclickai/sellers"; const verification = await verifyRequest(request, { signingSecrets: { hsec_k5nq0v7m3d8p: process.env.ZEROCLICK_SIGNING_SECRET!, }, }); ``` The package root exports TypeScript types for every input and result: `SellerConfig`, `GuardInput`, `GuardResult`, `ZeroClickContext`, `UsageItem`, `SyncUsageItem`, `CheckAllowanceInput`, `AllowanceDecision`, `UsageDenialReason`, `ReportUsageInput`, `ReportUsageResult`, and the rest. ## The contracts subpath `@zeroclickai/sellers/contracts` exports the seller-facing Zod schemas and their inferred types: guard input, usage items, allowance requests, responses, and denial reasons, the `payment_required` body, `zc-usage` items, signature headers, the verified context, report inputs and results, seller configuration, and API call options. ```ts theme={null} import { checkAllowanceInputSchema, paymentRequiredBodySchema, reportUsageInputSchema, syncUsageSchema, zeroClickContextSchema, } from "@zeroclickai/sellers/contracts"; const usage = syncUsageSchema.parse([ { serviceSlug: "product-watch", meterSlug: "requests", quantity: 1 }, ]); ``` Public SDK methods already validate their inputs, so reach for the schemas only to validate data at an earlier boundary: a queue message that will become a `reportUsage` call, a stored usage draft, a test fixture. ## Encryption The `@zeroclickai/sellers/encryption` subpath exports `decryptRequest(request, { resolvePrivateKey })` and `encryptResponse(response, envelope)`. Run `guard` or `verifyRequest` against the original encrypted request before decryption. The signature then covers the original Compact JWE bytes. The suite is fixed to `ECDH-ES+A256KW` key management and `A256GCM` content encryption. `decryptRequest` selects a private key with the protected `kid`. Private encryption keys remain seller-owned. The SDK does not generate, upload, persist, or rotate them. See [end-to-end body encryption](/docs/concepts/end-to-end-encryption) for the complete data path and trust boundary. ## The stateful subpath `@zeroclickai/sellers/stateful` implements the account routes for [sellers whose purchases create accounts and API keys](/docs/integrate/stateful-sellers): * `handleAccessRequest(request, { onWrite, onMint }, options)`: routes, verifies, and validates both account calls, then hands off to your two handlers. Returns `null` for anything that is not one of its routes. * `shouldApply`, `deriveCreditDelta`, `periodAdvanced`, and `parseEntitlement`: the dedup and never-regress arithmetic an account write must be applied with. * `isServiceable`: the one request-time gate — `true` only while the account is `active` and its period, when it has an `end`, has not lapsed. * `parseMoneyUsd` and `formatMoneyUsd`: six-decimal money strings to integer micros and back, so no floating-point math ever touches money. * `verifyAccessSignature`, `canonicalAccessString`, and `signAccessRequest`: the purpose-carrying access signature on its own, plus a signer for integration tests. * The wire schemas and their types (`accessUpsertRequestSchema`, `mintKeyResponseSchema`, and the rest), mirroring the [contracts subpath](#the-contracts-subpath) pattern. Do not route these calls through `guard` or `verifyRequest`: account calls carry a different, purpose-separated signature by design. The [account and key reference](/docs/resources/stateful-access-reference) documents every field, status, and retry rule. # TypeScript SDK configuration Source: https://zeroclickai.mintlify.dev/docs/sdks/typescript/configuration Every createSeller option, signing-secret rotation, split usage keys, the allowance outage policy, and per-call overrides. `createSeller(config)` validates its configuration up front and returns a frozen client. Invalid configuration throws a `ZCError` with code `malformed_input` at construction, not at request time. Construction enforces two constraints: * **Exactly one signing-secret source.** Provide `signingSecrets` or `resolveSigningSecret`: not both, not neither. * **Both usage directions covered.** Allowance checks (`guard`, `checkAllowance`) use `usageReadKey`. Usage reporting (`reportUsage`) uses `usageWriteKey`. A single `apiKey` with both scopes backfills either side. `createSeller` rejects a config that leaves a direction without a key; `context.issues` names the missing side. ## Options | Option | Required | Default | Description | | - | - | - | - | | `signingSecrets` | One secret source | None | Record from ZeroClick signing-secret `kid` (`hsec_…`) to secret value (`zcsec_…`). Keep the current and previous keys in the record during rotation. | | `resolveSigningSecret` | One secret source | None | Async resolver `({ kid }) => secret`, returning `null` for an unknown `kid`. For a secret manager or other dynamic store. | | `apiKey` | Key coverage | None | API key with both the `usage:read` and `usage:write` scopes. Backfills whichever scoped key below is absent. | | `usageReadKey` | Key coverage | None | API key with `usage:read`, used for the allowance checks behind `guard` and `checkAllowance`. | | `usageWriteKey` | Key coverage | None | API key with `usage:write`, used for `reportUsage`. | | `apiBaseUrl` | No | `https://api.zeroclick.io` | Absolute API base URL, as a string or `URL`. | | `fetch` | No | `globalThis.fetch` | Injected Fetch-compatible implementation, useful for private deployments and tests. | | `toleranceSeconds` | No | `300` | Maximum absolute age of a request signature, in seconds. | | `clock` | No | `Date.now` | Millisecond clock function, primarily for deterministic tests. | | `checkTimeoutMs` | No | `1500` | Allowance-check timeout in milliseconds. | | `allowanceUnavailable` | No | `"allow"` | Outage policy when the allowance API gives no answer: `"allow"`, `"deny"`, or `"throw"`. | | `onAllowanceUnavailable` | No | None | Callback receiving the sanitized `ZCError` when the allowance API is unavailable. | ## Usage keys One API key with both usage scopes covers everything. To separate concerns (a request path that only checks, a worker that only reports), pass scoped keys: ```ts theme={null} import { createSeller } from "@zeroclickai/sellers"; const zeroClick = createSeller({ signingSecrets: { hsec_k5nq0v7m3d8p: process.env.ZEROCLICK_SIGNING_SECRET!, }, usageReadKey: process.env.ZEROCLICK_USAGE_READ_KEY!, usageWriteKey: process.env.ZEROCLICK_USAGE_WRITE_KEY!, }); ``` A scoped key can also override one direction while `apiKey` backfills the other. See [keys and secrets](/docs/integrate/keys-and-secrets) for minting scoped keys. ## Signing-secret rotation ZeroClick identifies each signature with a `kid`: the signing secret's id, carried in every `zc-signature` header. Keep every key that may still sign an in-flight request available to the SDK: ```ts theme={null} const zeroClick = createSeller({ signingSecrets: { hsec_k5nq0v7m3d8p: process.env.ZEROCLICK_SIGNING_SECRET_CURRENT!, hsec_j2rw8t4c6y1z: process.env.ZEROCLICK_SIGNING_SECRET_PREVIOUS!, }, apiKey: process.env.ZEROCLICK_API_KEY!, }); ``` If a request's `kid` is missing from the record, the SDK denies it with a `401` (reason `unknown_kid`). Never log or return a signing secret. Revoke an old key only after requests signed by it can no longer be in flight. ## Resolving secrets dynamically For managed secret storage, resolve by `kid` instead of holding secrets in memory: ```ts theme={null} const zeroClick = createSeller({ resolveSigningSecret: async ({ kid }) => secretStore.get(kid), apiKey: process.env.ZEROCLICK_API_KEY!, }); ``` The resolver runs on every verification with the `kid` from the request's signature header. Return the secret, or `null` for a `kid` you do not recognize. The SDK denies that request as `unknown_kid`. A resolver that throws surfaces as a `ZCError` with code `signing_secret_resolution_failed` rather than a deny. An outage in your secret store shows up as an error instead of silently rejecting traffic. ## Allowance outage policy The default policy is fail-open after the 1.5-second check timeout: the SDK allows a verified request with `allowance.status === "unavailable"`, and `onAllowanceUnavailable` receives the sanitized error. Configure `"deny"` to return `503 {"error":"allowance_unavailable"}` instead, or `"throw"` to handle the typed error in application code: ```ts theme={null} const zeroClick = createSeller({ signingSecrets: { hsec_k5nq0v7m3d8p: process.env.ZEROCLICK_SIGNING_SECRET!, }, apiKey: process.env.ZEROCLICK_API_KEY!, allowanceUnavailable: "deny", onAllowanceUnavailable: (error) => { console.error("allowance check unavailable", error.code, error.context); }, }); ``` The policy applies when the allowance check produces no usable answer: the call failed or timed out (`api_transport_error`), the API answered with an unsuccessful status (`api_status_error`), or the response body did not validate (`api_response_invalid`). It applies only after the signature verifies: the SDK never allows an unverified request because the allowance API is unavailable. A definite `allowed: false` answer is never subject to the policy; it always denies with the `402`. ## Per-call cancellation The bound `checkAllowance` and `reportUsage` methods accept an optional `{ signal }`: ```ts theme={null} await zeroClick.reportUsage(input, { signal: request.signal }); ``` The signal combines with the built-in timeout; whichever fires first aborts the call. `guard` already ties its allowance check to the incoming request's own `AbortSignal`, so an agent that disconnects does not leave a check running. Through the client, the allowance check times out after `checkTimeoutMs`, and `reportUsage` after the fixed 1,500 ms default. To raise the reporting timeout, call the standalone export with `timeoutMs`. ## Standalone function options The `checkAllowance` and `reportUsage` named exports hold no client state. Each call carries its own options, for middleware layers or workers that never construct a client: | Option | Required | Default | Description | | - | - | - | - | | `apiKey` | Yes | None | API key with the scope the call needs: `usage:read` for `checkAllowance`, `usage:write` for `reportUsage`. | | `apiBaseUrl` | No | `https://api.zeroclick.io` | Absolute API base URL, as a string or `URL`. | | `fetch` | No | `globalThis.fetch` | Injected Fetch-compatible implementation. | | `signal` | No | None | `AbortSignal` combined with the timeout. | | `timeoutMs` | No | `1500` | Per-call timeout in milliseconds. | ```ts theme={null} import { reportUsage } from "@zeroclickai/sellers"; const result = await reportUsage( { zcAgentId: "agt_x7f2kq93bh0d", idempotencyKey: "zcreq_8h2m4x0q9k1f_output_tokens", serviceSlug: "product-watch", meterSlug: "output_tokens", quantity: 4200, }, { apiKey: process.env.ZEROCLICK_USAGE_WRITE_KEY!, timeoutMs: 5000 }, ); ``` The standalone `guard`, `guardIdentity`, and `verifyRequest` exports take the options a client would otherwise hold; the [API reference](/docs/sdks/typescript/api#standalone-exports) lists their shapes. # TypeScript SDK errors Source: https://zeroclickai.mintlify.dev/docs/sdks/typescript/errors Deny decisions vs ZCError exceptions, the full error-code list, narrowing with isZCError, and which operations throw which codes. The SDK separates expected protocol outcomes from failures. Missing, stale, malformed, or invalid ZeroClick signatures are expected protocol outcomes, not exceptions. `guard` and `guardIdentity` return a deny decision that carries the exact `Response` to return. The lower-level `verifyRequest` returns `{ ok: false, reason, response }`. Business denials (`allowed: false` from the allowance API) are deny decisions too. Malformed inputs, ZeroClick API failures, signing-secret resolution failures, and encryption failures throw `ZCError`. ## ZCError `ZCError` extends `Error` with a machine-readable `code` and a sanitized `context`: ```ts theme={null} class ZCError extends Error { readonly name: "ZCError"; readonly code: ZCErrorCode; readonly context: { operation: string; // the SDK operation that failed issues?: { code: string; message: string; path: (string | number)[] }[]; kid?: string; reason?: string; status?: number; }; } ``` `context` contains only sanitized operational fields: the operation, status, reason, key id, and validation issue paths. It never includes API keys, signing secrets, or request body bytes, so it is safe to log and is what `onAllowanceUnavailable` receives. ## Narrowing with isZCError Use `isZCError` to narrow an unknown error, optionally to one error code: ```ts theme={null} import { isZCError } from "@zeroclickai/sellers"; try { await zeroClick.reportUsage({ zcAgentId: "agt_x7f2kq93bh0d", idempotencyKey: "zcreq_8h2m4x0q9k1f_output_tokens", serviceSlug: "product-watch", meterSlug: "output_tokens", quantity: 4200, }); } catch (error) { if (isZCError(error, "api_status_error")) { console.error(error.code, error.context.status, error.context.reason); } throw error; } ``` `isZCError(error)` narrows to `ZCError`; passing a code narrows further, at runtime and in types: inside the branch, `error` is `ZCError & { code: "api_status_error" }`. ## Error codes Sixteen codes cover the SDK. The first seven come from the core package; only the `@zeroclickai/sellers/encryption` subpath throws the nine JWE codes. ### Core codes | Code | Meaning | | - | - | | `malformed_input` | An SDK input failed validation: configuration, guard input, usage items, or call options. `context.issues` lists each violation's path. | | `malformed_request` | The value passed as the request is not a usable web-native `Request`, or the SDK could not clone and read its body. | | `crypto_unavailable` | The runtime provides no Web Crypto (`globalThis.crypto.subtle`), so the SDK cannot verify signatures. | | `signing_secret_resolution_failed` | The signing-secret resolver threw or returned an unusable value. Returning `null` for an unknown `kid` is not an error: the SDK denies that request as `unknown_kid`. | | `api_transport_error` | The call to the ZeroClick API failed or timed out before any response arrived. | | `api_status_error` | The ZeroClick API answered with an unsuccessful status. `context.status` carries it; `reportUsage` denials add `context.reason`. | | `api_response_invalid` | The ZeroClick API answered, but with a body the SDK could not parse or validate. | ### JWE codes | Code | Meaning | | - | - | | `invalid_compact_jwe` | The request body is not a valid Compact JWE. | | `unsupported_jwe_suite` | The JWE does not use the fixed `ECDH-ES+A256KW` / `A256GCM` suite. | | `jwe_kid_required` | The JWE protected header carries no key id to resolve a private key by. | | `invalid_reply_jwk` | The buyer's reply JWK is not a public P-256 key. | | `private_reply_jwk` | The reply JWK contains private-key material, so the SDK rejects it. | | `private_key_not_found` | The resolver returned no private key for the JWE's key id. | | `private_key_resolution_failed` | The private-key resolver threw or returned an unusable value. | | `decryption_failed` | The SDK could not decrypt the Compact JWE with the resolved key. | | `encryption_failed` | The SDK could not encrypt the response body for the buyer's reply key. | ## What throws where | Operation | Codes it can throw | | - | - | | `createSeller` | `malformed_input`, when the config violates the one-secret-source rule or leaves a usage direction without a key. | | `verifyRequest`, `guard`, `guardIdentity` (verification step) | `malformed_input`, `malformed_request`, `crypto_unavailable`, `signing_secret_resolution_failed`. Signature outcomes never throw. | | `guard` (allowance step) | `api_transport_error`, `api_status_error`, `api_response_invalid`, routed through the outage policy. The default `"allow"` converts them into an allow with `allowance.status: "unavailable"`, surfacing them only to `onAllowanceUnavailable`. `"deny"` converts them into the `503`, and `"throw"` rethrows them. | | `checkAllowance` | `malformed_input`, `api_transport_error`, `api_status_error`, `api_response_invalid`. | | `reportUsage` | Same as `checkAllowance`. On a `402`, `404`, or `409` denial, `context.reason` carries the machine reason, such as `usage_exhausted` or `meter_not_priced`. | | `paymentRequired`, `withUsage` | `malformed_input`, including a `withUsage` call on an already-read `Response`. | | `decryptRequest` | `malformed_input`, `malformed_request`, and every JWE code except `encryption_failed`. | | `encryptResponse` | `malformed_input`, `encryption_failed`. | > [!NOTE] > > A duplicate usage report is not an error: `reportUsage` resolves with `duplicate: true` and replays the stored event. Only denials and infrastructure failures throw. The [error reference](/docs/resources/errors) documents the wire-level error envelope behind `api_status_error`. # TypeScript SDK quickstart Source: https://zeroclickai.mintlify.dev/docs/sdks/typescript/quickstart Install @zeroclickai/sellers and guard one route end to end: verify the signature, check the allowance, serve, and settle usage. [`@zeroclickai/sellers`](https://www.npmjs.com/package/@zeroclickai/sellers) implements the ZeroClick billing guard for web-native TypeScript backends. It verifies that ZeroClick signed each forwarded request, checks the buyer's allowance before you do the work, builds the refusal responses ZeroClick expects, and settles what was used. This page guards one route with it. The [quickstart](/docs/quickstart) covers the same flow across all four SDKs, and the [integration contract](/docs/integrate/overview) defines what the guard implements. > [!NOTE] > > You need the keys from the [quickstart](/docs/quickstart): a signing secret (`zcsec_…`) with its key id (`hsec_…`), and an API key (`zc_…`) with the `usage:read` and `usage:write` scopes. You can pass a scoped key per direction instead; see [configuration](/docs/sdks/typescript/configuration). This page uses a service `product-watch` with a meter `requests`; substitute your own slugs. ## Install ```sh theme={null} pnpm add @zeroclickai/sellers ``` The package is ESM and uses the standard `Request`, `Response`, `fetch`, `AbortSignal`, and Web Crypto APIs. It works in any runtime that provides those, including current Node.js and compatible edge runtimes. Nothing in the SDK is framework-specific; you adapt at the boundary, covered [below](#framework-integration). ## Guard a route Configure the client once, then use `guard` before doing work and `withUsage` on the successful response: ```ts theme={null} import { createSeller } from "@zeroclickai/sellers"; const signingSecretKid = process.env.ZEROCLICK_SIGNING_SECRET_KID; const signingSecret = process.env.ZEROCLICK_SIGNING_SECRET; const apiKey = process.env.ZEROCLICK_API_KEY; if (!signingSecretKid || !signingSecret || !apiKey) { throw new Error("ZeroClick seller credentials are not configured"); } const zeroClick = createSeller({ signingSecrets: { [signingSecretKid]: signingSecret, }, apiKey, }); export async function handle(request: Request): Promise { const decision = await zeroClick.guard(request, { serviceSlug: "product-watch", usage: [{ meterSlug: "requests", quantity: 1 }], }); if (decision.action === "deny") return decision.response; const response = Response.json({ message: "Hello from the seller", zcRequestId: decision.context.zcRequestId, }); return zeroClick.withUsage(response, [ { serviceSlug: "product-watch", meterSlug: "requests", quantity: 1, }, ]); } ``` `withUsage` stamps the validated `zc-usage` header on the response so ZeroClick settles the usage synchronously; ZeroClick strips the header before the agent sees the response. Set it on successful (`2xx`) responses only. [Settle usage](/docs/integrate/settle-usage) covers the asynchronous alternative for work that outlives the request. ## Decisions, not exceptions `guard` always verifies the signature before it calls the allowance API. Its result is an explicit decision: * `action: "allow"` carries the verified context (`zcRequestId`, `zcAgentId`, the signature timestamp, and the `kid` that verified) and an allowance status of `"allowed"` or `"unavailable"`. * `action: "deny"` carries a `reason` and the exact `Response` to return. Invalid signatures produce a `401`, business denials produce the seller `402 payment_required` body, and fail-closed allowance outages produce a `503`. Return `decision.response` unchanged: each body is exactly what ZeroClick expects back from your API. The [API reference](/docs/sdks/typescript/api) lists every deny reason, and [errors](/docs/sdks/typescript/errors) draws the line between decisions and thrown `ZCError`s. ## Anonymous probes Signed anonymous probes are valid requests. ZeroClick sends them with no agent id when it checks your endpoints: the signature verifies, and `decision.context.zcAgentId` is `null`. Buyer calls always carry the agent id (`agt_…`), including the unpaid call ZeroClick forwards to price a pay-as-you-go challenge. Treat probes like any other request: run the same guard and return the same responses. ## Framework integration Adapt your framework's request object to a web-native `Request` at the boundary. Preserve the exact method, URL, headers, and body bytes. The SDK reads a clone, so the original request body remains readable in your handler. Return the SDK-provided `Response` directly, or adapt it back to the framework's response type. A framework that already speaks web standards needs no glue. Hono hands you the untouched request as `c.req.raw`: ```ts theme={null} import { Hono } from "hono"; const app = new Hono(); app.post("/v1/product-watch", async (c) => { // zeroClick is the client from createSeller above. const decision = await zeroClick.guard(c.req.raw, { serviceSlug: "product-watch", usage: [{ meterSlug: "requests", quantity: 1 }], }); if (decision.action === "deny") return decision.response; // guard read a clone, so the body is still readable here. const { productId } = await c.req.json(); const response = Response.json({ watching: productId }); return zeroClick.withUsage(response, [ { serviceSlug: "product-watch", meterSlug: "requests", quantity: 1 }, ]); }); export default app; ``` A Next.js route handler already receives a web-native `Request` and returns a `Response`. The `handle` function above drops in as `export async function POST(request: Request)` in a `route.ts` file. > [!WARNING] > > The signature covers the raw bytes ZeroClick sent: the percent-encoded path and query exactly as requested, and the unmodified body. An adapter that re-parses and re-serializes the body, or normalizes the URL, breaks verification. Hand the original request through untouched. ## Next steps > [card] [Configuration](/docs/sdks/typescript/configuration) > > Every `createSeller` option: rotation, split keys, timeouts, outage policy. > [card] [API reference](/docs/sdks/typescript/api) > > Every export, decision shape, and deny reason. > [card] [Errors](/docs/sdks/typescript/errors) > > `ZCError` codes and what throws where. > [card] [Charge up to a maximum](/docs/integrate/charge-up-to-a-maximum) > > Bill work you can't size up front, like output tokens. # Buy with AI widget Source: https://zeroclickai.mintlify.dev/docs/website/buy-with-ai-widget Add a Buy with AI handoff to your website, then customize its layout, copy, colors, corners, and typography with data attributes. The Buy with AI widget gives shoppers an on-page way to hand a purchase to an AI agent they already use. The agent asks what they need, compares the live offerings in your ZeroClick storefront, recommends an option, and completes the purchase only after the shopper approves it. When a shopper picks an agent, the widget fetches a walkthrough prompt from your storefront and opens that agent when a direct handoff is available. It also copies the prompt, so the shopper can paste it if the app does not open. If the prompt cannot load, the widget sends the shopper to your storefront instead. The widget does not contain your catalog, prices, or purchasing instructions. Those stay on your storefront, so the handoff always starts with current information. > [card] [Open the visual customizer](https://dashboard.zeroclick.io) > > Open your store, then go to **Discovery listings → Buy with AI → Customize** to preview the widget and copy a generated snippet. ## Add the widget Copy the generated snippet from the dashboard when possible. It fills in the storefront URL, store name, and agent-readable discovery attributes for you. The base snippet has one marker element and one hosted script: ```html theme={null}
``` Place the `
` where the widget should render. Replace every Acme value with your own store's values if you write the snippet by hand. The hosted script can appear anywhere after the marker and can initialize widgets added later by a single-page app. > [!NOTE] > > If you place more than one widget on a page, add a marker for each location but load `buy-with-ai.js` only once. The script reads each marker's attributes when it initializes that widget. To change an attribute after the widget has rendered, replace the marker element so the script initializes it again. > [!NOTE] > > If your site sets a strict Content-Security-Policy, allow `script-src` for `cdn.zeroclick.io` and `connect-src` for your storefront origin. The widget fetches the walkthrough prompt and sends its analytics beacons to that origin. ### Required attributes Keep these attributes in every snippet. The last three make the handoff legible to agents that read the page's raw HTML without running JavaScript. | Attribute | Value | | - | - | | `data-zeroclick-buy-with-ai` | Marks the element for the hosted widget script. It has no value. | | `data-pay-host` | Your storefront origin, such as `https://acme.pay.zeroclick.io` or your custom storefront domain. The widget fetches `/prompt.txt` from this origin. | | `data-seller-name` | Your store's display name. Default copy substitutes it for `{SELLER}`. | | `data-agent-description` | A declarative description of the shopper-initiated handoff. Keep the dashboard-generated wording. | | `data-agent-storefront-url` | The full URL of your storefront's `llms.txt`, including `?src=buy-with-ai`. | | `data-agent-prompt-url` | The full URL of your storefront's `prompt.txt`, including `?src=buy-with-ai`. | ## Customize the layout and actions Add any optional attribute below to the marker element. Omitted attributes use the defaults shown here. | Attribute | Accepted values | Default | Effect | | - | - | - | - | | `data-layout` | `card`, `banner`, or `launcher` | `card` | Selects the widget's composition. See [layouts](#layouts). | | `data-theme` | `auto`, `light`, or `dark` | `auto` | Chooses the widget's color theme. `auto` follows the visitor's system preference. | | `data-verb` | Text such as `Buy`, `Choose`, or `Book` | Empty | Changes action labels to the form “verb with agent,” such as “Choose with Claude.” | | `data-heading` | Any text | Layout default | Replaces the visible heading. This shorthand takes precedence over `data-string-heading`. | ### Layouts | Value | Best fit | | - | - | | `card` | A full-width benefit block on a homepage, pricing page, or product page. | | `banner` | A compact strip below navigation, above the fold, or between sections. | | `launcher` | A compact button that expands into an agent-selection card. | ## Customize the style Style attributes accept CSS values. Colors accept any valid CSS color; the dashboard emits hexadecimal colors. The widget renders in a shadow root, so these attributes are the most predictable way to align it with your site. | Attribute | Value | Effect | | - | - | - | | `data-accent` | CSS color | Primary buttons and focus rings. | | `data-accent-text` | CSS color | Text placed on the accent color. | | `data-background` | CSS color | Widget, menu, and row backgrounds. | | `data-text` | CSS color | Headings, body text, buttons, and menu items. | | `data-muted-text` | CSS color | Descriptions, secondary labels, and “Powered by” text. | | `data-border` | CSS color | Widget, button, menu, and row borders. | | `data-radius` | CSS length or `pill` | Corners throughout the widget. The default is `10px`; `pill` resolves to `999px`. | | `data-font` | CSS `font-family` value | Widget typography. By default, the widget inherits the page's font. | For example: ```html theme={null}
``` ## Customize the copy Every copy override uses `data-string-{key}`. You can change one string without supplying the others, or override the full set to translate the widget. Three placeholders insert runtime values: * `{SELLER}` inserts `data-seller-name`. * `{BRAND}` inserts the selected agent brand, such as Claude or ChatGPT. * `{LABEL}` inserts the selected agent's full label after a copy action. Keep a placeholder in your override when you want that value to appear. No other placeholders are substituted. ### Main copy | Attribute | Default | Used by | | - | - | - | | `data-string-heading` | `We are Agent-optimized` | The `card` and `banner` headings. When set explicitly, it also replaces the `launcher` heading. | | `data-string-heading-launcher` | `Buy with AI` | The expanded `launcher` heading when `data-string-heading` is absent. | | `data-string-description` | `{SELLER} is agent-optimized. Your AI agent can interview you, compare every option, and buy only what fits.` | The `card` description. When set explicitly, it also replaces the `launcher` description. | | `data-string-description-launcher` | `Pick your agent. It asks a few questions, then handles the rest.` | The expanded `launcher` description when `data-string-description` is absent. | | `data-string-banner-text` | `{SELLER} is agent-ready. Your AI agent can choose and buy for you.` | Supporting text in the `banner` layout. | | `data-string-launcher-label` | `Buy with AI` | The collapsed `launcher` button. | `data-heading` takes precedence over every heading string. An explicit `data-string-description` takes precedence over each layout-specific description. ### Actions and menus | Attribute | Default | Used by | | - | - | - | | `data-string-button-label` | `With {BRAND}` | Standard agent buttons. | | `data-string-more-options` | `Other options` | The general overflow menu. | | `data-string-more-brand-options` | `More {BRAND} options` | The accessible label for a brand button's menu. | | `data-string-copy-prompt` | `Copy prompt` | The clipboard action in an overflow menu. | | `data-string-copy-prompt-done` | `Copied` | The clipboard action after a successful copy. | | `data-string-item-done` | `Copied - paste into {LABEL}` | A copy-only agent option after a successful copy. | If you set `data-verb`, it composes the standard labels in English word order. Set `data-string-button-label` when you need the full label or a different word order; that attribute takes precedence over `data-verb`. ### Status and attribution | Attribute | Default | Used by | | - | - | - | | `data-string-copy-recovered` | `Couldn't copy automatically. The prompt opened in a new tab.` | Accessible status after the widget recovers from a blocked clipboard write. | | `data-string-copy-failed` | `Couldn't copy the prompt. The storefront opened in a new tab.` | Accessible status when both the prompt fetch and clipboard path fail. | | `data-string-powered-by` | `Powered by` | Attribution before the ZeroClick.ai link. | > [!NOTE] > > `data-string-eyebrow`, whose default is `Agent-optimized`, is reserved for a future visible eyebrow label. Current layouts accept the attribute but do not render it. ## Translate the widget Override the copy attributes while keeping the runtime placeholders you need: ```html theme={null}
``` The widget's agent names remain fixed. Translate each surrounding label, menu action, success message, and failure message that can appear in your chosen layout. ## Next steps > [card] [Enable agent traffic](/docs/website/enable-agent-traffic) > > Add the website signals that help agents discover your storefront directly. > [card] [How ZeroClick works](/docs/concepts/how-zeroclick-works) > > Follow discovery, payment, forwarding, and settlement end to end. # Enable agent traffic Source: https://zeroclickai.mintlify.dev/docs/website/enable-agent-traffic Make your storefront discoverable by AI agents: head tags, the agent callout, an llms.txt entry, markdown for agent fetchers, a Link header, and the visible badge. Agents find your storefront through your website. They read your pages as raw HTML, top to bottom, without running JavaScript, so a storefront that only humans can find gets no agent traffic. This page walks through the website changes that point agents at your pay URL, with each step marked required, highly recommended, or optional. > [!NOTE] > > Examples on this page use a seller named Acme whose storefront runs on the custom domain `agents.acme.com` from step 1. Substitute your own values as you paste: your storefront domain everywhere `agents.acme.com` appears (or your default pay URL, like `https://acme.pay.zeroclick.io`, if you skip the custom domain), your store name in the callout and badge text, and your seller id in the head snippet's `?seller=` parameter. > > The storefront URLs below carry a `?src=` parameter naming the surface they sit on (`head-link`, `body-text`, `llms-txt`, `link-header`, `badge`). Your storefront records it on every visit, so you can see which pointer actually routed each agent. Keep it as written when you paste. **1. Serve your storefront on your own domain** Required Agents click through to a domain they recognize more often than a generic one, so serve your storefront on a subdomain you own rather than the default `.pay.zeroclick.io`. Acme, the example seller on this page, uses `agents.acme.com`, and every snippet below carries it. Configure yours under **Custom domains** in your store's settings before you paste anything: the domain is baked into the head tags, the callout, the badge, and the llms.txt links, so setting it up first means you paste each snippet once. **2. Add the head tags to every page** Required Paste into every page's ``: ```html theme={null} ``` The `alternate` link advertises your storefront's llms.txt to crawlers. The inline script marks the document as JavaScript-capable and removes the agent callout (next step) for human visitors once the page loads. The badge script advertises the storefront to crawlers that do run JavaScript. > [!WARNING] > > The snippets on this page carry Acme's example values, so substitute your own before pasting: your storefront domain everywhere `agents.acme.com` appears, your store name in place of Acme, and your seller id in place of `{YOUR_SELLER_ID}`, which is the `sel_` value in your dashboard store URL. The **Enable agent traffic** step in your store's setup shows every snippet with your values already filled in. > [!NOTE] > > If your site sets a strict Content-Security-Policy, allow `img-src` for your storefront domain (the badge image) and `script-src` for `cdn.zeroclick.io`. **3. Paste the agent callout right after the opening body tag** Required Agents read raw HTML top to bottom, so this block must lead the document. Paste it immediately after the opening `` tag: ```html theme={null}

Acme sells to AI agents - live prices and self-serve payment

The agent storefront at https://agents.acme.com/llms.txt?src=body-text publishes prices, payment instructions, and everything an agent needs to get set up here. Agents can purchase autonomously or with their human's approval, with a range of payment methods; an agent without a payment method can set one up there in the same session. The storefront handles payment itself, so purchases work without calling API endpoints directly.

``` The callout is text for agents, and it does not need to look like part of your page. The head script removes it for human visitors once the page loads, and it stays visible without JavaScript, so nothing on your site is served only to agents. Of everything on this page, this step does the most to route agent purchases through your storefront. > [!TIP] > > Keep the wording as written, with only the names and URLs substituted. It deliberately names no billing model, so it stays correct when you add or retire plans - your storefront's own pages state what an agent has to do first. **4. Add your storefront to llms.txt** Required Raw HTTP agents fetch `/llms.txt` at your domain before anything else - plain text by construction, so no markup layer can strip it - and verification fetches it too: your site must serve `/llms.txt` with your storefront referenced in it. Add this block near the top of the file, right after the title and summary. If your site does not serve one yet, create the file with it: ```markdown theme={null} ## Agentic commerce - [Acme agent storefront](https://agents.acme.com/llms.txt?src=llms-txt): the full catalog, live prices, and payment setup for Acme. AI agents can purchase autonomously or with their human's approval through ZeroClick, and an agent without a payment method can set one up on the spot. Complete purchasing guide: https://agents.acme.com/llms-full.txt?src=llms-txt - live pricing: https://agents.acme.com/manifest.json?src=llms-txt ``` This block doubles as the markdown the next step's no-SDK path serves, so writing it once covers both. **5. Serve markdown to agent fetchers** Required Many agent tools fetch pages with an `Accept` header that prefers `text/markdown` over `text/html`; browsers never do. Answering those requests with markdown reaches summarizing fetchers that would otherwise drop head tags and links during HTML conversion. Verification asks each submitted page for markdown - your homepage always, plus the docs, pricing, and sign-up pages you add - and requires the returned markdown to reference your storefront. Apply it to every page, not just those: agents land everywhere. The managed path is [Agentify](/docs/agentify/overview): mount the seller SDK's middleware in front of your site, and it detects markdown-preferring and AI-agent traffic, serves an agent-optimized markdown rendering of the requested page with your storefront inlined - which is exactly what verification checks for - and falls through to your HTML on any failure: ```ts TypeScript theme={null} import { withAgentify } from "@zeroclickai/sellers"; // zeroClick is your createSeller client with agentifyKey configured. const handler = withAgentify(zeroClick, serveSite); ``` ```python Python theme={null} from zeroclick_sellers.adapters import AgentifyAsgiMiddleware app.add_middleware(AgentifyAsgiMiddleware, seller=zeroclick) ``` ```go Go theme={null} mux.Handle("/", seller.Agentify(sellers.AgentifyOptions{})(site)) ``` ```ruby Ruby theme={null} config.middleware.use ZeroClick::Sellers::Middleware::Agentify ``` [SDK middleware](/docs/agentify/sdk-middleware) covers configuration and options. A single-page app on a CDN, with no server to mount middleware in, runs the same contract in an edge function: see [SPA setup](/docs/agentify/spa-setup). Without an SDK, serve your llms.txt content for markdown-preferring requests yourself. This is content negotiation, not cloaking: the same page in the representation the client asked for. It does change what your existing URLs serve to markdown-preferring clients, so decide deliberately. Send `Vary: Accept` so caches keep the two representations apart. ```js theme={null} // Express-style example; adapt to your framework. // Middleware so every page negotiates, not just the homepage - agents // land on docs, pricing, and sign-up pages just as often. Serving your // llms.txt keeps your storefront referenced in the markdown agents read. app.use((req, res, next) => { const accept = req.headers.accept ?? ""; const markdown = accept.indexOf("text/markdown"); const html = accept.indexOf("text/html"); if (req.method === "GET" && markdown !== -1 && (html === -1 || markdown < html)) { res.set("vary", "accept").type("text/markdown"); return res.sendFile("llms.txt", { root: "public" }); } next(); }); ``` **6. Send the storefront Link header** Highly Recommended Raw HTTP clients - curl, HEAD requests, fetchers that never parse HTML - see response headers and nothing else. An RFC 8288 `Link:` header is the one pointer that survives every fetch path: no HTML parsing, no JavaScript execution, no markdown conversion step to lose it. Send it on every page response: ```text theme={null} Link: ; rel="alternate"; type="text/plain"; title="llms.txt" ``` ```js theme={null} // Express-style example; adapt to your framework. Static hosts set this // as a response header in their hosting config instead. app.use((req, res, next) => { res.set( "link", '; rel="alternate"; type="text/plain"; title="llms.txt"', ); next(); }); ``` > [!NOTE] > > On a static host or CDN, set the header in the hosting config (a per-path headers map or an edge rule) - the value stays the same. If something in front of your site already sends a `Link` header, append this entry to it rather than replacing it. Verification records the header when present but does not require it yet. **7. Show the badge to human visitors** Optional The visible ZeroClick badge is a plain link and image for humans, typically in the footer. The image is served from your storefront domain, so it carries your store name and updates automatically; swap `badge-light.svg` for `badge-dark.svg` on dark footers: ```html theme={null} Acme - Agent Storefront, powered by ZeroClick ``` Nothing moves it at runtime, so render it however your site renders content, including natively inside a React or Vue app. The callout and head tags carry the agent traffic. ## Why every step matters Each required signal catches an agent class the others cannot reach, so the steps compose rather than substitute: * **Raw HTTP clients** (curl, HEAD requests, plain fetchers) never parse HTML. They find your site's `/llms.txt` - and the `Link:` header when you send it - or nothing at all. * **Markdown-converting fetchers**, the summarizers behind most agent browsing tools, strip `` and `