Skip to main content
Back to Blog
Tutorial

How to Add USDC Payments to Any AI Agent: The Complete 2026 Integration Guide

Working code in TypeScript and Python for adding USDC payments to LangChain, CrewAI, OpenAI Agents SDK, AutoGen, and custom agents. Test-mode walkthrough, error handling, and a production checklist.

How to Add USDC Payments to Any AI Agent: The Complete 2026 Integration Guide
May 18, 2026
12 min read
#Tutorial#USDC#Integration#Agent Wallet

What this guide gives you

A complete, copy-paste integration of USDC payments for an AI agent. Five frameworks covered (LangChain, CrewAI, OpenAI Agents SDK, AutoGen, plus a framework-agnostic pattern). Working code in TypeScript and Python. Test-mode setup so you can exercise the full flow with no real money. A production checklist for when you flip the switch.

If you only want the headline: agents pay over USDC on Base, settle through the x402 protocol, enforce limits via a wallet-side spend policy, and verify identity via the agent payment identity layer. The rest is wiring.

For the long-form playbook on going from $0 to $1k in agent revenue, see our companion piece on the 30-day playbook.

Prerequisites (5 minutes)

Before any framework code:

  • A Blockchain0x account. Free signup at wallet.blockchain0x.com/signup. You will get one workspace and a default agent wallet.
  • A sk_test_ API key. This key transacts on Base Sepolia with faucet-funded test USDC. Switch to sk_live_ only after you have validated the end-to-end flow.
  • Node 20+ or Python 3.11+ (the SDKs work with both, the examples are cross-language).
  • For LangChain/CrewAI/AutoGen: working installs of those frameworks. For OpenAI Agents SDK: an OpenAI API key.

Install the SDK:

BASH
# Node
npm install @blockchain0x/sdk

# Python
pip install blockchain0x

Set environment variables:

BASH
BLOCKCHAIN0X_API_KEY=sk_test_xxxxxxxxxxxxxxxx
BLOCKCHAIN0X_WALLET_ID=wlt_xxxxxxxxxxxxxxxx

You now have everything you need to wire payments into an agent.

The core pattern (framework-agnostic)

Every agent payment integration follows the same shape, regardless of framework:

  1. The agent calls a paid endpoint (an API, a paid MCP tool, another agent).
  2. The endpoint returns HTTP 402 with a price and a payment URL.
  3. The agent's wallet client intercepts the 402, evaluates the spend policy, settles if approved.
  4. The endpoint receives a receipt, validates it, returns 200 with the actual result.
  5. The agent uses the result.

The wallet client is the part that does the work. Here is the framework-agnostic Node version:

TS
import { Blockchain0x } from "@blockchain0x/sdk";

const wallet = new Blockchain0x({
  apiKey: process.env.BLOCKCHAIN0X_API_KEY!,
  walletId: process.env.BLOCKCHAIN0X_WALLET_ID!,
});

async function paidFetch(url: string, opts: RequestInit = {}) {
  const res = await fetch(url, opts);
  if (res.status !== 402) return res;

  const { paymentUrl, price } = await res.json();
  const receipt = await wallet.pay({ paymentUrl, price });
  return fetch(url, {
    ...opts,
    headers: { ...opts.headers, "x-payment-receipt": receipt.id },
  });
}

That is the whole abstraction. paidFetch behaves identically to fetch for free endpoints and transparently settles 402 responses for paid ones. The wallet enforces the policy, signs the transaction, returns a receipt. You wire paidFetch into your agent's HTTP layer and you are done.

Python is symmetric:

PYTHON
from blockchain0x import Wallet
import os, httpx

wallet = Wallet(
    api_key=os.environ["BLOCKCHAIN0X_API_KEY"],
    wallet_id=os.environ["BLOCKCHAIN0X_WALLET_ID"],
)

async def paid_fetch(url: str, **kwargs) -> httpx.Response:
    async with httpx.AsyncClient() as client:
        res = await client.request(kwargs.get("method", "GET"), url, **kwargs)
        if res.status_code != 402:
            return res
        body = res.json()
        receipt = await wallet.pay(payment_url=body["paymentUrl"], price=body["price"])
        headers = {**kwargs.get("headers", {}), "x-payment-receipt": receipt.id}
        return await client.request(kwargs.get("method", "GET"), url, headers=headers)

Now we wire this into each framework.

Framework 1: LangChain (Python)

LangChain agents typically call tools via the @tool decorator or Tool class. The cleanest integration is a payment-aware HTTP tool:

PYTHON
from langchain.tools import tool
from blockchain0x import Wallet
import os, httpx

