Laravel Stripe payment gateway integration, rebuilt for Laravel 12 and 13
If you followed a Laravel 8 Stripe tutorial, the payment code probably took a card token from Stripe.js and turned it into a charge on your server. That pattern no longer works for new integrations. Stripe has deprecated card payments on the Charges API and says plainly that "new integrations can't use the Charges API to create payments".
This guide rebuilds the Laravel Stripe payment gateway integration the way Stripe expects it now. You get a Checkout Session created on your server, a signed webhook that confirms the money arrived, and fulfillment code that's safe to run twice. The code targets Laravel 12 and 13 as of October 2026. If you're still on Laravel 8, there's a short section on what changes for you further down.
Two routes to a Laravel Stripe payment gateway integration
There are two sensible ways to do payment gateway integration in Laravel with Stripe. Both send customers to a Stripe-hosted payment page, and both need the same webhook discipline. The difference is how much Laravel code you write yourself.
Laravel Cashier (laravel/cashier) |
Stripe PHP library (stripe/stripe-php) |
|
|---|---|---|
| Best fit | Subscriptions, invoices and billing tied to a user account | One-time orders, guest checkout and custom order flows |
| What you add | Billable trait on your user model plus Cashier's migrations |
Your own orders table, a controller and a webhook handler |
| Webhooks | Built-in route at /stripe/webhook with signature checks |
You write the handler and verify the signature |
| Stripe SDK | Cashier 16 accepts stripe-php up to 21.x | Latest release, 22.1.0 as of October 29, 2026 |
| Laravel versions | 10 through 13, PHP 8.1 or later | Any Laravel version on PHP 7.4 or later |
Selling a product catalog or one-off services? The direct route keeps everything visible in your own code, so the steps below use it. Cashier gets its own section after the steps, because for subscription billing it saves a lot of work.
Before you start
- Laravel 12 or 13. Laravel 13 requires PHP 8.3 and gets security fixes until March 17, 2028. Laravel 12's security fixes run to February 24, 2027.
- A Stripe account with a sandbox. Sandbox keys start with
pk_test_(publishable) andsk_test_orrk_test_(secret and restricted). Stripe recommends restricted keys over full secret keys for new server code, scoped to the permissions your integration needs. - The Stripe CLI. You'll use it to forward webhook events to your laptop.
- HTTPS in production. Stripe's integration security guide requires TLS 1.2 or later on payment pages, and live webhook endpoints must be HTTPS.
- A Price for each product. Create Products and Prices in the Stripe Dashboard and store each Price ID (
price_...) against your own product record. Stripe advises keeping price and availability on your server so customers can't change them from the browser.
Step 1: Install the Stripe PHP library
composer require stripe/stripe-php
Version 22.1.0 pins Stripe API version 2026-10-28.endive, according to the stripe-php changelog. The pinned version decides the shape of every response, so read the changelog before you jump a major version.
Step 2: Store your keys and register the client
Put the keys in .env, never in code or anything committed to Git:
STRIPE_KEY=pk_test_...
STRIPE_SECRET=rk_test_...
STRIPE_WEBHOOK_SECRET=whsec_...
Map them in config/services.php:
'stripe' => [
'key' => env('STRIPE_KEY'),
'secret' => env('STRIPE_SECRET'),
'webhook_secret' => env('STRIPE_WEBHOOK_SECRET'),
],
Then bind one StripeClient in AppServiceProvider::register() so controllers and jobs can type-hint it:
use Stripe\StripeClient;
$this->app->singleton(StripeClient::class, fn () => new StripeClient(
config('services.stripe.secret')
));
Reading keys through config() rather than env() matters once you run php artisan config:cache in production. After caching, Laravel stops loading .env, so env() calls outside config files only see system-level variables.
Step 3: Create the order and the Checkout Session
Create the order in your database first, with a pending status. Then ask Stripe for a Checkout Session and redirect the customer to its URL.
namespace App\Http\Controllers;
use App\Models\Order;
use App\Models\Product;
use Illuminate\Http\Request;
use Stripe\StripeClient;
class CheckoutController extends Controller
{
public function store(Request $request, StripeClient $stripe)
{
$product = Product::findOrFail($request->integer('product_id'));
$order = Order::create([
'user_id' => $request->user()?->id,
'product_id' => $product->id,
'status' => 'pending',
]);
$session = $stripe->checkout->sessions->create([
'mode' => 'payment',
'line_items' => [[
'price' => $product->stripe_price_id,
'quantity' => 1,
]],
'client_reference_id' => (string) $order->id,
'success_url' => route('checkout.success').'?session_id={CHECKOUT_SESSION_ID}',
'cancel_url' => route('checkout.cancel'),
], ['idempotency_key' => 'checkout-order-'.$order->id]);
$order->update(['stripe_session_id' => $session->id]);
return redirect()->away($session->url, 303);
}
}
Three details carry most of the weight here:
client_reference_idties the session to your order. Stripe describes it as a field for reconciling the session with your internal systems.{CHECKOUT_SESSION_ID}is a literal placeholder. Stripe swaps in the real session ID when it redirects the customer back.- The idempotency key makes a retried request return the original session instead of creating a second one. Stripe's idempotency docs say every
POSTaccepts a key of up to 255 characters, and keys can be pruned once they're at least 24 hours old.
Checkout shows cards and the other payment methods you've switched on in the Dashboard, so there's no payment_method_types list to maintain in code.
Step 4: Add the routes and open a gap in CSRF protection
use App\Http\Controllers\CheckoutController;
use App\Http\Controllers\StripeWebhookController;
Route::post('/checkout', [CheckoutController::class, 'store'])->name('checkout.store');
Route::get('/checkout/success', [CheckoutController::class, 'success'])->name('checkout.success');
Route::view('/checkout/cancel', 'checkout.cancel')->name('checkout.cancel');
Route::post('/webhooks/stripe', StripeWebhookController::class)->name('webhooks.stripe');
Stripe can't send your CSRF token, so the webhook route has to be excluded. On Laravel 13, do it in bootstrap/app.php:
->withMiddleware(function (Middleware $middleware): void {
$middleware->preventRequestForgery(except: [
'webhooks/stripe',
]);
})
On Laravel 12 the method is validateCsrfTokens(except: [...]). Exclude only this one path. The signature check in the next step is what protects it instead.
Step 5: Verify the webhook signature
This is the step most older tutorials skip, and it's the one that decides whether money and orders stay in sync.
namespace App\Http\Controllers;
use App\Jobs\FulfillCheckout;
use Illuminate\Http\Request;
use Stripe\Exception\SignatureVerificationException;
use Stripe\Exception\UnexpectedValueException;
use Stripe\Webhook;
class StripeWebhookController extends Controller
{
public function __invoke(Request $request)
{
try {
$event = Webhook::constructEvent(
$request->getContent(),
$request->header('Stripe-Signature'),
config('services.stripe.webhook_secret'),
);
} catch (UnexpectedValueException|SignatureVerificationException $e) {
return response('Invalid webhook', 400);
}
if (in_array($event->type, [
'checkout.session.completed',
'checkout.session.async_payment_succeeded',
], true)) {
FulfillCheckout::dispatch($event->data->object->id);
}
return response('', 200);
}
}
$request->getContent() passes the raw body. Stripe's webhook guide warns that any change to the raw body makes signature verification fail. The library also rejects signatures older than 5 minutes by default, which blocks replayed requests.
The second event type matters for US buyers who pay by ACH Direct Debit. Delayed payment methods fire checkout.session.async_payment_succeeded when the funds actually clear, after the session has already completed.
Dispatching a queued job keeps the response fast. Stripe asks for a 2xx before any slow work, and a timed-out delivery counts as a failure.
Step 6: Fulfill the order once, even when Stripe calls twice
Stripe's own fulfillment guide says your function might be called multiple times, possibly concurrently, for the same session. Webhooks can arrive twice, out of order, or after the customer has already landed on your success page. Design for all three.
namespace App\Jobs;
use App\Models\Order;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\DB;
use Stripe\StripeClient;
class FulfillCheckout implements ShouldQueue
{
use Queueable;
public function __construct(public string $sessionId) {}
public function handle(StripeClient $stripe): void
{
$session = $stripe->checkout->sessions->retrieve(
$this->sessionId, ['expand' => ['line_items']]
);
if ($session->payment_status === 'unpaid') {
return; // ACH and other delayed methods settle later
}
DB::transaction(function () use ($session) {
$order = Order::where('stripe_session_id', $session->id)
->lockForUpdate()
->firstOrFail();
if ($order->status === 'paid') {
return; // already fulfilled
}
$order->update(['status' => 'paid']);
// Ship goods, grant access, send the receipt, adjust stock.
});
}
}
The row lock plus the status check is what makes this safe. Two workers can pick up two copies of the same event, and only one of them will ever mark the order paid.
Stripe also recommends calling the same fulfillment code from your success page, because webhooks are sometimes delayed. In CheckoutController::success(), run FulfillCheckout::dispatchSync($request->query('session_id')) and then render the receipt. The webhook still has to exist: a customer can pay and lose their connection before your success page ever loads.
Step 7: Test locally with the Stripe CLI and test cards
Start Laravel with php artisan serve, then forward events to it in a second terminal:
stripe login
stripe listen --forward-to localhost:8000/webhooks/stripe
The CLI prints a whsec_... signing secret. Put it in STRIPE_WEBHOOK_SECRET and run php artisan config:clear. Then pay through Checkout with Stripe's test cards, any future expiry date such as 12/34, and any 3-digit CVC:
| Scenario | Card number |
|---|---|
| Payment succeeds | 4242 4242 4242 4242 |
| Bank asks for 3D Secure authentication | 4000 0025 0000 3155 |
| Declined: insufficient funds | 4000 0000 0000 9995 |
| Declined: generic decline | 4000 0000 0000 0002 |
Watch for three things: the CLI shows checkout.session.completed forwarded with a 200, your queue worker runs the job, and the order flips to paid exactly once. Stripe's Services Agreement prohibits testing in live mode with real card details, so keep all of this in the sandbox.
Step 8: Go live without surprises
- Swap the keys. Live keys start with
pk_live_,rk_live_orsk_live_. Store them in your host's secrets manager or environment, not in the repo. - Register the production webhook endpoint in the Webhooks tab of Stripe Workbench, subscribed only to the events you handle. The live signing secret is different from the CLI one and from the sandbox one.
- Run a queue worker in production, or
FulfillCheckout::dispatch()will sit in the queue unprocessed. - Expect retries. In live mode Stripe retries failed deliveries for up to three days with exponential backoff, and it doesn't guarantee event order. Your idempotent job already copes with both.
- Check your Content Security Policy. If you send one, Stripe lists the
checkout.stripe.comdirectives that Checkout needs.
The Cashier route: less code for subscriptions
Laravel Cashier wraps the same Stripe objects behind methods on your user model. It's the better choice when you sell subscriptions, need invoices, or want customers to manage their own billing.
composer require laravel/cashier
php artisan vendor:publish --tag="cashier-migrations"
php artisan migrate
Add the Laravel\Cashier\Billable trait to your User model and set STRIPE_KEY, STRIPE_SECRET and STRIPE_WEBHOOK_SECRET in .env. A one-time Checkout for a Dashboard product then looks like this:
Route::get('/checkout', function (Request $request) {
return $request->user()->checkout(['price_deluxe_album' => 1], [
'success_url' => route('checkout-success'),
'cancel_url' => route('checkout-cancel'),
]);
})->name('checkout');
A few Cashier specifics trip people up:
- Webhooks. Cashier listens at
/stripe/webhook. Runphp artisan cashier:webhookto create the endpoint with every event Cashier needs, and excludestripe/*from CSRF protection. Signature checks switch on onceSTRIPE_WEBHOOK_SECRETis set. - One-time orders. Cashier's default event list is about subscriptions and invoices. For product orders, enable
checkout.session.completedand handle it in a listener forLaravel\Cashier\Events\WebhookReceived. - Guests.
Checkout::guest()->create(...)starts a session for visitors without an account. - Ad hoc amounts.
checkoutCharge()works without a Dashboard product, but Cashier notes it creates a new product and price in Stripe every time. Create products up front instead. - SDK version. Cashier 16's
composer.jsonallows stripe-php^17.4through^21.0, and the Cashier docs give 21.x as using API version2026-08-26.dahlia. Don't require stripe-php 22 separately in the same app, or Composer won't resolve.
Still on Laravel 8? What changes for Stripe
Plenty of production apps still run Stripe on Laravel 8, so start with the support dates. Laravel 8's security fixes ended on January 24, 2023, and it supports PHP 7.3 to 8.1.
The direct route above still works on Laravel 8 if the server runs PHP 7.4 or later, which stripe-php needs. Two things differ. You exclude the webhook from CSRF in the $except array of app/Http/Middleware/VerifyCsrfToken.php, and the queue job uses the older trait set (Dispatchable, InteractsWithQueue, Queueable, SerializesModels). Current Cashier is out of reach, because Cashier 16 requires Laravel 10 or later.
Treat that as a stopgap. A payment flow is exactly the code you don't want running on a framework that no longer gets security patches. Plan the framework upgrade alongside the Stripe migration, and see securing a Laravel application for the version-by-version support picture.
Other payment gateways in Laravel
Laravel's first-party billing packages cover two providers: Cashier for Stripe and Cashier Paddle. For any other gateway, you'll usually work from the provider's own PHP SDK or REST API, and community packages vary a lot in upkeep.
Whatever gateway you pick, the same four habits from this guide carry over:
- Create the payment on the server, with amounts read from your database, not the browser.
- Send card entry to the provider's hosted page or embedded fields so card numbers never touch your server.
- Treat the signed webhook as the source of truth, never the redirect.
- Make fulfillment idempotent and keyed to your own order ID.
The second habit has a real compliance payoff. Stripe's security guide says businesses that handle raw card data directly may need to meet more than 300 security controls in PCI DSS. Hosted fields keep most of that off your plate, though you still attest to PCI compliance once a year.
Hosted Checkout won't suit every storefront. Some designs need a fully custom card form inside your page. The Payment Element and the Payment Intents API give you that control, at the cost of more front-end code and more testing.
Moving an existing app off the Charges API
Still running a Laravel app on the Charges API? Start with an inventory: every place that creates a charge, stores a card token or trusts a redirect. Each one maps to a step above, and the webhook and fulfillment job usually take the most care. Our Laravel developers can run that audit and move the flow to Checkout and webhooks, whether it powers a custom app or a full ecommerce storefront. Tell us what your checkout runs on.
FAQ
Is Stripe free to integrate with Laravel?
The libraries cost nothing: stripe-php and Laravel Cashier are both open source. Stripe says it doesn't charge setup fees, monthly fees or closure fees on standard pricing, so you pay per successful transaction. Rates vary by country and payment method, so check the pricing page for the country your Stripe account is registered in.
How does 3D Secure work in a Laravel Stripe integration?
With Checkout, Stripe shows the bank's authentication step on its own page, so your Laravel code doesn't change. If you charge a saved card with Cashier's charge() method instead, catch the IncompletePayment exception and redirect to Cashier's cashier.payment route. There, the customer completes the extra step.
How do I refund a Stripe payment from Laravel?
With the Stripe PHP library, call $stripe->refunds->create(['payment_intent' => $paymentIntentId]), adding amount in cents for a partial refund. With Cashier, $user->refund($paymentIntentId) does the same thing. Store the Payment Intent ID from the Checkout Session on your order so a refund never means searching the Dashboard.
Can I build my own card form instead of using Stripe Checkout?
Yes. Create a Payment Intent on the server, send its client secret to the browser, and collect card details with Stripe.js and the Payment Element. Cashier's pay() method returns that client secret for you. You still need the same signed webhook to confirm payment before you fulfill the order.
Related reading
Embedded systems programming: how firmware is structured, written and testedJuly 28, 2021 · 12 min read
eLearning management systems: 18 LMS platforms grouped by who you trainDecember 16, 2024 · 13 min read