AgentPay Documentation

Everything you need to give your AI agent a wallet. Fund via Telegram Stars, spend via API.

Getting Started

Get your agent making payments in under 5 minutes.

1. Create your agent via Telegram

Open @FundmyAIbot on Telegram and send /start. Follow the prompts to create a new agent.

2. Get your API key

After creating an agent, the bot will generate an API key starting with ap_live_. Store this securely — it’s shown only once.

3. Fund your agent

Use the Telegram bot to top up your agent’s balance with Telegram Stars. The funds are instantly available.

4. Make your first API call

Shell
curl -X POST https://leofundmybot.dev/v1/spend \
  -H "Content-Type: application/json" \
  -H "X-API-Key: ap_live_your_api_key" \
  -d '{
    "amount": 1.00,
    "description": "Test payment"
  }'

If successful, you’ll get a 200 response with the transaction details.

Authentication

All API requests require an API key sent via the X-API-Key header.

HTTP Header
X-API-Key: ap_live_your_api_key
⚠️
Keep your API key secret. Do not expose it in client-side code, public repos, or logs. If compromised, rotate it immediately via the Telegram bot with /rotate_key.

Key types

PrefixEnvironmentDescription
ap_live_ProductionReal transactions, real money
ak_test_SandboxTest transactions, no real charges

Endpoints Reference

Base URL: https://leofundmybot.dev

All request and response bodies are JSON. All amounts are in USD.

POST/v1/spend

Create a spend transaction. Deducts from your agent’s balance.

Request Body

FieldTypeRequiredDescription
amountnumberYesAmount in USD (min 0.01)
descriptionstringYesHuman-readable description
idempotency_keystringNoUnique key to prevent duplicate charges
skip_approvalbooleanNoSkip manual approval (default: false). Only works if amount is under auto-approve threshold.

Example

Request
curl -X POST https://leofundmybot.dev/v1/spend \
  -H "Content-Type: application/json" \
  -H "X-API-Key: ap_live_your_api_key" \
  -d '{
    "amount": 5.00,
    "description": "OpenAI GPT-4 API call",
    "idempotency_key": "req_abc123",
    "skip_approval": false
  }'
Response — 200 OK
{
  "id": "txn_8x7k2mNpQ",
  "status": "completed",
  "amount": 5.00,
  "description": "OpenAI GPT-4 API call",
  "idempotency_key": "req_abc123",
  "balance_remaining": 245.00,
  "created_at": "2026-02-23T07:00:00Z"
}
💡
If the amount exceeds your auto-approve threshold and skip_approval is false, the response will have "status": "pending_approval". The owner will be notified on Telegram.

GET/v1/balance

Get your agent’s current balance.

Response — 200 OK
{
  "available": 245.00,
  "pending": 10.00,
  "currency": "USD"
}

GET/v1/transactions

List recent transactions. Supports pagination.

Query Parameters

ParamTypeDefaultDescription
limitinteger20Number of results (max 100)
offsetinteger0Offset for pagination
statusstringFilter by status: completed, pending_approval, declined
Response — 200 OK
{
  "transactions": [
    {
      "id": "txn_8x7k2mNpQ",
      "amount": 5.00,
      "description": "OpenAI GPT-4 API call",
      "status": "completed",
      "created_at": "2026-02-23T07:00:00Z"
    }
  ],
  "total": 42,
  "limit": 20,
  "offset": 0
}

GET/v1/wallet

Get your agent’s USDC wallet details.

Response — 200 OK
{
  "address": "0x1234...abcd",
  "chain": "base",
  "balance_usdc": 150.00,
  "created_at": "2026-01-15T12:00:00Z"
}

POST/v1/wallet/send-usdc

Send USDC from your agent’s wallet to an external address.

Request Body

FieldTypeRequiredDescription
to_addressstringYesRecipient wallet address
amountnumberYesAmount in USDC
chainstringNoChain to send on (default: base). Options: base, ethereum, polygon
Response — 200 OK
{
  "id": "send_xk29m...",
  "status": "pending",
  "tx_hash": "0xabc123...",
  "amount": 50.00,
  "to_address": "0x5678...efgh",
  "chain": "base"
}

GET/v1/card

Get your agent’s virtual Visa card details.

Response — 200 OK
{
  "card_id": "card_m8x2...",
  "last4": "4242",
  "brand": "visa",
  "exp_month": 12,
  "exp_year": 2027,
  "status": "active",
  "spending_limit": 500.00
}
💡
Full card number, CVC, and billing address are only available in the Telegram bot for security. The API returns masked details.

POST/v1/webhook

Register or update your webhook endpoint.

Request Body

FieldTypeRequiredDescription
urlstringYesHTTPS URL to receive webhooks
eventsstring[]NoEvent types to subscribe to (default: all). See Webhooks.
secretstringNoCustom signing secret. Auto-generated if omitted.
Response — 200 OK
{
  "id": "wh_3k9x...",
  "url": "https://your-server.com/webhooks/agentpay",
  "events": ["transaction.completed", "approval.required"],
  "secret": "whsec_...",
  "created_at": "2026-02-23T07:00:00Z"
}

GET/v1/approvals/{id}

Check the status of a pending approval request.

Response — 200 OK
{
  "id": "apr_x8m2...",
  "transaction_id": "txn_8x7k2mNpQ",
  "status": "approved",
  "amount": 50.00,
  "description": "Monthly server bill",
  "approved_by": "owner",
  "approved_at": "2026-02-23T07:05:00Z",
  "created_at": "2026-02-23T07:00:00Z"
}

