What is the x402 payment protocol

Unknown component: x402
allows API consumers to pay with crypto (usually USDC) on each request without registering for an account or managing API keys.

The x402 protocol replaces static API keys with an HTTP 402 "Payment Required" status code. Instead of managing subscriptions or rotating keys, developers send a cryptographic signature with their request. If the signature includes a valid payment, the API responds with 200 OK and the requested data.

This keyless, pay-per-request model is particularly useful for crypto data and infrastructure services. As documented by Elfa and Nansen, any wallet can call any x402-enabled endpoint. There is no registration process, no subscription tier, and no need to store sensitive credentials in environment variables. You just need a wallet with enough USDC to cover the cost of the request.

For developers, this means less boilerplate and fewer points of failure. You don't need to handle key rotation or worry about leaked secrets. The payment is atomic, tied directly to the request, and settled on-chain. This approach aligns with the decentralized ethos of Web3, where access is granted through proof of payment rather than proof of identity.

The mechanics are straightforward: your client library detects a 402 response, prompts the user (or automatically uses a connected wallet) to sign a payment message, resends the request, and receives the data. It's a seamless shift from "who are you?" to "have you paid?".

Set up a wallet and fund it with USDC

Before you can make a payment through an x402 endpoint, you need a Web3 wallet that can sign transactions and hold stablecoins. The x402 protocol is designed to be lightweight, so you don’t need a complex multi-sig setup or a hardware wallet for initial testing. A standard browser-based wallet like MetaMask or a mobile wallet like Rabby is sufficient.

Create your wallet

If you don’t already have a Web3 wallet, install one and create a new account. During the setup process, you will be given a seed phrase. Store this securely offline; it is the only way to recover your funds if you lose access to your device. Once created, ensure your wallet is connected to a network that supports USDC, such as Ethereum Mainnet, Polygon, or Arbitrum. For most x402 demonstrations, Polygon is a popular choice due to its low transaction fees, which keeps the cost of testing minimal.

Fund the wallet with USDC

x402 endpoints typically require payment in USDC (USD Coin), a stablecoin pegged to the US dollar. You need to transfer USDC from an exchange or another wallet into your new wallet address.

  1. Get your address: Copy your public wallet address from your wallet interface.
  2. Transfer USDC: Send USDC from your exchange (e.g., Coinbase, Binance) or a friend’s wallet to this address. Ensure you select the correct network (e.g., if your wallet is on Polygon, send USDC on the Polygon network).
  3. Verify balance: Check your wallet’s balance to confirm the USDC has arrived. You should also have a small amount of the native token (e.g., MATIC on Polygon or ETH on Ethereum) to cover gas fees for the transaction.

Check your network and gas

x402 payments are recorded on-chain, meaning you need gas to process the transaction. If you are testing on a testnet like Goerli or Sepolia, you can get free test USDC and native tokens from a faucet. For mainnet testing, ensure you have enough of the native currency to cover the gas cost. While x402 payments are small, failed transactions due to insufficient gas will not trigger the payment, and the API will return an error.

Test with a demo endpoint

Many x402 implementations include a demo endpoint to help you verify your setup. These demos often provide a simple API call that returns a small amount of data in exchange for a tiny USDC payment. This is the best way to confirm your wallet is correctly funded and connected before integrating x402 into your production workflow. If the demo fails, double-check your network selection and USDC balance.

Make a request and handle the 402 response

The x402 protocol turns a standard HTTP call into a payment gateway. You don’t need an API key or a subscription to access data; you just need a crypto wallet. The interaction follows a strict sequence: you ask for data, the server refuses with a specific error code, and then you pay to unlock it.

1. Send the initial request

Start by sending a standard HTTP request to the protected endpoint. This can be a GET or POST request, depending on the API. At this stage, you are not authenticated. The server recognizes your request but sees no payment history for this specific call.

