PHPackages                             johnguoy/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. johnguoy/laravel-x402

ActiveLibrary[Payment Processing](/categories/payments)

johnguoy/laravel-x402
=====================

Laravel SDK for the x402 V2 HTTP payment protocol. Charge AI agents and API clients per request using USDC stablecoins over HTTP.

v1.0.0-rc1(1mo ago)10MITPHPPHP ^8.2

Since Jun 14Pushed 1mo agoCompare

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

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

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

[](#laravel-x402)

[![Latest Version on Packagist](https://camo.githubusercontent.com/f5f81c2453142d9c580cc27d2110c5b3572229a719e88dcd4ee6a105fdce4afd/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6a6f686e67756f792f6c61726176656c2d783430322e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/johnguoy/laravel-x402)[![Tests](https://camo.githubusercontent.com/f298cd6f34e616b0078df322147e1e4c6a12e6edc4d6e7761ac20f4cbf6f1152/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f6a6f686e67756f792f6c61726176656c2d783430322f74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/johnguoy/laravel-x402/actions/workflows/tests.yml)[![Total Downloads](https://camo.githubusercontent.com/579d974d921b38e277881ba95b698d91d160b3ad946c5680e7d5aa0547227e68/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6a6f686e67756f792f6c61726176656c2d783430322e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/johnguoy/laravel-x402)[![License](https://camo.githubusercontent.com/45c7befd3323ef68f4dd4aa7ab1288b28d4f09aa0ceb5878125cdb99376a443d/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f6a6f686e67756f792f6c61726176656c2d783430322e7376673f7374796c653d666c61742d737175617265)](LICENSE.md)

**laravel-x402** is a Laravel SDK for the [x402 V2](https://x402.org) HTTP payment protocol. Protect any API route with a single middleware line and start collecting **USDC micropayments** from AI agents and developer clients — no accounts, no API keys, no subscriptions.

```
Client                  Laravel (you)               Facilitator (Coinbase, etc.)
  |                          |                               |
  |── GET /api/data ─────────▶|                               |
  |                          |── no PAYMENT-SIGNATURE header  |
  |◀── 402 PAYMENT-REQUIRED ──|                               |
  |   (Base64 JSON in header)|                               |
  |                          |                               |
  | [client signs payment]   |                               |
  |                          |                               |
  |── GET /api/data ─────────▶|                               |
  |   PAYMENT-SIGNATURE: ... |── POST /verify ───────────────▶|
  |                          |◀── {isValid: true} ────────────|
  |                          |── POST /settle ───────────────▶|
  |                          |◀── {success, txHash} ──────────|
  |◀── 200 + PAYMENT-RESPONSE─|                               |

```

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

[](#requirements)

DependencyVersionPHP^8.2Laravel^11.0 | ^12.0 | ^13.0BCMath extensionenabled (standard in PHP 8.x)Installation
------------

[](#installation)

```
composer require johnguoy/laravel-x402
```

Laravel's package auto-discovery will register the service provider and `X402` facade automatically.

### Publish the config file

[](#publish-the-config-file)

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

This creates `config/x402.php` in your application where you configure your wallet, networks, and facilitators.

Configuration
-------------

[](#configuration)

Open `config/x402.php` (or set environment variables in `.env`):

```
// config/x402.php

return [

    // Which facilitator to use by default
    'default_facilitator' => env('X402_FACILITATOR', 'coinbase'),

    // Facilitator endpoints
    'facilitators' => [
        'coinbase'   => ['url' => env('X402_COINBASE_URL',   'https://facilitator.cdp.coinbase.com'), 'timeout' => 10],
        'cloudflare' => ['url' => env('X402_CLOUDFLARE_URL', 'https://x402.cloudflare.com'),          'timeout' => 10],
        'stellar'    => ['url' => env('X402_STELLAR_URL',    'https://facilitator.stellar.org'),       'timeout' => 10],
        'dexter'     => ['url' => env('X402_DEXTER_URL',     'https://facilitator.dexter.cash'),       'timeout' => 10],
        'mogami'     => ['url' => env('X402_MOGAMI_URL',     'https://facilitator.mogami.tech'),       'timeout' => 10],
        'testnet'    => ['url' => env('X402_TESTNET_URL',    'https://x402.org/facilitator'),          'timeout' => 15],
    ],

    // Your receiving wallet address (EVM: 0x…, Solana: base58 pubkey)
    'wallet_address' => env('X402_WALLET_ADDRESS'),

    // Default network in CAIP-2 format
    'network' => env('X402_NETWORK', 'eip155:8453'), // Base Mainnet

    // Default payment scheme
    'scheme' => env('X402_SCHEME', 'exact'),

    // On-chain token contract addresses, keyed by symbol then CAIP-2 network
    'assets' => [
        'USDC' => [
            'eip155:8453'  => '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913', // Base Mainnet
            'eip155:84532' => '0x036CbD53842c5426634e7929541eC2318f3dCF7e', // Base Sepolia
            'eip155:1'     => '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', // Ethereum
            'eip155:137'   => '0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359', // Polygon
        ],
    ],

    // Token decimal places (USDC = 6, ETH = 18, SOL = 9, …)
    'decimals' => [
        'USDC' => 6, 'USDT' => 6, 'EURC' => 6,
        'DAI'  => 18, 'ETH' => 18, 'WETH' => 18, 'MATIC' => 18,
        'SOL'  => 9, 'XLM' => 7,
    ],

    'asset'               => env('X402_ASSET', 'USDC'),
    'max_timeout_seconds' => (int) env('X402_MAX_TIMEOUT_SECONDS', 60),
    'description'         => env('X402_DESCRIPTION', 'API access via x402'),
    'mime_type'           => env('X402_MIME_TYPE', 'application/json'),
];
```

### Minimal `.env` for development (testnet)

[](#minimal-env-for-development-testnet)

```
X402_WALLET_ADDRESS=0xYourWalletAddress
X402_NETWORK=eip155:84532
X402_FACILITATOR=testnet
```

### Minimal `.env` for production (Base Mainnet)

[](#minimal-env-for-production-base-mainnet)

```
X402_WALLET_ADDRESS=0xYourWalletAddress
X402_NETWORK=eip155:8453
X402_FACILITATOR=coinbase
```

---

Usage
-----

[](#usage)

### 1. Protect a route with the `x402` middleware

[](#1-protect-a-route-with-the-x402-middleware)

```
// routes/api.php

use Illuminate\Support\Facades\Route;

// Basic: 1 cent per request, defaults from config
Route::get('/api/data', fn () => response()->json(['result' => 'secret']))
    ->middleware('x402:0.01');

// Custom price with explicit asset
Route::get('/api/premium', [ReportController::class, 'daily'])
    ->middleware('x402:0.10,USDC');

// Specify price, asset, and a non-default facilitator
Route::get('/api/pro', [ProController::class, 'data'])
    ->middleware('x402:1.00,USDC,coinbase');

// Group: same price for a whole section of your API
Route::middleware('x402:0.05')->group(function () {
    Route::get('/api/report/daily',  [ReportController::class, 'daily']);
    Route::get('/api/report/weekly', [ReportController::class, 'weekly']);
});
```

**Middleware parameter order:**

```
x402:{price},{asset},{facilitator},{network}

```

All parameters after `price` are optional and fall back to config values.

---

### 2. What clients receive

[](#2-what-clients-receive)

**Step 1 — request without payment (402 response):**

```
HTTP/1.1 402 Payment Required
PAYMENT-REQUIRED: eyJzY2hlbWUiOiJleGFjdCIsIm5ldHdvcmsiOiJlaXAxNTU...
Content-Type: application/json

{
  "error": "Payment required.",
  "accepts": [{
    "scheme": "exact",
    "network": "eip155:8453",
    "maxAmountRequired": "10000",
    "resource": "https://yourapi.com/api/data",
    "description": "API access via x402",
    "mimeType": "application/json",
    "payTo": "0xYourWalletAddress",
    "maxTimeoutSeconds": 60,
    "asset": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
    "extra": { "name": "USDC", "version": "2", "decimals": 6 }
  }]
}
```

**Step 2 — request with payment signature (200 response):**

```
GET /api/data HTTP/1.1
PAYMENT-SIGNATURE:

HTTP/1.1 200 OK
PAYMENT-RESPONSE: eyJzdWNjZXNzIjp0cnVlLCJ0eEhhc2giOiIweGFiYz...
Content-Type: application/json

{"result": "secret"}
```

---

### 3. Use the Facade for advanced scenarios

[](#3-use-the-facade-for-advanced-scenarios)

```
use JohnGuoy\LaravelX402\Facades\X402;

// Resolve a facilitator and call it manually
$facilitator = X402::facilitator('coinbase');
$result = $facilitator->verify($paymentPayload, $requirements);

// Look up an asset contract address
$address = X402::assetAddress('USDC', 'eip155:8453');
// → "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"
```

### 4. Use PaymentAmount for precision math

[](#4-use-paymentamount-for-precision-math)

```
use JohnGuoy\LaravelX402\Support\PaymentAmount;

$amount = app(PaymentAmount::class);

// Human-readable → atomic units (BCMath, no float drift)
$amount->toAtomicUnits('0.01', 'USDC');   // "10000"
$amount->toAtomicUnits('1',    'USDC');   // "1000000"
$amount->toAtomicUnits('1',    'ETH');    // "1000000000000000000"

// Atomic units → human-readable
$amount->fromAtomicUnits('10000',   'USDC');  // "0.010000"
$amount->fromAtomicUnits('1000000', 'USDC');  // "1.000000"

// Parse price strings
$amount->parsePrice('$0.01');        // ['amount' => '0.01', 'symbol' => 'USDC']
$amount->parsePrice('0.01 USDT');    // ['amount' => '0.01', 'symbol' => 'USDT']

// Register a custom token (e.g., 8 decimals)
$amount->register('MYTOKEN', 8);
```

---

Networks &amp; Facilitators
---------------------------

[](#networks--facilitators)

### Supported Networks (CAIP-2)

[](#supported-networks-caip-2)

NetworkCAIP-2Base Mainnet`eip155:8453`Base Sepolia (testnet)`eip155:84532`Ethereum Mainnet`eip155:1`Polygon Mainnet`eip155:137`Avalanche C-Chain`eip155:43114`Solana Mainnet`solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp`Solana Devnet`solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1`### Known Production Facilitators

[](#known-production-facilitators)

KeyURLNotes`coinbase``https://facilitator.cdp.coinbase.com`KYT/OFAC checks`cloudflare``https://x402.cloudflare.com`Edge-native`stellar``https://facilitator.stellar.org`Stellar network only`dexter``https://facilitator.dexter.cash`Free, no account`mogami``https://facilitator.mogami.tech`Free, Base focused`testnet``https://x402.org/facilitator`Dev/testnet only---

Testing
-------

[](#testing)

```
composer test
# or directly:
vendor/bin/phpunit
```

Run only unit or feature tests:

```
vendor/bin/phpunit --testsuite Unit
vendor/bin/phpunit --testsuite Feature
```

---

Changelog
---------

[](#changelog)

See [CHANGELOG.md](CHANGELOG.md).

License
-------

[](#license)

MIT — see [LICENSE.md](LICENSE.md).

Credits
-------

[](#credits)

- Built on the [x402 V2 open specification](https://x402.org) — a Linux Foundation project
- Protocol co-founded by [Coinbase](https://coinbase.com) and [Cloudflare](https://cloudflare.com)

###  Health Score

34

—

LowBetter than 75% of packages

Maintenance91

Actively maintained with recent releases

Popularity2

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity34

Early-stage or recently created project

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

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

Every ~0 days

Total

2

Last Release

45d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/9858c06522c0092863e5f8467f68571c2f08a691b07d9f62e421459b6832a47a?d=identicon)[JohnGuoy](/maintainers/JohnGuoy)

---

Top Contributors

[![JohnGuoy](https://avatars.githubusercontent.com/u/34481947?v=4)](https://github.com/JohnGuoy "JohnGuoy (4 commits)")

---

Tags

laravelpaymentweb3ai-agentcoinbasestablecoinUSDCx402http-402micropaymentbase-chain

###  Code Quality

TestsPHPUnit

Code StyleLaravel Pint

### Embed Badge

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

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

###  Alternatives

[psalm/plugin-laravel

Psalm plugin for Laravel

3345.3M348](/packages/psalm-plugin-laravel)[roots/acorn

Framework for Roots WordPress projects built with Laravel components.

9762.4M134](/packages/roots-acorn)[laravel/mcp

Rapidly build MCP servers for your Laravel applications.

77922.3M189](/packages/laravel-mcp)[api-platform/laravel

API Platform support for Laravel

58174.6k17](/packages/api-platform-laravel)[sebdesign/laravel-viva-payments

A Laravel package for integrating the Viva Payments gateway

4851.0k](/packages/sebdesign-laravel-viva-payments)[fleetbase/core-api

Core Framework and Resources for Fleetbase API

1235.9k21](/packages/fleetbase-core-api)

PHPackages © 2026

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