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

# Coinbase X402

> Coinbase X402 Payment Integration - Pay for sessions with X402 Protocol

Anchor Browser supports X402 cryptocurrency payments for browser sessions when you have insufficient credits. This allows you to pay for sessions using cryptocurrency wallets.

<video autoPlay muted loop playsInline src="https://mintcdn.com/anchor-b3ec2715/hJc2I0-WvjLCCXOl/images/X402.mp4?fit=max&auto=format&n=hJc2I0-WvjLCCXOl&q=85&s=8c7be419fa2e12ff5e7c669ebd1c1449" alt="X402 use in the Playground" data-path="images/X402.mp4" />

## How It Works

1. **Attempt Session Creation**: Try to create a browser session
2. **Credit Check**: System checks if you have sufficient credits
3. **Payment Prompt**: If Error 402 is returned, you're prompted to connect a wallet
4. **Automatic Payment**: Payment is processed automatically through your wallet
5. **Session Creation**: Session is created immediately after successful payment

## Using X402 Payments via API

### Prerequisites

1. **Install Coinbase Wallet**: Currently only Coinbase Wallet is supported
2. **Get Funds**: Ensure your wallet has USDC on the Base mainnet network
3. **Set Up WalletConnect**: Configure WalletConnect for wallet connection

### API Usage Example

When you make a session creation request without sufficient credits, the system will:

1. Return a 402 (Payment Required) status
2. Include payment details in the response
3. Your client can automatically handle the payment using X402
4. Retry the request with payment headers

Here are examples using the x402 library with both Python and Node.js:

<CodeGroup>
  ```python python theme={null}
  import os, json, requests
  from eth_account import Account
  from x402.clients.requests import x402_requests
  from anchorbrowser import Anchorbrowser

  ENDPOINT = "https://api.anchorbrowser.io/v1/sessions"
  BODY = {}

  key = os.getenv("PRIVATE_KEY") or exit("Set PRIVATE_KEY=0x...")

  # Try to create session normally first
  try:
      anchor_client = Anchorbrowser(api_key=os.getenv("ANCHOR_API_KEY"))
      session = anchor_client.sessions.create()
      print(json.dumps(session.data, indent=2))
  except Exception as e:
      # If we get a 402 error, handle payment
      if "402" in str(e):
          # Get payment details and process with x402
          pre = requests.post(ENDPOINT, json=BODY, timeout=30)
          price = int(pre.json()["accepts"][0]["maxAmountRequired"])
          
          res = x402_requests(Account.from_key(key)).post(ENDPOINT, json=BODY, timeout=60)
          print(json.dumps(res.json(), indent=2))
      else:
          raise e
  ```

  ```javascript node.js theme={null}
  import AnchorBrowser from 'anchorbrowser';
  import { Account } from 'eth-account';
  import { x402Fetch } from 'x402';

  (async () => {
    const ENDPOINT = "https://api.anchorbrowser.io/v1/sessions";
    const BODY = {};
    
    const key = process.env.PRIVATE_KEY;
    if (!key) {
      console.error("Set PRIVATE_KEY=0x...");
      process.exit(1);
    }
    
    try {
      // Try to create session normally first
      const anchor_client = new AnchorBrowser({apiKey: process.env.ANCHOR_API_KEY});
      const session = await anchor_client.sessions.create();
      console.log(JSON.stringify(session.data, null, 2));
    } catch (error) {
      // If we get a 402 error, handle payment
      if (error.message.includes("402")) {
        const pre = await fetch(ENDPOINT, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(BODY)
        });
        
        const preData = await pre.json();
        const price = parseInt(preData.accepts[0].maxAmountRequired);
        
        const account = Account.fromPrivateKey(key);
        const res = await x402Fetch(account, ENDPOINT, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(BODY)
        });
        
        console.log(JSON.stringify(await res.json(), null, 2));
      } else {
        throw error;
      }
    }
  })().catch(console.error);
  ```
</CodeGroup>

## Pricing

* **Price per Session**: \$0.50 USDC
* **Network**: Base mainnet only
* **Payment Method**: USDC via X402 protocol

***

## Read More

* [X402 Protocol Specification](https://www.x402.org/)
* [X402 GitHub Repository](https://github.com/coinbase/x402)
* [X402 NPM package](https://www.npmjs.com/package/x402)
* [X402 Python Library](https://pypi.org/project/x402/)