For example, if you are using the Laevitas API, you would POST to a pass route. If you are using Elfa, you would hit their data endpoints directly. The request headers should be normal. Do not include any special payment tokens yet. The server needs to see a standard request to trigger the x402 flow.

2. Receive the 402 Payment Required response

Instead of returning the data, the server responds with an HTTP 402 Payment Required status code. This is the core signal of the x402 protocol. A 402 status is rarely used in traditional web development, but it is the standard here for pay-per-request access.

The response body contains more than just an error message. It includes the payment instructions. These instructions tell you exactly what to do next: which cryptocurrency to send, the amount, the recipient wallet address, and the blockchain network. This turns the error response into a bill.

3. Parse the payment instructions

You need to extract the payment details from the 402 response. The structure varies slightly by provider, but the goal is the same. You are looking for a payment payload that defines the transaction parameters.

For instance, the Laevitas API documentation notes that the server returns USDC payment instructions in the response. You must parse these instructions to construct a valid transaction. This usually involves identifying the token contract address, the decimal precision, and the exact amount owed for this specific data request.

JavaScript
// Example: Handling a 402 response in JavaScript
const response = await fetch('https://api.example.com/data', {
  method: 'GET',
  headers: { 'Authorization': 'Bearer your-wallet-signature' }
});

if (response.status === 402) {
  const paymentInstructions = await response.json();
  console.log('Pay this amount to access the data:', paymentInstructions.amount);
  // Proceed to sign and broadcast transaction
} else {
  const data = await response.json();
  console.log('Access granted:', data);
}

4. Execute the payment

Once you have parsed the instructions, you must execute the transaction. This step is separate from the initial HTTP request. You use your wallet to send the specified amount of cryptocurrency to the provided address on the specified blockchain.

This is where the "keyless" aspect comes in. You don’t send a password. You send value. The blockchain serves as the public ledger that proves you have paid. Once the transaction is broadcast, the network confirms it. This confirmation is what the server will eventually check to grant access.

5. Resend the request with proof

After the payment is broadcast, you must make a second request to the same endpoint. This time, you include proof of payment. This proof is typically a signature from your wallet that references the transaction hash.

The server validates this proof against the blockchain. If the payment is confirmed and matches the instructions from the first 402 response, the server returns the data with a 200 OK status. If the proof is invalid or the payment hasn’t cleared yet, the server may return a 402 again, prompting you to wait or check your transaction status.

This cycle—request, 402, pay, resubmit—is the fundamental rhythm of x402. It allows APIs to monetize individual calls without managing user accounts or credit card processing. The protocol handles the friction of payment by embedding it directly into the HTTP response code.

Sign the transaction and retrieve the data

With the x-402-payment header in hand, the final step is to prove you have paid. This is where the protocol moves from a request to a completed transaction. You will sign the payment details using your wallet, attach the signature to the request, and send it one last time to the API provider.

1. Sign the payment proof

The payment proof is a cryptographic signature that binds your wallet identity to the payment intent. You do not need to sign the entire HTTP request body; instead, you sign a specific payload that includes the transaction ID, the amount, and the recipient address.

Using a library like viem or ethers, you construct the signable message. This message typically looks like a structured object containing the paymentId and the amount in wei. Your wallet prompts you to sign this message, ensuring you are explicitly authorizing the payment for this specific API call. This step prevents replay attacks, as the signature is unique to the transaction context.

2. Attach the signature to the request

Once you have the signature (a hex string starting with 0x), you must attach it to your HTTP request. The x402 protocol expects this in the x-402-payment header. This header now contains the full payment proof, which includes the wallet address, the signature, and the transaction details.

If you are using a tool like curl or a JavaScript fetch call, the structure looks like this:

JavaScript
const response = await fetch(endpoint, {
  headers: {
    'x-402-payment': JSON.stringify({
      wallet: '0xYourWalletAddress',
      signature: '0xYourSignature',
      paymentId: 'unique-tx-id',
      amount: '1000000000000000' // in wei
    })
  }
});

