---
name: x402-client
description: Call APIs protected by x402 and pay automatically with a USDC wallet, within a per-request and total budget the user sets. Use when a request returns HTTP 402 Payment Required, or the user asks an agent to buy data or services from an x402 endpoint.
---

# x402 client

## Safety rules

- Only pay when the user has explicitly allowed it and set a budget: a maximum per request and a maximum total for the session. Default to asking before every payment if no budget is given.
- Read the wallet key from an environment variable (`AGENT_PRIVATE_KEY`). Never print it, log it, or ask the user to paste it into the conversation. Recommend a dedicated low-balance wallet.
- Before paying, show the user: resource URL, amount in USD, network and `payTo`.

## Inspect a 402

```bash
curl -s -i https://api.example.com/paid-endpoint
```

The JSON body's `accepts` lists acceptable payments. Pick the entry whose `network` your wallet is funded on. `maxAmountRequired` is in the token's smallest unit (USDC: 6 decimals, so `10000` = $0.01). Refuse if it exceeds the per-request budget.

## Pay with x402-fetch (Node)

```bash
npm install x402-fetch viem
```

```js
import { wrapFetchWithPayment, decodeXPaymentResponse } from "x402-fetch";
import { privateKeyToAccount } from "viem/accounts";

const account = privateKeyToAccount(process.env.AGENT_PRIVATE_KEY);
// third argument: maximum payment in base units (here $0.10)
const pay = wrapFetchWithPayment(fetch, account, BigInt(100_000));

const res = await pay("https://api.example.com/paid-endpoint");
console.log(res.status, await res.json());
const receipt = res.headers.get("x-payment-response");
if (receipt) console.log(decodeXPaymentResponse(receipt)); // { success, transaction, network, payer }
```

## Python

```bash
pip install x402 eth-account httpx
```

```python
import os
from eth_account import Account
from x402.clients.httpx import x402HttpxClient

account = Account.from_key(os.environ["AGENT_PRIVATE_KEY"])
async with x402HttpxClient(account=account, base_url="https://api.example.com") as client:
    r = await client.get("/paid-endpoint")
    print(r.status_code, r.json())
```

## After paying

Report the amount, network and settlement transaction hash, and keep a running total against the budget. If the server returns 402 again after a payment, stop and report the `error` field instead of retrying.
