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
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.
Sol CLI Guide: Every Solana Command for AI Agents and Humans
The complete guide to Sol CLI β trade, stake, lend, and manage portfolios on Solana from OpenClaw, Claude Code, or any AI agent. No API keys, no code required.
How to Give Your AI Agent Access to Financial Markets on Solana
Your OpenClaw bot or Claude Code agent can buy tokenized stocks, gold, Bitcoin, Ethereum, and hundreds more β plus earn yield on stablecoins. Set up AI-powered investing on Solana.
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.
Why Your AI Agent Needs a Permissions System (Before It Gives Away $250,000)
An OpenClaw bot gave away $250K in tokens. Malicious ClawHub skills target crypto wallets. Here's why your Clawdbot, OpenClaw, or Claude Code agent needs code-level permissions, not prompt engineering.
Polymarket with an AI Agent: Trade Prediction Markets on Solana
Your OpenClaw bot or Claude Code agent can browse, research, and trade Polymarket and Kalshi prediction markets on Solana. Binary YES/NO contracts on crypto, politics, sports, and more β all settled in USDC.
Staking On Solana: How To Stake Your Sol + Earn APY Rewards
Learn how you can earn rewards on your crypto assets by staking them on the Solana network,
What makes Solana Unique? How Is it different to Ethereum?
One of the most exciting features of Solana is its speed and scalability. It is one of the few protocols that boast over 1000 TPS because of its genuine web-scale blockchain features.
Token Swaps & Trading On Decentralized Exchanges (DEX)
Yield farming is a process that involves lending or staking crypto assets to generate rewards or high returns as passive incomes in the form of additional cryptocurrency
The Top Solana Projects: The Best Apps, Dapps, Defi, & NFTs
Want to learn what you can do with Solana Blockchain? The Solana Ecosystem is filled with a wide range of apps, Dapps, Defi projects, and NFTs. Below weβve highlighted some of the most popular and best apps, Dapps, Defi, and NFT projects based on th
Solana Stake Pools Guide: How They Work, Fees + The Best Pools
Learn how stake pools on Solana can help keep your staking rewards consistent while securing the Solana network
The Best Wallets for Solana for Staking, NFTs, and Defi
To make the most of Solana you'll need a wallet that is secure and supports NFTs, Defi and tokens. Read on to find our favourites
Why is Solana's price and popularity going up? Should I invest?'
Since Solana can boldly compete with Ethereum, itβs worth considering as a solid investment in 2021.
Turbo Staking
Get Bonus APY on your SOL with Turbo Staking via Solana Compass and Marinade
Yield & Liquidity Farming For Passive Income - Solana Defi Guide
Yield farming is a process that involves lending or staking crypto assets to generate rewards or high returns as passive incomes in the form of additional cryptocurrency
Solana Token Markets
