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
The API asks for payment
The server answers
402 Payment Requiredwith aPAYMENT-REQUIREDheader: base64-encoded JSON listing the price, asset, payee and the payment schemes it accepts.The SDK checks the policy
Before anything is signed, the SDK checks the amount against your per-request maximum and the account policy.
The router settles
The account asks the settlement router to pay. The buffer pays the merchant at once, in one transaction.
The request is retried with proof
The SDK repeats the original request with a
PAYMENT-SIGNATUREheader. The server verifies it and answers 200 with aPAYMENT-RESPONSEheader describing the settlement.
Schemes
| Scheme | How it settles |
|---|---|
exact | The 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-direct | The 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.
curl -si https://www.unslept.xyz/api/demo/x402 | grep -i payment-requiredconst 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:
- Issue a fresh payment ID with every 402 and remember it until it expires.
- Read the receipt of the transaction hash the client sends, and find the router's
Settledevent whose payment ID matches. - Check the payee, the recipient, the amount and that the mode is direct.
- Accept each transaction and each payment ID once only.