wallet = Wallet(
    api_key=os.environ["BLOCKCHAIN0X_API_KEY"],
    wallet_id=os.environ["BLOCKCHAIN0X_WALLET_ID"],
)

@tool
async def paid_api_call(url: str, query: dict) -> str:
    """Calls a paid HTTP endpoint, settling any 402 response automatically."""
    async with httpx.AsyncClient() as client:
        res = await client.get(url, params=query)
        if res.status_code == 402:
            body = res.json()
            receipt = await wallet.pay(payment_url=body["paymentUrl"], price=body["price"])
            res = await client.get(url, params=query, headers={"x-payment-receipt": receipt.id})
        return res.text

agent = initialize_agent(
    tools=[paid_api_call, ...other_tools],
    llm=ChatOpenAI(model="gpt-4o"),
    agent_type=AgentType.STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION,
)

The agent now treats any paid endpoint as a regular tool. The payment is invisible to the agent's planner; the spend policy lives at the wallet API. See the LangChain integration guide for the full pattern.

Framework 2: CrewAI (Python)

CrewAI uses crews of role-specialized agents that share tools. The same pattern applies:

PYTHON
from crewai import Agent, Task, Crew
from crewai_tools import Tool
from blockchain0x import Wallet
import os, httpx

wallet = Wallet(
    api_key=os.environ["BLOCKCHAIN0X_API_KEY"],
    wallet_id=os.environ["BLOCKCHAIN0X_WALLET_ID"],
)

async def paid_call(url: str, params: dict) -> str:
    async with httpx.AsyncClient() as c:
        r = await c.get(url, params=params)
        if r.status_code == 402:
            body = r.json()
            receipt = await wallet.pay(payment_url=body["paymentUrl"], price=body["price"])
            r = await c.get(url, params=params, headers={"x-payment-receipt": receipt.id})
        return r.text

paid_research_tool = Tool(
    name="paid_research",
    description="Calls premium research APIs that may require payment.",
    func=paid_call,
)

researcher = Agent(
    role="Researcher",
    goal="Gather high-quality data using paid sources when free ones are insufficient.",
    tools=[paid_research_tool],
)

For the CrewAI integration, the wallet client lives at the tool layer. Spend policy applies across the whole crew because it is enforced at the wallet, not per-agent.

Framework 3: OpenAI Agents SDK (Node)

OpenAI's Agents SDK uses function calling. Wire the wallet client into a function-call handler:

TS
import OpenAI from "openai";
import { Blockchain0x } from "@blockchain0x/sdk";

const openai = new OpenAI();
const wallet = new Blockchain0x({
  apiKey: process.env.BLOCKCHAIN0X_API_KEY!,
  walletId: process.env.BLOCKCHAIN0X_WALLET_ID!,
});

const tools = [{
  type: "function",
  function: {
    name: "paid_api_call",
    description: "Calls a paid HTTP endpoint; payment is handled transparently.",
    parameters: {
      type: "object",
      properties: {
        url: { type: "string" },
        method: { type: "string" },
        body: { type: "object" },
      },
      required: ["url", "method"],
    },
  },
}];

async function callTool(name: string, args: any) {
  if (name === "paid_api_call") {
    const res = await fetch(args.url, {
      method: args.method,
      body: args.body ? JSON.stringify(args.body) : undefined,
    });
    if (res.status === 402) {
      const { paymentUrl, price } = await res.json();
      const receipt = await wallet.pay({ paymentUrl, price });
      const retry = await fetch(args.url, {
        method: args.method,
        body: args.body ? JSON.stringify(args.body) : undefined,
        headers: { "x-payment-receipt": receipt.id },
      });
      return await retry.text();
    }
    return await res.text();
  }
}

Plug callTool into the SDK's tool_call handler and your agent transparently pays for paid endpoints. The full pattern lives at the OpenAI Agents SDK integration page.

Framework 4: AutoGen (Python)

AutoGen uses message-passing conversational agents. The wallet client lives in the function-tool registration:

PYTHON
from autogen import ConversableAgent, register_function
from blockchain0x import Wallet
import os, httpx

wallet = Wallet(
    api_key=os.environ["BLOCKCHAIN0X_API_KEY"],
    wallet_id=os.environ["BLOCKCHAIN0X_WALLET_ID"],
)

async def paid_call(url: str, params: dict | None = None) -> str:
    async with httpx.AsyncClient() as c:
        r = await c.get(url, params=params)
        if r.status_code == 402:
            body = r.json()
            receipt = await wallet.pay(payment_url=body["paymentUrl"], price=body["price"])
            r = await c.get(url, params=params, headers={"x-payment-receipt": receipt.id})
        return r.text

