Developer Documentation
A practical guide to set up AgnicWallet, connect OAuth2, and start making X402 payments in apps, N8N, or AI agents.
Search & Filter
Find the right section fast. Filters update the left navigation too.
π Quick Start
Create a wallet, issue a token, and start paying for APIs.
Create an account
Sign up with your email. We automatically create a wallet for you.
Sign Up FreeGenerate API token
Go to dashboard β "Connect App" β Set spending limits β Generate token.
Start making payments
Use your token in N8N, AI agents, or any application to make automated payments.
β‘ How X402 Works
X402 is the HTTP payment flow AgnicWallet automates. Hereβs the exact request sequence.
The 3-Step Payment Flow
- Your app calls the API
- Response: 402 Payment Required + payment details
- AgnicWallet signs the payment
- Using your wallet delegation signature
- Retry with payment proof
- Response: 200 OK + API data
Why X402?
- Automatic payments
- Pay-per-use
- Spending limits
- Web3 native
π OAuth2 Integration
Use OAuth2 when your users should control their own spending limits and approvals.
Why OAuth2?
OAuth2 lets your application request permission from AgnicPay users to make X402 payments on their behalf. Users choose limits and can revoke access anytime.
- User-controlled limits - Users set daily/monthly spending caps
- Revocable access - Users can disconnect your app anytime
- Network selection - Users choose which networks to allow
- Long-lived tokens - Access tokens last 30-60 days with refresh
Authorization Flow
1. Redirect to Authorization
Redirect users to our consent page with your client details:
https://app.agnicpay.xyz/oauth-consent?
client_id=your-app-name
&redirect_uri=https://yourapp.com/callback
&state=random_csrf_token
&scope=payments:sign+balance:read2. User Grants Permission
User logs in, sets spending limits (per-transaction, daily, monthly), selects allowed networks, and approves your app.
3. Receive Authorization Code
User is redirected back to your app with an authorization code.
4. Exchange for Tokens
Exchange the code for access and refresh tokens:
curl -X POST https://api.agnicpay.xyz/oauth/token \
-H "Content-Type: application/json" \
-d '{
"grant_type": "authorization_code",
"code": "abc123",
"redirect_uri": "https://yourapp.com/callback",
"client_id": "your-app-name"
}'Token Response
{
"access_token": "agnic_at_abc123...",
"refresh_token": "agnic_rt_xyz789...",
"token_type": "Bearer",
"expires_in": 2592000,
"scope": "payments:sign balance:read"
}Token Expiration:
β’ Access tokens expire based on client type (30-60 days typically)
β’ Refresh tokens last 90 days
β’ Use refresh token to get new access token when expired
Using the Access Token
Use the access token to call AgnicPay APIs on behalf of the user:
# Check user's balance
curl https://api.agnicpay.xyz/api/balance \
-H "Authorization: Bearer agnic_at_abc123..."
# Make X402 payment (OpenAI-compatible endpoint)
curl https://api.agnicpay.xyz/v1/chat/completions \
-H "Authorization: Bearer agnic_at_abc123..." \
-H "Content-Type: application/json" \
-d '{
"model": "openai/gpt-4o",
"messages": [{"role": "user", "content": "Hello!"}]
}'
# Get transaction history
curl https://api.agnicpay.xyz/api/transactions \
-H "Authorization: Bearer agnic_at_abc123..."Refreshing Tokens
When the access token expires, use the refresh token to get a new one:
curl -X POST https://api.agnicpay.xyz/oauth/token \
-H "Content-Type: application/json" \
-d '{
"grant_type": "refresh_token",
"refresh_token": "agnic_rt_xyz789..."
}'Authorization Parameters
| Parameter | Required | Description |
|---|---|---|
| client_id | Yes | Your application identifier |
| redirect_uri | Yes | Where to send user after authorization |
| state | Yes | CSRF protection token (returned unchanged) |
| scope | No | Space-separated scopes (default: payments:sign balance:read) |
| code_challenge | No | PKCE code challenge (recommended for security) |
| code_challenge_method | No | PKCE method (default: S256) |
Available Scopes
- payments:sign - Sign X402 payment proofs on behalf of the user
- balance:read - View the user's USDC balance
Register Your Application
To use OAuth2, contact us to register your application and get your redirect URIs whitelisted.
Register Your App β
π§ AI Gateway
OpenAI-compatible API with automatic X402 payments and spending limits.
Drop-in OpenAI Replacement
- /v1/chat/completions
- Base URL:
- https://api.agnicpay.xyz
Quick Start
Using curl:
curl https://api.agnicpay.xyz/v1/chat/completions \
-H "Authorization: Bearer agnic_tok_YOUR_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"model": "openai/gpt-4o",
"messages": [{"role": "user", "content": "Hello!"}]
}'Using OpenAI SDK (Python):
from openai import OpenAI
client = OpenAI(
api_key="agnic_tok_YOUR_TOKEN", # or agnic_at_... for OAuth
base_url="https://api.agnicpay.xyz/v1"
)
response = client.chat.completions.create(
model="openai/gpt-4o",
messages=[{"role": "user", "content": "Hello!"}]
)
print(response.choices[0].message.content)Using OpenAI SDK (JavaScript):
import OpenAI from 'openai';
const client = new OpenAI({
apiKey: 'agnic_tok_YOUR_TOKEN', // or agnic_at_... for OAuth
baseURL: 'https://api.agnicpay.xyz/v1'
});
const response = await client.chat.completions.create({
model: 'openai/gpt-4o',
messages: [{ role: 'user', content: 'Hello!' }]
});
console.log(response.choices[0].message.content);Available Models
Access models from multiple providers with pay-per-use pricing:
OpenAI
- openai/gpt-4o
- openai/gpt-4o-mini
- openai/gpt-4-turbo
- openai/o1
Anthropic
- anthropic/claude-3.5-sonnet
- anthropic/claude-3-opus
- anthropic/claude-3-haiku
- google/gemini-pro
- google/gemini-1.5-pro
And More...
- Meta Llama, Mistral, and other models available via X402-enabled providers
Authentication
The AI Gateway accepts both API tokens and OAuth2 access tokens:
# With API Token
-H "Authorization: Bearer agnic_tok_YOUR_API_TOKEN"
# With OAuth2 Access Token
-H "Authorization: Bearer agnic_at_YOUR_OAUTH_TOKEN"Streaming Support
Enable streaming responses with "stream": true:
from openai import OpenAI
client = OpenAI(
api_key="agnic_tok_YOUR_TOKEN",
base_url="https://api.agnicpay.xyz/v1"
)
stream = client.chat.completions.create(
model="openai/gpt-4o",
messages=[{"role": "user", "content": "Write a poem"}],
stream=True
)
for chunk in stream:
if chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="")Spending Limits Apply
All requests through the AI Gateway respect your token's spending limits:
- Per-transaction limit
- Daily limit
- Monthly limit
Requests exceeding limits will return a 402 error with details.
π N8N Integration
Connect N8N workflows to X402-enabled APIs with OAuth2 or API tokens.
OAuth 2.0 Method
The easiest way to connect N8N - no token copying required.
Step 1: Install N8N Node
# In your N8N directory
npm install n8n-nodes-agnicwallet
# Or use N8N Community Nodes
# Settings β Community Nodes β Install β "n8n-nodes-agnicwallet"Step 2: Create OAuth Credential
- In N8N, go to Credentials β Add Credential
- Authorize with your wallet and set spending limits
- You're done! Start using the credential in workflows
Step 3: Use in Workflow
{
"authentication": "oAuth2",
"method": "POST",
"url": "https://api.example.com/x402-endpoint",
"body": {
"prompt": "Generate a summary"
}
}API Key Method
For CI/CD pipelines or programmatic access.
Step 1: Generate Token
- Go to AgnicWallet Dashboard
- Set spending limits and label
- Sign wallet delegation
- agnic_tok_...
Step 2: Add to N8N
- Paste your API token
- Save and use in workflows
Example: Automated Content Generation
This workflow calls an X402-enabled AI API every hour to generate content:
[Schedule Trigger: Every 1 hour]
β
[AgnicWallet X402 Request]
β URL: https://api.example.com/generate
β Method: POST
β Body: {"prompt": "Daily news summary"}
β
[Save to Database]
β
[Send Email with Results]π MCP Server Integration
Connect AI assistants like Claude to X402 APIs using our hosted MCP server.
What is the MCP Server?
Our hosted Model Context Protocol (MCP) server enables AI assistants to discover, access, and pay for X402-enabled APIs. It's a bridge between your AI tools and paid APIs.
Server Address:
https://mcp.agnicpay.xyz/sse
No installation needed. Add the URL and your API key to your MCP client.
Quick Setup (3 Steps)
- 1. Get Your API KeySign up, add USDC to your wallet, and generate an API token from your dashboard.
- 2. Add Server to Your MCP ClientConfigure your MCP client (n8n, Claude Desktop, etc.) with these details:text
Server URL: https://mcp.agnicpay.xyz/sse Server Type: HTTP/SSE Authentication: Authorization: Bearer <your-api-token> - 3. Start Using ToolsYour AI can now use the 5 available tools to discover APIs, check balance, make payments, and more.
Available MCP Tools
Your AI assistant gets access to these 5 tools:
make_x402_request
Automatically fetch data from any X402-enabled API with seamless payment handling.
Parameters: url, method, headers, body
check_balance
Check your AgnicPay wallet balance across different networks (Base, Solana).
Parameters: network (optional)
get_payment_history
View complete payment history with timestamps, amounts, and transaction hashes.
Parameters: limit, startDate, network
discover_apis
Browse and search through available X402-enabled APIs with pricing and categories.
Parameters: category, search, maxPrice, sort
fund_wallet
Get instructions on how to fund your AgnicPay wallet with USDC.
Parameters: network (optional)
Example: n8n Workflow
Add an MCP Client node in your n8n workflow:
// 1. Add MCP Client node configuration
{
"serverType": "HTTP/SSE",
"serverUrl": "https://mcp.agnicpay.xyz/sse",
"authHeader": "Authorization: Bearer agnic_tok_sk_live_..."
}
// 2. Use the make_x402_request tool
{
"tool": "make_x402_request",
"parameters": {
"url": "https://api.example.com/data",
"method": "POST",
"body": {
"prompt": "Generate a summary"
}
}
}
// The MCP server handles payment automatically!Learn More
For detailed information about the MCP server, connection examples, and all available tools, visit our dedicated MCP Server page.
View MCP Server Documentation β
π€ AI Agent Integration
Enable your AI agents to make autonomous payments with API-key auth.
β¨ AI Agent Capabilities
With your API key, AI agents can:
- Check balance (GET /api/balance)
- Sign payments (POST /api/sign-payment)
- Review transaction history (GET /api/transactions)
All endpoints support API key authentication - no OAuth setup needed.
LangChain (Python)
Create a custom tool for LangChain agents to make X402 payments
from langchain.tools import BaseTool
import requests
class AgnicWalletTool(BaseTool):
name = "make_payment"
description = "Make a payment to an X402 API and get the response"
def _run(self, url: str, method: str = "POST", body: dict = None):
# Step 1: Try initial request
response = requests.request(method, url, json=body)
if response.status_code != 402:
return response.text
# Step 2: Sign payment - pass the FULL 402 response
# The 402 response contains all required X402 fields
payment_requirements = response.json()
sign_response = requests.post(
'https://api.agnicpay.xyz/api/sign-payment',
headers={
'X-Agnic-Token': 'YOUR_TOKEN_HERE',
'Content-Type': 'application/json'
},
json={
'paymentRequirements': payment_requirements,
'requestData': {'url': url, 'method': method}
}
)
if not sign_response.ok:
return f"Payment failed: {sign_response.text}"
# Step 3: Retry with payment proof
final_response = requests.request(
method, url, json=body,
headers={'X-Payment': sign_response.json()['paymentHeader']}
)
return final_response.text
# Use in your agent
from langchain.agents import initialize_agent
from langchain.llms import OpenAI
tool = AgnicWalletTool()
agent = initialize_agent(
[tool],
OpenAI(temperature=0),
agent="zero-shot-react-description"
)
result = agent.run("Call the AI API to summarize quantum computing")JavaScript / Node.js
Simple fetch-based integration for any JavaScript application
async function callX402Api(url, options = {}) {
const { method = 'POST', body = null } = options;
const token = 'YOUR_TOKEN_HERE';
// Step 1: Initial request
let response = await fetch(url, {
method,
headers: { 'Content-Type': 'application/json' },
body: body ? JSON.stringify(body) : null
});
if (response.status !== 402) {
return await response.json();
}
// Step 2: Sign payment - pass the FULL 402 response
// The 402 response contains all required X402 fields:
// scheme, network, maxAmountRequired, maxTimeoutSeconds,
// resource, description, mimeType, asset, payTo, extra
const paymentRequirements = await response.json();
const signResponse = await fetch('https://api.agnicpay.xyz/api/sign-payment', {
method: 'POST',
headers: {
'X-Agnic-Token': token,
'Content-Type': 'application/json'
},
body: JSON.stringify({
paymentRequirements, // Pass entire 402 response
requestData: { url, method }
})
});
if (!signResponse.ok) {
throw new Error(\`Payment failed: \${await signResponse.text()}\`);
}
const { paymentHeader } = await signResponse.json();
// Step 3: Retry with payment
const final = await fetch(url, {
method,
headers: {
'Content-Type': 'application/json',
'X-Payment': paymentHeader
},
body: body ? JSON.stringify(body) : null
});
return await final.json();
}
// Usage
const result = await callX402Api('https://api.example.com/generate', {
method: 'POST',
body: { prompt: 'Explain quantum computing' }
});Python (Requests)
Simple integration for Python scripts with balance checking
import requests
class AgnicWalletClient:
def __init__(self, token):
self.token = token
self.base_url = 'https://api.agnicpay.xyz'
self.headers = {'X-Agnic-Token': token}
def get_balance(self, network='base-sepolia'):
"""Check wallet USDC balance"""
response = requests.get(
f'{self.base_url}/api/balance',
headers=self.headers,
params={'network': network}
)
return response.json()
def call_x402_api(self, url, method='POST', data=None):
"""Call X402-enabled API with automatic payment"""
# Step 1: Initial request
response = requests.request(method, url, json=data)
if response.status_code != 402:
return response.json()
# Step 2: Sign payment - pass the FULL 402 response
# The 402 response contains all required X402 fields:
# scheme, network, maxAmountRequired, maxTimeoutSeconds,
# resource, description, mimeType, asset, payTo, extra
payment_requirements = response.json()
sign_response = requests.post(
f'{self.base_url}/api/sign-payment',
headers={**self.headers, 'Content-Type': 'application/json'},
json={
'paymentRequirements': payment_requirements,
'requestData': {'url': url, 'method': method}
}
)
if not sign_response.ok:
raise Exception(f"Payment failed: {sign_response.text}")
payment_header = sign_response.json()['paymentHeader']
# Step 3: Retry with payment
final_response = requests.request(
method, url, json=data,
headers={'X-Payment': payment_header}
)
return final_response.json()
def get_transactions(self, page=1, limit=10):
"""Get transaction history"""
response = requests.get(
f'{self.base_url}/api/transactions',
headers=self.headers,
params={'page': page, 'limit': limit}
)
return response.json()
# Usage
client = AgnicWalletClient(token='YOUR_TOKEN_HERE')
# Check balance before making payment
balance = client.get_balance()
print(f"Balance: {balance['usdcBalance']} USDC")
# Make payment
result = client.call_x402_api(
url='https://api.example.com/generate',
method='POST',
data={'prompt': 'Explain quantum computing'}
)
# Review recent transactions
transactions = client.get_transactions(limit=5)
print(f"Recent transactions: {transactions['stats']['totalSpent']} USDC")π‘ API Reference
Core endpoints for payment signing, balance, and transaction history.
Transparent X402 payment proxy. Fetch any URL - if it returns 402, we automatically sign the payment and retry. Supports both "exact" and "upto" payment schemes (auto-detected). You get the actual API response back, not payment headers.
β¨ Why use this endpoint?
β’ One API call - No need to handle 402 responses yourself
β’ Transparent payments - We handle signing and retrying automatically
β’ Safety cap - Set maxValue to limit payment amount
β’ Works with any X402 API - Just pass the URL
Query Parameters:
url (required) - Target URL to fetch
method - HTTP method (default: GET)
maxValue - Max payment in atomic units (e.g., 100000 = $0.10 USDC)
timeout - Request timeout in ms (default: 30000, max: 60000)Example Request:
# Simple GET request
curl -X POST "https://api.agnicpay.xyz/api/x402/fetch?url=https://api.example.com/data" \
-H "X-Agnic-Token: agnic_tok_YOUR_TOKEN"
# POST request with body and safety cap
curl -X POST "https://api.agnicpay.xyz/api/x402/fetch?url=https://api.example.com/generate&method=POST&maxValue=100000" \
-H "X-Agnic-Token: agnic_tok_YOUR_TOKEN" \
-H "Content-Type: application/json" \
-d '{"prompt": "Explain quantum computing"}'Response:
Returns the actual API response, plus metadata headers:
HTTP/2 200
X-Agnic-Paid: true
X-Agnic-Amount: 0.01
X-Agnic-Network: base-sepolia
X-Agnic-Wallet: 0x1234...
X-Agnic-Scheme: exact
X-Agnic-Response-Time: 2500ms
Content-Type: application/json
{
"result": "Quantum computing uses quantum mechanics...",
"tokens": 150
}JavaScript Example:
// It's this simple! One API call, get data back.
const response = await fetch(
'https://api.agnicpay.xyz/api/x402/fetch?url=https://api.example.com/data&maxValue=100000',
{
method: 'POST',
headers: {
'X-Agnic-Token': 'agnic_tok_YOUR_TOKEN',
'Content-Type': 'application/json'
},
body: JSON.stringify({ prompt: 'Hello' })
}
);
// Response is the actual API data - payment was handled automatically!
const data = await response.json();
console.log(data);
// Check if payment was made via headers
console.log('Paid:', response.headers.get('X-Agnic-Paid'));
console.log('Amount:', response.headers.get('X-Agnic-Amount'));Response Headers:
- X-Agnic-Paid - "true" if payment was made, "false" if API was free
- X-Agnic-Amount - Amount paid in USD (if paid)
- X-Agnic-Network - Network used (base-sepolia, base, solana, etc.)
- X-Agnic-Wallet - Your wallet address that made the payment
- X-Agnic-Scheme - Payment scheme used ("exact" or "upto")
- X-Agnic-Response-Time - Total request time
Sign an X402 payment proof. Supports both "exact" (EIP-3009 TransferWithAuthorization) and "upto" (EIP-2612 Permit) payment schemes. The scheme is auto-detected from the payment requirements.
Headers:
X-Agnic-Token: agnic_tok_YOUR_TOKEN_HERE
Content-Type: application/jsonRequest Body:
Note: The easiest approach is to pass the full 402 response from the X402 API directly. If constructing manually, all fields below are required.
{
"paymentRequirements": {
"accepts": [{
"scheme": "exact",
"network": "base-sepolia",
"maxAmountRequired": "250000",
"maxTimeoutSeconds": 300,
"resource": "https://api.example.com/endpoint",
"description": "Payment for API access",
"mimeType": "application/json",
"asset": "0x036CbD53842c5426634e7929541eC2318f3dCF7e",
"payTo": "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb7",
"extra": {
"name": "USD Coin",
"version": "2"
}
}]
},
"requestData": {
"url": "https://api.example.com/endpoint",
"method": "POST"
}
}Required Fields (EVM - Base):
- scheme - "exact" (EIP-3009) or "upto" (EIP-2612 Permit)
- network - "base-sepolia" or "base"
- maxAmountRequired - Amount in atomic units (string)
- maxTimeoutSeconds - Payment validity window (number)
- resource - The API URL being paid for
- description - Payment description
- mimeType - Response type (e.g., "application/json")
- asset - USDC contract address
- payTo - Recipient wallet address
- extra.name - "USD Coin" (for EIP-712)
- extra.version - "2" (for EIP-712)
Required Fields (Solana):
- scheme - Always "exact"
- network - "solana-devnet" or "solana"
- maxAmountRequired - Amount in atomic units (string)
- maxTimeoutSeconds - Payment validity window (number)
- resource - The API URL being paid for
- description - Payment description
- mimeType - Response type (e.g., "application/json")
- asset - USDC mint address
- payTo - Recipient wallet address
- extra.feePayer - Facilitator address (pays tx fees)
Recommended: Pass Full 402 Response
Instead of constructing the payload manually, simply pass the entire JSON response from the 402 Payment Required response. This ensures all required fields are included.
// Step 1: Call the X402 API
const response = await fetch('https://api.example.com/endpoint');
if (response.status === 402) {
// Step 2: Pass the FULL 402 response to sign-payment
const paymentRequirements = await response.json();
const signResponse = await fetch('https://api.agnicpay.xyz/api/sign-payment', {
method: 'POST',
headers: {
'X-Agnic-Token': 'your_token',
'Content-Type': 'application/json'
},
body: JSON.stringify({
paymentRequirements, // Pass entire 402 response
requestData: { url: 'https://api.example.com/endpoint', method: 'GET' }
})
});
}Response:
{
"success": true,
"paymentHeader": "eyJ2ZXJzaW9uIjoxLCJwYXls...",
"paymentProof": { ... },
"amountPaid": 0.25,
"network": "base-sepolia",
"userWallet": "0x1234...",
"signingWallet": "0x5678...",
"scheme": "exact",
"paidFromCredit": false
}Response Fields:
- paymentHeader - Base64-encoded X402 payment proof for X-Payment header
- paymentProof - Decoded payment object for inspection
- amountPaid - Amount in USD
- network - Blockchain network used
- userWallet - User's wallet address
- signingWallet - Wallet that signed (pool or user)
- scheme - Payment scheme: "exact" or "upto"
- paidFromCredit - Whether paid from credit balance
Check your wallet's USDC balance. Supports API keys, OAuth tokens, and Privy tokens.
Authentication Options:
# With API key (for AI agents)
curl https://api.agnicpay.xyz/api/balance \
-H "X-Agnic-Token: agnic_tok_YOUR_TOKEN"
# With OAuth token (for n8n)
curl https://api.agnicpay.xyz/api/balance \
-H "Authorization: Bearer agnic_at_YOUR_OAUTH_TOKEN"
# With network parameter
curl "https://api.agnicpay.xyz/api/balance?network=base" \
-H "X-Agnic-Token: agnic_tok_YOUR_TOKEN"Response:
{
"usdcBalance": "50.000000",
"address": "0x1234567890abcdef...",
"hasWallet": true,
"network": "base-sepolia"
}Get your transaction history with pagination and filtering. Supports API keys, OAuth tokens, and Privy tokens.
Authentication Options:
# With API key (for AI agents)
curl https://api.agnicpay.xyz/api/transactions \
-H "X-Agnic-Token: agnic_tok_YOUR_TOKEN"
# With OAuth token (for n8n)
curl https://api.agnicpay.xyz/api/transactions \
-H "Authorization: Bearer agnic_at_YOUR_OAUTH_TOKEN"
# With pagination and filters
curl "https://api.agnicpay.xyz/api/transactions?page=1&limit=10&status=success" \
-H "X-Agnic-Token: agnic_tok_YOUR_TOKEN"
# Search transactions
curl "https://api.agnicpay.xyz/api/transactions?search=example.com" \
-H "X-Agnic-Token: agnic_tok_YOUR_TOKEN"Response:
{
"transactions": [
{
"id": "tx_1730044800000",
"amount_usd": 0.25,
"network": "base-sepolia",
"endpoint": "https://api.example.com/endpoint",
"timestamp": "2025-10-27T12:00:00Z",
"status": "success"
}
],
"pagination": {
"currentPage": 1,
"totalPages": 5,
"totalCount": 100,
"limit": 20,
"hasNextPage": true,
"hasPrevPage": false
},
"stats": {
"totalTransactions": 100,
"totalSpent": 25.50,
"successfulTransactions": 95,
"failedTransactions": 5,
"successRate": 95.0
}
}Need Help?
We're here to help you integrate AgnicWallet
Ready to Get Started?
Create your free account and start automating payments today.