Laravel MPP: Charge AI Agents for API Access with 402 Payment Required

Last updated on by

Laravel MPP: Charge AI Agents for API Access with 402 Payment Required image

Laravel MPP is middleware that implements the Machine Payments Protocol (MPP), letting you charge AI agents for access to protected routes. It returns an HTTP 402 Payment Required response with a signed challenge; an agent that can pay fulfills the challenge over a supported payment rail and retries the request.

Main features:

  • Two payment rails — Stripe Shared Payment Tokens (SPTs) and Tempo pathUSD
  • Per-route or metered pricing — charge per request, or take one payment that grants multiple accesses
  • HMAC-signed challenges — agents receive a signed 402 challenge to pay and retry
  • Metered sessions — atomic, scope-checked credit balances backed by cache or database
  • Preconditions — named checks that run before the payment gate to reject ineligible requests early

Gating a Route

Attach the mpp middleware to a route with a price and currency. A request without payment gets a 402 challenge back:

Route::get('/resource', MyPaidResource::class)
->middleware('mpp:0.50,USD');

You can also declare pricing with the RequiresPayment attribute on a controller method and let the middleware read it, or enable automatic enforcement with MPP_ATTRIBUTES_ENABLED=true:

#[RequiresPayment(amount: '5.00', currency: 'USD', grants: 10)]
public function report()
{
// ...
}
 
Route::get('/report', ReportController::class)->middleware('mpp');

Metered Sessions

When a payment specifies grants greater than one, a single payment covers multiple accesses. The successful response includes a Payment-Session header with the remaining balance and scope:

Payment-Session: id="sess_...", remaining="9", scope="report.basic", expiresAt="..."

The agent replays the session identifier on later requests instead of paying again:

curl -si https://your-host/report \
-H 'Authorization: Payment method="stripe", session="sess_..."'

Sessions are stored in the cache by default, or in the database for persistence:

MPP_SESSION_DRIVER=cache # Default
MPP_SESSION_DRIVER=database # Persisted; run the published migrations
MPP_SESSION_CACHE_STORE=redis # Optional custom cache store

Preconditions

Preconditions are named checks that run before the payment gate, so you can reject an ineligible request before asking an agent to pay. Register them in config/mpp.php and attach them per route, or run some globally:

// config/mpp.php
'preconditions' => [
'checks' => [
'postexists' => [\App\Mpp\Checks\PostExists::class, 'check'],
],
'global' => ['usernotblocked'],
],

A check returns null to pass, or a Response to short-circuit the request:

class PostExists
{
public function check(Request $request, PaymentSpec $spec): ?Response
{
return Post::find($request->route('post'))
? null
: response()->json(['error' => 'No such post.'], 404);
}
}
Route::get('/posts/{post}', ShowPost::class)
->middleware('mpp:1.00,USD,preconditions=postexists');

Payment Rails

The package ships with two rails. Stripe uses Shared Payment Tokens (SPTs), configured with your Stripe keys and the preview API version:

STRIPE_SECRET_KEY=sk_test_...
STRIPE_NETWORK_ID=profile_...
STRIPE_API_VERSION=2026-05-27.preview

Tempo settles in pathUSD on-chain. Select it per route with method=tempo:

Route::get('/paid', fn () => response()->json(['data' => 'paid']))
->middleware('mpp:0.01,USD,method=tempo,scope=paid');

You can accept multiple rails on one route with methods=stripe|acme, and register a custom rail by implementing the Verifier interface. On a paid request, the response carries a Payment-Receipt header identifying the method, amount, and reference.

Installation

Install via Composer and publish the config:

composer require square1/laravel-mpp
php artisan vendor:publish --tag=mpp-config

For metered sessions on the database driver, publish and run the migrations:

php artisan vendor:publish --tag=mpp-migrations
php artisan migrate

Note that MPP and the Stripe SPT APIs are still in preview and may change. The latest release is v1.1.0 is MIT licensed; you can find it on GitHub.

Paul Redmond photo

Staff writer at Laravel News. Full stack web developer and author.

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

image
Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Visit Laravel Cloud
Laravel Cloud logo

Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Cloud
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit
Harpoon: Next generation time tracking and invoicing logo

Harpoon: Next generation time tracking and invoicing

The next generation time-tracking and billing software that helps your agency plan and forecast a profitable future.

Harpoon: Next generation time tracking and invoicing
PhpStorm logo

PhpStorm

The go-to PHP IDE with extensive out-of-the-box support for Laravel and its ecosystem.

PhpStorm
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Acquaint Softtech logo

Acquaint Softtech

Acquaint Softtech offers AI-ready Laravel developers who onboard in 48 hours at $3000/Month with no lengthy sales process and a 100 percent money-back guarantee.

Acquaint Softtech
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
No Compromises logo

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $9500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum

The latest

View all →
What's missing from your PHP development environment image

What's missing from your PHP development environment

Read article
EnvKit: A Local Development Stack for Laravel on Windows and macOS image

EnvKit: A Local Development Stack for Laravel on Windows and macOS

Read article
A Copy/Paste Detector CLI for PHP 8.5+ image

A Copy/Paste Detector CLI for PHP 8.5+

Read article
Commune: A Private Community for Founders and Builders image

Commune: A Private Community for Founders and Builders

Read article
 Laravel AI Tasks: An AI Orchestration Package for Queues, Logging, and Cost Control image

Laravel AI Tasks: An AI Orchestration Package for Queues, Logging, and Cost Control

Read article
Worker Metrics on the WorkerStopping Event in Laravel 13.18 image

Worker Metrics on the WorkerStopping Event in Laravel 13.18

Read article