agent = ConversableAgent(
    name="payer",
    system_message="You can call paid_call(url, params) to fetch premium data.",
    llm_config={"model": "gpt-4o"},
)

register_function(
    paid_call,
    caller=agent,
    executor=agent,
    name="paid_call",
    description="Calls a paid HTTP endpoint with transparent settlement.",
)

See the AutoGen integration for the multi-agent conversational pattern.

Framework 5: Custom / framework-agnostic

If your agent is not built on a popular framework, wire the wallet as middleware in your HTTP client. The pattern from the core section above is the entire integration:

TS
import { Blockchain0x } from "@blockchain0x/sdk";

const wallet = new Blockchain0x({
  apiKey: process.env.BLOCKCHAIN0X_API_KEY!,
  walletId: process.env.BLOCKCHAIN0X_WALLET_ID!,
});

export async function paidFetch(input: RequestInfo, init?: RequestInit) {
  const res = await fetch(input, init);
  if (res.status !== 402) return res;
  const { paymentUrl, price } = await res.json();
  const receipt = await wallet.pay({ paymentUrl, price });
  return fetch(input, {
    ...init,
    headers: { ...(init?.headers || {}), "x-payment-receipt": receipt.id },
  });
}

That is 14 lines of code that adds USDC payments to any HTTP-speaking agent runtime.

Setting the spend policy

Before any production traffic, set a spend policy on the wallet. The policy enforces budget and counterparty restrictions at the API level, outside the agent's manipulable scope:

TS
await wallet.setPolicy({
  perCallMax: "0.10",       // dollars per single call
  perDayMax: "50.00",       // dollars per UTC day
  counterpartyAllowlist: ["agent.example.com", "premium-api.dev"],
  timeWindow: { start: "00:00", end: "23:59", tz: "UTC" },
});

If the agent tries to spend beyond these bounds, the wallet rejects the payment intent without consulting the agent's planner. Prompt injection cannot bypass this; the policy lives in the wallet API, not in the agent's prompt. See 12 production-ready spend policy templates for use-case-specific configs.

Test mode walkthrough

With sk_test_ keys, all transactions are simulated on Base Sepolia using faucet-funded USDC. The flow is identical to mainnet:

BASH
# Fund the test wallet
blockchain0x wallet fund --network base-sepolia --amount 10

# Check balance
blockchain0x wallet balance
# → 10.00 USDC (Base Sepolia)

Run your agent against a test paid endpoint:

BASH
curl https://demo-paid-api.blockchain0x.com/quote -i
# HTTP/1.1 402 Payment Required
# Content-Type: application/json
# {"paymentUrl": "https://wallet.blockchain0x.com/pay/...","price": "0.005"}

Plug that demo endpoint into your agent and watch a full 402 → settle → 200 cycle in your dashboard. See testing agent payments without real money for the deep dive.

Production checklist

Before flipping sk_test_ to sk_live_:

  • The wallet has a spend policy set with realistic limits based on your week-one test data.
  • API keys are stored in a secret manager (AWS Secrets Manager, Google Secret Manager, Vault), not environment files.
  • The agent has its own wallet, not a workspace-shared one.
  • Webhook handlers are deployed and tested (see the webhook handling guide).
  • Receipt validation is server-side; never trust a client-supplied receipt header.
  • A reconciliation report runs daily and lands somewhere a human reads.
  • The runbook for a leaked API key is written and the on-call rotation knows where it is.
  • The wallet's identity profile is populated so counterparties can verify the agent before accepting larger payments.

When all of those are true, flip the key and watch the first live transaction land. Most teams overestimate how scary the cutover is - the test-to-live transition is one configuration change because the test infrastructure mirrors production.

What to do next

If you got to a working agent payment in this guide, the most useful next steps are:

  1. Tighten the spend policy from your first week of real data. Most teams over-allocate by 3-5x on day one and never tighten.
  2. Add an identity layer so counterparties can verify your agent before larger transactions. The agent identity feature is free and dramatically expands the agents that will trust yours.
  3. If you operate the paid endpoints too, wire webhooks for payment events so you can run async reconciliation and post-payment workflows.

Or, if you want the fastest path from "I just got it working" to "I have real users paying real agents", spin up an account and run a test transaction in the next ten minutes: wallet.blockchain0x.com/signup.

Key Takeaways

  • USDC on Base is the production default - sub-cent fees, sub-second settlement, regulated issuer.
  • Start in `sk_test_` mode with Base Sepolia. Flip to `sk_live_` only after you have a working end-to-end flow.
  • Every framework integrates the same way: create wallet, attach payment intent handler, set spend policy at the API.
  • The fastest production teams treat the wallet as a tool the agent can call, not a sidecar service.
Krishav Iyer

Auther

Krishav Iyer