Laravel 8 – Integrating Stripe Payment Gateway Tutorial

Laravel 8 – Integrating Stripe Payment Gateway Tutorial

Avatar photoPosted by

Introduction:

Today, I will be showing you how to integrate Stripe payment gateway in Laravel 8. Payment gateway is one of the most important part of a e-commerce site or any apps that requires payment processing. One of the most popular payment processing platform is stripe. Stripe has been one of the most chosen payment platform for its simple integration and fast account setup.

I will be showing how to create a Charge in Stripe API using a token. We will now start the integration of Stripe to Laravel.

Step 1: Install Laravel 8

First, select a folder that you want the Laravel to be installed then execute this command on Terminal or CMD to install Laravel 8:

Install via composer:

composer create-project --prefer-dist laravel/laravel laravel-8-stripe-payment-gateway

Install via Laravel Install:

laravel new laravel-8-stripe-payment-gateway

Step 2: Install Stripe Package

Move to the newly created Laravel project and install the stripe package.

Execute this command:

composer require stripe/stripe-php

Step 3: Set Up Stripe Configurations

Add stripe api keys on the .env file. the API keys are found on your Stripe Dashboard under Developer API keys.

.env

STRIPE_KEY=pk_test_XXXXXXXXX
STRIPE_SECRET=sk_test_XXXXXXXXX

After adding this value to .env file. Open the config/service.php file and add the stripe credentials as array.

config/service.php

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

You can find you API keys on you stripe account dashboard, just navigate to Developers > API Keys.

Step 4: Create StripeController

Run this command to create a controller:

php artisan make:controller StripeController

After creating a controller, add these line of codes to the app\Http\Controllers\StripeController.php file:

app\Http\Controllers\StripeController.php

<?php
 
namespace App\Http\Controllers;
 
use Illuminate\Http\Request;
use Stripe;
 
class StripeController extends Controller
{
    public function index()
    {
        return view('checkout');
    }
    
     
    public function createCharge(Request $request)
    {
        Stripe\Stripe::setApiKey(env('STRIPE_SECRET'));
        Stripe\Charge::create ([
                "amount" => 5 * 100,
                "currency" => "usd",
                "source" => $request->stripeToken,
                "description" => "Binaryboxtuts Payment Test"
        ]);
    
        return redirect('stripe')->with('success', 'Payment Successful!');
    }
}

Step 5: Create Blade File

Blade is the simple but powerful templating engine in laravel. blade view files have a .blade.php files extension and usually stores on “resources/views/” folder.

Create a blade file “checkout.blade.php”  inside this following path “resources/views/”. After creating the blade file, Insert the code below:

resources/views/checkout.blade.php

<!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>
</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;">
                            Payment Successful!
                        </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>
                            <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 $5
                            </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;
            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>

Step 6: Create Routes

After creating controller and its blade, register the routes for stripe:

routes/web.php

<?php
 
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\StripeController;
 
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
 
Route::get('/', function () {
    return view('welcome');
});
 
Route::get('stripe', [StripeController::class, 'index']);
Route::post('stripe/create-charge', [StripeController::class, 'createCharge'])->name('stripe.create-charge');

Step 7 : Run the Application

After finishing the steps above, you can now run your application by executing the code below:

php artisan serve

After successfully running your app, open this URL in your browser:

http://localhost:8000/stripe

Screenshots:

Before Payment Transaction:

laravel 8 stripe before payment Binaryboxtuts

After Payment Transaction:

laravel 8 stripe after payment Binaryboxtuts