solanaguide/laravel-x402
Composer 安装命令:
composer require solanaguide/laravel-x402
包简介
x402 Payment Middleware for Laravel & Symfony — gate routes behind instant USDC micropayments on Solana
README 文档
README
x402 Payment Middleware for Laravel & Symfony — gate routes behind instant USDC micropayments on Solana.
The x402 protocol revives HTTP 402 (Payment Required) to enable automatic, instant payments over HTTP. This package lets you protect any route with a single middleware call — AI agents and API consumers pay per-request in USDC on Solana.
Features
- One-line setup:
->middleware('x402:0.001')gates a route behind $0.001 USDC - Native Solana verification: No third-party facilitator — verifies and settles transactions directly via Solana JSON-RPC
- Laravel + Symfony: Shared core with framework-specific adapters
- SpherePay compatible: Point
X402_PAY_TOto a SpherePay offramp address for automatic fiat conversion - Charge AI crawlers: Keep content free for humans, charge AI bots automatically
- x402 V2 compliant: Full protocol support with
PAYMENT-REQUIREDandPAYMENT-RESPONSEheaders
Requirements
- PHP 8.1+
ext-sodium(built into PHP since 7.2)- Solana RPC endpoint (public or private via Helius, QuickNode, etc.)
Installation
composer require solanaguide/laravel-x402
Laravel
The service provider is auto-discovered. Publish the config:
php artisan vendor:publish --tag=x402-config
Symfony
Register the bundle in config/bundles.php:
return [ // ... SolanaGuide\X402\X402Bundle::class => ['all' => true], ];
Setup
1. Configure environment
X402_PAY_TO=YourSolanaWalletAddressHere SOLANA_RPC_URL=https://api.mainnet-beta.solana.com
2. Initialize the pay-to wallet
Your X402_PAY_TO wallet must have an active USDC token account before it can receive payments. If the wallet has never held USDC, the token account won't exist and payments will fail.
To initialize it, send a small amount of USDC (e.g., $0.01) to the wallet from:
- A crypto exchange (Coinbase, Kraken, etc.) — withdraw USDC to your Solana address
- A Solana wallet app (Phantom, Solflare, Backpack, etc.)
- Swap SOL for USDC at jup.ag if you already have SOL
This automatically creates the Associated Token Account.
3. Verify your setup
php artisan x402:check
This command validates your configuration and checks on-chain that the token account exists. Run it before going live.
Configuration
Full Config Options
| Variable | Default | Description |
|---|---|---|
X402_PAY_TO |
(required) | Solana address to receive payments |
X402_ASSET |
USDC mainnet mint | Token mint address |
X402_NETWORK |
solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp |
CAIP-2 network ID |
X402_SCHEME |
exact |
Payment scheme |
SOLANA_RPC_URL |
https://api.mainnet-beta.solana.com |
Solana RPC endpoint |
SOLANA_COMMITMENT |
confirmed |
Commitment level |
SOLANA_RPC_TIMEOUT |
30 |
RPC timeout (seconds) |
SOLANA_CONFIRM_RETRIES |
30 |
Confirmation poll attempts |
SOLANA_CONFIRM_INTERVAL |
500 |
Ms between confirmation polls |
X402_AI_CRAWLER_PRICE |
false |
Price to charge AI crawlers (e.g., 0.001) |
X402_MAX_TIMEOUT_SECONDS |
60 |
Max payment timeout |
X402_DESCRIPTION |
(empty) | Default payment description |
X402_MIME_TYPE |
application/json |
Default response MIME type |
Usage
Laravel — Middleware Parameter (Simplest)
// Routes that cost $0.001 USDC per request Route::get('/api/weather', WeatherController::class) ->middleware('x402:0.001'); // With a description Route::get('/api/premium', PremiumController::class) ->middleware('x402:0.01,Premium weather data');
Laravel — Config-Based Pricing
// config/x402.php 'routes' => [ 'GET /api/premium/*' => ['price' => '0.01', 'description' => 'Premium content'], 'POST /api/generate' => ['price' => '0.05', 'description' => 'AI generation'], ],
Symfony — Route Attribute
use Symfony\Component\Routing\Annotation\Route; #[Route('/api/weather')] public function weather(): Response { // Set _x402_price on the request attributes return $this->json(['temp' => 72]); }
How It Works
- Client sends a request to a gated route
- If no
PAYMENT-SIGNATUREheader is present, the middleware returns HTTP 402 with aPAYMENT-REQUIREDheader containing payment details (amount, recipient, token, network) - Client constructs and signs a Solana SPL Token transfer transaction
- Client retries the request with the signed transaction in the
PAYMENT-SIGNATUREheader - The middleware:
- Deserializes the Solana transaction
- Verifies the SPL Token transfer instruction (recipient, amount, token mint)
- Verifies Ed25519 signatures
- Submits the transaction to Solana via RPC
- Polls for confirmation
- On success, the original content is served with a
PAYMENT-RESPONSEheader containing the transaction hash
402 Response Format
{
"x402Version": 2,
"accepts": [
{
"scheme": "exact",
"network": "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",
"maxAmountRequired": "1000",
"resource": "YourSolanaAddress...",
"payTo": "YourSolanaAddress...",
"asset": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",
"maxTimeoutSeconds": 60,
"scheme": "exact",
"description": "",
"mimeType": "application/json",
"extra": {}
}
]
}
SpherePay Integration
For automatic fiat conversion, create a SpherePay account and set your offramp Solana address as the pay-to address:
X402_PAY_TO=YourSpherePayOfframpSolanaAddress
All USDC payments are automatically converted to fiat and deposited to your bank account. No code changes needed.
Charging AI Crawlers
AI bots like GPTBot, ClaudeBot, and PerplexityBot scrape your content for training and retrieval. With x402, you can keep your content free for humans while charging AI crawlers automatically.
X402_AI_CRAWLER_PRICE=0.001
Then add the x402 middleware globally or to your web routes (without a price parameter):
// app/Http/Kernel.php — apply to all web routes protected $middlewareGroups = [ 'web' => [ // ... existing middleware \SolanaGuide\X402\Middleware\PaymentRequiredMiddleware::class, ], ];
Human visitors browse your site for free. AI crawlers get a 402 response with payment instructions. If they pay, they get the content.
Routes with an explicit price (x402:0.01) always charge that price regardless of the crawler setting.
The package detects 70+ known AI user agents across categories — agents, assistants, data scrapers, search crawlers, and undocumented bots. The full list is sourced from knownagents.com and includes GPTBot, ChatGPT-User, ClaudeBot, Claude-SearchBot, PerplexityBot, DeepSeekBot, Google-Extended, Bytespider, CCBot, Amazonbot, meta-externalagent, OAI-SearchBot, Manus-User, and many more.
Note: The x402 protocol is in its early days. Most AI crawlers today will not pay — they'll simply receive the 402 and move on. Setting a crawler price effectively blocks non-paying bots while laying the groundwork for a future where crawlers are expected to pay for content access.
Add custom patterns:
$detector = app(AiCrawlerDetector::class); $detector->addPattern('MyCustomBot');
Testing
composer test
Or directly:
vendor/bin/phpunit
Architecture
src/
├── Core/ # Framework-agnostic x402 logic
├── Data/ # Value objects (PaymentRequirements, PaymentPayload, etc.)
├── Detection/ # AI crawler detection
├── Exceptions/ # Custom exceptions
├── Middleware/ # Laravel + Symfony middleware adapters
├── Solana/ # Solana transaction parsing + RPC (extracted from Attestto SDK)
└── Support/ # Constants (networks, tokens)
Credits
- Solana transaction parsing adapted from Attestto solana-php-sdk (MIT License)
- x402 Protocol
License
MIT License. See LICENSE for details.
solanaguide/laravel-x402 适用场景与选型建议
solanaguide/laravel-x402 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 1 次下载、GitHub Stars 达 0, 最近一次更新时间为 2026 年 03 月 08 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「symfony」 「payment」 「middleware」 「laravel」 「micropayments」 「solana」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 solanaguide/laravel-x402 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 solanaguide/laravel-x402 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 solanaguide/laravel-x402 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Shoot aims to make providing data to your templates more manageable
The bundle for easy using json-rpc api on your project
Bundle Symfony DaplosBundle
Slim Framework 3 CSRF protection middleware utilities
Cloudflare Middleware For Guzzle
PSR-15 middleware to handle CSRF-token verification
统计信息
- 总下载量: 1
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 28
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2026-03-08