Webhooks

Receive real-time notifications when events happen in your agent’s account.

Setup

Register a webhook endpoint via POST /v1/webhook or through the Telegram bot with /webhook.

Event Types

EventDescription
transaction.completedA spend transaction was completed successfully
transaction.declinedA transaction was declined (insufficient funds, limit exceeded)
approval.requiredA transaction requires manual approval
approval.approvedAn approval request was approved
approval.rejectedAn approval request was rejected
balance.lowAgent balance fell below the configured threshold
balance.fundedAgent balance was topped up

Signature Verification

Every webhook request includes an X-AgentPay-Signature header containing an HMAC-SHA256 signature of the request body, signed with your webhook secret.

Python — Verify Signature
import hmac
import hashlib

def verify_webhook(payload: bytes, signature: str, secret: str) -> bool:
    expected = hmac.new(
        secret.encode(),
        payload,
        hashlib.sha256
    ).hexdigest()
    return hmac.compare_digest(f"sha256={expected}", signature)

Retry Policy

If your endpoint returns a non-2xx status code, we retry with exponential backoff:

After 5 failed attempts, the webhook is marked as failed and you’ll be notified on Telegram.

Approval Workflow

Control what your agent can spend autonomously vs. what needs your sign-off.

How it works

  1. Your agent calls POST /v1/spend with an amount
  2. If the amount is below your auto-approve threshold → transaction completes instantly
  3. If the amount is above the threshold → status is pending_approval
  4. You receive a Telegram notification with one-tap Approve / Reject buttons
  5. Your agent can poll GET /v1/approvals/{id} to check the status

Auto-approve threshold

Set via the Telegram bot with /set_threshold <amount>. Default is $10.00.

Python — Poll for Approval
import time
import agentpay

client = agentpay.Client(api_key="ap_live_...")

# Create a spend that may need approval
txn = client.spend(amount=100.00, description="Cloud server monthly")

if txn.status == "pending_approval":
    print(f"Waiting for approval: {txn.id}")
    while True:
        approval = client.get_approval(txn.approval_id)
        if approval.status == "approved":
            print("Approved! Transaction will complete.")
            break
        elif approval.status == "rejected":
            print("Rejected by owner.")
            break
        time.sleep(5)  # Poll every 5 seconds
else:
    print(f"Auto-approved: {txn.id}")

Error Codes

All errors return a JSON body with error and message fields.

Error Response Format
{
  "error": "insufficient_funds",
  "message": "Your agent's balance ($5.00) is less than the requested amount ($10.00)."
}
StatusError CodeDescription
401unauthorizedMissing or invalid API key
403forbiddenAPI key doesn’t have permission for this action
403insufficient_fundsNot enough balance to complete the transaction
403spending_limit_exceededTransaction exceeds spending limit
404not_foundResource not found
429rate_limitedToo many requests. Retry after the Retry-After header value.
500internal_errorSomething went wrong on our end. Try again or contact support.

Python SDK

The official Python SDK provides sync and async clients for the AgentPay API.

Installation

Shell
pip install agentpay

Initialize the client

Python
from agentpay import AgentPayClient

client = AgentPayClient(api_key="ap_live_your_api_key")

# Or async:
from agentpay import AgentPayAsyncClient
client = AgentPayAsyncClient(api_key="ap_live_your_api_key")

Make a payment

Python
result = client.spend(
    amount=5.00,
    description="OpenAI GPT-4 API call",
    idempotency_key="req_abc123"
)

print(f"Transaction: {result.transaction_id}")
print(f"Remaining: ${result.remaining_balance}")

Check balance

Python
balance = client.get_balance()
print(f"Available: ${balance.balance_usd}")
print(f"Daily spent: ${balance.daily_spent_usd}")

List transactions

Python
txns = client.get_transactions(limit=10)
for t in txns:
    print(f"{t.created_at}: ${t.amount} — {t.description}")

Send USDC on-chain

Python
import httpx

# On-chain send via REST API
response = httpx.post(
    "https://leofundmybot.dev/v1/wallet/send-usdc",
    headers={"X-API-Key": "ap_your_api_key"},
    json={"to_address": "0x5678...efgh", "amount": 50.0, "chain": "base"}
)
result = response.json()
print(f"TX Hash: {result['tx_hash']}")

Set up webhooks

Python
webhook = client.register_webhook(
    url="https://your-server.com/webhooks/agentpay",
    events=["spend", "refund", "transfer"]
)
print(f"Signing secret: {webhook.secret}")

# Verify incoming webhooks with HMAC-SHA256
import hmac, hashlib
def verify_webhook(payload: bytes, signature: str, secret: str) -> bool:
    expected = hmac.new(secret.encode(), payload, hashlib.sha256).hexdigest()
    return hmac.compare_digest(f"sha256={expected}", signature)

TypeScript SDK

Use AgentPay from Node.js or any TypeScript/JavaScript runtime.

Installation

Shell
npm install agentpay

Usage

TypeScript
import { AgentPayClient } from 'agentpay';

const client = new AgentPayClient({ apiKey: 'ap_live_your_api_key' });

// Spend
const tx = await client.spend(5.00, 'GPT-4 API call');
console.log(`Remaining: $${tx.remaining_balance}`);

// Check balance
const balance = await client.getBalance();
console.log(`Available: $${balance.balance_usd}`);

// Send USDC
const send = await client.sendUsdc('0x5678...', 50.0, 'base');
console.log(`TX: ${send.tx_hash}`);