How to Implement x402 Payments with AsterPay

The Complete Guide to AI Agent Payments + EUR Off-Ramp

⏱️ ~15 min read πŸ’» TypeScript πŸ”— Base, Polygon, Arbitrum, BSC

Overview

x402 is the open protocol for internet-native payments, using HTTP 402 "Payment Required" to let AI agents and services pay each other instantly. AsterPay is an x402 Facilitator that adds:

In this guide, you'll build:

  1. An x402-protected API endpoint
  2. An AI agent that pays for API calls automatically
  3. EUR off-ramp integration for European developers

What You Will Need

Part 1: Setting Up the Server (Seller)

Step 1: Initialize Project

mkdir asterpay-x402-demo
cd asterpay-x402-demo
npm init -y
npm install express @asterpay-io/x402 dotenv
npm install -D typescript @types/express @types/node ts-node

Step 2: Environment Variables

Create .env:

# Your wallet address (receives payments)
WALLET_ADDRESS=0xYourWalletAddressHere

# AsterPay API Key (get from dashboard)
ASTERPAY_API_KEY=ap_live_xxxxxxxxxxxx

# Network (base-sepolia for testing, base for production)
NETWORK=base-sepolia

# Server port
PORT=3000

Step 3: Create the x402 Protected Server

import express from 'express';
import { createX402Middleware, X402Config } from '@asterpay-io/x402';
import dotenv from 'dotenv';

dotenv.config();

const app = express();
app.use(express.json());

// AsterPay x402 Configuration
const x402Config: X402Config = {
  payTo: process.env.WALLET_ADDRESS!,
  network: process.env.NETWORK as 'base' | 'base-sepolia',
  
  facilitator: {
    url: 'https://x402.asterpay.io',
    apiKey: process.env.ASTERPAY_API_KEY
  },
  
  // Optional: EUR off-ramp
  eurOfframp: {
    enabled: true,
    iban: process.env.EUR_IBAN
  }
};

// Create middleware with pricing
const x402Middleware = createX402Middleware(x402Config, {
  'GET /api/market-data': { price: '$0.005' },
  'GET /api/ai-analysis': { price: '$0.004' },
  'POST /api/generate-image': { price: '$0.10' },
});

app.use(x402Middleware);

// Market data endpoint - $0.005 per request
app.get('/api/market-data', (req, res) => {
  res.json({
    symbol: 'BTC',
    price: 98542.50,
    timestamp: new Date().toISOString()
  });
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`πŸš€ x402 API running on http://localhost:${PORT}`);
});

Part 2: Creating the AI Agent Client (Buyer)

import { AgentWallet, createX402Fetch } from '@asterpay-io/x402';

async function main() {
  // Create AI Agent Wallet with Spending Limits
  const agentWallet = new AgentWallet({
    privateKey: process.env.AGENT_PRIVATE_KEY!,
    network: 'base-sepolia',
    
    // Spending controls - critical for AI agents!
    spendingLimits: {
      perTransaction: 0.10,  // Max $0.10 per tx
      daily: 5.00,           // Max $5.00 per day
      monthly: 50.00         // Max $50.00 per month
    }
  });

  console.log('πŸ€– Agent Wallet:', agentWallet.address);
  console.log('πŸ’° Balance:', await agentWallet.getBalance(), 'USDC');

  // Create x402-enabled Fetch (auto-handles payments)
  const x402Fetch = createX402Fetch(agentWallet);

  // Make Paid API Call
  const response = await x402Fetch('http://localhost:3000/api/market-data');
  const data = await response.json();
  console.log('Data:', data);
}

main();

Part 3: EUR Off-Ramp Integration

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ AI Agent │────▢│ AsterPay │────▢│ Settlement │────▢│ Your Bank β”‚
β”‚ Pays USDC β”‚ β”‚ Facilitatorβ”‚ β”‚ SEPA API β”‚ β”‚ (EUR) β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
$0.10 Verify Convert €0.09
Settle USDC β†’ EUR <30 min
const x402Config: X402Config = {
  payTo: process.env.WALLET_ADDRESS!,
  network: 'base',
  
  facilitator: {
    url: 'https://x402.asterpay.io',
    apiKey: process.env.ASTERPAY_API_KEY
  },
  
  // Enable EUR off-ramp
  eurOfframp: {
    enabled: true,
    iban: 'FI21 1234 5600 0007 85', // Your IBAN
    autoConvert: true,
    minAmount: 10.00,
    schedule: 'daily'
  }
};

Part 4: LangChain Integration

import { ChatOpenAI } from '@langchain/openai';
import { createOpenAIToolsAgent } from 'langchain/agents';
import { AsterPayTool } from '@asterpay-io/x402/langchain';

// Create AsterPay tool for LangChain
const asterPayTool = new AsterPayTool({
  wallet: agentWallet,
  description: 'Pay for external API services using x402'
});

// Create agent with payment capability
const agent = await createOpenAIToolsAgent({
  llm: new ChatOpenAI({ modelName: 'gpt-4' }),
  tools: [asterPayTool],
  prompt: agentPrompt
});

// Agent can now pay for services automatically
const result = await executor.invoke({
  input: 'Get the current BTC price from the market API'
});

Part 5: Production Deployment

Vercel Deployment

{
  "version": 2,
  "builds": [
    { "src": "src/server.ts", "use": "@vercel/node" }
  ],
  "routes": [
    { "src": "/(.*)", "dest": "src/server.ts" }
  ]
}
vercel env add WALLET_ADDRESS
vercel env add ASTERPAY_API_KEY
vercel --prod

Security Best Practices

⚠️ Important: Never use your main wallet for AI agents. Always create dedicated agent wallets with strict spending limits.

// βœ… DO: Use dedicated agent wallet with limits
const agentWallet = new AgentWallet({
  privateKey: AGENT_SPECIFIC_KEY,
  spendingLimits: {
    perTransaction: 0.10,
    daily: 5.00
  },
  // Only allow payments to trusted APIs
  allowedRecipients: [
    '0xTrustedAPI1...',
    '0xTrustedAPI2...'
  ]
});

Ready to Get Started?

Create your free AsterPay account and get your API key in seconds.

Get API Key β†’

Resources