Implementing Payment System in your Laravel 11 App using Stripe

              Stripe is a payment processing platform to help applications securely accept and manage online payments. Its developer-friendly API makes it a top choice in websites. In this Laravel 11 Stripe integration tutorial, we will use this platform to aid our payments in web applications.

Laravel 11 Stripe Payment Gateway: Fast & Secure Payment Integration

Table Of Content

1 Prerequisites

1.) PHP version of >= 8.2
2.) Composer
3.) Mysql

2 Introduction

This guide is an ideal starting point to understand how to integrate Stripe payment gateway in Laravel 11 and how you can integrate Stripe into an existing web application.

3 Create / Install a Laravel Project

3.1 Install Laravel Project

Ensure Composer is installed. Run:

composer create-project laravel/laravel laravel11-stripe-app

Then navigate to your project:

cd laravel11-stripe-app

3.2 Configure MySql Database

To store payment data, access the .env file to define database credentials:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel11
DB_USERNAME=root
DB_PASSWORD=

4 Install the  Stripe Library

Install the Stripe library:

composer require stripe/stripe-php

5 Configure Stripe Keys

Add Stripe API keys in the .env file, which you can find in your Stripe dashboard:

    # STRIPE
    stripe.key = 'pk_test_XXXXXX'
    stripe.secret = 'sk_test_XXXXXX'
    
Then update config/services.php:
    
        'stripe' => [
                'secret' => env('STRIPE_SECRET'),
            ],
    

6 Create A Model and Migration

To create a migration for the payments table:

    php artisan make:migration create_payments_table

Add the following fields:
    
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('payments', function (Blueprint $table) {
            $table->id();
            $table->string('charge_id');
            $table->string('transaction_id');
            $table->string('amount');
            $table->string('card_id');
            $table->string('card_last_four');
            $table->string('card_exp_month');
            $table->string('card_exp_year');
            $table->string('postal_code');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('payments');
    }
};

Run the migration:

php artisan migrate

Create the Payment model in app/Models/Payment.php:
    
<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Payment extends Model
{
    protected $fillable = [
        'charge_id',
        'transaction_id',
        'amount',
        'card_id',
        'card_last_four',
        'card_exp_month',
        'card_exp_year',
        'postal_code',
    ];
}

7 Create Controller ( StripeController )

Create StripeController:

php artisan make:controller StripeController

In your controller, you can use the index() and createCharge() methods:

<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Payment;


use Stripe;
  
class StripeController extends Controller
{
    public function index()
    {
        return view('checkout');
    }
     
      
    public function createCharge(Request $request)
    {
        Stripe\Stripe::setApiKey(env('STRIPE_SECRET'));
        $charge= Stripe\Charge::create ([
                "amount" => $request->amount * 100,
                "currency" => "cad",
                "source" => $request->stripeToken,
                "description" => "Get Sample Code - Stripe Test  Card Payment"
        ]);
        $payment=new Payment;
        $payment->charge_id=$charge->id;
        $payment->transaction_id=$charge->balance_transaction;
        $payment->amount=number_format(($charge->amount)/100,2);
        $payment->card_id=$charge->source->id;
        $payment->card_last_four=$charge->source->last4;
        $payment->card_exp_month=$charge->source->exp_month;
        $payment->card_exp_year=$charge->source->exp_year;
        $payment->postal_code=$charge->source->address_zip;
        
        $payment->save();
     
        return redirect('stripe')->with('success', 'Card Payment Successful!');
    }
}
?>

8 Define a Route

Add routes in routes/web.php:

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\StripeController;
Route::get('/', function () {
    return view('welcome');
});
Route::get('stripe', [StripeController::class, 'index']);
Route::post('stripe/create-charge', [StripeController::class, 'createCharge'])->name('stripe.create-charge');

9 Create Blade File

Create a Blade view checkout.blade.php(resources/views/checkout.blade.php) to show Payment Form:


   <!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

</head>
<body>
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-4">
                <div class="card">
                    <div class="card-body">
                        @if (session('success'))
                        <div 
                            style="color: green;
                                border: 2px green solid;
                                text-align: center;
                                padding: 5px;margin-bottom: 10px;">
                            {{ session('success') }}
                        </div>
                        @endif
                        <form id='checkout-form' method='post' action="{{url('/stripe/create-charge')}}">   
                            @csrf             
                            <input type='hidden' name='stripeToken' id='stripe-token-id'>                              
                            <label for="card-element" class="mb-5">Checkout Forms</label>
                            <br>
                            <input name="amount" id="amount" class="form-control" required placeholder="Amount"> <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 Now
                            </button>
                        <form>
                    </div>
                </div>
            </div>
        </div>
    </div>
 
    <script src="https://js.stripe.com/v3/"></script>
    <script>
        var stripe = Stripe('{{ env('STRIPE_KEY') }}')
        var elements = stripe.elements();
        var cardElement = elements.create('card');
        cardElement.mount('#card-element');
  
        function createToken() {
            document.getElementById("pay-btn").disabled = true;
            if($('#amount').val()=='' || $('#amount').val()==0)
           {
            alert("Invalid Amount Please enter correct Amount to Pay");
            document.getElementById("pay-btn").disabled = false;
           }else
           {

            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>
</body>
</html>

10 Folder Structure

11 Run Laravel Server to Test the App

Start your server with:

php artisan serve

12 Conclusion

This Laravel 11 Stripe integration tutorial should help you understand how to set up a secure and seamless payment gateway.

Reference URL

Tags