PHPackages                             solanaguide/laravel-x402 - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Payment Processing](/categories/payments)
4. /
5. solanaguide/laravel-x402

ActiveLibrary[Payment Processing](/categories/payments)

solanaguide/laravel-x402
========================

x402 Payment Middleware for Laravel &amp; Symfony — gate routes behind instant USDC micropayments on Solana

v0.1.0(3mo ago)01MITPHPPHP ^8.1

Since Mar 8Pushed 3mo agoCompare

[ Source](https://github.com/solanaguide/laravel-x402)[ Packagist](https://packagist.org/packages/solanaguide/laravel-x402)[ RSS](/packages/solanaguide-laravel-x402/feed)WikiDiscussions main Synced 3w ago

READMEChangelogDependencies (4)Versions (2)Used By (0)

laravel-x402
============

[](#laravel-x402)

x402 Payment Middleware for Laravel &amp; Symfony — gate routes behind instant USDC micropayments on Solana.

The [x402 protocol](https://www.x402.org/) 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
--------

[](#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_TO` to 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-REQUIRED` and `PAYMENT-RESPONSE` headers

Requirements
------------

[](#requirements)

- PHP 8.1+
- `ext-sodium` (built into PHP since 7.2)
- Solana RPC endpoint (public or private via Helius, QuickNode, etc.)

Installation
------------

[](#installation)

```
composer require solanaguide/laravel-x402
```

### Laravel

[](#laravel)

The service provider is auto-discovered. Publish the config:

```
php artisan vendor:publish --tag=x402-config
```

### Symfony

[](#symfony)

Register the bundle in `config/bundles.php`:

```
return [
    // ...
    SolanaGuide\X402\X402Bundle::class => ['all' => true],
];
```

Setup
-----

[](#setup)

### 1. Configure environment

[](#1-configure-environment)

```
X402_PAY_TO=YourSolanaWalletAddressHere
SOLANA_RPC_URL=https://api.mainnet-beta.solana.com
```

### 2. Initialize the pay-to wallet

[](#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](https://jup.ag) if you already have SOL

This automatically creates the Associated Token Account.

### 3. Verify your setup

[](#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
-------------

[](#configuration)

### Full Config Options

[](#full-config-options)

VariableDefaultDescription`X402_PAY_TO`(required)Solana address to receive payments`X402_ASSET`USDC mainnet mintToken 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 typeUsage
-----

[](#usage)

### Laravel — Middleware Parameter (Simplest)

[](#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

[](#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

[](#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
------------

[](#how-it-works)

1. Client sends a request to a gated route
2. If no `PAYMENT-SIGNATURE` header is present, the middleware returns **HTTP 402** with a `PAYMENT-REQUIRED` header containing payment details (amount, recipient, token, network)
3. Client constructs and signs a Solana SPL Token transfer transaction
4. Client retries the request with the signed transaction in the `PAYMENT-SIGNATURE` header
5. 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
6. On success, the original content is served with a `PAYMENT-RESPONSE` header containing the transaction hash

402 Response Format
-------------------

[](#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
---------------------

[](#spherepay-integration)

For automatic fiat conversion, create a [SpherePay](https://spherepay.co) 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
--------------------

[](#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](https://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
-------

[](#testing)

```
composer test
```

Or directly:

```
vendor/bin/phpunit
```

Architecture
------------

[](#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
-------

[](#credits)

- Solana transaction parsing adapted from [Attestto solana-php-sdk](https://github.com/Attestto-com/solana-php-sdk) (MIT License)
- [x402 Protocol](https://www.x402.org/)

License
-------

[](#license)

MIT License. See [LICENSE](LICENSE) for details.

###  Health Score

30

—

LowBetter than 62% of packages

Maintenance79

Regular maintenance activity

Popularity1

Limited adoption so far

Community2

Small or concentrated contributor base

Maturity33

Early-stage or recently created project

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

110d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/314ff0de149b201ec52a1c848a71446abb0045ee6789632915fc0bc366727761?d=identicon)[solanaguide](/maintainers/solanaguide)

---

Tags

middlewaresymfonylaravelpaymentsolanaUSDCmicropaymentsx402

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/solanaguide-laravel-x402/health.svg)

```
[![Health](https://phpackages.com/badges/solanaguide-laravel-x402/health.svg)](https://phpackages.com/packages/solanaguide-laravel-x402)
```

###  Alternatives

[sebdesign/laravel-viva-payments

A Laravel package for integrating the Viva Payments gateway

4849.3k](/packages/sebdesign-laravel-viva-payments)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
