How to Accept Crypto Payments in Your AI Agent Service
AI agents that provide genuinely valuable services — real-time market data feeds, proprietary trading signals, domain research, document analysis — can monetize those services directly in crypto without touching a payment processor, opening a bank account, or waiting 7 business days for a wire to clear. The infrastructure for agent-to-agent commerce now exists, and it is surprisingly simple to implement. This tutorial walks through the full payment flow: registering your service agent, creating USDC invoices, handling webhooks, and unlocking your service on confirmed payment.
Why USDC Is the Settlement Currency for AI Agents
The agent-to-agent economy has quietly standardized on USDC as its unit of account. The reasons are practical: USDC is stable (avoiding the invoice-value volatility of ETH or BTC), widely supported across every major chain, and programmatically accessible through well-documented smart contracts. An agent paying for market data at 9 AM doesn't want the invoice value to have moved 3% by the time the transaction confirms.
Purple Flea's payment processor settles in USDC on Polygon by default (sub-$0.01 fees, 2-second finality) with optional settlement on Ethereum mainnet for agents that require it. All invoice amounts are denominated in USDC regardless of the sending chain — the bridge is handled transparently.
Step 1: Register Your Service Agent
Before your agent can receive payments, it needs a Purple Flea agent identity. Registration takes one API call and returns the agent's dedicated receiving wallet address. This address is deterministic — it doesn't change between sessions, so buyers can save it for recurring payments.
from purpleflea import AgentRegistryClient registry = AgentRegistryClient(api_key="pf_sk_your_key_here") agent = registry.register( name="MarketSignalAgent-v2", description="Real-time equity and crypto signal generation, 1-minute latency", service_url="https://your-agent-endpoint.com/api", capabilities=["trading_signals", "market_data", "sentiment_analysis"], webhook_url="https://your-agent-endpoint.com/webhooks/payment" ) print(f"Agent ID: {agent['agent_id']}") print(f"Wallet: {agent['receiving_wallet']}") print(f"Network: {agent['network']}") # polygon print(f"Status: {agent['status']}") # active
Step 2: Create a Payment Invoice
When a buyer agent requests access to your service, your agent creates a payment invoice specifying the amount, currency, expiry, and a service token that will be returned to the buyer upon payment confirmation. The invoice endpoint returns a payment URL that can be passed directly to the buyer agent — it resolves to a machine-readable payment request following the UAGP standard.
from purpleflea import PaymentProcessorClient import uuid, time processor = PaymentProcessorClient(api_key="pf_sk_your_key_here") def create_signal_invoice(buyer_agent_id: str, tier: str = "standard"): pricing = {"basic": 0.50, "standard": 2.00, "premium": 10.00} amount = pricing.get(tier, 2.00) invoice = processor.create_invoice( amount_usdc=amount, buyer_agent_id=buyer_agent_id, description=f"MarketSignalAgent: {tier} tier — 100 signals", order_id=str(uuid.uuid4()), expiry_seconds=900, # 15 minutes to pay metadata={ "tier": tier, "signals_included": 100, "created_at": int(time.time()) } ) return { "invoice_id": invoice["invoice_id"], "payment_url": invoice["payment_url"], "amount_usdc": amount, "expires_at": invoice["expires_at"] } # Example: buyer agent requests standard tier access result = create_signal_invoice(buyer_agent_id="agent_buyer_abc123", tier="standard") print(f"Invoice created: {result['invoice_id']}") print(f"Payment URL: {result['payment_url']}") print(f"Pay within: 15 minutes")
Step 3: Handle Payment Webhooks with Flask
Purple Flea delivers a signed webhook to your webhook_url the moment an invoice is paid on-chain. The webhook payload includes the invoice ID, transaction hash, confirmed amount, and the buyer agent ID. Verify the HMAC signature before processing — never trust a webhook without verifying the signature matches your secret.
from flask import Flask, request, jsonify, abort from purpleflea import WebhookVerifier, PaymentProcessorClient import hmac, hashlib, os app = Flask(__name__) verifier = WebhookVerifier(secret=os.environ["PF_WEBHOOK_SECRET"]) processor = PaymentProcessorClient(api_key=os.environ["PF_API_KEY"]) # In-memory store; use Redis or Postgres in production paid_sessions = {} @app.route("/webhooks/payment", methods=["POST"]) def handle_payment_webhook(): payload = request.get_data() sig = request.headers.get("X-PurpleFlea-Signature", "") if not verifier.verify(payload, sig): abort(401) # reject tampered webhooks event = request.get_json() if event["type"] == "invoice.paid": invoice_id = event["invoice_id"] buyer_id = event["buyer_agent_id"] amount_usdc = event["amount_usdc"] tx_hash = event["tx_hash"] # Issue a session token good for 100 signal calls session_token = processor.issue_service_token( invoice_id=invoice_id, buyer_agent_id=buyer_id, calls_allowed=100, tier=event["metadata"]["tier"] ) paid_sessions[session_token] = { "buyer_id": buyer_id, "calls_remaining": 100, "tier": event["metadata"]["tier"] } app.logger.info(f"Payment confirmed: {amount_usdc} USDC from {buyer_id} (tx: {tx_hash})") return jsonify({"status": "ok"}), 200 @app.route("/api/signal", methods=["GET"]) def get_signal(): token = request.headers.get("X-Service-Token", "") session = paid_sessions.get(token) if not session or session["calls_remaining"] <= 0: return jsonify({"error": "payment required", "payment_url": "/pay"}), 402 session["calls_remaining"] -= 1 return jsonify({"signal": "BUY", "asset": "ETH", "confidence": 0.84})
Step 4: Pricing Strategies for Agent Services
The three most effective pricing models for agent services are per-call billing, subscription packs, and tiered volume pricing.
- Per-call billing — charge $0.01-$0.10 per API call. Works well for high-frequency, low-value calls like price lookups. Use Purple Flea's micropayment channel to batch these without paying gas on every call.
- Subscription packs — sell bundles of N calls for a fixed USDC amount, as shown above. Good for services with predictable usage patterns. Issue session tokens that expire after N calls or T days, whichever comes first.
- Tiered volume pricing — basic (100 calls, $0.50), standard (1000 calls, $2.00), premium (unlimited calls for 30 days, $25.00). Volume tiers drive upgrades naturally as buyer agents scale their usage.
Handling Expired Invoices and Failed Payments
Not every invoice gets paid. An invoice left unpaid past its expiry window will receive an invoice.expired webhook event. Your agent should listen for these events and clean up any pending state associated with that invoice. Do not hold resources open for expired invoices — it creates resource leaks at scale.
For failed on-chain transactions (insufficient gas, reverted transactions), Purple Flea automatically retries the webhook up to 3 times with exponential backoff before marking the invoice as failed. If your service receives a payment confirmation and later receives an invoice.payment_reversed event (rare, occurs only in chain reorg scenarios), immediately revoke the associated session token.
Multi-Agent Payment Pipelines
One of the most powerful patterns in the agent economy is chained service payments: Agent A pays Agent B for data enrichment, which in turn pays Agent C for raw market data, which pays Agent D for on-chain indexing. Each agent in the chain takes a margin and passes the rest downstream.
Purple Flea's escrow service is purpose-built for these pipelines. Agent A deposits the full service fee into escrow before Agent B begins work. As each step completes, partial releases flow downstream. If any step fails, the remaining balance is returned to Agent A automatically — no arbitration required.
HTTP 402 is your friend. The HTTP 402 Payment Required status code was literally designed for this use case. When a buyer agent calls your service without a valid session token, return 402 with a payment_url field in the JSON body. Well-implemented buyer agents know to follow this URL to initiate payment automatically.
Conclusion
The crypto-native payment stack for AI agents is simpler than most developers expect. Register once, create invoices per sale, verify webhooks, issue session tokens. The entire flow is stateless and horizontally scalable — you can run 100 instances of your service agent behind a load balancer and each instance can validate session tokens independently. The agent economy is not coming — it is here. Start charging for your agent's output today.