Charge AI Agents for Your Laravel APIs and Content with x402
Published on 2026-03-08
Add one line of Laravel middleware to charge AI agents and crawlers per-request in USDC on Solana. Keep content free for humans, monetize AI traffic. No API keys, no billing portal.
Charge AI Agents for Your Laravel APIs and Content with x402
AI agents are the new API consumers. Claude, GPT, Perplexity, and countless custom agents are crawling the web and hitting APIs millions of times a day — extracting value from your content and services without paying a cent.
API keys and rate limits were built for human developers. They don't work for a world where autonomous agents discover and consume APIs on the fly. What if there was a way for an AI agent to just... pay you? Automatically, instantly, no signup required?
There is. It's called x402.
What is x402?
HTTP has always had a status code for payments: 402 Payment Required. It's been "reserved for future use" since 1997. The x402 protocol finally puts it to work.
The flow is simple:
- An agent requests your API endpoint
- Your server responds with 402 and a header describing the price, token, and wallet address
- The agent constructs a USDC payment on Solana, signs it, and retries the request with the signed transaction in a header
- Your server verifies and settles the transaction on-chain, then serves the content
The whole exchange takes about a second. No API keys, no OAuth, no billing portal, no invoices. The agent pays per-request in USDC on Solana and gets what it asked for.
One line of Laravel middleware
With the solanaguide/laravel-x402 package, you can gate any route behind a micropayment with a single middleware call:
Route::get('/api/weather', function () {
return response()->json([
'city' => 'San Francisco',
'temp' => 62,
'conditions' => 'Foggy, as usual',
]);
})->middleware('x402:0.001');
That's it. Any request without a valid payment gets a 402 response with machine-readable payment instructions. Any request with a valid signed USDC transaction gets the weather data. One tenth of a cent per request.
Setting it up
Install the package
composer require solanaguide/laravel-x402
Configure your wallet
You need a Solana wallet address to receive payments. If you don't have one, create one with any Solana wallet app like Phantom or Solflare.
Add two environment variables:
X402_PAY_TO=YourSolanaWalletAddress
SOLANA_RPC_URL=https://api.mainnet-beta.solana.com
X402_PAY_TO is the wallet that receives your USDC payments. SOLANA_RPC_URL is a Solana RPC endpoint — the public one works, but a dedicated provider like Helius or QuickNode is more reliable for production.
Initialize your wallet
Your wallet needs an active USDC token account before it can receive payments. If your wallet has never held USDC, you need to send a small amount to it first (even $0.01 is enough). You can do this from:
- An exchange like Coinbase or Kraken — withdraw USDC to your Solana address
- Another Solana wallet app (Phantom, Solflare, Backpack, etc.)
- Swap a small amount of SOL for USDC at jup.ag if you already have SOL
Verify everything works
php artisan x402:check
This validates your configuration and checks on-chain that your wallet is ready to receive USDC. You'll see something like:
Checking x402 configuration...
Pay-to address: G1LJVRs...
Token mint: EPjFWdd5...
RPC endpoint: https://api.mainnet-beta.solana.com
Network: solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp
Checking on-chain state...
Associated Token Address: 6PNyZgi...
Token account exists
USDC balance: 0.010000
SOL balance: 0.010000000
All checks passed. Ready to accept payments!
Publish the config (optional)
php artisan vendor:publish --tag=x402-config
This gives you full control over the network, token, commitment level, confirmation polling, and more.
Pricing your routes
Simple: middleware parameter
The easiest approach — pass the price in USDC directly to the middleware:
// $0.001 per request (~$1 per 1,000 requests)
Route::get('/api/weather', WeatherController::class)
->middleware('x402:0.001');
// $0.01 per request with a description
Route::get('/api/analysis', AnalysisController::class)
->middleware('x402:0.01,Market analysis report');
// $0.10 for expensive operations
Route::post('/api/generate', GenerateController::class)
->middleware('x402:0.10,AI content generation');
Advanced: config-based pricing
For complex setups with wildcards and per-method pricing, define routes in config/x402.php:
'routes' => [
'GET /api/data/*' => ['price' => '0.001', 'description' => 'Data access'],
'POST /api/generate' => ['price' => '0.05', 'description' => 'Generation'],
'GET /api/premium/*' => ['price' => '0.01', 'description' => 'Premium content'],
],
What agents see
When an agent hits a gated endpoint without payment, it gets a 402 Payment Required response with a PAYMENT-REQUIRED header:
{
"x402Version": 2,
"accepts": [
{
"scheme": "exact",
"network": "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",
"maxAmountRequired": "1000",
"asset": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",
"payTo": "YourSolanaAddress...",
"resource": "YourSolanaAddress...",
"maxTimeoutSeconds": 60,
"description": "Weather data",
"mimeType": "application/json",
"extra": {}
}
]
}
This is fully machine-readable. The agent knows: pay 1000 units ($0.001) of USDC on Solana mainnet to this address, and you'll get application/json back. x402-compatible agents handle this automatically.
After a successful payment, the response includes a PAYMENT-RESPONSE header with the Solana transaction hash — a verifiable on-chain receipt.
Who's paying?
x402 is designed for the emerging world of AI agents with wallets. Several tools already support x402 payments:
- sol fetch — CLI tool for testing x402 endpoints
- AI agent frameworks — agents built with wallet capabilities can discover and pay for APIs automatically
- Custom integrations — any HTTP client that can sign Solana transactions
The protocol is an open standard. As more agents get wallet access, any agent will be able to discover and pay for your API without prior arrangement.
Automatic fiat conversion
If you'd rather receive dollars in your bank account instead of USDC, use SpherePay. Create an account, get your offramp Solana address, and set it as your X402_PAY_TO:
X402_PAY_TO=YourSpherePayOfframpAddress
USDC payments are automatically converted to fiat and deposited to your bank. No code changes needed.
Charging AI crawlers for your content
This is where it gets interesting beyond APIs. Say you run a blog, a documentation site, or a news publication. You want humans to read it for free — but AI crawlers like GPTBot, ClaudeBot, and PerplexityBot are scraping your pages to train models and power AI search. They're extracting value from your work without paying.
With x402, you can charge them while keeping your site free for everyone else.
Add one line to your .env:
X402_AI_CRAWLER_PRICE=0.001
Then add the x402 middleware to your web routes (note: no price parameter):
// app/Http/Kernel.php
protected $middlewareGroups = [
'web' => [
// ... existing middleware
\SolanaGuide\X402\Middleware\PaymentRequiredMiddleware::class,
],
];
That's it. When a human visits your blog in Chrome or Firefox, they see your content for free — the middleware does nothing. When GPTBot or ClaudeBot makes the same request, they get a 402 with payment instructions. If they pay $0.001 USDC, they get the content. If they don't, they don't.
Your existing routes with explicit prices (x402:0.01) are unaffected — they charge everyone the route price regardless.
The package detects 70+ known AI user agents sourced from knownagents.com — including GPTBot, ChatGPT-User, ClaudeBot, Claude-SearchBot, PerplexityBot, DeepSeekBot, Google-Extended, Bytespider, OAI-SearchBot, Manus-User, Crawl4AI, and many more. You can add custom patterns too:
$detector = app(AiCrawlerDetector::class);
$detector->addPattern('MyCustomBot');
A note on adoption
Let's be honest: x402 is in its early days. Most AI crawlers today won't pay — they'll hit the 402 and give up. Right now, setting a crawler price effectively blocks non-paying bots from scraping your content, which is useful in its own right.
But the direction is clear. AI agents are increasingly being built with wallets and the ability to make autonomous payments. As more crawlers adopt x402 support, your site will be ready to accept payments from day one — and in the meantime, you're protecting your content from unpaid scraping.
The bigger picture
You might be wondering how this relates to Cloudflare's recent moves to help site owners control AI bot access. Cloudflare operates at the CDN layer — they're solving detection: "is this an AI crawler?" They can block bots, serve challenges, or rate-limit them. But blocking is a blunt instrument. It's all-or-nothing.
x402 operates at the protocol layer — it solves what happens next: "this is an AI crawler, now what?" Instead of a block page, the crawler gets a price. Pay and you're in. Don't pay, don't scrape.
These aren't competing approaches. They're complementary layers. Cloudflare tells you who's at the door. x402 gives you a way to let them in — for a fee. The most interesting future is one where infrastructure providers like Cloudflare adopt x402 as the response to detected AI traffic, turning bot management from a security problem into a revenue opportunity.
How it works under the hood
The package does native Solana transaction verification — no third-party payment facilitator in the middle. When a payment comes in:
- The signed Solana transaction is deserialized from the request header
- The SPL Token transfer instruction is inspected to verify the recipient address, USDC token mint, and amount
- Ed25519 signatures are verified cryptographically
- The transaction is submitted to Solana via JSON-RPC
- The package polls for on-chain confirmation
- Your content is served with a transaction hash receipt
All of this happens in about a second. Your server never holds private keys — clients sign their own transactions.
A practical example
Here's a complete API that charges for weather data and premium forecasts:
// routes/api.php
// Free endpoint — no middleware
Route::get('/api/status', function () {
return response()->json(['status' => 'ok']);
});
// $0.001 per request
Route::get('/api/weather/{city}', function (string $city) {
return response()->json([
'city' => $city,
'temperature' => rand(40, 95),
'humidity' => rand(20, 90),
'conditions' => collect(['Sunny', 'Cloudy', 'Rainy', 'Windy'])->random(),
'timestamp' => now()->toIso8601String(),
]);
})->middleware('x402:0.001,Current weather data');
// $0.01 per request
Route::get('/api/forecast/{city}', function (string $city) {
$forecast = collect(range(1, 7))->map(fn ($day) => [
'date' => now()->addDays($day)->toDateString(),
'high' => rand(50, 95),
'low' => rand(35, 70),
'conditions' => collect(['Sunny', 'Cloudy', 'Rainy', 'Stormy'])->random(),
]);
return response()->json([
'city' => $city,
'forecast' => $forecast,
]);
})->middleware('x402:0.01,7-day weather forecast');
Test it locally:
php artisan serve --port=8402
Hit the free endpoint to confirm it works:
curl http://localhost:8402/api/status
Hit a paid endpoint to see the 402 response:
curl -s http://localhost:8402/api/weather/london | jq
You'll get the payment requirements. An x402-compatible client handles the rest automatically.
Thinking about pricing
Micropayments change how you think about API pricing. Some rules of thumb:
- $0.001 (1/10 cent) — lightweight reads, status checks, simple lookups
- $0.01 (1 cent) — richer data, aggregated content, search results
- $0.05-0.10 — expensive computation, AI generation, large dataset access
- $1.00+ — premium reports, bulk exports, high-value analysis
At $0.001 per request, an agent making 10,000 requests pays you $10. No contracts, no negotiations, no accounts receivable. Just money in your wallet.
Getting started
composer require solanaguide/laravel-x402
Add your wallet to .env, send it a few cents of USDC to initialize the token account, run php artisan x402:check, and add ->middleware('x402:0.001') to any route.
Your API is now monetized for the age of AI agents.
On this page
Related Content
Sol CLI: A Solana Skill for AI Agents
A Solana skill for OpenClaw, Claude Code, and AI agents. Trade tokens, manage wallets, stake SOL, earn yield, and track portfolios — no API keys, no code.
x402 on Solana: Your AI Agent Can Pay for Its Own Data
AI agents can now pay for premium APIs, web scraping, and market data per-request using USDC on Solana. No API keys, no subscriptions — just sol fetch and a wallet.
Ship or Die at Accelerate 2025: Time Is Money (Kawz - Time.fun)
Kawz introduces Time.fun, a platform that tokenizes time and creates new capital markets on Solana
Solana Changelog - Feb 27 - Partitioned Epoch Rewards, Anchor CI, and 2.0
Discover the latest Solana updates, including partitioned epoch rewards, Anchor CI enhancements, and the upcoming 2.0 release. Learn about performance improvements and new developer tools in the Solana ecosystem.
Kyle Samani on Crypto's Role in AI, Consumer Tech, & other Contrarian Views
Explore the future of prediction markets on Solana with Hedgehog CEO Kyle Samani. Learn about innovative betting mechanisms, challenges in the space, and how Solana is positioned to revolutionize crypto prediction markets.
Ship or Die at Accelerate 2025: Lightning Talk: Chipped
Leah Winberg introduces Chipped and Tapstack, revolutionizing wearable tech and digital payments in the Solana ecosystem
Crypto Needs More Product, Investing In Great Founders | Craig Burel
Craig Burel discusses Reciprocal Ventures' journey into Solana, the importance of product and go-to-market strategy in crypto, and insights on investing in founders and applications versus tokens.
Ship or Die at Accelerate 2025: The Future of Digital Assets
Franklin Templeton's Roger Bayston discusses the company's journey into blockchain and the future of tokenized assets on Solana.
The Solana Bull Thesis & Pantera's DAT Strategy | Cosmo Jiang
Pantera Capital's Cosmo Jiang reveals why they launched HSDT, their Solana digital asset treasury, with over $1 billion in disclosed SOL holdings and plans to become the preeminent Solana DAT.
Ship or Die at Accelerate 2025: Verifying Dogecoin on Solana
Carter Feldman of Psy Protocol unveils a groundbreaking bridge between Dogecoin and Solana, enabling seamless integration and new utility for DOGE holders.
Product Keynote: Coinbase
Coinbase announces native Solana token trading directly within its retail app, bringing millions of on-chain assets to its massive user base
Solana Changelog - Test validator fix, new Syscall, RPC updates, and more
Dive into the latest Solana improvements including a test validator fix, new GetEpochStake syscall, RPC updates for interest-bearing tokens, and continued Core BPF migration progress.
Ship or Die at Accelerate 2025: Advancing Solana DeFi Innovation
OKX announces major developments for Solana, including XBTC integration and increased wallet usage
Breakpoint 2023: Creating Opportunities for Artists and Collectors
A discussion on the evolving landscape of digital art and the synergistic relationship between artists and collectors in the Solana ecosystem.
Breakpoint 2024: Keynote: ZK Compression (Swen Schaeferjohann, Nicolas Pennie)
Solana introduces ZK compression to scale the network, reduce costs, and enable new use cases
- Borrow / Lend
- Liquidity Pools
- Token Swaps & Trading
- Yield Farming
- Solana Explained
- Is Solana an Ethereum killer?
- Transaction Fees
- Why Is Solana Going Up?
- Solana's History
- What makes Solana Unique?
- What Is Solana?
- How To Buy Solana
- Agent Permissions & Security
- AI Agent Financial Markets
- Solana Agent Skill
- Complete Sol CLI Guide
- x402 Laravel Middleware
- AI Agent Prediction Markets
- x402 Agent API Payments
- Solana's Best Projects: Dapps, Defi & NFTs
- Choosing The Best Solana Validator
- Staking Rewards Calculator
- Liquid Staking
- Can You Mine Solana?
- Solana Staking Pools
- Stake with us
- How To Unstake Solana
- How validators earn
- Best Wallets For Solana
