x402 API Developer Guide
Integrate with Zahlen's isolated x402 gateway, merchant policy, observability, reconciliation, visibility, CSV import, and audit-evidence interfaces. This guide documents the API that is implemented today and clearly marks the boundary between deterministic test payments and gated real-facilitator connections.
Current Implementation Status
The API described here is complete for simulated x402 payments, policy evaluation,
immutable event recording, merchant visibility, reconciliation, CSV ingestion, and audit
exports. The dashboard and prototype still use
DeterministicLocalFacilitator. It makes no network calls and moves no money.
A Coinbase CDP live adapter is implemented behind the provider-neutral interface, but it
is not registered with the gateway or enabled by default.
local:zahlen-test using the synthetic ZTEST asset.Coinbase CDP Facilitator Adapter
Zahlen's first real-provider adapter uses Coinbase CDP's hosted x402 facilitator. It sends the standard x402 version 2 payment envelope to the provider for verification and settlement. The rest of Zahlen continues to use the same provider-neutral records, policy decisions, reconciliation, and audit evidence.
exacteip155:84532eip155:8453/platform/v2/x402/verify and /platform/v2/x402/settleRuntime configuration
Install the optional x402-live package group and load the following values
from the approved deployment secret manager. Never place these values in code, CSV
files, URLs, logs, screenshots, dashboard fields, or audit records.
| Setting | Purpose |
|---|---|
ZAHLEN_X402_CDP_API_KEY_ID | Identifies the Coinbase CDP Secret API Key used to create short-lived request tokens. |
ZAHLEN_X402_CDP_API_KEY_SECRET | Signs the short-lived provider request token. It stays in runtime memory and is never a Zahlen payment record. |
ZAHLEN_X402_CDP_TIMEOUT_SECONDS | Optional request timeout. The default is 10 seconds; accepted values are 0.1 through 30 seconds. |
Provider authentication, rate limits, rejected requests, timeouts, outages, and invalid responses become short deterministic reason codes. Raw provider response bodies and credential values do not cross the adapter boundary. Zahlen withholds the resource when verification or settlement cannot be trusted.
Environments and Feature Flags
| Environment | Base URL | Intended use |
|---|---|---|
| Development | https://zahlenfinancial.com | Dashboard review, example data, and approved integration testing. |
| Production | https://zahlenfinancial.com | Merchant visibility and deployed application access. Prototype and live-payment flags remain off unless explicitly approved. |
| Local test | http://localhost:<port> | Deterministic lifecycle tests with no monetary value. |
Prototype flag
ZAHLEN_X402_PROTOTYPE_ENABLED=true enables routes under
/v1/x402/prototype. Use this only in an approved local or test environment.
When it is absent or false, prototype routes fail closed with HTTP 404.
Live-payment flag
ZAHLEN_X402_LIVE_PAYMENTS_ENABLED=true is one part of the future live-adapter
gate. The flag alone cannot create live support. A registered live adapter, capability
match, operational approval, and production-readiness evidence are also required.
Authentication and Merchant Scope
The x402 surfaces use three authentication patterns.
X-API-Key./admin/x402 use the authenticated browser session and tenant security context.Merchant API-key header
The API key is resolved to one merchant and tenant. The merchant_id in the URL
must match that identity. A mismatch returns HTTP 403. Missing, malformed, unknown,
inactive, or revoked keys return HTTP 401.
X-API-Key request header over HTTPS. Do not include it in
query strings, logs, screenshots, CSV files, or x402 payment payloads.
x402 Protocol Headers
| Header | Direction | Purpose |
|---|---|---|
PAYMENT-REQUIRED | Merchant → agent | Base64-encoded x402 v2 payment challenge returned with HTTP 402. |
PAYMENT-SIGNATURE | Agent → merchant | Base64-encoded x402 v2 payment payload containing the selected terms and proof. |
PAYMENT-RESPONSE | Merchant → agent | Base64-encoded x402 v2 settlement response returned when the resource is released. |
X-Agent-ID | Agent → merchant | Optional identity supplied when requesting the initial challenge. |
X-Wallet-Address | Agent → merchant | Optional public wallet identity supplied when requesting the challenge. |
Encoding
Protocol headers contain standard Base64 text created from UTF-8 JSON. The decoded JSON limit is 16,384 bytes. Invalid Base64, oversized content, or a payload that fails x402 v2 validation returns HTTP 400.
Payment challenge shape
Payment payload shape
The accepted object must exactly match one challenge option. A nonce or proof
must never be reused. Live provider payloads will be documented with their adapter when a
live adapter is connected and approved.
Endpoint Summary
Protocol and merchant API routes
| Method | Path | Authentication | Result |
|---|---|---|---|
| GET | /v1/x402/prototype/{merchant_id}/resources/{resource_id} | x402 headers | Issue a challenge or process proof and return/withhold the resource. |
| GET | /v1/x402/prototype/{merchant_id}/observability/{correlation_id} | X-API-Key | Return the immutable lifecycle timeline. |
| POST | /v1/x402/prototype/{merchant_id}/reconciliation/{correlation_id} | X-API-Key | Append a new reconciliation assessment. |
| POST | /v1/x402/prototype/{merchant_id}/policies | X-API-Key | Append a versioned merchant policy. |
| GET | /v1/x402/prototype/{merchant_id}/policies/effective | X-API-Key | Return the currently effective policy. |
| GET | /v1/x402/prototype/{merchant_id}/visibility | X-API-Key | Return merchant activity, policy, anomalies, reconciliation, and trends. |
| GET | /v1/x402/prototype/{merchant_id}/visibility/identity-history | X-API-Key | Return history for one agent, wallet, or both. |
| GET | /v1/x402/prototype/{merchant_id}/visibility/audit-evidence/{correlation_id}.zip | X-API-Key | Download a verifiable audit ZIP. |
Protected Resource Lifecycle
1. Request the resource
When no payment proof is present, the response is HTTP 402. Its JSON body reports
payment_required, deterministic test mode, and no monetary value. Decode the
PAYMENT-REQUIRED response header to read the x402 v2 challenge.
2. Build and submit the proof
3. Interpret the result
- HTTP 200: verification, policy, and test settlement succeeded; the resource body is returned with
PAYMENT-RESPONSE. - HTTP 402 payment_denied: proof or policy failed and delivery was withheld.
- HTTP 402 payment_review_required: the policy requires human or approved follow-up before delivery.
Observability Timeline
The response contains the complete ordered record history for the correlation ID.
A denied, failed, or replayed lifecycle can contain a different number of records because settlement or release may not occur.
Append a Reconciliation Assessment
A successful request returns HTTP 201 with a new reconciliation record. Earlier records stay unchanged. Repeating the assessment creates new evidence rather than overwriting the original result.
Versioned Policy Profiles
Policy profiles are append-only. Post a new policy version instead of editing an existing
row. Zahlen assigns contract_version, profile_id,
tenant_id, and merchant_id; clients must not send those fields.
Create a policy
Amounts are strings containing non-negative atomic units, not floating-point numbers. Required lists cannot be empty or contain duplicates. The review threshold must be lower than the deny threshold.
Read the effective policy
The response is {"profile": {...}}. HTTP 404 means no policy is currently
effective for that merchant.
Merchant Visibility APIs
Dashboard visibility
| Query parameter | Rules | Meaning |
|---|---|---|
window_hours | 1–720; default 24 | How far back to read immutable records. |
limit | 1–500; default 100 | Maximum result rows per dashboard collection. |
agent_id | Optional; 1–255 characters | Filter activity to one agent identity. |
wallet_address | Optional; 1–2,048 characters | Filter activity to one public wallet identity. |
The response contains:
scopeand selected time-window information.summarycounts and settled amounts by asset.transactionswith payment, policy, settlement, delivery, and reconciliation states.identitiesfor agent and wallet history.policyDecisionswith reason codes and anomaly scores.anomaliesAndReplaysfor unusual or repeated activity.settlementAndDeliveryandreconciliationExceptions.trendswith time buckets and attempts per hour.dataQualityshowing immutable x402 ledgers as the source.
Identity history
Supply agent_id, wallet_address, or both. Omitting both returns
HTTP 422. The maximum activity window is 720 hours and the maximum limit is 500.
Downloadable Audit Evidence
The response is an application/zip download with these headers:
Cache-Control: no-storeX-Zahlen-Evidence-FingerprintX-Zahlen-Evidence-Record-CountContent-Dispositionwith the generated filename
The ZIP contains:
Operator Dashboard APIs
These routes support the Zahlen browser dashboard. They use an authenticated browser session and tenant security context. They are not replacements for merchant-key API integration.
| Method | Path | Purpose |
|---|---|---|
| GET | /admin/x402 | Render the x402 Merchant Dashboard. |
| GET | /admin/x402/data | Return tenant-scoped dashboard JSON. Requires merchant_id. |
| GET | /admin/x402/uploads/template.csv | Return an example ZIP without a merchant, or a merchant-bound CSV template. |
| POST | /admin/x402/uploads/preview | Validate a multipart CSV without saving rows. |
| POST | /admin/x402/uploads/commit | Append valid rows after fingerprint-verified preview. |
| GET | /admin/x402/audit-evidence/{correlation_id}.zip | Download tenant-scoped evidence from the dashboard. |
CSV preview
CSV commit
Submit the same file and merchant scope, plus the exact 71-character
expected_fingerprint returned by preview. A changed file returns HTTP 409 and
must be previewed again.
X-Zahlen-Requested-With: x402-dashboard.
Canonical Schema and Data Rules
Zahlen records lifecycle evidence using contract version 1.0. Every record
answers who attempted to pay, what they requested, under which authorization, what
happened, whether it was expected, and what should happen next.
sha256: followed by 64 lowercase hexadecimal characters.Canonical record types
payment_resource_requesthttp_402_challengepayment_authorization_proofverification_resultpolicy_decisionsettlement_resultresource_delivery_resultreplay_duplicate_attemptreconciliation_record
HTTP Status and Error Guide
| Status | Meaning | Developer action |
|---|---|---|
| 200 | Read succeeded or paid resource released. | Process the body and, for resource delivery, retain PAYMENT-RESPONSE. |
| 201 | Policy or reconciliation record appended. | Store returned IDs and version information. |
| 400 | Malformed, oversized, or invalid PAYMENT-SIGNATURE. | Rebuild the Base64 x402 v2 payload from the current challenge. |
| 401 | Merchant API key missing, malformed, invalid, inactive, or revoked. | Send a current key in X-API-Key. |
| 402 | Payment required, denied, or held for review. | Read the body, reason code, policy decision, and challenge header. |
| 403 | Merchant or tenant scope mismatch, or required dashboard write header missing. | Use credentials and identifiers from the same merchant scope. |
| 404 | Prototype disabled, merchant/resource absent, evidence absent, or no effective policy. | Confirm environment, flag, scope, resource ID, and correlation ID. |
| 409 | Append conflict or CSV changed after preview. | Do not overwrite evidence; refresh or preview the current file again. |
| 413 | CSV file exceeds 2 MB. | Split or reduce the file. |
| 422 | Request, policy, filter, or CSV validation failed. | Correct the fields using the returned detail or row reason codes. |
Facilitator failures are normalized into safe reason codes such as
facilitator_verify_timeout and facilitator_settle_timeout.
Delivery is withheld when verification or settlement cannot be trusted.
Security Requirements
- Use HTTPS for all non-local requests.
- Never send or store private keys, seed phrases, mnemonics, signing secrets, passwords, bearer tokens, or unrelated credentials in x402 payloads.
- Treat wallet addresses, public transaction identifiers, public signatures, and agent IDs as identities and audit data.
- Keep merchant API keys server-side and rotate or revoke them under your normal access policy.
- Never reuse a nonce or payment proof.
- Do not release a resource based only on the presence of a proof; require verification and the policy result.
- Respect Review as a hold state, not an approval.
- Use correlation IDs rather than payment secrets when requesting support.
- Retain audit ZIPs according to your organization's evidence and privacy rules.
Integration Checklist
- Use a local or approved development environment with the prototype flag enabled.
- Create or select an active merchant and obtain a merchant-scoped API key.
- Request
weather-currentand decode thePAYMENT-REQUIREDheader. - Build a unique deterministic test proof using the exact accepted terms.
- Submit the proof and confirm HTTP 200 plus
PAYMENT-RESPONSE. - Read the correlation timeline and confirm expected record types.
- Post and read a versioned policy profile.
- Test Allow, Deny, Review, invalid proof, replay, timeout, and unavailable-facilitator paths.
- Review visibility, identity history, reconciliation exceptions, and trends.
- Download an audit bundle and verify its manifest fingerprint.
- Confirm that card-payment regression tests and x402 tests remain green.
- Keep live payments disabled until the Coinbase adapter, merchant terms, credentials, and rollout evidence pass the separate production-hardening review.