Set up your trading signal API

Before integrating x402, you need a functioning endpoint that serves trading data. Think of this as building the engine before installing the fuel system. If your API cannot return valid JSON with a standard 200 OK status, adding payment logic will only complicate debugging.

We will start with a basic structure that mimics a real-time signal provider. This endpoint will return mock trading data, which we will later secure with the x402 payment requirement.

x402 Endpoints for AI Trading Signals
1
Create the base endpoint

Initialize a new route in your preferred framework (Express, FastAPI, or Next.js). For this guide, we will use a simple Node.js Express structure. Create a GET route at /api/signals that returns a JSON object containing a symbol, price, and action (buy/sell).

2
Return standard HTTP 200 OK

Ensure your endpoint responds with a 200 OK status code and a valid JSON body. Do not add any authentication headers or payment checks yet. The goal is to verify that the data structure is correct and accessible via a standard HTTP request.

3
Validate the response structure

Test the endpoint using curl or Postman. You should receive a response similar to:

JSON
JSON
{
  "symbol": "BTC/USD",
  "price": 65000.00,
  "action": "buy",
  "timestamp": 1698765432
}

This structure serves as the payload that x402 will eventually gate behind a payment.

With the baseline endpoint established, you are ready to layer on the x402 protocol. The next step involves modifying this endpoint to require a valid x402 token before returning the trading signals.

Configure the x402 Payment Response

When an AI agent first connects to your trading signal endpoint, it needs clear instructions on how to pay. Instead of a standard success or error code, your API must return a 402 Payment Required status. This signals to the agent that access is restricted until payment is settled.

The response must include specific headers that define the payment terms. These headers tell the agent which blockchain network to use, which stablecoin (typically USDC) to send, and the exact amount due. Without this metadata, the agent cannot initiate the transaction or retry the request successfully.

Step 1: Return the 402 Status Code

Start by configuring your endpoint to intercept unauthorized requests. When the agent sends its initial call, do not return the trading data. Instead, send back an HTTP 402 status code. This is the standard indicator for payment-required scenarios in the x402 protocol.

Step 2: Define the Payment Metadata

The core of the x402 response lies in its headers. You must include x-payment-url to point the agent to a payment processor or smart contract interface. Additionally, use x-payment-amount to specify the cost in the smallest unit of the chosen currency (e.g., wei for ETH or cents for USDC). This ensures the agent knows exactly what to transfer.

Step 3: Specify the Blockchain and Asset

Agents operate across multiple chains. Your response must explicitly state where the payment should occur. Include the x-payment-chain-id to identify the network (such as Base or Ethereum) and x-payment-token to define the asset. This prevents agents from attempting to pay on the wrong chain or with unsupported tokens, which would cause the transaction to fail silently.

Step 4: Handle the Retry Logic

Once the agent pays, it will receive a payment receipt (often a transaction hash or JWT). It will then retry the original request, attaching this receipt in the Authorization header. Your server must verify this receipt against the blockchain or your payment gateway. If valid, return the trading signal data with a 200 OK status. If invalid or expired, return 402 again to prompt a new payment.

x402 Endpoints for AI Trading Signals
1
Return 402 Status

Configure your endpoint to intercept unauthorized requests and send back an HTTP 402 status code. This is the standard indicator for payment-required scenarios in the x402 protocol.

2
Define Payment Metadata

The core of the x402 response lies in its headers. You must include x-payment-url to point the agent to a payment processor or smart contract interface. Additionally, use x-payment-amount to specify the cost in the smallest unit of the chosen currency (e.g., wei for ETH or cents for USDC). This ensures the agent knows exactly what to transfer.

3
Specify Blockchain and Asset

Agents operate across multiple chains. Your response must explicitly state where the payment should occur. Include the x-payment-chain-id to identify the network (such as Base or Ethereum) and x-payment-token to define the asset. This prevents agents from attempting to pay on the wrong chain or with unsupported tokens, which would cause the transaction to fail silently.

4
Handle the Retry Logic

Once the agent pays, it will receive a payment receipt (often a transaction hash or JWT). It will then retry the original request, attaching this receipt in the Authorization header. Your server must verify this receipt against the blockchain or your payment gateway. If valid, return the trading signal data with a 200 OK status. If invalid or expired, return 402 again to prompt a new payment.

Handle agent payment verification

When your endpoint receives a retry request, the x-pay header contains the payment receipt. Your code must validate this receipt before returning the trading signal. This step ensures the AI agent actually paid for the data and that the transaction is settled on-chain.

x402 Endpoints for AI Trading Signals
1
Extract the transaction hash

Parse the x-pay header to extract the transaction hash (txid) and the chain identifier. The x402 standard defines a specific format for this receipt. If the header is missing or malformed, reject the request with a 402 Payment Required status immediately. Do not proceed to chain verification if the header is invalid.

2
Verify the chain and asset