This header is the key that unlocks the data. It tells the API provider exactly who is paying, how much, and that they have authorized it cryptographically.

3. Send the request and retrieve data

Send the request with the attached payment proof. The API provider’s gateway will verify the signature against the sender’s wallet address and check if the payment has been confirmed on-chain or off-chain, depending on the implementation.

If the signature is valid and the payment is confirmed, the gateway strips the payment header and forwards your original request to the backend service. You will receive a standard 200 OK response with the requested data. If the signature is invalid or the payment is missing, you will receive a 402 Payment Required error again, often with a new challenge or a specific error code indicating why the payment was rejected.

Verification Checklist

Before assuming the data is secure and complete, run through these quick checks:

  • Confirm transaction hash is visible in wallet history
  • Verify API response status is 200 OK
  • Check data payload matches expected schema
  • Ensure no sensitive wallet keys were logged

This completes the x402 payment flow. You have successfully demonstrated that you are willing to pay for the resource, and the API has delivered the data in return. This mechanism removes the need for pre-funded accounts or complex subscription management, making it ideal for one-off data queries or micro-transactions.

Common integration errors and fixes

Even with a solid x402 setup, the payment flow can fail silently or crash your service if specific conditions aren't met. These errors usually stem from mismatched network contexts, insufficient funds, or malformed request structures. Below are the most frequent pitfalls and how to resolve them.

Insufficient gas or wrong chain selection

The most common failure point is a mismatch between the wallet's native currency and the API's expected payment chain. If your server expects payment on Ethereum Mainnet but the client sends from a Polygon wallet, the transaction will fail immediately.

Ensure your server validates the chainId before processing the request. If you're using a multi-chain setup, explicitly document which networks are supported. Clients must ensure their wallet is connected to the correct network and holds enough native gas tokens to cover the transaction fee.

Malformed payment signatures

x402 relies on valid cryptographic signatures to verify intent. If the signature is missing, expired, or does not match the expected payload, the server will reject the request with a 401 or 403 error, not a 402. This often happens when the client library is outdated or when the payload structure changes between versions.

Always verify the signature format against the official x402 specification. Use a debugger or log the raw signature data to ensure it aligns with the server's validation logic. If the signature is valid but still rejected, check for timestamp expiration.

Missing or incorrect headers

The HTTP 402 response includes specific headers that guide the client on how to proceed. If these headers are missing or incorrectly formatted, the client may not know which address to send payment to or what the required amount is.

Ensure your server returns the Payment header with the correct URI and amount. Clients should parse this header dynamically rather than hardcoding payment addresses. This allows for flexible pricing and multi-currency support without code changes.

Transaction confirmation delays

Blockchain transactions are not instant. If your server checks for payment confirmation too early, it may reject a valid payment that is still pending. This is particularly common on slower chains or during network congestion.

Implement a polling mechanism or use a webhook service to listen for transaction confirmations. Wait for at least one block confirmation before granting access. This prevents race conditions where a user accesses the API before the payment is fully secured on the ledger.

Testing in isolation

Many integration issues arise because developers test the API endpoint in isolation without simulating the full payment flow. A successful API response does not guarantee a successful payment transaction.

Use a testnet or local blockchain environment to simulate the entire x402 flow. Verify that the client can sign the payment, the server can validate the signature, and the access control logic triggers correctly. This end-to-end testing catches most integration errors before they reach production.

Frequently asked questions about x402

Work through Pay-Per-API 402

1
Gather what you need
Confirm the materials, tools, account access, or setup pieces for Pay-Per-API 402 before changing anything.
2
Work in order
Complete one step at a time and verify the result before moving on. Most failed guides get confusing when two changes happen at once.
3
Check the finished result
Compare the outcome with the expected shape, connection, texture, or behavior, then adjust only the part that is actually off.