402 Flow

When an API requires payment, it returns 402 Payment Required and includes payment requirements (amount, asset, payTo, network, etc.) in a header—typically as base64-encoded JSON. AgentPay consumes these requirements, performs the payment via an x402 facilitator, and returns a payment signature so the client can retry the original request and receive the resource. This page describes the flow in detail.

End-to-end sequence

  1. Your agent calls the paid API (e.g. client.get(url) using the AgentPay SDK).
  2. The paid API responds with 402 and a Payment-Required (or protocol-specific) header containing the requirements, often base64-encoded.
  3. The SDK decodes the header and calls POST /v1/pay with paymentRequiredHeader (the raw header value) and requestUrl (the URL that returned 402).
  4. AgentPay resolves your API key from X-Api-Key, decodes the requirements, and looks up a wallet for the required network. It builds a payment payload and sends it to the x402 facilitator's /verify endpoint.
  5. If verification succeeds, the API calls the facilitator's /settle endpoint to execute the payment on-chain.
  6. On success, AgentPay records a spend event (if the database is configured) and returns paymentSignature (base64). The SDK retries the original request with this signature (e.g. in a PAYMENT-SIGNATURE header).
  7. The paid API validates the signature and returns 200 with the requested resource.

POST /v1/pay

You typically do not call this endpoint manually—the SDK does it when it receives a 402. For reference, the request and response shapes are:

POST /v1/pay
X-Api-Key: pk_...
Content-Type: application/json

{
  "paymentRequiredHeader": "<base64-encoded payment requirements>",
  "requestUrl": "https://paid-api.example/resource",
  "idempotencyKey": "optional"
}

# Success 200
{
  "paymentSignature": "<base64>",
  "settled": true,
  "transaction": "..."
}

# Failure 402
{
  "error": "Payment verification failed",
  "facilitator": { ... }
}

If verification or settlement fails, the API returns 402 with an error message and optional facilitator details. See Errors & troubleshooting for common causes and resolutions.

Payment requirements

The decoded requirements usually include scheme, network, maxAmountRequired, asset (contract address), and payTo (recipient address). AgentPay uses these to build the payload for the facilitator. Ensure you have a wallet for the requested network before calling paid APIs so the API can resolve a wallet and complete the flow.