Step by Step Guide : Laravel 11 Stripe Implementation With Clean Setup



Welcome to our step-by-step guide on implementing Stripe payment integration with Laravel 11, the latest version of the popular PHP framework. With the ever-growing demand for online transactions, having a seamless and secure payment gateway is essential for any web application. Stripe, known for its simplicity and robustness, is a popular choice among developers for handling online payments.

In this comprehensive tutorial, we'll walk you through the process of setting up Stripe payment integration with Laravel 11 from scratch. We'll ensure a clean and organized setup, making it easy to understand and maintain your codebase as your project grows.

Whether you're a seasoned Laravel developer looking to enhance your e-commerce platform or a newcomer eager to learn the ropes of payment integration, this guide is designed to provide you with the knowledge and tools you need to succeed.

So, let's dive in and unlock the power of Laravel 11 and Stripe to create seamless payment experiences for your users. Get ready to embark on a journey of learning and innovation as we build a robust payment system together.

Let's get started!


To get your Stripe API keys, you'll need to follow these steps:

Sign up for a Stripe Account


Go to the Stripe website (https://stripe.com) and click on the "Start Now" button.
Enter your email address and create a password for your Stripe account.
Fill out the required information about your business, such as the business name, address, and industry.

Activate Your Stripe Account


After signing up, you'll need to activate your account by providing additional information about your business and yourself.
Stripe will guide you through the activation process, which may include verifying your email address, phone number, and identity.
Navigate to the Stripe Dashboard
Once your account is activated, log in to the Stripe Dashboard (https://dashboard.stripe.com).

Find Your API Keys


In the Stripe Dashboard, click on the "Developers" menu, and then select "API Keys".
You'll see two keys: a "Publishable Key" and a "Secret Key".
The "Publishable Key" is used to identify your account and initiate the payment process on the client-side (e.g., in your JavaScript code).
The "Secret Key" is used to interact with Stripe's API from your server-side code (e.g., in your Laravel application). This key should be kept secret and never shared or exposed in client-side code.

Copy the API Keys


Copy both the "Publishable Key" and the "Secret Key" separately, as you'll need them when integrating Stripe into your Laravel application.
It's important to note that the Publishable Key can be safely included in client-side code, as it's used for identifying your account and initiating the payment process. However, the Secret Key should always be kept confidential and never exposed in client-side code or shared publicly, as it grants full access to your Stripe account.





Step 1 : Create a new project





composer create-project laravel/laravel:^11.0 example-app

Step 2 : install stripe package



composer require stripe/stripe-php

Step 3 : Set Publishable key and Secret key in your Env file






STRIPE_KEY=pk_test_xxxxxxxxxxxx
STRIPE_SECRET=sk_test_xxxxxxxxxxxx

Step 4: Create a Controller File


We'll now craft a dedicated controller named PaymentController to orchestrate the Stripe payment integration process within our Laravel application. This controller will house two fundamental methods to streamline the payment flow. Let's dive into the creation of this controller and explore each method in detail.

app/Http/Controllers/PaymentController.php

    <?php
    namespace App\Http\Controllers;
    use Illuminate\Http\Request;
    use Session;
    use Stripe;
       
    class PaymentController extends Controller
    {
        public function stripe()
        {
            return view('view');
        }
        public function payment(Request $request)
        {
            Stripe\Stripe::setApiKey(env('STRIPE_SECRET'));
            Stripe\Charge::create ([
                    "amount" => 10 * 100,
                    "currency" => "usd",
                    "source" => $request->stripeToken,
                    "description" => "Test payment"
            ]);

        Session::flash('success', 'Payment successfully Done');
        return back();
        }
    }

Step 5: Create Routes


routes/web.php


    <?php
   
    use Illuminate\Support\Facades\Route;
    use App\Http\Controllers\PaymentController;
   
    Route::controller(PaymentController::class)->group(function(){
       
        Route::get('payment', 'stripe');
        Route::post('payment', 'payment')->name('payment.procceed');
    });


Step 6: Create View File


resources/views/view.blade.php

<!DOCTYPE html>
    <html>
    <head>
        <title>Laravel - Stripe Payment Gateway Integration Example </title>
        <script src="https://cdn.tailwindcss.com"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    </head>
    <body>

    <div class="container">
       
        <div class="flex justify-center">
        <div class="w-full max-w-md">
            <div class="bg-white rounded-lg shadow-md">
                <div class="flex justify-between items-center px-4 py-3 bg-gray-100 rounded-t-lg">
                    <h3 class="text-lg font-semibold">Laravel 11 - Stripe Payment</h3>
                </div>
                <div class="p-6">
                    @if (Session::has('success'))
                        <div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded mb-4">
                            <p>{{ Session::get('success') }}</p>
                        </div>
                    @endif

                    <form role="form"
                    action="{{ route('payment.procceed') }}"
                    method="post" class="require-validation"
                    data-cc-on-file="false"
                    data-stripe-publishable-key="{{ env('STRIPE_KEY') }}"
                    id="payment-form">
                        @csrf

                        <div class="mb-4">
                            <label class="block text-gray-700 font-semibold mb-2" for="name">Name on Card</label>
                            <input class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" type="text" id="name" placeholder="Enter name on card">
                        </div>

                        <div class="mb-4">
                            <label class="block text-gray-700 font-semibold mb-2" for="cardNumber">Card Number</label>
                            <input class="card-number shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" type="text" id="cardNumber" placeholder="Enter card number">
                        </div>

                        <div class="flex mb-4">
                            <div class="w-1/3 pr-2">
                                <label class="block text-gray-700 font-semibold mb-2 required" for="cvc">CVC</label>
                                <input class="card-cvc shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" type="text" id="cvc" placeholder="CVC">
                            </div>
                            <div class="w-1/3 px-2">
                                <label class="block text-gray-700 font-semibold mb-2 required" for="expiryMonth">Exp Month</label>
                                <input class=" card-expiry-month shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" type="text" id="expiryMonth" placeholder="MM">
                            </div>
                            <div class="w-1/3 pl-2">
                                <label class="block text-gray-700 font-semibold mb-2 required" for="expiryYear">Exp Year</label>
                                <input class="card-expiry-year shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" type="text" id="expiryYear" placeholder="YYYY">
                            </div>
                        </div>

                        <div class="mb-4 hidden">
                            <div class="bg-red-100 error border border-red-400 text-red-700 px-4 py-3 rounded">
                                Please correct the errors and try again.
                            </div>
                        </div>

                        <div>
                            <button class="w-full bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline" type="submit">
                                Pay Now ($100)
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
           
    </div>
       
    </body>
       
    <script type="text/javascript" src="https://js.stripe.com/v2/"></script>
       
    <script type="text/javascript">
   
    $(function() {
   
        /*------------------------------------------
        --------------------------------------------
        Stripe Payment Code
        --------------------------------------------
        --------------------------------------------*/
       
        var $form = $(".require-validation");
       
        $('form.require-validation').bind('submit', function(e) {
            var $form = $(".require-validation"),
            inputSelector = ['input[type=email]', 'input[type=password]',
                            'input[type=text]', 'input[type=file]',
                            'textarea'].join(', '),
            $inputs = $form.find('.required').find(inputSelector),
            $errorMessage = $form.find('div.error'),
            valid = true;
            $errorMessage.addClass('hide');
       
            $('.has-error').removeClass('has-error');
            $inputs.each(function(i, el) {
            var $input = $(el);
            if ($input.val() === '') {
                $input.parent().addClass('has-error');
                $errorMessage.removeClass('hide');
                e.preventDefault();
            }
            });
       
            if (!$form.data('cc-on-file')) {
            e.preventDefault();
            Stripe.setPublishableKey($form.data('stripe-publishable-key'));
            Stripe.createToken({
                number: $('.card-number').val(),
                cvc: $('.card-cvc').val(),
                exp_month: $('.card-expiry-month').val(),
                exp_year: $('.card-expiry-year').val()
            }, stripeResponseHandler);
            }
       
        });
       
        /*------------------------------------------
        --------------------------------------------
        Stripe Response Handler
        --------------------------------------------
        --------------------------------------------*/
        function stripeResponseHandler(status, response) {
            if (response.error) {
                $('.error')
                    .removeClass('hide')
                    .find('.alert')
                    .text(response.error.message);
            } else {
                /* token contains id, last4, and card type */
                var token = response['id'];
                   
                $form.find('input[type=text]').empty();
                $form.append("<input type='hidden' name='stripeToken' value='" + token + "'/>");
                $form.get(0).submit();
            }
        }
       
    });
    </script>
</html>


Run Project 



php artisan serve
and go to http://localhost:8000/payment




Source Code : https://github.com/BugBlitz98/laravel11Stripe

Congratulations! You've reached the end of our step-by-step guide on implementing Stripe payment integration with Laravel 11. Throughout this journey, we've covered the essential steps required to set up a clean and efficient payment system, ensuring seamless transactions for your web application.

By following the instructions provided in this guide, you've gained valuable insights into integrating Stripe with Laravel, from setting up your environment to handling payments securely. With a clean setup and organized codebase, you're well-equipped to scale your application and adapt to evolving business needs.

As you continue to explore the possibilities of Laravel and Stripe, remember the importance of security and user experience. Regularly update your dependencies, implement best practices for handling sensitive data, and prioritize usability to deliver a frictionless payment experience for your users.

We hope this guide has empowered you to harness the power of Laravel 11 and Stripe to create robust and reliable payment solutions. Embrace the opportunities that lie ahead, innovate with confidence, and watch as your web application thrives in the competitive digital landscape.

Thank you for joining us on this journey of learning and discovery. Here's to building remarkable payment systems that delight users and drive success for your business.

Happy coding!
Post a Comment (0)
Previous Post Next Post