# A Developer's Guide to Implementing the x402 Protocol
This guide follows on from our previous article about EIP-3009, you can read that [here](https://hackmd.io/@Extropy/EIP3009)
For developers, the x402 protocol is a practical toolset for monetising web services. It offers a direct alternative to cumbersome API key management and inflexible subscription models, enabling a true, pay-per-use economy.
At its core, x402 is an open-source standard that activates the long-dormant `HTTP 402 "Payment Required"` status code. It provides a chain-agnostic choreography for an AI agent or client to pay for a resource, like an API call, at the very moment it is requested.
## The Server-Side: "One Line of Code" Monetisation
If you are a developer looking to monetise an API (the "supply" side), the integration is simple. Using middleware libraries for popular frameworks, you can payment-gate an endpoint with just a single line of code.
For a Node.js server (using Express for example), the implementation looks like this:
```javascript
// This example shows how to protect an endpoint and set a price
app.use(
paymentMiddleware("0xYourWalletAddress", {
"/your-premium-endpoint": "$0.01"
})
);
// That's it. This endpoint is now monetised.
app.get("/your-premium-endpoint", (c) => {
return c.json({ data: "secret premium data" });
});
```
This middleware automatically handles the entire payment negotiation, verification, and settlement flow, allowing you to focus on your application's logic.
So what is happening behind the scenes ?
## The Core x402 Handshake
While the middleware makes it simple, it's crucial to understand the three-phase HTTP handshake that happens under the hood.
### **Phase 1: Request → Quote**
1. **Initial Request:** The client (which could be an AI agent) makes a standard `GET` request to your protected resource (`/your-premium-endpoint`).
2. **Payment Required:** Your server's middleware intercepts this. Seeing no payment, it returns an `HTTP 402: Payment Required` status.
3. **Quote:** The *body* of this 402 response is a JSON payload. This is the "bill," specifying the `PaymentRequirements`, such as the price (0.01 USDC), the supported network (e.g., Base), and the facilitator's API endpoint.
### **Phase 2: Pay → Verify**
1. **Sign Payload:** The client's logic (see below) receives the 402, parses the JSON "bill," and creates a payment payload. It then *signs this payload off-chain* using its private key.
2. **Retry with Payment:** The client retries the original request. This time, it includes a new HTTP header: `X-PAYMENT`. The value of this header is the Base64-encoded JSON `Payment Payload`, which contains the signed authorisation.
### **Phase 3: Settle → Deliver**
1. **Verify Payload:** Your server's middleware intercepts the new request. It doesn't need to understand crypto; it simply forwards the `X-PAYMENT` payload to the specified facilitator's `POST /verify` endpoint. The facilitator cryptographically verifies the signature and returns a simple `{"isValid": true}`.
2. **Settle & Deliver:** Once verified, the server does two things in parallel: it fulfils the request (granting access to the data) and sends the payload to the facilitator's `POST /settle` endpoint to execute the on-chain transfer.
3. **Confirmation:** The server returns the final `HTTP 200 OK` response to the client, containing the requested resource. It also includes an `X-PAYMENT-RESPONSE` header, which contains the transaction hash as a receipt.
## The Role of the Facilitator
The "magic" that makes the server-side implementation so simple is the **facilitator**. This is a third-party service that acts as the bridge between your HTTP-native server and the blockchain.
Your server remains crypto-agnostic. It never holds keys, runs a node, or pays for gas. It simply makes two stateless REST API calls (`/verify` and `/settle`) to a trusted facilitator (like those provided by Coinbase, Meridian, or [Mogami](https://mogami.tech/)), which handles all the on-chain complexity.
## The Client-Side: Building an x402-Aware Agent
While the server-side is simple, the client bears the burden of complexity. Developers building agents must integrate client-side SDKs like `@coinbase/x402-sdk` and manage wallet capabilities.
The agent's core logic must be architected as a state machine capable of handling three scenarios:
1. **Free Requests:** Standard handling for `response.ok`.
2. **Payment-Gated Requests:** The primary logic path, triggered by `response.status === 402`. The agent must parse the 402, use its wallet to sign the payment, and manage the stateful retry with the `X-PAYMENT` header.
3. **Payment Failures:** Graceful error handling if the payment fails or the service fails after payment.
## The "Gasless" Magic: How EIP-3009 is Used
The "gasless" client experience is another key technical component. The client doesn't need the network's native gas token (e.g., ETH) to make a payment.
This is enabled by the **EIP-3009** standard (`transferWithAuthorization`). The client doesn't submit a transaction; it simply *signs* an off-chain authorisation message. The facilitator takes this signed message and submits it to the blockchain, *paying the gas fee* on the client's behalf.
This abstraction is what makes autonomous, high-frequency micropayments feasible.
Ultimately, x402 is a lightweight and open standard that provides the essential choreography for on-chain value exchange, finally turning the web's original, dormant "Payment Required" code into a live, usable rail for developers.