x402: How AI Agents Pay for APIs Without Human Oversight

```html

x402: How AI Agents Pay for APIs Without Human Oversight

As AI agents become more autonomous, they increasingly need to call third-party APIs to accomplish tasks. But here's the problem: most API services require human intervention for payment processing. An autonomous agent can't fill out a credit card form or approve a charge request. It needs a way to programmatically discover available services, check pricing, and pay automatically—all without waking up a human at 3 AM.

AiPayGent solves this with the x402 Payment Required protocol, allowing AI agents to autonomously discover APIs, understand their costs, and make micropayments using prepaid credits or USDC on Base. Let's walk through how to build this.

The Problem: Autonomous API Access

Traditional API payment models assume human users: enter payment info once, get a static API key, make unlimited calls. But autonomous agents need something different:

AiPayGent's /discover endpoints and x402 protocol handle all of this.

Getting Started: Free Calls and Credit Management

Every AiPayGent account gets 10 free API calls per day. After that, you need either:

First, let's see your current balance and discover available endpoints:

curl -X GET "https://api.aipaygent.xyz/discover/endpoints" \
  -H "X-API-Key: your-api-key-here"

Response (example):

{
  "endpoints": [
    {
      "id": "claude-instant-summarize",
      "name": "Claude Instant - Summarize Text",
      "cost_credits": 2,
      "cost_usd": 0.001,
      "rate_limit": "100/min",
      "description": "Fast summarization using Claude Instant"
    },
    {
      "id": "gpt4-vision-analyze",
      "name": "GPT-4 Vision - Image Analysis",
      "cost_credits": 50,
      "cost_usd": 0.02,
      "rate_limit": "10/min",
      "description": "Analyze images with GPT-4 Vision"
    }
  ],
  "free_calls_remaining_today": 8,
  "account_credits": 500
}

Great! Your agent now knows what's available and the cost. It has 8 free calls left today and 500 prepaid credits in the account.

Discovery in Action: Building an Agent Query

Let's build a Python agent that discovers endpoints, checks affordability, and makes a decision:

import requests
import json

API_KEY = "your-api-key-here"
BASE_URL = "https://api.aipaygent.xyz"
HEADERS = {"X-API-Key": API_KEY}

# Step 1: Discover available endpoints
def discover_endpoints():
    response = requests.get(
        f"{BASE_URL}/discover/endpoints",
        headers=HEADERS
    )
    return response.json()

# Step 2: Check if we can afford a specific endpoint
def can_afford(endpoint_id, budget_credits):
    endpoints = discover_endpoints()
    for ep in endpoints["endpoints"]:
        if ep["id"] == endpoint_id:
            cost = ep["cost_credits"]
            remaining = endpoints["account_credits"]
            free_today = endpoints["free_calls_remaining_today"]
            
            # Use free calls first
            if free_today > 0:
                return True, "Using free call", 0
            
            if remaining >= cost:
                return True, f"Have {remaining} credits, need {cost}", cost
            else:
                return False, f"Insufficient credits. Have {remaining}, need {cost}", None
    
    return False, "Endpoint not found", None

# Step 3: If we can't afford it, buy more credits
def buy_credits(usd_amount):
    response = requests.post(
        f"{BASE_URL}/buy-credits",
        headers=HEADERS,
        json={"amount_usd": usd_amount, "payment_method": "usdc_base"}
    )
    return response.json()

# Example: Agent decides whether to call an expensive endpoint
endpoint_choice = "gpt4-vision-analyze"  # Costs 50 credits
can_call, reason, cost = can_afford(endpoint_choice, budget_credits=500)

print(f"Can call {endpoint_choice}? {can_call}")
print(f"Reason: {reason}")

if not can_call:
    print("Buying more credits...")
    purchase = buy_credits(usd_amount=10.00)
    print(f"Purchase response: {purchase}")

Example Output:

Can call gpt4-vision-analyze? True
Reason: Have 500 credits, need 50

Making the Actual API Call

Once your agent has verified it can afford the call, it proceeds with the actual request:

def call_endpoint(endpoint_id, payload):
    response = requests.post(
        f"{BASE_URL}/execute/{endpoint_id}",
        headers=HEADERS,
        json=payload
    )
    return response.json()

result = call_endpoint(
    "claude-instant-summarize",
    {"text": "The quick brown fox jumped over the lazy dog..."}
)

print(json.dumps(result, indent=2))

Response Example:

{
  "output": "A fox jumped over a dog.",
  "tokens_used": 145,
  "credits_charged": 2,
  "cost_usd": 0.001,
  "transaction_id": "tx_abc123def456"
}

Key Takeaways for Autonomous Agents

With x402 and AiPayGent's discover endpoints, your AI agents can operate autonomously in a resource-constrained world, making smart decisions about what APIs to call based on real budget constraints.

Learn More

Explore all available endpoints and their costs: