AI agents are devouring APIs left and right, but traditional paywalls with keys or subscriptions cramp their style. X402 Payment Intents on Solana flips the script: instant stablecoin micropayments over HTTP 402, tailored for seamless ai agent x402 integration. No accounts, no friction – just pay and play on Solana’s lightning-fast chain.
This x402 developer tutorial solana dives into building it. We’re talking Express. js servers, Solana devnet, and facilitators that make coinbase x402 api payments dead simple. Buckle up; your agents will thank you.
X402 Basics: HTTP 402 Meets Solana Speed
X402 leverages the long-dormant HTTP 402 ‘Payment Required’ status to gate APIs. Your server spits a 402 response with payment details – recipient wallet, amount in USDC, facilitator URL. Agents pay instantly via stablecoins, prove it with a header, and boom: access granted. On Solana, transactions settle in milliseconds, crushing latency woes for http 402 micropayments solana.
I love how it sidesteps Web2 nonsense. Open standard from Coinbase, no vendor lock-in. GitHub repo’s buzzing, Solana docs have quickstarts. Perfect for AI swarms querying weather, stocks, or LLMs without billing drama.
“x402 lets developers and AI agents pay for APIs directly with stablecoins over HTTP. With just a few lines of code. . . ” – Coinbase Intro
Pro tip: Use devnet first. Facilitator at https://x402.org/facilitator handles proofs without real funds.
Prepping Your Solana Server Stack
Spin up a fresh Express app. npm init, then grab x402 middleware. For Solana, it’s plug-and-play with x402 payment intents solana verifiers.
- Install deps:
npm i express @x402/express-middleware @solana/web3. js - Fund a devnet wallet. Airdrop SOL via solfaucet. com, swap for USDC on devnet DEX.
- Set your receiver address – that’s where payments land.
Check out this M2M guide for deeper Solana specifics; it aligns perfectly with agent flows.
Environment vars? Key ones: RECEIVER_WALLET, FACILITATOR_URL=’https://x402.org/facilitator’, CHAIN=’solana: devnet’. Testnet keeps it risk-free while you iterate.
Locking Down APIs with X402 Middleware
Core magic: middleware wraps your routes. Specify price per call – say 0.001 USDC for a simple query. Server checks proofs on retries.
X402 Middleware Integration for Express.js + Solana
π Lock down your Solana devnet APIs with X402 payment intents. Drop this Express.js middleware to enforce wallet payments:
const express = require('express');
const { Connection, Keypair } = require('@solana/web3.js');
const { X402Middleware } = require('x402-solana-middleware');
// Solana devnet connection
const connection = new Connection('https://api.devnet.solana.com');
// Load your wallet (use env vars in prod!)
const wallet = Keypair.fromSecretKey(
Uint8Array.from(JSON.parse(process.env.WALLET_SECRET_KEY))
);
// Facilitator config for payment processing
const facilitatorConfig = {
publicKey: 'YOUR_FACILITATOR_PUBKEY_HERE',
authority: 'YOUR_AUTHORITY_PUBKEY_HERE',
feeBasisPoints: 100 // 1% fee
};
const app = express();
app.use(express.json());
// π Integrate X402 middleware
app.use(X402Middleware({
connection,
wallet,
facilitator: facilitatorConfig,
network: 'devnet',
minPayment: 0.001 // SOL
}));
// Protected AI agent endpoint
app.post('/api/ai-agent', async (req, res) => {
// Payment verified by middleware
const { prompt } = req.body;
// Your AI logic here
res.json({ response: `AI output for: ${prompt}` });
});
app.listen(3000, () => console.log('π₯ X402-protected API on port 3000'));
π₯ Payment-gated! AI agents now pay SOL via intents before hitting your endpoints. Tweak facilitator config and scale to mainnet.
Here’s the flow in action:
- Agent hits/api/data? – gets 402 with payment URL.
- Agent pays via wallet or facilitator.
- Retry with Payment-Proof header – server verifies on-chain, serves data.
Tweak metadata for X402 Bazaar discovery: add OpenAPI specs with payment hints. Agents scan, pay, consume. Read more in this real-time agent tutorial.
Edge case: Failed proofs? 402 again. Idempotency via nonces prevents double-pays. Solana’s cheap fees make it viable for micro-cents.
Real-world test: Fire curl at your endpoint. Expect a crisp 402 JSON: payment details, facilitator endpoint, exact USDC amount. Copy the payment URL, hit it with a devnet wallet – transaction hashes in seconds. Retry curl with Payment-Proof: and lt;signature and gt; header. Green light: data flows.
Wiring Up AI Agents for Autonomous Payments
Agents aren’t spectators; they need to handle 402s natively. Grab @x402/client or roll a fetch wrapper. On 402, extract payment intent, sign via Solana wallet (Phantom, anyone?), submit to facilitator. Boom – proof back, request resumes. This ai agent x402 integration turns agents into self-funding machines, querying high-value APIs without human babysitting.
402 Handler: Sign Solana Tx & Retry API
AI agent hits paywall? Handle 402 like a pro: snag intent, sign Solana tx via wallet, submit to facilitator, retry with proof. Instant unlock! β‘
async function callAIWithPayment(apiUrl, prompt) {
let response = await fetch(apiUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ prompt })
});
if (response.status === 402) {
// Extract payment intent from header
const paymentIntent = JSON.parse(response.headers.get('X-Payment-Intent') || '{}');
const unsignedTxBytes = Uint8Array.from(atob(paymentIntent.transaction), c => c.charCodeAt(0));
// Sign via Solana wallet (e.g., Phantom)
const wallet = window.solana;
if (!wallet?.isPhantom) throw new Error('Connect Phantom wallet!');
const signedTx = await wallet.signTransaction(unsignedTxBytes);
// Submit signed tx to facilitator
const submitRes = await fetch(paymentIntent.facilitatorUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/octet-stream' },
body: signedTx.serialize()
});
const proof = await submitRes.text(); // Tx sig or proof
// Retry with proof
response = await fetch(apiUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Payment-Proof': proof
},
body: JSON.stringify({ prompt })
});
}
if (!response.ok) throw new Error(`API failed: ${response.status}`);
return response.json();
}
// Usage: const result = await callAIWithPayment('https://api.aiagent.xyz/v1/chat', 'Explain Solana payments');
Drop this in your agent flow. Validates tx implicitly via walletβstay secure. Scale your AI on Solana. Next: error handling upgrades. π
Picture an agent swarm scraping real-time Solana DEX prices or feeding LLMs with premium datasets. Each call: 0.0001 USDC, verified idempotently. Solana’s sub-second finals mean no waiting games. I rate this setup 10/10 for http 402 micropayments solana – beats Stripe’s fees and latency every time.
Pro move: Bundle with LangChain or Auto-GPT plugins. Emerging x402 agent toolkits on GitHub make it drop-in. Check Solana’s official guide for verifier tweaks; it’s gold for custom logic.
Production Polish: Mainnet, Bazaar, and Beyond
Mainnet swap: Update CHAIN to ‘solana: mainnet’, swap facilitator if needed (x402. org still rocks). List in X402 Bazaar – add X402-Metadata header with service desc, pricing tiers, OpenAPI YAML. Agents discover via/well-known/x402. json, auto-pay.
Security first: Rate limits via nonces, multi-sig receivers, audit verifiers. Scale with serverless – Vercel or Cloudflare Workers love Express middleware. Monitor via Solana RPC for proof fails.
- Export RECEIVER_WALLET securely.
- Test mainnet with tiny amounts.
- Publish to Bazaar for visibility.
For agent-heavy workloads, pair with this 2025 autonomous agent guide – it amps up M2M flows. Watch fees: Solana’s dirt-cheap, but volume spikes? Batch proofs.
X402 on Solana isn’t hype; it’s the micropayment rail AI needs now. Agents pay-per-query, devs cash in frictionlessly. Fork the Next. js template, deploy today – your APIs go autonomous. Adapt fast, build smart.
