Short answer
Install leverprice/leverprice-php, bind one Leverprice singleton, and exclude __pp and __pp_f from cookie encryption in bootstrap/app.php. In the controller, call getPrice() with the request and return $quote->applyCookiesTo(response()->view(...)). At checkout, price again and pass $quote->price and the whole $quote->metadata to Stripe Checkout. Then connect Stripe's webhook to Leverprice.
- EncryptCookies encrypts every cookie on the response, which breaks the HMAC-signed __pp cookie; list __pp and __pp_f in encryptCookies(except: [...]).
- The view() helper returns a View, not a response, so return response()->view() through applyCookiesTo().
- After php artisan config:cache Laravel stops loading .env, so read the keys through config().
- Laravel 13's CSRF middleware is PreventRequestForgery; exclude only your own Stripe webhook route from it.
- Under Octane there is no per-request shutdown, so call terminate() when each request ends.
Laravel encrypts every cookie your app sends, and for a price test that default has to change. The Leverprice visitor cookie is already HMAC-signed; an encrypted copy fails verification when it comes back, so every page view starts a new visitor with a fresh draw of the price. The fix is one line in bootstrap/app.php, and this guide puts it next to everything else a Laravel price test needs.
The code targets Laravel 13 (PHP 8.3+), stripe-php 23 and leverprice/leverprice-php, which runs on PHP 8.1+.
How does price testing work in a Laravel app?
Your server decides the price. getPrice() reads the visitor's __pp cookie and user agent from the Laravel Request, picks their price from a signed config, checks it against bounds you set in code and returns a Quote: price in minor units (2900 is $29.00), currency, signed metadata and a list of Set-Cookie values. No Leverprice JavaScript runs in the browser.
PHP starts every request from scratch, so the SDK keeps the verified config in a cache shared by your workers: APCu or a temp file by default, or any PSR-16 store you pass, Laravel's cache included. Every load re-verifies the signature chain, so a tampered cache cannot change a price. The checkout controller calls getPrice() again and gets the same answer from the signed cookie. For why this has to happen on the server, see server-side price testing.
How do I install the SDK in Laravel?
composer require leverprice/leverprice-php stripe/stripe-phpLEVERPRICE_SECRET_KEY=pp_sk_test_...
STRIPE_SECRET=sk_test_...
STRIPE_WEBHOOK_SECRET=whsec_...Route every value through config/services.php. Laravel's configuration docs warn that once config:cache runs, "the .env file will not be loaded", so env() belongs in config files only:
// Inside the array that config/services.php returns:
'leverprice' => [
'secret' => env('LEVERPRICE_SECRET_KEY'),
'disabled' => (bool) env('LEVERPRICE_DISABLED', false),
'products' => [
// Guardrails in minor units: a price outside them is never returned.
'pro' => ['currency' => 'usd', 'fallbackPrice' => 2900, 'minPrice' => 1900, 'maxPrice' => 4900],
],
],
'stripe' => [
'secret' => env('STRIPE_SECRET'),
'webhook_secret' => env('STRIPE_WEBHOOK_SECRET'),
],Bind one client per worker as a singleton, and hand it Laravel's cache so all workers share one verified config:
use Leverprice\Leverprice;
use Stripe\StripeClient;
public function register(): void
{
$this->app->singleton(Leverprice::class, fn () => new Leverprice([
'secretKey' => config('services.leverprice.secret'),
'disabled' => config('services.leverprice.disabled'),
'products' => config('services.leverprice.products'),
'cache' => cache()->store(), // any PSR-16 cache
]));
$this->app->singleton(StripeClient::class, fn () => new StripeClient(config('services.stripe.secret')));
}fallbackPrice is what visitors pay when Leverprice cannot answer: no key, the kill switch, or no signed config within 500 ms. getPrice() never throws for those reasons, only for a product key missing from products. The SDK docs cover the remaining options.
Why must Laravel leave the Leverprice cookie unencrypted?
Because EncryptCookies encrypts every cookie in the response's header bag on its way out, and that includes the Set-Cookie values the SDK adds. Laravel's response docs say all cookies it generates "are encrypted and signed so that they can't be modified or read by the client". The browser then returns ciphertext, the SDK's HMAC check fails, and each request starts over as a new visitor.
Exclude both names in bootstrap/app.php:
->withMiddleware(function (Middleware $middleware): void {
$middleware->encryptCookies(except: ['__pp', '__pp_f']);
})The docs add that "cookie encryption should never be disabled" in general, and the advice holds for your own cookies. These two are different: __pp carries its own HMAC signature, and the __pp_f outage pin can only select your own fallback price. If you renamed the cookie with the cookieName option, list the new name and its _f twin. An app upgraded from Laravel 10 that still has app/Http/Middleware/EncryptCookies.php takes the same names in its $except array.
How do I show the tested price in a Laravel controller?
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Leverprice\Leverprice;
class PricingController extends Controller
{
public function show(Request $request, Leverprice $leverprice)
{
$quote = $leverprice->getPrice('pro', ['request' => $request, 'userId' => $request->user()?->id]);
return $quote->applyCookiesTo(response()->view('pricing', ['quote' => $quote]));
}
}<p class="price">{{ number_format($quote->price / 100, 2) }} {{ strtoupper($quote->currency) }}</p>
<form method="POST" action="{{ route('checkout') }}">
@csrf
<button type="submit">Buy Pro</button>
</form>use App\Http\Controllers\CheckoutController;
use App\Http\Controllers\PricingController;
use Illuminate\Support\Facades\Route;
Route::get('/pricing', [PricingController::class, 'show'])->name('pricing');
Route::post('/checkout', CheckoutController::class)->name('checkout');Return response()->view(), not view(). The helper gives you a View, which Laravel turns into a response after your controller returns, so there is nothing to attach a header to; the view responses section points to response()->view() whenever you need headers. applyCookiesTo() adds each value with headers->set('Set-Cookie', $cookie, false). Avoid withHeaders(['Set-Cookie' => ...]), which replaces Set-Cookie headers already on the response.
userId puts a signed-in customer in the same bucket on every device, and only an HMAC of it leaves your server. Pass it the same way in every controller that prices the product.
How do I charge the same price with Stripe Checkout?
Price the checkout on the server again and ignore any amount in the request. Stripe's price_data takes the amount inline, so you need no Stripe Price per tested price:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Leverprice\Leverprice;
use Stripe\StripeClient;
class CheckoutController extends Controller
{
public function __invoke(Request $request, Leverprice $leverprice, StripeClient $stripe)
{
$quote = $leverprice->getPrice('pro', ['request' => $request, 'userId' => $request->user()?->id]);
$session = $stripe->checkout->sessions->create([
'mode' => 'payment',
'line_items' => [[
'quantity' => 1,
'price_data' => [
'currency' => $quote->currency,
'unit_amount' => $quote->price,
'product_data' => ['name' => 'Pro'],
],
]],
'metadata' => $quote->metadata, // signed attribution: pass it whole
'payment_intent_data' => ['metadata' => $quote->metadata],
'success_url' => url('/thanks'),
'cancel_url' => route('pricing'),
]);
return $quote->applyCookiesTo(redirect()->away($session->url));
}
}redirect()->away() sends the browser to Stripe "without any additional URL encoding, validation, or verification", per the redirect docs. $quote->metadata holds pp_exp, pp_var, pp_vid and pp_sig, signed together, so it goes into Stripe whole.
The form keeps @csrf: Laravel 13's PreventRequestForgery middleware checks Sec-Fetch-Site first and falls back to the token (CSRF docs). Using Cashier? Bind StripeClient to Cashier::stripe(), which returns the client Cashier already configured (Cashier docs), and the controller stays the same.
Selling a subscription? Set 'mode' => 'subscription', add 'recurring' => ['interval' => 'month'] to price_data, and move the metadata copy into subscription_data, since the Checkout Session API takes payment_intent_data only in payment mode. Leverprice's Stripe verification covers one-time payments, so a subscription's first payment must be reported with trackPurchase() from your own webhook controller, below; it shows as unverified, and renewals never count toward a test.
Other providers take the same two rules. Polar accepts an ad-hoc price per checkout, and Leverprice verifies one-time orders and a subscription's first payment there. Lemon Squeezy takes custom_price in cents but stops processing payments on March 31, 2027. Dodo Payments takes a custom amount only on pay-what-you-want products, with one-time payments verified.
Can I show a different price per country?
Yes. With regional prices on in the dashboard, each country gets a price you set by hand or one derived from its tier (5 tiers by World Bank price level), in the currency it pays in. Example: ₹999 in India where the US sees $29. Add the country header and a regional guard:
'leverprice' => [
'secret' => env('LEVERPRICE_SECRET_KEY'),
'disabled' => (bool) env('LEVERPRICE_DISABLED', false),
'country_header' => 'cf-ipcountry', // Cloudflare; CloudFront: cloudfront-viewer-country
'products' => [
'pro' => [
'currency' => 'usd', 'fallbackPrice' => 2900, 'minPrice' => 1900, 'maxPrice' => 4900,
'regional' => [ // currencies you accept, each with hard bounds
'usd' => ['minPrice' => 800, 'maxPrice' => 4900],
'eur' => ['minPrice' => 1100, 'maxPrice' => 6000],
'inr' => ['minPrice' => 48000, 'maxPrice' => 230000],
],
],
],
],Then pass 'countryHeader' => config('services.leverprice.country_header') in the singleton. There is no default header, on purpose: one that visitors can send themselves would let them choose their price, so name only a header your CDN overwrites, or pass 'country' to getPrice() from your own lookup. Unlisted currencies, prices outside their bounds, bots and unknown countries get the standard price.
The checkout already sends $quote->currency to Stripe; confirm your account can charge in each listed currency. Blade's / 100 suits two-decimal currencies only: JPY has no minor unit, per Stripe's zero-decimal list.
How does Leverprice verify revenue from Stripe?
Stripe sends its signed webhooks to Leverprice directly. In the dashboard, open Payments and connect Stripe to get an endpoint URL. Add it in Stripe for checkout.session.completed, checkout.session.async_payment_succeeded and charge.refunded, then paste that endpoint's signing secret into Leverprice.
A signing secret can confirm events but cannot move money, so never paste an API key. If Cashier already receives webhooks at /stripe/webhook, leave it alone: Stripe delivers each event to every endpoint subscribed to it (up to 16 per account). Details on the Stripe integration page.
Write your own controller only if you cannot add an endpoint or you sell subscriptions. Its revenue is labeled unverified and never overrides a verified purchase:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Leverprice\Leverprice;
use Stripe\Exception\SignatureVerificationException;
use Stripe\Webhook;
class StripeWebhookController extends Controller
{
private const PAID = ['checkout.session.completed', 'checkout.session.async_payment_succeeded'];
public function __invoke(Request $request, Leverprice $leverprice)
{
try {
$event = Webhook::constructEvent(
$request->getContent(),
$request->header('Stripe-Signature', ''),
config('services.stripe.webhook_secret'),
);
} catch (\UnexpectedValueException|SignatureVerificationException) {
abort(400);
}
if (in_array($event->type, self::PAID, true) && $event->data->object->payment_status === 'paid') {
$session = $event->data->object;
$leverprice->trackPurchase([
'provider' => 'stripe',
'orderId' => $session->payment_intent ?? $session->invoice, // invoice: subscription mode
'amount' => $session->amount_total - ($session->total_details->amount_tax ?? 0),
'currency' => $session->currency,
'metadata' => $session->metadata,
'timestamp' => $event->created,
]);
}
return response()->noContent();
}
}Route it with Route::post('/webhooks/stripe', StripeWebhookController::class) and exempt only that path from request forgery protection, as the CSRF docs show for Stripe:
->withMiddleware(function (Middleware $middleware): void {
$middleware->encryptCookies(except: ['__pp', '__pp_f']);
$middleware->preventRequestForgery(except: ['webhooks/stripe']);
})How do I test it locally?
Serve the app with php artisan serve and test keys, connect a test-mode Stripe endpoint in Leverprice, then:
- Load the pricing page, note the price, reload. It must not change.
- Check the
__ppcookie in your browser's dev tools. A value starting witheyJpdiI6(base64 for{"iv":) means Laravel encrypted it and the exclusion is missing. - Click Buy and compare Stripe's amount with the page. Pay with a card from Stripe's testing docs, such as 4242 4242 4242 4242.
- Remove
LEVERPRICE_SECRET_KEYand reload: the fallback price appears and nothing breaks.
php artisan serve listens on plain HTTP and the cookie is Secure by default. MDN documents the HTTPS exception only for localhost, so on a LAN address pass 'cookieSecure' => false in local development. Keep feature tests offline with <env name="LEVERPRICE_DISABLED" value="1"/> in phpunit.xml.
What changes in production?
Run php artisan config:cache as usual; with every key read through config(), nothing breaks. Swap in pp_sk_live_… and your live Stripe key, and connect the live-mode Stripe endpoint in Leverprice with its own signing secret. To switch the test off, set LEVERPRICE_DISABLED=1 in the server's real environment, which the SDK checks on every call, or in .env followed by config:cache.
Under PHP-FPM the SDK sends queued exposures after the response, through fastcgi_finish_request(), so visitors never wait for them. Octane keeps workers alive between requests and has no per-request shutdown, so finish the background work yourself in AppServiceProvider::boot():
use Illuminate\Support\Facades\Event;
use Laravel\Octane\Events\RequestTerminated;
Event::listen(RequestTerminated::class, fn () => app(Leverprice::class)->terminate());What breaks most often?
| Symptom | Likely cause | Fix |
|---|---|---|
| Price changes on every reload | EncryptCookies encrypted __pp | encryptCookies(except: ['__pp', '__pp_f']) |
No __pp cookie at all | Controller returns view() | Return $quote->applyCookiesTo(response()->view(...)) |
| 419 on the Buy button | Form lacks @csrf | Add it |
| 419 on your own Stripe webhook | Route not exempt from request forgery protection | preventRequestForgery(except: ['webhooks/stripe']) |
| Fallback price everywhere after a deploy | env() called outside config files, so values vanish after config:cache | Read keys through config() |
| Exposures stop under Octane | terminate() never runs | Listen for RequestTerminated |
| Test runs show up as visitors | Feature tests price with a real key | LEVERPRICE_DISABLED=1 in phpunit.xml |
Frequently asked questions
Does this work with Inertia?
Yes. Inertia::render() returns a Responsable, so turn it into a response first: $quote->applyCookiesTo(Inertia::render('Pricing', ['price' => $quote->price, 'currency' => $quote->currency])->toResponse($request)). Pass only the fields the page needs: the full quote also carries the Set-Cookie value, which page props would expose to JavaScript.
How do I price monthly and yearly plans on one page?
Give each plan its own product key, call getPrice() for both with the same $request, and apply both quotes' cookies. They share one visitor, and the last cookie carries every assignment.
Does Symfony work the same way?
Yes. The SDK reads a Symfony Request the same way, and applyCookiesTo() accepts a Symfony response. Symfony doesn't encrypt cookies by default, so the EncryptCookies step is Laravel-only. Rails has its own pitfalls, covered in the Rails guide.
What happens when the test ends?
You lock in the winner in the dashboard, and every visitor gets it within about a second. The Laravel code stays as it is.