Charge AI Agents for Your Laravel APIs and Content with x402
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.
Comments
Please login to leave a comment.
On this page
Related Content
The Rise Of AI Agents | Jeffy Yu & Yash Agarwal
How Two 20-Year-Olds Built a DeFi Protocol Managing $6B
Product Keynote: ShardLab
Micropayments Are Crypto's Untapped Use Case | Ted Livingston (CEO of Code)
Scale or Die 2025: Building Better Remote MCPs: Web3's Answer to Auth & Monetization
Validated | Does the Internet Really Need Blockchain-Powered AI?
The Rise of Crypto's Superapp | Fiskantes, Matti (Zee Prime Capital)
Breakpoint 2024: Keynote: The State of the USDC Economy Is Strong (Jeremy Allaire)
What Is Flipcash? | Ted Livingston
The Bull Case For Solana In 2025 | Ryan Watkins
Ship or Die at Accelerate 2025: Lightning Talk: Doodles
Crypto's Fastest Payments App, Only Possible On Solana | Ted Livingston
Understanding The Intersection Of Crypto & AI | Lucas Tcheyan (Galaxy)
Ship or Die 2025: Project Liberty and DAIS
Sunny talks about owning a Basketball team with Icecube | ep. 17
Latest news
Mastercard Brings Always-On Stablecoin Settlement to Solana With USDC, PYUSD, and RLUSD
Solana Foundation Backs Fully Onchain Perpetuals Push to Challenge Hyperliquid
Andrew Yang's Noble Mobile Acquires Helium Mobile, Leaving HNT and DAO Intact
Solana Launches Native Subscription Billing and Recurring Payments on Mainnet
Charles Schwab Adds 24/7 SOL Futures to thinkorswim
Raiku Launches rkuSOL, a Solana Liquid Staking Token Backed by Blockspace Auction Revenue
Backpack Securities Launches Tokenized US Equity and ETF Trading on Solana
Solana Led All Blockchains in App Revenue in May 2026
Fitell Launches What It Calls Australia's First Solana Corporate Treasury With $100M Convertible Note Facility
Galaxy Research: Solana Held Its DEX Lead in Q1 While RWAs Grew 58% and Stablecoins Diversified
Solana Token Markets
