Laravel 11 Stripe Payment Gateway Integration Example

Stripe payment gateway integration in Laravel 11; Through this tutorial, i am going to show you how to integrate stripe payment geteway in Laravel 11 apps.

In this tutorial, i will use jQuery, ajax and stripe javascript library for payment deduction in Laravel 11 app. And will call ajax request to deduct payment and store payment information into database in Laravel 11 app.

Laravel 11 Stripe Payment Gateway Integration Example

Use the below given steps to implement stripe payment gateway in Laravel 11 apps:

  • Step 1 – Installing Laravel 11 Application
  • Step 2 – Create account in Stripe and generate key and secret
  • Step 3 – Install Stripe package And Configure
  • Step 4 – Database and Stripe Key Configuration
  • Step 5 – Creating Payment Model & Migration
  • Step 6 – Create Routes
  • Step 7 – Creating Stripe Controller
  • Step 8 – Create Directory and Blade View
    • Create Directory Name Stripe
    • Create Stripe Payment Blade View
  • Step 9 – Start Development Server
  • Step 10 – Run This App On Browser

Step 1 – Installing Laravel 11 Application

In step 1, open your terminal and navigate to your local web server directory using the following command:

//for windows user
cd xampp/htdocs

//for ubuntu user
cd var/www/html

Then install laravel latest application using the following command:

composer create-project --prefer-dist laravel/laravel blog

Step 2 – Create account in Stripe and generate key and secret

In step 2, Create stripe account. Then generate key and secret.

Step 3 – Install Stripe package And Configure

In step 3, open terminal and run the following command on it to install stripe packate in laravel app:

composer require cartalyst/stripe-laravel

Then configure stripe package in app.php, which is located inside config directory:

'providers' => [
 ..........
 Cartalyst\Stripe\Laravel\StripeServiceProvider::class 
],
 
'aliases' => [
 ..........
 'Stripe' => Cartalyst\Stripe\Laravel\Facades\Stripe::class 
], 

Step 4 – Database and Stripe Key Configuration

In step 4, open your downloaded laravel app into any text editor. Then find .env file and configure database detail and stripe key and secret like following:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db name
DB_USERNAME=db user name
DB_PASSWORD=db password

STRIPE_KEY=pk_test_xxxxxxxxxxxxxxxxxxx 
STRIPE_SECRET=sk_test_xxxxxxxxxxxxxx 

Next step, you need to set up the Stripe API key, to do this open or create the config/services.php file, and add or update the 'stripe' array:

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

Step 5 – Creating Payment Model & Migration

In step 5, run the following command on terminal to create model and migration file by using the following command:

php artisan make:model Payment -m

The above command will create two files into your laravel stripe payment gateway integration tutorial app, which is located inside the following locations:

  • /app/Models/Payment.php
  • /database/migrations/create_payments_table.php

So, find create_payments_table.php file inside /database/migrations/ directory. Then open this file and add the following code into function up() on this file:

    public function up()
    {
        Schema::create('payments', function (Blueprint $table) {
            $table->id();
            $table->string('s_payment_id'); // stripe payment id
            $table->string('user_id');
            $table->string('product_id');
            $table->string('amount');
            $table->timestamps();
        });
    }

Now, open again your terminal and type the following command on cmd to create tables into your selected database:

php artisan migrate

Step 6 – Create Routes

In step 6, open your web.php file, which is located inside routes directory. Then add the following routes into web.php file:

use App\Http\Controllers\StripeController;

Route::get('stripe', [StripeController::class, 'index']);
Route::post('payment-process', [StripeController::class, 'process']);

Step 7 – Creating Stripe Controller

In step 7, create stripe payment controller by using the following command:

php artisan make:controller StripeController

The above command will create StripeController.php file, which is located inside /app/Http/Controllers/ directory.

So open StripeController.php file and add the following code into it:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\Payment;

use Stripe;

class StripeController extends Controller
{
     public function index()
	 {
	   return view('stripe.index');
	 }

	public function process(Request $request)
    {
  
        $stripe = Stripe::charges()->create([
            'source' => $request->get('tokenId'),
            'currency' => 'USD',
            'amount' => $request->get('amount') * 100
        ]);
  
        return $stripe;
    }
}

Step 8 – Create Directory and Blade View

In step 8, create the following directory and blade view file.

  • create directory name stripe inside resources/views directory.
  • Create Payment Blade View name index.blade.php inside resources/views/stripe directory. Then add the following code into it:
<!DOCTYPE html>
<html>
   <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <meta http-equiv="X-UA-Compatible" content="ie=edge">
      <title>Laravel 11 Stripe Payment Gateway Integration Example - LaraTutorials.com</title>
      <meta name="csrf-token" content="{{ csrf_token() }}">
      <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
      <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
      <style>
         .container{
         padding: 0.5%;
         } 
      </style>
   </head>
   <body>
      <div class="container">
         <div class="row">
            <div class="col-md-12 mt-2 mb-2">
               <h3 class="text-center">Laravel 11 Stripe Payment Gateway Integration Example Tutorial</h3><hr>
            </div>            
            <div class="col-md-12 mt-2 mb-2">
               <pre id="res_token"></pre>
            </div>
         </div>
         <div class="row">
            <div class="col-md-4">
               <button class="btn btn-primary btn-block" onclick="stripePay(10)">Pay $10</button>
            </div>
            <div class="col-md-4">
               <button class="btn btn-success btn-block" onclick="stripePay(50)">Pay $50</button>
            </div>
            <div class="col-md-4">
               <button class="btn btn-info btn-block" onclick="stripePay(100)">Pay $100</button>
            </div>
         </div>
      </div>
<script src = "https://checkout.stripe.com/checkout.js" > </script> 
<script type = "text/javascript">
    $(document).ready(function() {
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
    });

function stripePay(amount) {
    var handler = StripeCheckout.configure({
        key: 'pk_test_5f6jfFP2ZV5U9TXQYG0vtqFJ00eFVWNoRX', // your publisher key id
        locale: 'auto',
        token: function(token) {
            // You can access the token ID with `token.id`.
            // Get the token ID to your server-side code for use.
            console.log('Token Created!!');
            console.log(token)
            $('#res_token').html(JSON.stringify(token));
            $.ajax({
                url: '{{ url("payment-process") }}',
                method: 'post',
                data: {
                    tokenId: token.id,
                    amount: amount
                },
                success: (response) => {
                    console.log(response)
                },
                error: (error) => {
                    console.log(error);
                    alert('Oops! Something went wrong')
                }
            })
        }
    });
    handler.open({
        name: 'Demo Site',
        description: '2 widgets',
        amount: amount * 100
    });
} 
</script>
   </body>
</html>

Step 9 – Start Development Server

Finally, open your command prompt again and run the following command to start development server for your laravel stripe payment gateway integration example:

php artisan serve

Step 10 – Run This App On Browser

In step 10, open your browser and fire the following url into your browser:

http://127.0.0.1:8000/stripe

Testing Card Credential

 Card No : 4242 4242 4242 4242
 Month : any future month
 Year : any future Year
 CVV : 123

Recommended Laravel Tutorials

Leave a Comment