Skip to Content
🚀 {xpay✦} is building the future of x402 payments - Join the developer beta →
Getting StartedQuick Start

Quick Start

Get up and running with {xpay✦} in under 10 minutes. This guide will help you make your first x402 payment and set up comprehensive agent spending controls.

Overview

{xpay✦} provides a complete platform for secure AI agent payments:

  1. 🛡️ Smart Proxy - Enterprise-grade spending controls and monitoring
  2. ⚡ Paywall Service - Instant API monetization with x402 payments
  3. 📊 Analytics & Monitoring - Real-time transaction tracking and insights

Choose your integration path:

New to x402? The x402 protocol enables instant, automatic stablecoin payments over HTTP. Learn more in our x402 Protocol guide.

Prerequisites

Before you begin, ensure you have:

Production Ready: All examples use mainnet configurations. For testing, use Base Sepolia testnet.

Installation

Install the {xpay✦} Agent Kit:

npm install @xpaysh/agent-kit

Or install individual packages:

npm install @xpaysh/agent-kit npm install @xpaysh/agent-kit npm install @xpaysh/explorer

Step 1: Create Your First Protected Agent

Set up an agent with enterprise-grade spending controls:

import { SmartProxy } from '@xpaysh/agent-kit' const smartProxy = new SmartProxy({ endpoint: 'https://smart-proxy-abc123.xpay.sh', apiKey: 'xpay_fw_...' }) // Create an agent with comprehensive controls const agent = await smartProxy.createAgent({ id: 'my-first-agent', name: 'Customer Support Agent', description: 'Handles customer inquiries with AI', walletAddress: '0x742d35Cc6634C0532925a3b8D3Ac2d00fBc1d555', dailyLimit: 50, // $50 daily limit perCallLimit: 2, // $2 per request limit monthlyLimit: 1000, // $1000 monthly limit allowedAPIs: ['openai.com', 'anthropic.com'], businessHours: { enabled: true, timezone: 'America/New_York', schedule: '09:00-17:00', weekdays: [1, 2, 3, 4, 5] // Monday-Friday }, autoShutoff: { enabled: true, threshold: 0.9, // Stop at 90% of limit action: 'pause' } }) console.log('Agent created:', agent.id)

Step 2: Make Protected API Calls

Now use your agent to make safe, monitored API calls:

// Make a protected AI API call async function askAI(question: string) { try { const response = await smartProxy.protectedFetch('https://api.openai.com/v1/chat/completions', { method: 'POST', headers: { 'Authorization': 'Bearer YOUR_OPENAI_KEY', 'Content-Type': 'application/json' }, body: JSON.stringify({ model: 'gpt-4', messages: [{ role: 'user', content: question }] }), agentId: 'my-first-agent', maxCost: 1.50, // Override per-request limit for this call metadata: { requestType: 'customer_support', priority: 'high' } }) if (!response.ok) { throw new Error(`API call failed: ${response.statusText}`) } const data = await response.json() return data.choices[0].message.content } catch (error) { if (error instanceof SpendingLimitError) { console.log(`Spending limit reached: ${error.limitType}`) console.log(`Resets at: ${error.resetTime}`) return "I'm currently at my spending limit. Please try again later." } throw error } } // Usage const answer = await askAI("How can I help you today?") console.log('AI Response:', answer)

Step 3: Set Up API Monetization

Turn your existing APIs into revenue streams with x402 payments:

