Integration of the Stripe payment gateway in Laravel 9; I'll demonstrate how to include Stripe payment gateway into Laravel 9 apps in this tutorial.

For payment deduction in this tutorial's Laravel 9 application, I'll utilize the jQuery, ajax, and stripe JavaScript libraries. Additionally, the Laravel 9 app will make an ajax request to deduct money and store payment details in the database.

Step 1 ? Installing Laravel 9 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

Step 9 ? Start Development Server

Step 10 ? Run This App On Browser

Step 1 ? Installing Laravel 9 Application

Launch your terminal and use the following command to browse to your local web server directory:

//for windows user
cd xampp/htdocs

//for ubuntu user
cd var/www/html

the most recent Laravel application by running the command:

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

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

Create a Stripe account in step two. then create a secret and key.

Step 3 ? Install Stripe package And Configure

Launch the terminal and enter the following command to install the Stripe package in the Laravel application:

composer require cartalyst/stripe-laravel

Then, in app.php, which is found in the config directory, configure the stripe package:

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

Step 4 ? Database and Stripe Key Configuration

In step 4, launch the Laravel app you downloaded into any text editor. Then locate the .env file and specify the database information, the stripe key, and the secret as follows:

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 

The Stripe API key needs to be configured next; to do this, edit 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

use the terminal to run the following command to create the model and migration file:

php artisan make:model Payment -m

The aforementioned command will produce two files in the following locations in your laravel stripe payment gateway integration tutorial app:

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

Consequently, locate the create payments table.php file in the migrations directory of your database. Open this file, and then add the following code to the method up().

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();
    });
}

Open your terminal once more, and then type the following command on cmd to create tables in the database of your choice:

php artisan migrate

Step 6 ? Create Routes

Open your web.php file, which may be found in the routes directory, in step 6. Add the following routes to the web.php file after that:

use App\Http\Controllers\StripeController;

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

Step 7 ? Creating Stripe Controller

The command to create a Stripe Payment Controller is:

php artisan make:controller StripeController

The StripeController.php file, which is found in the /app/Http/Controllers/ directory, will be created by the aforementioned command.

Enter the following code into the StripeController.php file by opening 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

Create the directory and blade view file indicated below in step 8.

  • inside of the resources/views directory, establish a directory name stripe.
  • Design a payment blade index.blade.php is the name of the view in the resources/views/stripe directory. Add the subsequent code after that:
<!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 9 Stripe Payment Gateway Integration Example - CodeSolutionStuff.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 9 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

The development server should now be running for your laravel stripe payment gateway integration example. To do this, reopen your command prompt and enter the following line:

php artisan serve

Step 10 ? Run This App On Browser

Step 10 is to launch your browser and type the following URL into it:

http://127.0.0.1:8000/stripe

Recommended Posts

View All

How to Generate a Variety of QR Codes in a Laravel 9 App


In the Laravel application, a basic QR code generator allows you to generate several sorts of QR Codes.

Laravel Eloquent Query - Laravel whereKey method


We'll look at the whereKey method in Laravel Eloquent in this post. whereKey is an extremely easy-to-use tool with a lot of potential.

Laravel 9 Install Vue Auth Tutorial with Example


In this article, I'll demonstrate how to use the Laravel UI and Vue Auth scaffolding to create login, register, logout, forget password, profile, and...

Laravel 8 How To Merge Two PDF Files Example


laravel 8 how To merge two PDF files example,how to merge two PDF files in laravel 8,merge two PDF files,pdf,pdf in laravel 8

Laravel 9 Captcha Tutorial – Create Captcha in Laravel


A CAPTCHA is a challenge-response test used in computing to determine if a user is human. It is an abbreviation for the Completely Automated Public Tu...