Valid number
send-icon
By submitting this form, you agree to the processing of your personal data by Zignuts Technolab as outlined in our Privacy Policy.
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
Software Development

How to Integrate Stripe Payment Gateway in Laravel (Step-by-Step Guide)

Blog bannerBlog banner

Hey there! 👋 If you're reading this, you're probably looking to add payment processing to your Laravel application. I recently implemented Stripe in one of my projects, and I thought I'd share my experience to help fellow developers avoid some of the headaches I encountered.

Why Stripe?

Before diving in, you might be wondering why I chose Stripe. Well, besides their excellent documentation and developer-friendly API, Stripe has become something of an industry standard. Their PHP SDK is rock-solid, and the Laravel integration is pretty straightforward. Plus, their test mode is fantastic for development.

Let's Get Started!

First things first, make sure you have:

  • A Laravel project up and running (I'm using Laravel 11+)
  • A Stripe account (grab one for free at stripe.com if you haven't already)
  • Your favorite code editor
  • A cup of coffee ☕

Step 1: Set Up Laravel and Install Stripe

First, set up a fresh Laravel project if you don’t already have one:

Code

    composer create-project --prefer-dist laravel/laravel stripe-checkout
            

Navigate to the project directory:

Code

    cd stripe-checkout
            

Next, install the Stripe PHP package using Composer:

Code

    composer require stripe/stripe-php
            

Step 2: Configure Stripe API Keys

To integrate Stripe with Laravel, you need to configure your API keys. Obtain these keys from your Stripe Dashboard.

Add the keys to your .env file:

Code

    STRIPE_KEY=your_stripe_publishable_key
    STRIPE_SECRET=your_stripe_secret_key
            

Update the config/services.php file with Stripe settings:

Code

                'stripe' => [
                'secret' => env('STRIPE_SECRET'),
                'key' => env('STRIPE_KEY'),
            ],
            

Step 3: Define Routes for Payment

In routes/web.php, add the necessary routes for handling the payment page and initiating Stripe Checkout.

Code

    use App\Http\Controllers\PaymentController;

    Route::get('/payment', [PaymentController::class, 'index'])->name('payment.form');
    Route::post('/checkout', [PaymentController::class, 'checkout'])->name('payment.checkout');
    Route::get('/success', function () {
        return "Payment Successful!";
    })->name('payment.success');
    Route::get('/cancel', function () {
        return "Payment Canceled!";
    })->name('payment.cancel');
            

Step 4: Create a Payment Controller

Next, create a Payment Controller to manage the payment flow.

Code

    php artisan make:controller PaymentController
            

Now, update the PaymentController with the methods to display the payment form and handle the Stripe Checkout session.

Code

    namespace App\Http\Controllers;

    use Illuminate\Http\Request;
    use Stripe\Stripe;
    use Stripe\Checkout\Session;
    
    class PaymentController extends Controller
    {
        public function index()
        {
            return view('payment');
        }
    
        public function checkout(Request $request)
        {
            Stripe::setApiKey(env('STRIPE_SECRET'));
    
            try {
                $session = Session::create([
                    'payment_method_types' => ['card'],
                    'line_items' => [[
                        'price_data' => [
                            'currency' => 'usd',
                            'product_data' => [
                                'name' => 'Laravel Stripe Payment',
                            ],
                            'unit_amount' => 1000, // $10.00 in cents
                        ],
                        'quantity' => 1,
                    ]],
                    'mode' => 'payment',
                    'success_url' => route('payment.success'),
                    'cancel_url' => route('payment.cancel'),
                ]);
    
                return redirect($session->url, 303);
            } catch (\\Exception $e) {
                return back()->withErrors(['error' => 'Unable to create payment session: ' . $e->getMessage()]);
            }
        }
    }
            

Step 5: Create the Payment Page with Tailwind CSS

Now, let’s create a Blade template to serve as the payment page. Since Laravel 11 has Tailwind CSS set up by default, we can take advantage of Tailwind to create a clean and professional UI.

Create a new file at resources/views/payment.blade.php:

Code

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Stripe Checkout Integration</title>
        @vite('resources/css/app.css') <!-- Laravel 11 uses Vite for assets -->
    </head>
    <body class="bg-gray-100">
    
    <div class="flex justify-center items-center min-h-screen">
        <div class="bg-white shadow-lg rounded-lg p-8 w-full max-w-md">
            <h2 class="text-2xl font-bold mb-6 text-center">Stripe Payment</h2>
    
            @if(session('error'))
                <div class="bg-red-100 text-red-800 p-4 rounded-md mb-4">
                    {{ session('error') }}
                </div>
            @endif
    
            <form action="{{ route('payment.checkout') }}" method="POST" class="space-y-4">
                @csrf
                <p class="text-lg font-medium mb-4">Amount: $10.00</p>
                <button type="submit" class="w-full py-3 bg-blue-600 text-white 
                font-semibold rounded-md hover:bg-blue-700 transition">
                    Checkout with Stripe
                </button>
            </form>
        </div>
    </div>
    
    </body>
    </html>
            

Explanation:

  1. Layout & Styling:
    • The layout uses Tailwind CSS for a clean look.
    • bg-gray-100 provides a neutral background color, and the card form (div) is styled with bg-white shadow-lg rounded-lg for a professional feel.
  2. Form Elements:
    • The payment form has a “Checkout with Stripe” button, which when clicked, sends a request to the /checkout route.
    • The button uses Tailwind classes for a sleek appearance and hover effects.

Step 6: Test Your Stripe Integration

To test your Stripe payment integration, first run the Laravel server:

Code

                php artisan serve
            

Navigate to http://127.0.0.1:8000/payment in your browser. You will see the payment page with the "Checkout with Stripe" button. Clicking this button will redirect you to Stripe's hosted Checkout page, where customers can securely enter their payment information.

Stripe’s Checkout form is pre-styled, mobile-friendly, and handles all payment details securely, minimizing your workload in terms of PCI compliance.

 Stripe Integration
Stripe Integration

Stripe Checkout Features

Stripe's hosted Checkout page comes with several useful features:

  • Secure Payment Interface: Stripe Checkout is PCI-DSS compliant, ensuring that sensitive payment information is handled safely.
  • Built-in Validation: The form includes validation out of the box, meaning you don't need to worry about custom input checks.
  • Multiple Payment Methods: Stripe Checkout supports cards, wallets, and other global payment methods.

Step 7: Handle Payment Success and Failure

In the routes/web.php file, we defined routes for payment success (/success) and payment cancellation (/cancel). These are used to display messages to users based on the outcome of the payment process.

  • Success Page: You can create a custom success page or add your thank-you message. It’s a great place to provide information about next steps.
  • Cancel Page: This lets users know their payment was canceled, and you can guide them to retry or get help.

Congratulations! You have successfully integrated Stripe Checkout into your Laravel application! 🎉

Allow us to introduce the Jetship Laravel SaaS Boilerplate — a comprehensive solution designed to fast-track your SaaS development journey. This boilerplate doesn’t just include one, but two industry-leading payment gateways: Stripe and Lemon Squeezy.

That’s just the beginning! The Jetship Boilerplate is packed with features to save you hundreds of hours when building a SaaS application from scratch:

  • Robust and Secure Authentication System
  • Dual Payment Gateway Integration for flexible transactions
  • Reusable UI Components and Blocks for faster development
  • SEO-Optimized Blog Pages to boost visibility
  • Two FilamentPHP Panels tailored for better admin & user management
  • Beautifully Designed Roadmap to track progress and plans
  • Multiple Theme Options for customisation
  • Built-in Multilingual Support to reach a global audience
  • Based on FlyonUI Free Tailwind CSS Components library

Want to see it in action? Check out the live demo here.

Conclusion

In this guide, we integrated Stripe Checkout into a Laravel 11 application using Stripe’s hosted checkout page. This approach has several key benefits:

  • Simplicity: Stripe Checkout abstracts away most of the complexity, making it quick to integrate.
  • Security: Stripe Checkout is fully PCI-compliant, which means sensitive customer data is handled securely.
  • Great User Experience: The self-hosted payment page ensures users have a smooth experience on both desktop and mobile devices.

Resources to Keep in Check:

card user img
Twitter iconLinked icon

Zignuts Technolab delivers future-ready tech solutions and keeps you updated with the latest innovations through our blogs. Read, learn, and share!

Say Hello

We’re just a message away from making great things happen.

Valid number
Submit
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
download ready
Thank You
Your submission has been received.
We will be in touch and contact you soon!

Our Latest Blogs

Load More

Our Latest Blogs

View All Blogs