Dedicated infrastructure for the agentic payment protocols. Essential tools that sit between AI agents and autonomous payments, ensuring agents never overspend while enabling instant API monetization.
## What is \{xpay✦\}?
\{xpay✦\} is building the essential infrastructure for the agentic payment protocols. We provide developers and businesses with the tools they need to safely integrate autonomous payments while enabling instant API monetization.
### Our Mission
**Helping the agentic community get paid and pay safely.**
As AI agents become more autonomous, they need secure, reliable payment infrastructure. \{xpay✦\} bridges this gap by providing:
- 🛡️ **Safety-first payment controls** for autonomous agents
- ⚡ **Instant API monetization** with zero setup complexity
- 📊 **Complete observability** into agent spending and revenue
- 🔧 **Developer-friendly tools** built for the modern web
## Core Products
### 🛡️ Smart Proxy
**Cost Control Dashboard**
Developers are concerned about their agents getting stuck in spending loops. Our smart proxy provides AWS proxy endpoints with hard spending limits, real-time alerts, and per-agent budgets.
[Learn more →](/products/smart-proxy)
### ⚡ Paywall-as-a-Service
**Easy Monetization**
Turn any API into a revenue stream. Paste your endpoint, get an x402-monetized URL, and start earning immediately with our managed payment infrastructure.
[Learn more →](/products/paywall-service)
### 📊 Transaction Explorer
**Observability**
Complete visibility into agent spending patterns, API performance, and transaction flows. The "Datadog for x402" that every agent developer needs.
[Learn more →](/products/transaction-explorer)
## Quick Start
Get started with \{xpay✦\} in under 5 minutes:
```bash
npm install @xpaysh/agent-kit
```
```typescript
import { SmartProxy } from '@xpaysh/agent-kit'
// Set spending limits for your agent
const smartProxy = new SmartProxy({
maxDailySpend: 100, // $100 USD
maxPerRequest: 5, // $5 USD per request
alertThreshold: 0.8 // Alert at 80% of limits
})
// Your agent's API calls are now protected
await smartProxy.protectedFetch('https://api.example.com/expensive-ai-service')
```
[Full Quick Start Guide →](/getting-started)
## Why x402?
The x402 protocol enables a new paradigm for internet payments:
- **Micropayments**: Pay per API call, per token, per second
- **Agent-native**: Designed for autonomous machine-to-machine payments
- **Instant settlement**: Payments settle in ~2 seconds on Base network
- **Zero subscription friction**: No signups, no monthly fees
## Open Source Ecosystem
\{xpay✦\} actively contributes to the x402 ecosystem with open source tools:
- [**awesome-x402**](https://github.com/xpaysh/awesome-x402) - Curated resources for x402 developers
- [**x402-agent-kit**](https://github.com/xpaysh/x402-agent-kit) - Build x402-paying agents in 5 minutes
- [**x402-local**](https://github.com/xpaysh/x402-local) - Local x402 development environment
- [**x402-sdk**](https://github.com/xpaysh/x402-sdk) - TypeScript-first x402 SDK
## Community
Join our growing community of x402 developers:
- [GitHub](https://github.com/xpaysh) - Contribute to our open source projects
- [Discord](https://discord.gg/vukXDGT7n5) - Connect with other developers
- [Twitter](https://twitter.com/xpaysh) - Follow our updates
- [Blog](https://www.xpay.sh/blog) - Read about x402 and autonomous payments
---
Ready to start building? [Get started →](/getting-started) or explore our [product documentation →](/products).
================================================================================
# Page: /en/integrations/activepieces
# Source: src/content/en/integrations/activepieces.mdx
================================================================================
# Activepieces Integration
Monetize your Activepieces flows using xpay Pay-to-Run webhooks.
## Overview
Activepieces is an open-source automation platform with a clean interface and powerful capabilities. With xpay, you can:
- Accept USDC payments before flow execution
- Collect customer information via custom forms
- Trigger any Activepieces flow after payment
---
## Setup Guide
### Step 1: Create a Webhook Trigger in Activepieces
1. Open Activepieces and create a new flow
2. Add the **Webhook** trigger
3. Select **Catch Request**
4. Copy the generated webhook URL
### Step 2: Create an xpay Checkout
1. Go to [xpay Dashboard](https://app.xpay.sh/dashboard/pay-to-run/new)
2. Create a new checkout:
- **Product Name**: Your flow's name
- **Price**: Amount to charge in USDC
- **Callback URL**: Your Activepieces webhook URL
- **Network**: Base Sepolia (testnet) or Base (mainnet)
- **Recipient Wallet**: Your wallet address
3. Add form fields for customer information
4. Save your checkout
### Step 3: Build Your Flow
After the webhook trigger, add your flow logic. The webhook data structure:
```json
{
"payment": {
"tx_hash": "0x...",
"payer_address": "0x...",
"amount": 5.00,
"currency": "USDC",
"network": "base",
"timestamp": 1703001234567
},
"customer_input": {
"email": "customer@example.com",
"prompt": "Generate a blog post about AI"
},
"metadata": {
"checkout_id": "chk_abc123",
"test_mode": false
}
}
```
---
## Example Flow: AI Content Generator
```
[Webhook] → [OpenAI: Generate] → [Gmail: Send Result]
```
1. **Webhook Trigger**
- Receives payment confirmation from xpay
2. **OpenAI Piece**
- Use `{{trigger.body.customer_input.prompt}}` as input
- Generate content based on customer request
3. **Gmail Piece**
- Send to `{{trigger.body.customer_input.email}}`
- Include generated content
---
## Signature Verification (Optional)
For production flows, verify webhook authenticity:
1. Add a **Code** piece after the webhook trigger
2. Use this JavaScript:
```javascript
const crypto = require('crypto');
const signature = inputs.headers['x-xpay-signature'];
const timestamp = inputs.headers['x-xpay-timestamp'];
const body = inputs.body;
const secret = 'YOUR_WEBHOOK_SECRET'; // Store in flow variables
const data = `${timestamp}.${JSON.stringify(body)}`;
const expected = 'sha256=' + crypto
.createHmac('sha256', secret)
.update(data)
.digest('hex');
if (signature !== expected) {
throw new Error('Invalid signature');
}
return body;
```
---
## Flow Templates
### Template 1: PDF Generator
Accept payment, generate PDF from customer data, email result.
```
[Webhook] → [Code: Build PDF] → [Gmail: Send PDF]
```
### Template 2: API Access
Accept payment, provide temporary API key or access token.
```
[Webhook] → [Code: Generate Key] → [HTTP: Store in DB] → [Gmail: Send Key]
```
### Template 3: Data Analysis
Accept payment with file upload, analyze data, return insights.
```
[Webhook] → [OpenAI: Analyze] → [Airtable: Store] → [Gmail: Send Report]
```
---
## Testing Your Flow
1. In Activepieces, use **Test Flow** to simulate webhooks
2. In xpay dashboard, click **Test Webhook** to send a test payload
3. Verify data flows through each piece correctly
---
## Tips for Production
### Handle Errors Gracefully
Add error handling pieces:
- **Branch** piece for conditional logic
- **HTTP Request** piece to notify xpay of failures
### Use Variables
Store sensitive data like webhook secrets in Activepieces variables:
1. Go to Project Settings → Variables
2. Add `XPAY_WEBHOOK_SECRET`
3. Reference as `{{vars.XPAY_WEBHOOK_SECRET}}`
### Logging
Add logging for debugging:
1. Use **HTTP Request** piece to send to a logging service
2. Or use **Airtable/Google Sheets** to log transactions
---
## Troubleshooting
### Flow not triggering
1. Ensure flow is **published and enabled**
2. Check webhook URL matches exactly in xpay dashboard
3. Look at Activepieces run history for errors
### Missing data
1. Check you're accessing `trigger.body` not just `trigger`
2. Verify customer form fields match expected names
3. Use **Code** piece to inspect raw payload
### Timeouts
Activepieces webhooks timeout after 30 seconds. For long flows:
1. Return response immediately
2. Use **Delay** piece with retries for external services
---
## Next Steps
- [Create your checkout](https://app.xpay.sh/dashboard/pay-to-run/new)
- [Universal Webhook Guide](/integrations/universal-webhook)
- [Activepieces Documentation](https://www.activepieces.com/docs)
================================================================================
# Page: /en/integrations/index
# Source: src/content/en/integrations/index.mdx
================================================================================
# Integrations
Connect \{xpay\} with your favorite tools and platforms to monetize workflows, APIs, and automation.
## Universal Pay-to-Run
The [Universal Webhook](/integrations/universal-webhook) approach works with **any** automation platform that supports webhooks. Create checkouts in the xpay dashboard, receive signed webhook calls after each payment.
## Available Integrations
### Workflow Automation
| Platform | Description | Status |
|----------|-------------|--------|
| [n8n (Self-hosted)](/integrations/n8n) | Custom xpay node for n8n | Available |
| [n8n Cloud](/integrations/n8n-cloud) | Standard webhook approach | Available |
| [Activepieces](/integrations/activepieces) | Webhook trigger integration | Available |
| Zapier | Accept payments in Zaps | Coming Soon |
| Make (Integromat) | Monetize Make scenarios | Coming Soon |
### AI & Agents
| Platform | Description | Status |
|----------|-------------|--------|
| LangChain | Protected fetch for LangChain agents | Available |
| AutoGPT | Spending limits for autonomous agents | Coming Soon |
| CrewAI | Multi-agent payment orchestration | Coming Soon |
### API Frameworks
| Platform | Description | Status |
|----------|-------------|--------|
| Express.js | Paywall middleware for Express APIs | Available |
| Next.js | API route protection with x402 | Available |
| FastAPI | Python x402 middleware | Coming Soon |
---
## Quick Links
- [Universal Webhook Guide](/integrations/universal-webhook) - Works with any platform
- [n8n Integration Guide](/integrations/n8n) - Custom node for self-hosted n8n
- [n8n Cloud Guide](/integrations/n8n-cloud) - Standard webhook for n8n Cloud
- [Activepieces Guide](/integrations/activepieces) - Monetize Activepieces flows
- [Developer Resources](/developer-resources) - SDKs, examples, and tools
- [x402 Protocol](/x402-protocol) - Learn about the payment protocol
---
Need an integration we don't have? [Let us know](https://github.com/xpaysh/xpay/issues)
================================================================================
# Page: /en/integrations/n8n-cloud
# Source: src/content/en/integrations/n8n-cloud.mdx
================================================================================
# n8n Cloud Integration
Use xpay Pay-to-Run with n8n Cloud using standard webhook nodes - no custom installation required.
## Why This Approach?
n8n Cloud doesn't allow unverified community nodes. Instead of the custom xpay node, you'll use:
- **Webhook node** as a trigger
- **HTTP Request node** for optional signature verification
- Standard n8n nodes for your workflow logic
This approach works identically to the custom node - you just configure it manually.
---
## Setup Guide
### Step 1: Create Your Webhook in n8n Cloud
1. Open n8n Cloud and create a new workflow
2. Add a **Webhook** node as the trigger
3. Configure it:
- **HTTP Method**: POST
- **Path**: Choose a unique path (e.g., `/xpay-payment`)
- **Response Mode**: Respond immediately
4. Activate the workflow to get your webhook URL
### Step 2: Create a Checkout in xpay
1. Go to [xpay Dashboard](https://app.xpay.sh/dashboard/pay-to-run/new)
2. Create a new checkout:
- **Product Name**: Your workflow name
- **Price**: Amount in USDC
- **Callback URL**: Your n8n webhook URL from Step 1
- **Network**: Base Sepolia (testnet) or Base (mainnet)
- **Recipient Wallet**: Your Ethereum wallet address
3. Add any custom fields to collect customer information
4. Save and copy your checkout URL
### Step 3: Connect Your Workflow
After the Webhook node, add your workflow logic. The incoming data includes:
```json
{
"body": {
"payment": {
"tx_hash": "0x...",
"payer_address": "0x...",
"amount": 5.00,
"currency": "USDC"
},
"customer_input": {
"email": "customer@example.com"
}
}
}
```
Access payment data: `{{ $json.body.payment.amount }}`
Access customer input: `{{ $json.body.customer_input.email }}`
---
## Complete Workflow Example
Here's a typical Pay-to-Run workflow:
```
[Webhook] → [IF: Verify Payment] → [Your Logic] → [Respond]
```
### Example: AI Content Generator
1. **Webhook** - Receives payment confirmation
2. **OpenAI** - Generates content based on customer input
3. **Send Email** - Delivers result to customer
4. **Respond to Webhook** - Returns success
---
## Import Ready-to-Use Template
Copy this JSON into n8n Cloud (Ctrl/Cmd + V in the canvas):
```json
{
"name": "xpay Pay-to-Run Template",
"nodes": [
{
"parameters": {
"httpMethod": "POST",
"path": "xpay-payment",
"responseMode": "responseNode",
"options": {}
},
"name": "Webhook",
"type": "n8n-nodes-base.webhook",
"typeVersion": 2,
"position": [250, 300]
},
{
"parameters": {
"respondWith": "json",
"responseBody": "={\"success\": true, \"message\": \"Payment processed\"}",
"options": {}
},
"name": "Respond to Webhook",
"type": "n8n-nodes-base.respondToWebhook",
"typeVersion": 1,
"position": [650, 300]
}
],
"connections": {
"Webhook": {
"main": [[{"node": "Respond to Webhook", "type": "main", "index": 0}]]
}
}
}
```
---
## Optional: Signature Verification
For production workflows, verify the webhook signature:
1. Add a **Code** node after Webhook
2. Use this code:
```javascript
const crypto = require('crypto');
// Get headers and body
const signature = $input.first().headers['x-xpay-signature'];
const timestamp = $input.first().headers['x-xpay-timestamp'];
const body = $input.first().json.body;
// Your webhook secret from xpay dashboard
const secret = 'YOUR_WEBHOOK_SECRET';
// Verify signature
const data = `${timestamp}.${JSON.stringify(body)}`;
const expected = 'sha256=' + crypto
.createHmac('sha256', secret)
.update(data)
.digest('hex');
if (signature !== expected) {
throw new Error('Invalid webhook signature');
}
return $input.all();
```
3. Store your webhook secret in n8n credentials for security
---
## Test Your Integration
1. In xpay dashboard, go to your checkout details
2. Click **Test Webhook**
3. Check your n8n workflow execution history
4. Verify the data flows correctly
---
## Comparison: Custom Node vs Webhook
| Feature | Custom Node (Self-hosted) | Webhook (Cloud) |
|---------|--------------------------|-----------------|
| Setup time | ~2 min | ~5 min |
| Signature verification | Automatic | Manual (optional) |
| Checkout URL display | In node | In dashboard |
| Test mode | Built-in | Dashboard button |
| Works on n8n Cloud | No | Yes |
---
## Troubleshooting
### Workflow not triggering
1. Ensure workflow is **active** (toggle in top-right)
2. Check webhook URL is correct in xpay dashboard
3. Verify webhook path matches exactly
### Missing data
1. Check Response Mode is set correctly
2. Verify you're accessing `$json.body` not just `$json`
3. Look at execution log for full payload
### Timeout errors
n8n Cloud webhooks have a 30-second timeout. For long-running workflows:
1. Return response immediately with Respond to Webhook node
2. Continue processing after response
---
## Next Steps
- [Create your checkout](https://app.xpay.sh/dashboard/pay-to-run/new)
- [Universal Webhook Guide](/integrations/universal-webhook) - Deep dive on webhook format
- [n8n Self-hosted Guide](/integrations/n8n) - Using the custom node
================================================================================
# Page: /en/integrations/n8n
# Source: src/content/en/integrations/n8n.mdx
================================================================================
# n8n Integration
Turn any n8n workflow into a paid service in 60 seconds. The \{xpay\} n8n community node creates a hosted payment form - when customers pay, your workflow runs automatically.
## Overview
The **xpay pay-to-run trigger** node enables you to:
- Accept USDC payments on Base network
- Create hosted Pay to Run forms - no frontend required
- Collect custom input from customers before payment
- Receive payments directly to your wallet (non-custodial)
- Test with sandbox mode before going live
## Installation
### n8n Cloud
1. Open **Settings > Community Nodes**
2. Click **Install a community node**
3. Enter `@xpaysh/n8n-nodes-xpay`
4. Click **Install**
### Self-Hosted n8n
```bash
npm install @xpaysh/n8n-nodes-xpay
```
Or install via the n8n UI under **Settings > Community Nodes**.
## Quick Start
### Step 1: Get Your API Key
1. Sign up at [app.xpay.sh](https://app.xpay.sh)
2. Go to **Settings > API Keys**
3. Create a new API key
4. Copy the secret key
### Step 2: Add Credentials in n8n
1. Go to **Credentials > Add Credential**
2. Search for "xpay API"
3. Paste your API key
4. Select environment:
- **Sandbox** - For testing (no real payments)
- **Production** - For real USDC payments
### Step 3: Create Your First Paid Workflow
1. Create a new workflow in n8n
2. Add the **xpay pay-to-run trigger** node
3. Configure:
- **Product Name**: e.g., "Premium SEO Audit"
- **Price (USDC)**: e.g., 5.00
- **Recipient Wallet**: Your Base wallet address
- **Customer Fields**: Add fields like "email", "website"
4. Connect your workflow nodes (HTTP Request, Send Email, etc.)
5. **Activate** the workflow
### Step 4: Get Your Pay to Run Form URL
Send an empty POST request to your webhook URL:
```bash
curl -X POST https://your-n8n-instance/webhook/abc123
```
Response:
```json
{
"message": "xpay pay-to-run trigger is listening!",
"form_url": "https://run.xpay.sh/p/chk_abc123",
"test_mode": true
}
```
Share the `form_url` with your customers. When they visit it, they'll see a payment form with your product details and custom fields.
## Node Properties
| Property | Description |
|----------|-------------|
| **Product Name** | Display name shown on payment form |
| **Description** | Brief description of what customer is paying for |
| **Price (USDC)** | Amount in USDC (e.g., 5.00 = $5) |
| **Network** | Base (production) or Base Sepolia (testnet) |
| **Recipient Wallet** | Your wallet address for receiving payments |
| **Customer Fields** | Custom input fields for customers to fill |
| **Redirect URL** | Optional URL to redirect after payment |
| **Test Mode** | Enable sandbox mode (no real payments) |
## Output Data
When a customer pays, your workflow receives this data:
```json
{
"payment": {
"txHash": "0x123...",
"amount": 5.00,
"currency": "USDC",
"payer": "0xABC...",
"network": "base",
"timestamp": 1702841234
},
"input": {
"email": "customer@example.com",
"website": "https://example.com"
},
"metadata": {
"checkoutId": "chk_abc123",
"receivedAt": "2024-12-17T10:00:00.000Z"
}
}
```
Use `{{ $json.payment.amount }}` or `{{ $json.input.email }}` in subsequent nodes to access this data.
## Test Mode vs Production Mode
| Aspect | Test Mode | Production Mode |
|--------|-----------|-----------------|
| Payments | Simulated | Real USDC |
| Network | Base Sepolia | Base Mainnet |
| Signature verification | Skipped | Enforced |
| Form URL | Temporary | Persistent |
### Testing Your Workflow
With **Test Mode** enabled:
1. Click "Simulate Payment" on the Pay to Run form, or
2. POST test data directly to your webhook:
```bash
curl -X POST https://your-n8n-instance/webhook/abc123 \
-H "Content-Type: application/json" \
-d '{"payment":{"amount":5},"input":{"email":"test@example.com"}}'
```
### Important: URL Persistence
- When **testing in n8n** (clicking "Execute workflow"), a temporary checkout is created. This expires when you stop testing.
- When you **Activate** the workflow, the checkout URL persists as long as the workflow is active.
## Use Cases
### SEO Audit Service
Charge $10 per website audit:
1. Customer enters website URL and email
2. After payment, workflow:
- Runs SEO analysis via API
- Generates PDF report
- Emails report to customer
### API Monetization
Sell API access per request:
1. Customer enters API parameters
2. After payment, workflow:
- Makes API call with customer's parameters
- Returns JSON response
- Logs transaction
### Consultation Booking
Accept payment before scheduling:
1. Customer enters preferred time and topic
2. After payment, workflow:
- Creates calendar event
- Sends confirmation email
- Adds to CRM
### Digital Product Delivery
Deliver files after payment:
1. Customer enters email
2. After payment, workflow:
- Generates download link
- Sends email with link
- Updates inventory
## Security
The \{xpay\} n8n node includes multiple security layers:
- **Non-custodial**: Payments go directly to your wallet - we never hold your funds
- **HMAC signatures**: Production webhooks are signed to prevent tampering
- **Replay protection**: Each payment can only trigger your workflow once
- **Timestamp validation**: Stale webhook requests are rejected
## Troubleshooting
### "Checkout not found" error
The checkout may have expired. This happens when:
- You were testing and stopped the test
- The workflow was deactivated
**Solution**: Activate the workflow to create a persistent checkout.
### Webhook not firing
Check that:
1. The workflow is **Activated** (not just testing)
2. Your n8n instance has a public URL (for cloud deployments)
3. Test mode is enabled if you're simulating payments
### Payment went through but workflow didn't run
1. Check n8n execution logs for errors
2. Verify the webhook URL is correct
3. In production mode, check that webhook signature verification passed
## Resources
- [GitHub Repository](https://github.com/xpaysh/n8n-nodes-xpay)
- [npm Package](https://www.npmjs.com/package/@xpaysh/n8n-nodes-xpay)
- [n8n Community Nodes Guide](https://docs.n8n.io/integrations/community-nodes/)
---
Need help? [Open an issue](https://github.com/xpaysh/n8n-nodes-xpay/issues) or email xpaysh@gmail.com
================================================================================
# Page: /en/integrations/universal-webhook
# Source: src/content/en/integrations/universal-webhook.mdx
================================================================================
# Universal Pay-to-Run Webhook
Accept payments for any workflow using standard webhooks. Works with any automation platform - no custom integrations required.
## Overview
Universal Pay-to-Run lets you monetize any automation workflow by:
1. Creating a checkout in your \{xpay\} dashboard
2. Getting a payment form URL and webhook secret
3. Adding a webhook node in your automation platform
4. Receiving signed webhook calls after each payment
### Supported Platforms
| Platform | Integration Type | Setup Time |
|----------|-----------------|------------|
| n8n (self-hosted) | Custom node or webhook | ~2 min |
| n8n Cloud | Standard webhook | ~5 min |
| Activepieces | Webhook trigger | ~5 min |
| Make (Integromat) | Custom webhook | ~5 min |
| Zapier | Webhooks by Zapier | ~5 min |
---
## Quick Start
### Step 1: Create a Checkout
Visit your [xpay dashboard](https://app.xpay.sh/dashboard/pay-to-run) and create a new checkout:
1. Set your product name and price
2. Enter your automation platform's webhook URL
3. Configure form fields to collect customer information
4. Save and copy your checkout URL
### Step 2: Set Up Your Webhook
In your automation platform, create a webhook trigger node that listens for POST requests. Configure it with:
- **Method**: POST
- **Content-Type**: application/json
- **Response**: Return 200 OK on success
### Step 3: Share Your Checkout URL
Share your checkout URL (`https://run.xpay.sh/p/your-checkout-id`) with customers. After payment:
1. Customer pays on your checkout page
2. xpay sends a signed webhook to your callback URL
3. Your workflow executes with the payment data
---
## Webhook Payload
When a payment is received, xpay sends a POST request to your callback URL with this payload:
```json
{
"payment": {
"tx_hash": "0x1234...abcd",
"payer_address": "0xabc...123",
"amount": 5.00,
"currency": "USDC",
"network": "base",
"timestamp": 1703001234567
},
"customer_input": {
"email": "customer@example.com",
"name": "John Doe"
},
"metadata": {
"checkout_id": "chk_abc123",
"test_mode": false,
"triggered_at": "2024-12-20T10:00:00Z"
}
}
```
### Headers
Each webhook request includes these headers for verification:
| Header | Description |
|--------|-------------|
| `X-xPay-Signature` | HMAC-SHA256 signature of the payload |
| `X-xPay-Timestamp` | Unix timestamp when the webhook was sent |
| `X-xPay-Test` | "true" if this is a test webhook |
---
## Signature Verification
For production use, verify webhook signatures to ensure requests come from xpay.
### Node.js Example
```javascript
const crypto = require('crypto');
function verifyWebhookSignature(payload, signature, timestamp, secret) {
const data = `${timestamp}.${JSON.stringify(payload)}`;
const expectedSignature = crypto
.createHmac('sha256', secret)
.update(data)
.digest('hex');
return crypto.timingSafeEquals(
Buffer.from(signature),
Buffer.from(`sha256=${expectedSignature}`)
);
}
// In your webhook handler:
const isValid = verifyWebhookSignature(
req.body,
req.headers['x-xpay-signature'],
req.headers['x-xpay-timestamp'],
process.env.WEBHOOK_SECRET
);
if (!isValid) {
return res.status(401).send('Invalid signature');
}
```
### Python Example
```python
import hmac
import hashlib
import json
def verify_webhook_signature(payload, signature, timestamp, secret):
data = f"{timestamp}.{json.dumps(payload, separators=(',', ':'))}"
expected = hmac.new(
secret.encode(),
data.encode(),
hashlib.sha256
).hexdigest()
return hmac.compare_digest(signature, f"sha256={expected}")
```
---
## Test Mode
Use test mode to verify your integration without real payments:
1. Enable "Test Mode" when creating your checkout
2. Click "Test Webhook" in the checkout details page
3. Your workflow receives a test payload with `test_mode: true`
Test webhooks have the same structure as production webhooks, with mock transaction data.
---
## Platform-Specific Guides
- [n8n (self-hosted)](/integrations/n8n) - Use the custom xpay node
- [n8n Cloud](/integrations/n8n-cloud) - Standard webhook approach
- [Activepieces](/integrations/activepieces) - Webhook trigger guide
---
## Troubleshooting
### Webhook not received
1. Check your callback URL is publicly accessible
2. Verify your server returns 200 OK
3. Check for firewall or rate limiting issues
4. Use the "Test Webhook" button to debug
### Invalid signature
1. Ensure you're using the correct webhook secret
2. Check that you're parsing the JSON correctly
3. Verify timestamp is being read as a string
### Timeout errors
xpay waits up to 10 seconds for a response. If your workflow takes longer:
1. Return 200 OK immediately
2. Process the workflow asynchronously
3. Use a message queue if needed
---
## Next Steps
- [Create your first checkout](https://app.xpay.sh/dashboard/pay-to-run/new)
- [Learn about the x402 protocol](/x402-protocol)
- [View webhook examples on GitHub](https://github.com/xpaysh/xpay-examples)
================================================================================
# Page: /en/products/mcp-monetization
# Source: src/content/en/products/mcp-monetization.mdx
================================================================================
# MCP Monetization
Monetize any MCP (Model Context Protocol) server with pay-per-tool-call billing. Wrap your existing MCP server with an xpay proxy and start earning from every tool invocation.
## Overview
MCP Monetization lets you place a payment layer in front of any MCP server. When an AI assistant (Claude, Cursor, Windsurf, etc.) calls a tool on your server, the payment is processed automatically via the x402 protocol before the tool executes.
- **Zero code changes** - Your MCP server stays exactly as it is
- **Per-tool pricing** - Set different prices for different tools
- **Instant payouts** - Revenue flows directly to your wallet via USDC
- **Works everywhere** - Compatible with any MCP client
## How It Works
```mermaid
sequenceDiagram
participant Client as AI Assistant
participant Proxy as xpay MCP Proxy
participant MCP as Your MCP Server
participant Chain as Base (L2)
Client->>Proxy: Call tool (e.g. search_web)
Proxy->>Proxy: Check pricing for tool
Proxy->>Client: 402 Payment Required
Client->>Chain: Sign USDC payment
Client->>Proxy: Retry with payment proof
Proxy->>Proxy: Verify payment
Proxy->>MCP: Forward tool call
MCP->>Proxy: Tool result
Proxy->>Client: Tool result
```
1. You register your MCP server URL on xpay and set per-tool pricing
2. xpay gives you a proxy URL: `https://{slug}.mcp.xpay.sh/mcp`
3. Users connect their AI assistant to the proxy URL instead of your server directly
4. Every tool call is metered and paid for automatically
## Quick Start
### 1. Register Your MCP Server
Go to [xpay.sh](https://xpay.sh) and create a new MCP monetization endpoint:
- **Server URL**: Your MCP server's SSE or Streamable HTTP endpoint
- **Receiving wallet**: Your USDC wallet address on Base
- **Pricing**: Set a default price per tool call, or configure per-tool pricing
### 2. Configure Per-Tool Pricing
Set different prices for each tool your server exposes:
| Tool | Price | Description |
|------|-------|-------------|
| `search_web` | $0.01 | Basic web search |
| `deep_research` | $0.10 | Multi-source research |
| `generate_report` | $0.25 | Full report generation |
You can also set a flat rate that applies to all tools.
### 3. Share Your Proxy URL
Give users your proxy URL to connect in their AI assistant:
```
https://my-service.mcp.xpay.sh/mcp
```
### 4. Connect in Claude Desktop
Users add your monetized MCP server to their `claude_desktop_config.json`:
```json
{
"mcpServers": {
"my-service": {
"url": "https://my-service.mcp.xpay.sh/mcp",
"headers": {
"Authorization": "Bearer USER_API_KEY"
}
}
}
}
```
### 5. Connect in Cursor / Windsurf
In Cursor or Windsurf settings, add the MCP server URL:
```
https://my-service.mcp.xpay.sh/mcp
```
The AI assistant will automatically handle x402 payments when calling tools.
## Pricing Configuration
### Flat Rate
Charge the same price for every tool call:
```json
{
"pricing": {
"model": "flat",
"price": 0.05,
"currency": "USDC"
}
}
```
### Per-Tool Pricing
Set individual prices for each tool:
```json
{
"pricing": {
"model": "per_tool",
"currency": "USDC",
"tools": {
"search": 0.01,
"analyze": 0.05,
"generate": 0.10
},
"default": 0.02
}
}
```
The `default` price applies to any tool not explicitly listed.
## API Key Management
Buyers authenticate with an API key to track their usage and manage spending:
- **Get an API key** from [hub.xpay.sh](https://hub.xpay.sh)
- **Include it** in the `Authorization` header when connecting to the MCP proxy
- **Track usage** and spending in the xpay dashboard
- **Set spending limits** to control costs
## Billing Receipts
After each tool call, the proxy includes billing metadata in the response:
```json
{
"result": { "...tool output..." },
"_billing": {
"tool": "search_web",
"cost": "0.01",
"currency": "USDC",
"txHash": "0xabc...",
"network": "base",
"timestamp": "2026-02-22T10:30:00Z"
}
}
```
## Supported MCP Transports
- **Streamable HTTP** (recommended) - Modern HTTP-based transport
- **SSE (Server-Sent Events)** - Legacy streaming transport
## Use Cases
- **Data providers** - Monetize search, enrichment, and lookup tools
- **AI model wrappers** - Charge per inference via MCP tools
- **SaaS integrations** - Expose your product's API as paid MCP tools
- **Research services** - Charge for web scraping, analysis, and report generation
---
Ready to monetize your MCP server? [Get started on xpay.sh](https://xpay.sh) or explore the [x402 Protocol](/x402-protocol) to understand the payment layer.
================================================================================
# Page: /en/products/paywall-service
# Source: src/content/en/products/paywall-service.mdx
================================================================================
# Paywall-as-a-Service
Transform any API into a revenue stream with x402-powered automatic payments. The Paywall Service provides instant API monetization with zero setup complexity.
## Overview
The Paywall Service wraps your existing APIs with x402 payment requirements, enabling:
- **Instant monetization** - Start earning from APIs immediately
- **Zero integration complexity** - Works with any existing API
- **Automatic payment processing** - Handles all payment logic
- **Real-time revenue tracking** - Monitor earnings as they happen
- **Flexible pricing models** - Per-request, tiered, subscription options
## Quick Start
### 1. Basic API Monetization
Turn any endpoint into a paid service in minutes:
```typescript
import { Paywall } from '@xpaysh/agent-kit'
import express from 'express'
const app = express()
const paywall = new Paywall({
receivingWallet: '0x742d35Cc6634C0532925a3b8D3Ac2d00fBc1d555',
facilitatorUrl: 'https://facilitator.xpay.sh'
})
// Protect your valuable API
app.get('/api/premium-data',
paywall.middleware({
price: 0.10, // $0.10 per request
description: 'Premium market data access'
}),
(req, res) => {
// This code only runs after successful payment
const marketData = {
prices: { BTC: 45000, ETH: 3000 },
timestamp: new Date().toISOString(),
premium: true
}
res.json(marketData)
}
)
app.listen(3000, () => {
console.log('Monetized API running on port 3000')
})
```
### 2. Advanced Pricing Configuration
```typescript
// Tiered pricing based on usage
app.post('/api/ai-analysis',
paywall.middleware({
pricing: {
model: 'tiered',
basePrice: 0.01,
tiers: [
{ from: 0, to: 100, price: 0.05 }, // First 100 requests: $0.05
{ from: 100, to: 1000, price: 0.03 }, // Next 900 requests: $0.03
{ from: 1000, price: 0.01 } // Beyond 1000: $0.01
]
},
description: 'AI-powered data analysis'
}),
async (req, res) => {
const analysis = await performAIAnalysis(req.body.data)
res.json({ analysis, tier: req.paymentTier })
}
)
// Token-based pricing for LLM APIs
app.post('/api/llm-completion',
paywall.middleware({
pricing: {
model: 'per_token',
basePrice: 0.0001, // $0.0001 per token
estimateTokens: (req) => {
// Estimate tokens from request
return req.body.prompt.length / 4 // Rough estimation
}
}
}),
async (req, res) => {
const completion = await callLLM(req.body.prompt)
res.json({
completion,
tokensUsed: completion.usage.total_tokens,
cost: completion.usage.total_tokens * 0.0001
})
}
)
```
## Pricing Models
### Per-Request Pricing
Simple flat rate per API call:
```typescript
const paywall = new Paywall({
receivingWallet: '0x...',
defaultPricing: {
model: 'per_request',
basePrice: 0.05, // $0.05 per request
currency: 'USDC'
}
})
```
### Tiered Pricing
Progressive pricing based on usage volume:
```typescript
app.use('/api/data', paywall.middleware({
pricing: {
model: 'tiered',
basePrice: 0.10,
tiers: [
{ from: 0, to: 50, price: 0.10 }, // First 50: $0.10 each
{ from: 50, to: 200, price: 0.08 }, // Next 150: $0.08 each
{ from: 200, to: 500, price: 0.06 }, // Next 300: $0.06 each
{ from: 500, price: 0.05 } // Beyond 500: $0.05 each
]
},
// Reset tiers daily per customer
tierReset: 'daily'
}))
```
### Token-Based Pricing
Perfect for AI and LLM APIs:
```typescript
app.post('/api/text-generation', paywall.middleware({
pricing: {
model: 'per_token',
inputTokenPrice: 0.00001, // $0.00001 per input token
outputTokenPrice: 0.00003, // $0.00003 per output token
minimumCharge: 0.001 // Minimum $0.001 per request
}
}), async (req, res) => {
const result = await generateText(req.body.prompt)
// Payment automatically calculated based on actual token usage
res.json({
text: result.text,
usage: {
inputTokens: result.inputTokens,
outputTokens: result.outputTokens,
totalCost: result.inputTokens * 0.00001 + result.outputTokens * 0.00003
}
})
})
```
### Time-Based Pricing
Charge per minute or hour of usage:
```typescript
app.ws('/api/realtime-stream', paywall.middleware({
pricing: {
model: 'per_minute',
basePrice: 0.02, // $0.02 per minute
billingInterval: 60 // Bill every 60 seconds
}
}), (ws, req) => {
// WebSocket connection with per-minute billing
ws.on('message', (data) => {
// Stream real-time data
const streamData = processRealtimeData(data)
ws.send(JSON.stringify(streamData))
})
})
```
## Revenue Optimization
### Dynamic Pricing
Adjust prices based on demand, time, or customer tier:
```typescript
app.get('/api/premium-content', paywall.middleware({
dynamicPricing: async (req) => {
const hour = new Date().getHours()
const isBusinessHours = hour >= 9 && hour <= 17
// Higher prices during business hours
const basePrice = isBusinessHours ? 0.15 : 0.10
// Customer tier pricing
const customerTier = await getCustomerTier(req.headers.authorization)
const tierMultiplier = {
'basic': 1.0,
'premium': 0.8, // 20% discount
'enterprise': 0.6 // 40% discount
}[customerTier] || 1.0
return {
price: basePrice * tierMultiplier,
description: `${customerTier} tier pricing`
}
}
}), (req, res) => {
res.json({ content: 'Premium content', tier: req.customerTier })
})
```
### Bundle Pricing
Offer discounts for multiple API calls:
```typescript
app.post('/api/batch-process', paywall.middleware({
bundlePricing: {
singlePrice: 0.10, // $0.10 per individual request
bundlePrice: 0.08, // $0.08 per request in bundle
minimumBundle: 10, // Minimum 10 requests for bundle pricing
maximumBundle: 100 // Maximum 100 requests per bundle
}
}), async (req, res) => {
const { requests } = req.body
if (requests.length >= 10) {
// Process as discounted bundle
const results = await processBatch(requests)
res.json({
results,
bundleDiscount: (0.10 - 0.08) * requests.length
})
} else {
// Process individual requests
const results = await processIndividual(requests)
res.json({ results })
}
})
```
## Advanced Features
### Rate Limiting Integration
Combine payment requirements with rate limiting:
```typescript
import rateLimit from 'express-rate-limit'
// Free tier with rate limits
const freeTierLimit = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // 100 requests per window
message: 'Free tier limit exceeded. Upgrade to paid tier for unlimited access.'
})
// Paid tier with higher limits
app.get('/api/free-data', freeTierLimit, (req, res) => {
res.json({ data: 'Free tier data', limited: true })
})
app.get('/api/unlimited-data',
paywall.middleware({ price: 0.01 }),
(req, res) => {
res.json({ data: 'Unlimited paid data', limited: false })
}
)
```
### Customer Analytics
Track customer usage patterns and optimize pricing:
```typescript
app.use(paywall.analyticsMiddleware({
trackMetrics: [
'request_count',
'revenue_per_customer',
'average_request_cost',
'customer_lifetime_value'
],
webhookUrl: 'https://your-app.com/webhooks/analytics'
}))
// Get customer analytics
app.get('/admin/customer-analytics', async (req, res) => {
const analytics = await paywall.getCustomerAnalytics({
timeframe: '30d',
includeChurn: true,
includeRetention: true
})
res.json({
totalCustomers: analytics.totalCustomers,
avgRevenuePerCustomer: analytics.avgRevenuePerCustomer,
topSpenders: analytics.topSpenders,
churnRate: analytics.churnRate
})
})
```
### Custom Payment Flow
Handle complex payment scenarios:
```typescript
app.post('/api/complex-service', async (req, res) => {
try {
// Pre-validate payment capability
const paymentCheck = await paywall.checkPaymentCapability(req.headers, {
estimatedCost: 0.50,
currency: 'USDC'
})
if (!paymentCheck.canPay) {
return res.status(402).json({
error: 'Insufficient funds',
required: 0.50,
available: paymentCheck.availableBalance,
topUpUrl: paymentCheck.topUpUrl
})
}
// Process service (expensive operation)
const result = await performExpensiveOperation(req.body)
// Calculate actual cost based on processing
const actualCost = calculateActualCost(result.complexity)
// Charge the actual cost
const payment = await paywall.processPayment(req.headers, {
amount: actualCost,
description: `Complex service processing (${result.complexity} complexity)`,
metadata: {
requestId: req.id,
complexity: result.complexity
}
})
res.json({
result: result.data,
payment: {
cost: actualCost,
transactionId: payment.transactionId,
complexity: result.complexity
}
})
} catch (error) {
if (error.code === 'PAYMENT_FAILED') {
res.status(402).json({
error: 'Payment failed',
details: error.message
})
} else {
res.status(500).json({ error: 'Service error' })
}
}
})
```
## Webhook Integration
Monitor payments and customer behavior in real-time:
```typescript
// Configure webhooks for payment events
await paywall.configureWebhooks({
endpoint: 'https://your-app.com/webhooks/paywall',
events: [
'payment.completed',
'payment.failed',
'customer.first_payment',
'revenue.milestone',
'pricing.tier_changed'
],
secret: 'webhook_secret_key'
})
// Handle webhook events
app.post('/webhooks/paywall', (req, res) => {
const { event, data } = req.body
switch (event) {
case 'payment.completed':
// Track successful payment
analytics.track('payment_completed', {
customerId: data.customerId,
amount: data.amount,
endpoint: data.endpoint
})
break
case 'customer.first_payment':
// Welcome new paying customer
sendWelcomeEmail(data.customerId)
break
case 'revenue.milestone':
// Celebrate revenue milestones
if (data.milestone === 1000) {
notifyTeam(`🎉 Hit $1000 in API revenue!`)
}
break
}
res.status(200).send('OK')
})
```
## Security Best Practices
### Payment Verification
Always verify payments on your server:
```typescript
app.post('/api/secure-endpoint', async (req, res) => {
// Verify payment headers
const paymentValid = await paywall.verifyPayment(req.headers, {
price: 0.25,
tolerance: 0.001, // Allow 0.1% tolerance for gas fluctuations
maxAge: 300 // Payment must be within 5 minutes
})
if (!paymentValid.valid) {
return res.status(402).json({
error: 'Invalid payment',
reason: paymentValid.reason,
required: paymentValid.expectedPayment
})
}
// Process request only after payment verification
const secureData = await getSecureData()
res.json(secureData)
})
```
### Rate Limiting & DDoS Protection
Protect against abuse while maintaining legitimate access:
```typescript
// Implement progressive rate limiting
const createRateLimit = (windowMs, max, price) => rateLimit({
windowMs,
max,
handler: (req, res) => {
res.status(429).json({
error: 'Rate limit exceeded',
resetTime: new Date(Date.now() + windowMs),
upgradeOption: {
price: price,
description: 'Pay per request to bypass rate limits'
}
})
}
})
// Free tier: 10 requests per minute
app.use('/api/free', createRateLimit(60 * 1000, 10, 0.01))
// Paid tier: No rate limits
app.use('/api/paid', paywall.middleware({ price: 0.01 }))
```
### Wallet Security
Protect your receiving wallet:
```typescript
const paywall = new Paywall({
receivingWallet: process.env.XPAY_RECEIVING_WALLET, // Use environment variables
facilitatorUrl: 'https://facilitator.xpay.sh',
security: {
requireHttps: true, // Only accept HTTPS requests
validateOrigin: true, // Validate request origin
maxPaymentAge: 300, // 5 minute payment window
enableIPWhitelist: false, // Enable for high-security applications
rateLimitByWallet: true // Rate limit per wallet address
}
})
```
## Deployment Guide
### Production Configuration
```typescript
import { Paywall } from '@xpaysh/agent-kit'
import Redis from 'ioredis'
const redis = new Redis(process.env.REDIS_URL)
const paywall = new Paywall({
receivingWallet: process.env.XPAY_RECEIVING_WALLET,
facilitatorUrl: process.env.XPAY_FACILITATOR_URL,
// Production optimizations
cache: {
provider: redis,
paymentTTL: 300, // Cache payments for 5 minutes
customerTTL: 3600 // Cache customer data for 1 hour
},
monitoring: {
enableMetrics: true,
metricsPort: 9090, // Prometheus metrics
healthCheckEndpoint: '/health'
},
logging: {
level: 'info',
destination: 'datadog', // or 'console', 'file'
apiKey: process.env.DATADOG_API_KEY
}
})
```
### Docker Deployment
```dockerfile
FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
ENV NODE_ENV=production
ENV XPAY_RECEIVING_WALLET=${XPAY_RECEIVING_WALLET}
ENV XPAY_FACILITATOR_URL=${XPAY_FACILITATOR_URL}
EXPOSE 3000
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
CMD curl -f http://localhost:3000/health || exit 1
CMD ["npm", "start"]
```
### Kubernetes Configuration
```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: xpay-paywall-api
spec:
replicas: 3
selector:
matchLabels:
app: xpay-paywall-api
template:
metadata:
labels:
app: xpay-paywall-api
spec:
containers:
- name: api
image: your-registry/xpay-paywall:latest
ports:
- containerPort: 3000
env:
- name: XPAY_RECEIVING_WALLET
valueFrom:
secretKeyRef:
name: xpay-secrets
key: receiving-wallet
resources:
requests:
cpu: 100m
memory: 128Mi
limits:
cpu: 500m
memory: 512Mi
livenessProbe:
httpGet:
path: /health
port: 3000
initialDelaySeconds: 30
periodSeconds: 10
```
## Migration Guide
### From Free API to Paid
Gradually migrate existing free APIs:
```typescript
// Phase 1: Optional payments (donations)
app.get('/api/data', async (req, res) => {
const data = await getData()
// Include payment information in response
res.json({
data,
support: {
message: 'Support this API with a small payment',
suggestedAmount: 0.01,
paymentDetails: paywall.getPaymentDetails(0.01)
}
})
})
// Phase 2: Freemium model
app.get('/api/data', async (req, res) => {
const isPaid = await paywall.checkPayment(req.headers, { price: 0.05 })
if (isPaid) {
// Full data for paying customers
const fullData = await getFullData()
res.json({ data: fullData, tier: 'premium' })
} else {
// Limited data for free users
const limitedData = await getLimitedData()
res.json({
data: limitedData,
tier: 'free',
upgrade: paywall.getPaymentDetails(0.05)
})
}
})
// Phase 3: Fully paid
app.get('/api/data',
paywall.middleware({ price: 0.05 }),
async (req, res) => {
const data = await getData()
res.json({ data })
}
)
```
---
Ready to start monetizing your APIs? Check our [getting started guide](/getting-started) or explore [advanced integration patterns](/developer-resources/integration-patterns).
================================================================================
# Page: /en/products/smart-proxy
# Source: src/content/en/products/smart-proxy.mdx
================================================================================
# Smart Proxy
The Smart Proxy is a cost control dashboard that provides developers with peace of mind when deploying autonomous agents. It acts as a proxy between your agents and x402-powered APIs, ensuring agents never overspend while maintaining full functionality.
## The Problem
**Developers are terrified their agent will get stuck in a loop and spend thousands of dollars on x402-powered APIs.**
Autonomous agents can make hundreds of API calls per minute. Without proper controls, a bug or unexpected behavior could result in:
- 💸 Runaway spending from infinite loops
- 📈 Unexpected cost spikes during high-traffic periods
- 🚫 No visibility into real-time spending
- ⏰ No way to stop spending once it starts
## The Solution
The Smart Proxy provides an AWS-hosted proxy endpoint that sits between your agents and x402 APIs. It offers:
### 🛡️ Hard Spending Limits
- **Per-request limits**: Maximum spend per API call
- **Daily/monthly budgets**: Automatic shutoffs when limits reached
- **Per-agent budgets**: Individual spending controls for each agent
- **Global limits**: Organization-wide spending controls
### 📊 Real-time Monitoring
- **Live spending dashboard**: Track costs as they happen
- **Usage analytics**: Detailed breakdowns by agent, API, and time
- **Cost forecasting**: Predict monthly costs based on current usage
- **Anomaly detection**: Alerts for unusual spending patterns
### ⚡ Instant Alerts
- **Slack/Discord notifications**: Real-time spending alerts
- **Email alerts**: Daily/weekly spending summaries
- **Webhook integration**: Custom alert handling
- **Emergency shutoffs**: Automatic agent pausing when limits exceeded
## Features
### Multi-Agent Management
Manage multiple agents from a single dashboard with complete lifecycle control:
```typescript
import { SmartProxy } from '@xpaysh/agent-kit'
const smartProxy = new SmartProxy({
endpoint: 'https://smart-proxy-abc123.xpay.sh',
apiKey: 'xpay_fw_...'
})
// Create agents with complete configuration
await smartProxy.createAgent({
id: 'customer-support-bot',
name: 'Customer Support Agent',
description: 'Handles customer inquiries and support tickets',
walletAddress: '0x742d35Cc6634C0532925a3b8D3Ac2d00fBc1d555',
dailyLimit: 50, // $50 USDC per day
perCallLimit: 2, // $2 USDC per API call
monthlyLimit: 1000, // $1000 USDC per month
allowedAPIs: ['openai.com', 'anthropic.com'],
status: 'active'
})
await smartProxy.createAgent({
id: 'data-analysis-bot',
name: 'Data Analysis Agent',
description: 'Processes large datasets and generates reports',
walletAddress: '0x853d46Dd7744C3dC23c3e8F3Bd2dF1e6fc1e8666',
dailyLimit: 200,
perCallLimit: 10,
monthlyLimit: 5000,
allowedAPIs: ['*'], // Allow all x402-enabled APIs
status: 'active'
})
// Update agent configuration
await smartProxy.updateAgent('customer-support-bot', {
dailyLimit: 75, // Increase daily limit
perCallLimit: 3
})
// Pause agent temporarily
await smartProxy.pauseAgent('data-analysis-bot')
// Get agent status and spending
const agent = await smartProxy.getAgent('customer-support-bot')
console.log(`Agent spent: $${agent.totalSpent} / $${agent.dailyLimit}`)
```
### Intelligent Routing
The smart proxyintelligently routes requests based on agent configuration:
```typescript
// Agent requests are automatically routed through smart proxy
const response = await fetch('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: {
'X-Agent-ID': 'customer-support-bot',
'X-SmartProxy-Token': smartProxy.getToken(),
'Authorization': 'Bearer sk-...'
},
body: JSON.stringify({
model: 'gpt-4',
messages: [{ role: 'user', content: 'Hello' }]
})
})
```
### Real-World Configuration Examples
Here are common agent configuration patterns for different use cases:
#### Customer Service Agent
```typescript
await smartProxy.createAgent({
id: 'customer-service-v1',
name: 'Customer Service Bot',
description: 'Handles customer inquiries during business hours',
walletAddress: '0x...',
dailyLimit: 25, // Conservative limit for customer interactions
perCallLimit: 0.50, // Small cost per interaction
monthlyLimit: 500, // Monthly budget control
allowedAPIs: ['openai.com'], // Only trusted LLM provider
emergencyContact: 'devops@company.com',
businessHours: {
enabled: true,
timezone: 'America/New_York',
schedule: '09:00-17:00' // Only active during business hours
}
})
```
#### Data Processing Agent
```typescript
await smartProxy.createAgent({
id: 'data-processor-prod',
name: 'Production Data Processor',
description: 'Processes customer data and generates reports',
walletAddress: '0x...',
dailyLimit: 100, // Higher limit for data processing
perCallLimit: 5, // Larger requests for bulk processing
monthlyLimit: 2000, // Monthly budget for data operations
allowedAPIs: ['*'], // Allow various data processing APIs
rateLimiting: {
maxConcurrentRequests: 3, // Prevent overwhelming APIs
requestsPerMinute: 30
}
})
```
#### Development/Testing Agent
```typescript
await smartProxy.createAgent({
id: 'dev-test-agent',
name: 'Development Testing Agent',
description: 'Agent for development and testing purposes',
walletAddress: '0x...',
dailyLimit: 10, // Low limit for testing
perCallLimit: 1, // Small requests during development
monthlyLimit: 200, // Development budget
allowedAPIs: ['openai.com', 'anthropic.com'],
autoShutoff: {
enabled: true,
threshold: 0.9 // Auto-pause at 90% of daily limit
}
})
```
### Advanced Controls
#### Time-based Limits
```typescript
await smartProxy.setScheduledLimits('trading-bot', {
// Higher limits during market hours
'09:00-16:00': { maxPerRequest: 5, maxHourly: 100 },
// Lower limits overnight
'16:00-09:00': { maxPerRequest: 1, maxHourly: 20 }
})
```
#### API-specific Limits
```typescript
await smartProxy.setAPILimits('data-bot', {
'openai.com': { maxPerRequest: 2, maxDaily: 50 },
'anthropic.com': { maxPerRequest: 1, maxDaily: 30 },
'huggingface.co': { maxPerRequest: 0.5, maxDaily: 20 }
})
```
#### Cost-based Routing
```typescript
await smartProxy.setCostRouting('smart-bot', {
// Use cheaper APIs first
strategy: 'cost-optimized',
fallbacks: [
{ api: 'huggingface.co', maxCost: 0.01 },
{ api: 'openai.com', maxCost: 0.05 },
{ api: 'anthropic.com', maxCost: 0.10 }
]
})
```
## Dashboard Features
### Real-time Overview
The web dashboard provides instant visibility into agent spending:
- **Live spending meter**: Current daily/monthly spend vs limits
- **Active agents**: Which agents are currently making requests
- **Top spenders**: Agents consuming the most budget
- **Recent transactions**: Live feed of x402 payments
### Analytics & Insights
Deep analytics help optimize agent performance:
- **Cost per response**: Average cost by model and API
- **Request patterns**: Usage patterns throughout the day
- **Efficiency metrics**: Cost vs quality analysis
- **Budget utilization**: How efficiently agents use their budgets
### Alert Configuration
Flexible alerting keeps you informed:
```javascript
// Configure alerts in dashboard or via API
{
"alerts": [
{
"trigger": "daily_spend_80_percent",
"channels": ["slack", "email"],
"message": "Agent {agent_id} has spent 80% of daily budget"
},
{
"trigger": "unusual_spending_pattern",
"channels": ["discord"],
"message": "Anomalous spending detected for {agent_id}"
}
]
}
```
## Pricing
The Smart Proxy uses a freemium SaaS model:
### Free Tier
- Up to 3 agents
- $100/month total spending limit
- Basic analytics (7-day history)
- Email alerts only
- Community support
### Pro Tier - $49/month
- Up to 25 agents
- $10,000/month total spending limit
- Advanced analytics (90-day history)
- All alert channels (Slack, Discord, webhooks)
- Priority support
- Custom API integrations
### Enterprise Tier - Custom pricing
- Unlimited agents
- Custom spending limits
- 1-year+ analytics retention
- White-label dashboard
- SSO integration
- Dedicated support
- On-premise deployment options
## Getting Started
### 1. Create Smart Proxy Instance
Sign up and create your first smart proxy:
```bash
npx @xpaysh/cli smart-proxy create --name "my-agents"
```
This creates a unique endpoint: `https://smart-proxy-abc123.xpay.sh`
### 2. Configure Your First Agent
```typescript
import { SmartProxy } from '@xpaysh/agent-kit'
const smartProxy = new SmartProxy({
endpoint: 'https://smart-proxy-abc123.xpay.sh',
apiKey: process.env.XPAY_SMART_PROXY_KEY
})
await smartProxy.configureAgent('my-first-agent', {
maxDailySpend: 25,
maxPerRequest: 1,
alertThreshold: 0.8 // Alert at 80%
})
```
### 3. Route Agent Requests
Update your agent to use the smart proxy:
```typescript
// Before: Direct API calls
const response = await fetch('https://api.openai.com/v1/chat/completions', {
// ... request config
})
// After: Smart Proxy-protected calls
const response = await smartProxy.protectedFetch('https://api.openai.com/v1/chat/completions', {
agentId: 'my-first-agent',
// ... request config
})
```
### 4. Monitor in Dashboard
Visit your dashboard to see real-time spending: `https://dashboard.xpay.sh/smart-proxy/abc123`
## Error Handling & Recovery
### Handling Spending Limit Errors
```typescript
import { SmartProxy, SpendingLimitError } from '@xpaysh/agent-kit'
async function makeProtectedRequest(agentId: string, apiCall: () => Promise