Laravel 11 Stripe Payment Gateway Integration Example

By Hardik Savani December 10, 2024 Category : Laravel

In this post, I will show you how to integrate stripe payment gateway in laravel 11 application from scratch.

Stripe is a very popular and secure internet payment gateway company that helps to accept payments worldwide. Stripe provides a really nice development interface to start, and you don’t have to pay subscription charges to learn it; it provides a free developer account before starting to code in your app.

Here, we will use the Stripe/stripe-php Composer library for the Stripe payment gateway in Laravel 11. We will create a simple payment form where users need to add credit card information and pay $10. You need to create a Stripe developer account and obtain API key and secret for this example.

laravel 11 stripe payment gateway

Step for How to Integrate Stripe Payment Gateway in Laravel 11?

  • Step 1: Install Laravel 11
  • Step 2: Install stripe-php Package
  • Step 3: Create a Stripe Account
  • Step 4: Create Controller
  • Step 5: Create Routes
  • Step 6: Create Blade File
  • Run Laravel App

Step 1: Install Laravel 11

This step is not required; however, if you have not created the Laravel app, then you may go ahead and execute the below command:

composer create-project laravel/laravel example-app

Step 2: Install stripe-php Package

In this step, we need to install stripe-php via the composer package manager, so open your terminal and fire the below command:

composer require stripe/stripe-php

Step 3: Create a Stripe Account

Now, we need to set the stripe key and secret in this step.

1. first you can go on Stripe website and create development account.

2. Click on "New Account" button:

3. Click on "Create Account" button:

4. Now, you need to click on "developers" link on header and copy Stripe key and secret.

You need to add in your .env file:

.env

STRIPE_KEY=pk_test_reFxwbsm9cdCKASdTfxARXXXXXX
STRIPE_SECRET=sk_test_oQMFWteJiPd4wj4AtgApYXXXXXXX

Step 4: Create Controller

In the next step, now we have to create a new controller named StripePaymentController and write both methods on it as below. So let's create both controllers:

app/Http/Controllers/StripePaymentController.php

<?php
      
namespace App\Http\Controllers;
       
use Illuminate\Http\Request;
use Stripe;
use Illuminate\View\View;
use Illuminate\Http\RedirectResponse;
       
class StripePaymentController extends Controller
{
    /**
     * success response method.
     *
     * @return \Illuminate\Http\Response
     */
    public function stripe(): View
    {
        return view('stripe');
    }
      
    /**
     * success response method.
     *
     * @return \Illuminate\Http\Response
     */
    public function stripePost(Request $request): RedirectResponse
    {
        Stripe\Stripe::setApiKey(env('STRIPE_SECRET'));
      
        Stripe\Charge::create ([
                "amount" => 10 * 100,
                "currency" => "usd",
                "source" => $request->stripeToken,
                "description" => "Test payment from itsolutionstuff.com." 
        ]);
                
        return back()
                ->with('success', 'Payment successful!');
    }
}

Step 5: Create Routes

In this step, we will create two routes for GET requests and another for POST requests. So, let's add a new route to that file.

routes/web.php

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

Step 6: Create Blade File

In the last step, let's create `stripe.blade.php` (resources/views/stripe.blade.php) for layout and write code of jQuery to get token from stripe here and put the following code:

resources/views/stripe.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 11 Stripe Payment Gateway Integration Example - ItSolutionStuff.com</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" crossorigin="anonymous">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <style type="text/css">
        #card-element{
            height: 50px;
            padding-top: 16px;
        }
    </style>
</head>
<body>

<div class="container">
    <div class="row">
        <div class="col-md-8 offset-md-2">
            <div class="card mt-5">
                <h3 class="card-header p-3">Laravel 11 Stripe Payment Gateway Integration Example - ItSolutionStuff.com</h3>
                <div class="card-body">

                    @session('success')
                        <div class="alert alert-success" role="alert"> 
                            {{ $value }}
                        </div>
                    @endsession
          
                    <form id='checkout-form' method='post' action="{{ route('stripe.post') }}">   
                        @csrf    

                        <strong>Name:</strong>
                        <input type="input" class="form-control" name="name" placeholder="Enter Name">

                        <input type='hidden' name='stripeToken' id='stripe-token-id'>                              
                        <br>
                        <div id="card-element" class="form-control" ></div>
                        <button 
                            id='pay-btn'
                            class="btn btn-success mt-3"
                            type="button"
                            style="margin-top: 20px; width: 100%;padding: 7px;"
                            onclick="createToken()">PAY $10
                        </button>
                    <form>
                </div>
            </div>
        </div>
    </div> 
</div>
      
</body>
     
<script src="https://js.stripe.com/v3/"></script>
<script type="text/javascript">
  
    var stripe = Stripe('{{ env('STRIPE_KEY') }}')
    var elements = stripe.elements();
    var cardElement = elements.create('card');
    cardElement.mount('#card-element');
  
    /*------------------------------------------
    --------------------------------------------
    Create Token Code
    --------------------------------------------
    --------------------------------------------*/
    function createToken() {
        document.getElementById("pay-btn").disabled = true;
        stripe.createToken(cardElement).then(function(result) {
   
            if(typeof result.error != 'undefined') {
                document.getElementById("pay-btn").disabled = false;
                alert(result.error.message);
            }
  
            /* creating token success */
            if(typeof result.token != 'undefined') {
                document.getElementById("stripe-token-id").value = result.token.id;
                document.getElementById('checkout-form').submit();
            }
        });
    }
</script>
 
</html>

Run Laravel App:

All the required steps have been done, now you have to type the given below command and hit enter to run the Laravel app:

php artisan serve

Now, Go to your web browser, type the given URL, and view the app output:

http://localhost:8000/stripe

Output:

Now you can check with the following card details:

Name: Test
Number: 4242 4242 4242 4242
CSV: 123
Expiration Month: 12
Expiration Year: 2028

Output:

I hope it can help you...

Shares