Guides

x402 payments

How the x402 flow works with Unslept, both as a payer and as an API that wants to get paid.

The flow in four steps

  1. The API asks for payment

    The server answers 402 Payment Required with a PAYMENT-REQUIRED header: base64-encoded JSON listing the price, asset, payee and the payment schemes it accepts.

  2. The SDK checks the policy

    Before anything is signed, the SDK checks the amount against your per-request maximum and the account policy.

  3. The router settles

    The account asks the settlement router to pay. The buffer pays the merchant at once, in one transaction.

  4. The request is retried with proof

    The SDK repeats the original request with a PAYMENT-SIGNATURE header. The server verifies it and answers 200 with a PAYMENT-RESPONSE header describing the settlement.

Schemes

SchemeHow it settles
exactThe standard x402 scheme. The router funds the agent's signer with exactly the price, and the signer signs an EIP-3009 transfer to the payee, verified and settled by the server's facilitator.
unslept-directThe router pays the payee directly and emits a Settled event. The server verifies that event in the transaction receipt itself, with no facilitator.

The SDK prefers unslept-direct when the server offers it, and falls back to exact.

Try the live endpoint

This site runs a real paid endpoint on mainnet. It asks for 0.01 USDG through unslept-direct and answers with a snapshot of protocol stats. Each payment ID expires after 10 minutes and can be used once.

terminal
curl -si https://www.unslept.xyz/api/demo/x402 | grep -i payment-required
demo.ts
const res = await unslept.fetch("https://www.unslept.xyz/api/demo/x402");
console.log(res.status, await res.json());

Accept x402 payments in your API

The repository includes a dependency-free sample endpoint, examples/x402-endpoint, that offers both schemes. To verify an unslept-direct payment yourself:

  1. Issue a fresh payment ID with every 402 and remember it until it expires.
  2. Read the receipt of the transaction hash the client sends, and find the router's Settled event whose payment ID matches.
  3. Check the payee, the recipient, the amount and that the mode is direct.
  4. Accept each transaction and each payment ID once only.