> ## Documentation Index
> Fetch the complete documentation index at: https://docs.x402x.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# 买家指南（Buyer）

> 使用 x402-fetch 自动处理 402 支付与重试

## 客户端示例

<Tabs>
  <Tab title="最简集成">
    ```ts theme={null}
    import { wrapFetchWithPayment } from "x402x-fetch";
    import { parseEther } from "viem";
    const fetchWithPay = wrapFetchWithPayment(fetch, walletClient, parseEther("0.01")); // 设置最大支付额度
    const res = await fetchWithPay("https://api.example.com/premium", { method: "POST" });
    ```
  </Tab>

  <Tab title="完整示例（Node + viem）">
    创建 `client.ts`，核心逻辑如下：

    ```typescript theme={null}
    // 1. 创建钱包客户端
    const client = createWalletClient({
      account,
      transport: http(),
      chain: bsc,
    });

    // 2. 包装 fetch 以支持自动支付
    const fetchWithPay = wrapFetchWithPayment(
      fetch,
      walletClient.extend(publicActions),
      parseEther("0.01")
    );

    // 3. 发起请求（自动处理支付）
    const response = await fetchWithPay('http://localhost:3939/api/data', {
      method: "POST",
    });
    ```

    <AccordionGroup>
      <Accordion title="查看完整客户端代码">
        ```typescript theme={null}
        import { createWalletClient, http, parseEther, publicActions } from "viem";
        import { privateKeyToAccount } from "viem/accounts";
        import { wrapFetchWithPayment } from "x402x-fetch";
        import { bsc } from "viem/chains";

        const PRIVATE_KEY='' // 持有 USD1 Token 的私钥钱包
        const SERVER_URL='http://localhost:3939/api/data'

        async function main() {
          // 创建钱包
          const account = privateKeyToAccount(PRIVATE_KEY);
          const client = createWalletClient({
            account,
            transport: http(),
            chain: bsc,
          });

          // 创建支付 fetch
          const fetchWithPay = wrapFetchWithPayment(
            fetch,
            client.extend(publicActions),
            parseEther("0.01")
          );

          // 请求付费 API
          const response = await fetchWithPay(SERVER_URL, {
            method: "POST",
          });

          if (!response.ok) {
            const error = await response.json();
            console.error("❌ Error:", error);
            return;
          }

          const data = await response.json();
          console.log("✅ Received:", data);
        }

        main();
        ```
      </Accordion>
    </AccordionGroup>
  </Tab>

  <Tab title="React示例（wagmi + viem）">
    ```typescript theme={null}
    import { useX402Payment } from 'x402x-react';
    import { useWalletClient } from 'wagmi';

    function PaymentComponent() {
      const { data: walletClient } = useWalletClient();
      
      const { mutate, isPending, error, data } = useX402Payment({
        targetUrl: 'https://api.example.com/resource',
        walletClient,
      });

      return (
        <button onClick={() => mutate()}>
          {isPending ? 'Processing...' : 'Pay'}
        </button>
      );
    }
    ```
  </Tab>
</Tabs>

## 工作流程

1. 调用受保护资源 → 收到 402
2. 解析 `accepts` → 选择一个 requirements
3. 生成支付签名（Permit/EIP-3009/Permit2）
4. 设置 `X-Payment` 重试请求 → 返回 200

## 最佳实践

* 始终设置 `maxValue`，避免过额支付
* 对多选项资源可传入 selector 优先 Token
* 失败时打印 payload 与 402 体，便于定位

## 常见问题

* 余额不足/过期/nonce 错误 → 按错误提示重新签名
* 网络切换后失败 → 确保 `network` 与 requirements 匹配

## 相关

<CardGroup cols={2}>
  <Card title="客户端 SDK" icon="laptop" href="/packages/fetch">API 与示例</Card>
  <Card title="支付负载" icon="file-code" href="/parameters-responses/core/payment-payload">Payload 规范</Card>
  <Card title="支付类型" icon="key" href="/user-guide/support/payment-types">授权方式对比</Card>
  <Card title="支持查询" icon="list" href="/api-reference/endpoint/supported">查询支持能力</Card>
</CardGroup>