Confirm that the transaction was broadcast on the chain specified in your endpoint’s configuration. Most x402 integrations use USDC on Base for low-cost, fast settlements. Check that the token amount in the transaction matches or exceeds the price you set in your x402 metadata. If the agent paid on the wrong chain or with the wrong token, the payment is invalid.

3
Check on-chain confirmation

Query a reliable block explorer or RPC node to check the status of the transaction hash. You need at least one block confirmation to prevent double-spending attacks. For high-stakes trading signals, consider waiting for three confirmations. If the transaction is still pending or has failed, return a 402 status and let the agent retry.

4
Validate the recipient address

Ensure the transaction was sent to your specific wallet address. The x402 protocol requires the payment to be directed to the endpoint operator. If the funds were sent to a different address, even if the amount is correct, the payment is not for your service. Reject the request if the recipient address does not match your configured wallet.

5
Cache the payment status

Once the payment is verified, cache the transaction hash or a unique payment ID in your database or memory store. This prevents the same payment from being used for multiple requests. Set a reasonable expiration time for this cache to avoid database bloat. When the agent retries, check the cache first before hitting the blockchain again.

This verification logic ensures that your AI trading signals are protected from unauthorized access. By strictly validating the x-pay header and on-chain status, you maintain a secure and reliable payment flow. For more details on the x402 standard, refer to the Coinbase Developer Documentation.

Note: The chart above shows USDC on Base, the most common asset for x402 payments due to its low fees and fast settlement times.

Register your endpoint in the Bazaar

Discovery is the difference between a private script and a scalable AI service. Once your endpoint is live and accepting payments, you need to register it in the CDP Bazaar. This catalog acts as the discovery layer where autonomous agents search for and evaluate x402-enabled services.

To get listed, you must interact with the CDP Facilitator. This tool validates your endpoint's schema and ensures your payment logic aligns with the x402 protocol standards. Without this registration, AI agents cannot find your trading signals, regardless of how accurate they are.

Follow these steps to publish your service:

1
Prepare your service manifest

Create a JSON manifest that describes your endpoint. Include the API URL, the specific trading signal types you offer (e.g., BTC/USD momentum), and the pricing structure. Be precise; agents parse this data to determine if your service fits their strategy.

2
Submit to the CDP Facilitator

Use the official CDP Facilitator interface to submit your manifest. The system will run automated checks against the x402 specification. If your endpoint rejects payments or lacks proper headers, the submission will fail. Fix any schema errors before proceeding.

3
Verify your listing

Once approved, your endpoint appears in the Bazaar. Test the discovery flow by querying the Bazaar API directly. Ensure that AI agents can retrieve your service details and initiate a test payment transaction successfully.

The Bazaar is the bridge between your code and the AI economy. Treat this registration process with the same rigor as your trading algorithms. A well-documented, compliant endpoint is more likely to be selected by high-volume agents.

Common integration errors to avoid

Even with a solid foundation, x402 endpoints can fail silently or lose revenue if you overlook specific implementation details. The protocol is straightforward, but the edge cases in network reliability and payment verification require careful handling.

Incorrect timeout handling

APIs are not instantaneous. If your client times out before the payment transaction confirms on-chain, the agent may return an error or, worse, the request may hang indefinitely. Always set generous timeouts and implement exponential backoff for retry attempts. This ensures that transient network issues don't result in lost signals or duplicate charges.

Missing payment receipts in retries

When a request times out, clients often retry. If your endpoint doesn't check for an existing payment receipt before processing the new request, you risk double-charging the user. Always validate the x-payment header or check your database for a matching transaction ID before executing the AI logic. This idempotency check is critical for maintaining trust and preventing revenue leakage.

Ignoring chain-specific confirmation requirements

Not all chains confirm transactions at the same speed. Base and Solana have different finality guarantees. If you're accepting payments across multiple chains, ensure your verification logic accounts for the specific block confirmation requirements of each network. Treating all transactions as instantly final can lead to accepting payments that are later reverted.

Frequently asked questions about x402

What is the x402 V2 protocol?

The x402 V2 standard defines how networks and digital assets are identified, creating a single payment format that works across different blockchains and legacy payment rails. Its most significant upgrade is multi-chain support by default, allowing stablecoins and tokens to move seamlessly across Base, Solana, and other chains without requiring custom integration logic.

How does x402 handle AI agent payments?

x402-secure is built specifically for transactions involving autonomous AI agents. It transparently integrates pre-payment risk checks, ensuring that an agent has the necessary funds or credit before executing a trade signal. This prevents failed transactions and secures the payment flow between the AI and the data provider.

Can I use x402 with existing trading bots?

Yes. Because x402 standardizes the payment format, it is designed to integrate with existing trading infrastructure. Developers can implement the protocol to handle the payment verification step automatically, allowing your bots to purchase real-time signals without manual intervention or complex wallet management.