Laravel 8 - Stripe payment gateway integration

Touseef Afridi
27 Aug 24

Laravel 8 - Stripe payment gateway integration

In this tutorial, we'll discuss how to integrate the Stripe payment gateway in Laravel 8. Stripe is a popular payment processing platform that enables businesses to securely accept and manage payments online with ease.


If you're a video person, feel free to skip the post and check out the video instead!


Quick Overview

In this guide, we’ll walk you through integrating Stripe payment into your Laravel project. First, you’ll create a fresh Laravel project and install the Stripe PHP library to handle payments. Then, you’ll set up a Stripe account to get your API keys for integration. Afterward, you’ll create a CheckoutController and define the necessary routes to handle the payment flow. You’ll also create a Blade view that integrates the Stripe payment form using Stripe Elements. Once everything is set up, you’ll test the integration by starting the development server and using dummy card details to simulate a successful transaction.

Step # 1 : Install fresh laravel project.

The below command creates a new Laravel project named stripe by installing the latest version from the Laravel repository using Composer.
composer create-project --prefer-dist laravel/laravel stripe

Step # 2 : Let's install stripe via composer.

Navigate to the project directory you just created using Git Bash or any command line interface of your choice.
cd c:xampp/htdocs/stripe
To install the Stripe package, run the following command which will add the Stripe PHP library to your Laravel project.
composer require stripe/stripe-php

Step # 3 : Create stripe account.

Visit the Stripe website(link : https://stripe.com/) and create an account. After successfully completing this step, you'll be able to access your publishable and secret keys for integration.

Step # 4 : Create a CheckoutController.

Use the following command to create a new CheckoutController in your Laravel project, which will handle the Stripe checkout functionality.
php artisan make:controller CheckoutController

Step # 5 : Access web.php and create routes.

In the web.php file, define the routes for handling the checkout process and post-payment actions. The checkout route will display the checkout page, while the afterpayment route will process the payment.
Route::get('checkout','App\Http\Controllers\CheckoutController@checkout');
Route::post('checkout','App\Http\Controllers\CheckoutController@afterpayment')->name('checkout.credit-card');

Step # 6 : Update CheckoutController with Stripe Payment Logic.

In the CheckoutController, add the provided code to set up the Stripe payment integration. Make sure to replace use-your-stripe-key-here with your actual Stripe secret key. The checkout method creates a payment intent, and the afterPayment method handles the payment confirmation.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class CheckoutController extends Controller
{
    public function checkout()
    {
        // Enter Your Stripe Secret
        \Stripe\Stripe::setApiKey('use-your-stripe-key-here');
  $amount = 100;
  $amount *= 100;
        $amount = (int) $amount;
        $payment_intent = \Stripe\PaymentIntent::create([
   'description' => 'Stripe Test Payment',
   'amount' => $amount,
   'currency' => 'AED',
   'description' => 'Payment From All About Laravel',
   'payment_method_types' => ['card'],
  ]);
  $intent = $payment_intent->client_secret;
  return view('checkout.credit-card',compact('intent'));
    }
    public function afterPayment()
    {
        echo 'Payment Received, Thanks you for using our services.';
    }
}

Step # 7 : Create Checkout Blade View for Stripe Payment.

Create a new folder named checkout inside the resources/views directory, and inside that folder, create a file named credit-card.blade.php. Paste the code below into credit-card.blade.php. Make sure to replace put your publishable key here with your actual Stripe publishable key.
This file will contain the frontend code necessary for integrating Stripe's payment form. It uses the Stripe.js library to securely handle credit card payments directly on your site.
<!DOCTYPE html>
<html lang="en">
<head>
  <title>Stripe Payment</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</head>
<body>
    @php
    $stripe_key = 'put your publishable key here';
    @endphp
    <div class="container" style="margin-top:10%;margin-bottom:10%">
        <div class="row justify-content-center">
            <div class="col-md-12">
                <div class="">
                    <p>Your Total Amount is 100 AED</p>
                </div>
                <div class="card">
                    <form action="{{route('checkout.credit-card')}}" method="post" id="payment-form">
                        @csrf
                        <div class="form-group">
                            <div class="card-header">
                                <label for="card-element">
                                    Enter your credit card information
                                </label>
                            </div>
                            <div class="card-body">
                                <div id="card-element">
                                    <!-- A Stripe Element will be inserted here. -->
                                </div>
                                <!-- Used to display form errors. -->
                                <div id="card-errors" role="alert"></div>
                                <input type="hidden" name="plan" value="" />
                            </div>
                        </div>
                        <div class="card-footer">
                          <button
                          id="card-button"
                          class="btn btn-dark"
                          type="submit"
                          data-secret="{{ $intent }}"
                          > Pay </button>
                      </div>
                  </form>
              </div>
          </div>
      </div>
  </div>
  <script src="https://js.stripe.com/v3/"></script>
  <script>
        // Custom styling can be passed to options when creating an Element.
        // (Note that this demo uses a wider set of styles than the guide below.)
        var style = {
            base: {
                color: '#32325d',
                lineHeight: '18px',
                fontFamily: '"Helvetica Neue", Helvetica, sans-serif',
                fontSmoothing: 'antialiased',
                fontSize: '16px',
                '::placeholder': {
                    color: '#aab7c4'
                }
            },
            invalid: {
                color: '#fa755a',
                iconColor: '#fa755a'
            }
        };
        const stripe = Stripe('{{ $stripe_key }}', { locale: 'en' }); // Create a Stripe client.
        const elements = stripe.elements(); // Create an instance of Elements.
        const cardElement = elements.create('card', { style: style }); // Create an instance of the card Element.
        const cardButton = document.getElementById('card-button');
        const clientSecret = cardButton.dataset.secret;
        cardElement.mount('#card-element'); // Add an instance of the card Element into the `card-element` <div>.
        // Handle real-time validation errors from the card Element.
        cardElement.addEventListener('change', function(event) {
            var displayError = document.getElementById('card-errors');
            if (event.error) {
                displayError.textContent = event.error.message;
            } else {
                displayError.textContent = '';
            }
        });
        // Handle form submission.
        var form = document.getElementById('payment-form');
        form.addEventListener('submit', function(event) {
            event.preventDefault();
            stripe.handleCardPayment(clientSecret, cardElement, {
                payment_method_data: {
                    //billing_details: { name: cardHolderName.value }
                }
            })
            .then(function(result) {
                console.log(result);
                if (result.error) {
                    // Inform the user if there was an error.
                    var errorElement = document.getElementById('card-errors');
                    errorElement.textContent = result.error.message;
                } else {
                    console.log(result);
                    form.submit();
                }
            });
        });
    </script>
</body>
</html>

Step # 8 : Test the Stripe Payment Integration.

To test the Stripe payment integration, start the Laravel development server using the command below.
php artisan serve
Then, visit the URL: http://127.0.0.1/checkout to access the checkout page and test the integration.

Step # 9 : Use Dummy Data to Test Stripe Payment.

To test the Stripe integration, use the following dummy card details
Card Number - 4242 4242 4242 4242
EXP - 12/32
CVV - 123
ZIP - 12345

These credentials can be used to simulate a successful transaction on the checkout page.

Conclusion

This guide simplifies the process of integrating Stripe payment into a Laravel project. By following these steps, you can easily set up a secure payment system, allowing users to make payments via credit card. With Stripe’s seamless integration, you can efficiently handle transactions while ensuring a smooth checkout experience for your users.

Share this with friends!


"Give this post some love and slap that 💖 button as if it owes you money! 💸😄"
1

0 Comments

To engage in commentary, kindly proceed by logging in or registering