> For the complete documentation index, see [llms.txt](https://docs.pharos.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.pharos.xyz/developer-guide/x402.md).

# x402

## Overview

x402 is an open, internet-native payment protocol. The HTTP 402 status code was defined in the early HTTP/1.1 specification as “Payment Required.” However, for a long time, it served only as a reserved status code with few practical applications. With the maturation of blockchain and crypto-payment infrastructure, this status code has been reactivated, evolving into a lightweight, trustless mechanism for content payment.

In this model, when a client requests protected resources (such as articles, API responses, or data streams), the server does not return the content directly. Instead, it returns an HTTP 402 response accompanied by payment instructions (e.g., recipient address, amount, supported payment networks, etc.). The client initiates a micro-payment—either on-chain or off-chain—via a wallet. Once the server verifies the validity of the transaction, it unlocks and delivers the requested content. In decentralized networks like Pharos, this process is typically implemented as follows: the user sends a micro-token transfer to a specified address → the network node or server-side listens for and verifies the transaction → the original requested resource is automatically returned upon successful verification. The entire process requires no registration, login, or traditional payment gateways, truly achieving “pay-as-you-go, instant access.”

This mechanism provides native, programmable payment capabilities for AI agents, automated services, or IoT devices, serving as one of the key infrastructures for building an Autonomous Economy.

## Working

<figure><img src="https://3298017099-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FNmFp0ycownpuaUNf2xeE%2Fuploads%2Fgit-blob-a1bf544d2e47c4a8180faa23a896ded777be26f9%2Fx402-1.png?alt=media" alt="x402 Flowchart"><figcaption><p>x402 Flowchart</p></figcaption></figure>

### Initial Request and Payment Requirements

* **Resource Request Initiation:** The client initiates an HTTP request (e.g., `GET /api`) to the resource server for a specific protected resource.
* **Payment Trigger Response:** The server returns an `HTTP 402 Payment Required` status code. A Base64-encoded `PaymentRequired` object is carried in the response body via the `PAYMENT-REQUIRED` header. This object defines the payment scheme, target network, and specific payment parameters required for the current transaction.

### Payment Credential Construction and Signing

* **Scheme Selection and Payment Payload Generation:** The client parses the payment requirements returned by the server and selects a specific payment scheme based on its own supported payment capabilities. Subsequently, the client constructs a `PaymentPayload` containing the necessary metadata according to the protocol specifications of that scheme.
* **Secondary Request Submission:** The client re-initiates the resource request and attaches the signed `PaymentPayload` in the `PAYMENT-SIGNATURE` HTTP header.

### Verification

* **Verification Routing:** Upon receiving the signed request, the resource server executes validation logic. The server can choose to perform local verification or forward the `PaymentPayload` and the original `PaymentRequirements` to the Facilitator's `/verify` interface for remote verification.

**Compliance Check:** The Facilitator verifies the payload according to the specified payment scheme and blockchain network rules, then returns a `Verification Response` to the resource server.

* **Access Control Decisions:**
  * **Verification Failed:** If the verification does not pass, the resource server returns a 402 status code and error details again.
  * **Verification Succeeded:** If the verification passes, the resource server confirms the payment credential is valid and immediately initiates business logic processing (Do Work), preparing for on-chain settlement.

### On-chain Settlement and Confirmation

* **Transaction Broadcasting:** The resource server is responsible for initiating fund settlement. This can be completed by interacting directly with a blockchain node or by delegating it to a Facilitator. If delegated, the server sends the payment credential to the Facilitator's `/settle` interface.
* **Block Inclusion:** The Facilitator submits the transaction to the blockchain network (Submit tx).

### Delivery and Receipt

* **Settlement Feedback:** Once the on-chain transaction is confirmed, the Facilitator returns a settlement execution response (Settlement Response) containing the transaction hash (`tx_hash`) to the resource server.
* **Resource Delivery:** The resource server sends an `HTTP 200 OK` response to the client, placing the requested resource content in the response body. Simultaneously, to provide proof of payment, the server attaches Base64-encoded settlement response information in the `PAYMENT-RESPONSE` response header, marking the completion of the entire "pay-before-receive" closed loop.

**Pharos Support:** The x402 protocol itself is chain-agnostic. On Pharos, it supports all ERC-20 tokens. Pharos’s high-performance features (30,000 TPS, sub-second finality) make it particularly suitable for x402 micro-payment scenarios.

## Use Cases

x402 enables micro-payment and pay-per-use scenarios that were previously impossible due to economic unfeasibility. Below are some possible application scenarios:

### Agent Commerce

* **AI Agents subscribing to content services with auto-renewal:** AI agents can represent users in subscribing to content services such as industry updates, financial newsletters, or in-depth analysis reports, automatically completing periodic fee payments and renewal operations through integrated digital wallets.
* **Pay-per-use AI capability calls:** Users or systems pay based on the actual number of uses when calling Large Language Model (LLM) inference, image generation, or other AI APIs.
* **Payments between agents:** Supports peer-to-peer payments between multiple autonomous agents for data sharing, task collaboration, or service provision without human intervention.
* **Automated financial trading agents:** Based on real-time market data and external information sources (e.g., paid data streams), these agents autonomously execute high-frequency trading strategies and dynamically procure necessary data resources to optimize decision-making.

### Medical and Health Tech

* **AI-assisted diagnostic reports:** After users upload medical images, they pay to unlock structured diagnostic suggestions.
* **Personalized health advice APIs:** Wearable devices call health analysis models and pay-per-call to obtain deep insights.
* **Access to electronic medical record fragments:** Third-party applications request specific medical visit records, and patients authorize and pay a small fee to share data.

### Education and Knowledge Services

* **AI Tutor single-question answering:** Basic prompts are free, while in-depth analysis requires payment to unlock.
* **Professional course fragment unlocking:** After a trial preview, users pay by the minute or chapter to continue learning.
* **Single academic paper access:** No subscription required; pay per paper for instant PDF access.

### E-commerce and Consumer Services

* **Personalized recommendation engine calls:** E-commerce platforms pay AI service providers based on successful conversions.
* **AR try-on/make-up experience:** Payment is required to unlock real-time rendering before high-precision virtual trials.
* **Supply chain risk assessment queries:** Enterprises pay-per-query for supplier risks, which can be used for procurement decision-making.

### Other Scenarios

* **Computing power rental:** Billing by the second for using GPU/CPU resources for training or inference.
* **IoT micro-transactions:** Sensor networks pay automatically based on data points or events (e.g., environmental monitoring, smart meters).
* **Sustainability and carbon credits:** Companies or individuals purchase carbon offsets on demand, with the API returning a 402 to trigger instant settlement.

**Key Advantage:** x402 transaction costs on Pharos are extremely low, making true micro-payments possible. Combined with instant finality, this enables real-time access control.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.pharos.xyz/developer-guide/x402.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