import { XpayPaywall } from '@xpaysh/agent-kit' import express from 'express' const app = express() app.use(express.json()) const paywall = new Paywall({ receivingWallet: '0x742d35Cc6634C0532925a3b8D3Ac2d00fBc1d555', facilitatorUrl: 'https://facilitator.base.org', apiKey: 'xpay_pw_...' }) // Create different pricing tiers const endpoints = [ { path: '/api/basic-data', price: 0.05, description: 'Basic market data' }, { path: '/api/premium-analysis', price: 0.25, description: 'AI-powered market analysis' }, { path: '/api/enterprise-insights', price: 1.00, description: 'Real-time enterprise analytics' } ] // Set up paywalled endpoints endpoints.forEach(endpoint => { app.get(endpoint.path, paywall.middleware({ price: endpoint.price, description: endpoint.description, metadata: { tier: endpoint.path.includes('enterprise') ? 'enterprise' : 'standard', version: 'v1' } }), (req, res) => { // Your API logic here - only runs after successful payment res.json({ message: `${endpoint.description} - Payment verified!`, data: generateMockData(endpoint.path), cost: endpoint.price, timestamp: new Date().toISOString() }) } ) }) // Revenue analytics endpoint app.get('/api/analytics', async (req, res) => { const analytics = await paywall.getRevenueAnalytics({ timeframe: '24h', groupBy: 'endpoint' }) res.json(analytics) }) function generateMockData(path: string) { // Return appropriate mock data based on endpoint if (path.includes('basic')) { return { price: 50000, volume: 1234567 } } else if (path.includes('premium')) { return { analysis: 'Bullish trend detected', confidence: 0.87, signals: ['RSI oversold', 'Volume increase'] } } else { return { insights: ['Market volatility increasing', 'Institutional buying detected'], riskScore: 0.23, recommendations: ['Reduce position size', 'Monitor closely'] } } } app.listen(3000, () => { console.log('🚀 Monetized API server running on port 3000') console.log('💰 Revenue tracking enabled') })

Step 4: Monitor and Analyze

Get comprehensive insights into your agent spending and API revenue:

// Monitor agent spending patterns const spendingAnalytics = await smartProxy.getSpendingAnalytics({ agentIds: ['my-first-agent'], timeframe: '24h', groupBy: 'agent', includeMetadata: true }) console.log('Spending Analytics:') console.log(`Total spent: $${spendingAnalytics.totalSpent}`) console.log(`Total calls: ${spendingAnalytics.totalCalls}`) console.log(`Average cost per call: $${spendingAnalytics.averageCostPerCall}`) spendingAnalytics.breakdown.forEach(item => { console.log(`${item.key}: $${item.spent} (${item.percentage}%)`) }) // Track transaction history const transactions = await smartProxy.getTransactionHistory({ agentIds: ['my-first-agent'], limit: 10, status: 'confirmed' }) console.log('\nRecent Transactions:') transactions.transactions.forEach(tx => { console.log(`${tx.createdAt}: $${tx.amount} - ${tx.status}`) }) // Set up real-time webhooks for monitoring await smartProxy.configureWebhooks({ endpoint: 'https://your-app.com/webhooks/xpay', events: [ 'agent.spending.warning', // 80% of limit reached 'agent.spending.exceeded', // Limit hit 'agent.unusual_pattern', // Suspicious activity 'transaction.failed' // Failed payments ], secret: 'webhook_secret_key', retries: 3 }) // Monitor paywall revenue const revenueAnalytics = await paywall.getRevenueAnalytics({ timeframe: '7d', groupBy: 'endpoint' }) console.log('\nRevenue Analytics:') console.log(`Total revenue: $${revenueAnalytics.totalRevenue}`) console.log(`Unique customers: ${revenueAnalytics.uniqueCustomers}`) revenueAnalytics.breakdown.forEach(endpoint => { console.log(`${endpoint.path}: $${endpoint.revenue} (${endpoint.requests} requests)`) })

🎉 Success! You’re Now Xpay-Enabled

You’ve successfully set up:

  • ✅ Agent with enterprise spending controls
  • ✅ Protected API calls with automatic monitoring
  • ✅ Monetized endpoints earning x402 payments
  • ✅ Real-time analytics and webhook notifications

Next Steps

🛡️ Advanced Agent Security

Scale Your Revenue

📊 Production Monitoring

🔧 Developer Resources

Get Support

Enterprise Support: Need dedicated support? Contact our enterprise team  for priority assistance, custom integrations, and SLA guarantees.

Community & Support Channels


Ready to build production systems? Continue to Production Deployment →

Last updated on: