You are currently viewing Stripe Payment Gateway integration into Laravel Application 2024

Stripe Payment Gateway integration into Laravel Application 2024

Are you ready to elevate your Laravel business website app by integrating a reliable and secure payment gateway? Look no further! Our comprehensive guide will walk you through the seamless integration of the Stripe payment gateway into your Laravel project. With Stripe, you can effortlessly accept payments from customers worldwide, ensuring a smooth and hassle-free transaction experience.

Stripe Integration Steps are:

  1. Create Stripe Account
  2. Install Laravel Stripe Package
  3. Setup Stripe API Keys
  4. Create StripeHandle Class Seperately
  5. Create view file Form with stripe js
  6. Routes and Controller create
  7. Handle Payments
  8. Handle WebHooks

1. Create The Stripe Account

If you haven’t already, sign up for a Stripe account at stripe.com It only takes a few minutes, and you’ll gain access to the dashboard where you can manage payments, view analytics, and more.

2. Install Laravel Stripe Package

Begin by installing the official Laravel package for Stripe. You can do this via Composer by running the following command in your terminal:

composer require stripe/stripe-php

3. Setup Stripe API Keys

In your Laravel application, locate the config/services.php file and add your Stripe API keys:

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

These keys are add in .env file

STRIPE_KEY = XXX-XXX-XXX
STRIPE_SECRET= XXX-XXX-XXX 

4. Create StripeHandle Class Seperately

and also create Folder Payment in app directory the separate class `app/Payment/StripeHandler.php`

<?php
namespace App\Payment;

use App\Models\AccountType;
use Exception;
use Stripe\Exception\CardException;
use Stripe\StripeClient;

class StripeHandler{
  private $stripe;
  public function __construct() {
    $acount_type=AccountType::where('slug','accounttype_stripe')->first();
  //  dd( $acount_type);
    $account_config=$acount_type->account_config->client_secret;
    $this->stripe = new StripeClient($account_config);
  }

  /**
   * createToken
   *
   * @param  mixed $cardData
   * @return void
   */
  public function createTokenStripe($cardData)
  {
      $token = null;
      try {
          $token = $this->stripe->tokens->create([
              'card' => [
                  'number' => $cardData['cardNumber'],
                  'exp_month' => $cardData['month'],
                  'exp_year' => $cardData['year'],
                  'cvc' => $cardData['cvv']
              ]
          ]);
      } catch (CardException $e) {
          $token['error'] = $e->getError()->message;
      } catch (Exception $e) {
          $token['error'] = $e->getMessage();
      }
      return $token;
  }

  /**
   * createCharge
   *
   * @param  mixed $tokenId
   * @param  mixed $amount
   * @param  mixed $description
   * @return void
   */
  public function createCharge($tokenId, $amount,$description=null)
  {
      $charge = null;
      try {
          $charge = $this->stripe->charges->create([
              'amount' =>  floatval($amount)*100,
              'currency' => 'usd',
              'source' => $tokenId,
              'description' => $description
          ]);
      } catch (Exception $e) {
          $charge['error'] = $e->getMessage();
      }
      return $charge;
  }
}

5. Create view file Form with stripe js

create view file Form Card views/payment/form.blade.php


<form id="addFundForm" class="row" method="POST" action="{{route('authenticated.user.seller.funds.store')}}" >
            @csrf
           
            <div class="col-sm-12 mb-3">
              <label for=""></label>
              <div class="form-check form-switch mt-2">
                <input class="form-check-input" type="checkbox" id="title" name="title" checked="">
                <label class="form-check-label" for="title">Title</label>
              </div>
            </div>
            <div id="card-element" class="mt-5">
              <!-- A Stripe Element will be inserted here. -->
            </div>
            <div id="card-errors"></div>
            <div class="col-12 text-cente demo-vertical-spacing mt-4">
              <button type="submit" class="btn btn-primary me-sm-3 me-1">Create</button>
            </div>
          </form>
          
<script src="https://js.stripe.com/v3/"></script>
<script>
			 var stripe = Stripe("{{env(STRIPE_KEY)}}");

            // Create an instance of Elements.
            var elements = stripe.elements();

            // Create an instance of the card Element.
            var card = elements.create('card', {
                hidePostalCode: true
            });

            // Add an instance of the card Element into the `card-element` div.
            card.mount('#card-element');

            // Handle real-time validation errors from the card Element.
            card.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('addFundForm');
            // console.log(form)
            form.addEventListener('submit', function(event) {
                event.preventDefault();
                stripe.createToken(card).then(function(result) {
                    if (result.error) {
                        // Inform the user if there was an error.
                        var errorElement = document.getElementById('card-errors');
                        errorElement.textContent = result.error.message;
                    } else {
                        // Send the token to your server.
                        stripeTokenHandler(result.token);
                    }
                });
            });

            // Submit the form with the token ID.
            function stripeTokenHandler(token) {
                // Insert the token ID into the form so it gets submitted to the server.
                var form = document.getElementById('addFundForm');
                var hiddenInput = document.createElement('input');
                hiddenInput.setAttribute('type', 'hidden');
                hiddenInput.setAttribute('name', 'stripeToken');
                hiddenInput.setAttribute('value', token.id);
                console.log(hiddenInput)
                form.appendChild(hiddenInput);
                // Submit the form.
                form.submit();
            }
</script>

6. Routes and Controllers create

Define routes and controllers to handle payment-related actions, such as creating a checkout session, processing payments, handling webhooks, and use this class StripeHandler according to your requirements.

      $stripe = new StripeHandler(); //StripeHandler instance
      $charge = $stripe->createCharge($request->stripeToken, $request->amount); //Give the different status of payment
      Log::debug('$message', [$charge]); // print message in log file

7. Handle Payments

Implement server-side logic to interact with the Stripe API, create payment intents, and handle successful or failed payment attempts.

8. Handle Webhooks

Set up webhook endpoints to receive notifications from Stripe regarding payment events, such as successful payments, failed payments, and refunds.

Tips:

Use the secure (https://) app Laravel for stripe payment. If you want to learn more?

Conclusion:

Congratulations! You’ve successfully integrated the Stripe payment gateway into your Laravel application. By offering a seamless and secure payment experience, you’re one step closer to delighting your customers and growing your business. With Stripe’s powerful features and Laravel’s flexibility, the possibilities are endless. Get ready to take your online business to new heights with Stripe!

Leave a Reply