Friday, February 14, 2020

How to Integrate Laravel 6 with Stripe Payment Gateway

How to Integrate Laravel 6 with Stripe Payment Gateway

Our main topic today is the integration of the Stripe Payment Gateway in Laravel 6. I will give you step-by-step instructions on how to integrate Stripe De Laravel 6, for example. You can easily integrate Stripe payment into the Laravel 6 application.

You need to create a Stripe developer account and get an API key and secret from there. Then we will use the Stripe / Stripe PHP Composer library for the Stripe Payment Gateway in Laravel 6. I am writing the step-by-step integration for the stripe payment gateway.

Stripe is a very popular and secure internet payment gateway company that accepts payments worldwide. Stripe offers a really nice development interface to get started with, and you don't have to pay any subscription fees to know that it offers a free developer account before you start coding in your application.

I'm going to give you an example from scratch to implement the band payment gateway in the Laravel 6 application. You only need to take a few steps to get a full example of the payment.


Step 1: Install Laravel 6


I'll explain step by step from scratch, so we need to get a new Laravel 6 application with the following command. So open your terminal OR the command prompt and run the following command:

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

Step 2: Install stripe-php Package


In this step we need to install stripe-php through the Composer package manager, hence one of its terminals and the following command:

composer require stripe/stripe-php

Step 3: Set Stripe API Key and SECRET


Now we have to set the strip key and the secret. So you can go to the Stripe website first and create the key and secret of the development stripe account and add below:

.env

STRIPE_KEY=pk_test_reFxwbsm9cdCKASdTfxAR

STRIPE_SECRET=sk_test_oQMFWteJiPd4wj4AtgApY

Step 4: Create Routes


In this step, we create two routes to receive the request and another one for the subsequent request. So let's add a new path to this file.

routes/api.php

<?php

    

Route::get('stripe', 'StripePaymentController@stripe');

Route::post('stripe', 'StripePaymentController@stripePost')->name('stripe.post');

Step 5: Create Controller File


In the next step, we have now created a new driver like StripePaymentController and write both methods as follows, so that we create both drivers:

app/Http/Controllers/StripePaymentController.php

<?php

   

namespace App\Http\Controllers;

   

use Illuminate\Http\Request;

use Session;

use Stripe;

   

class StripePaymentController extends Controller

{

    /**

     * success response method.

     *

     * @return \Illuminate\Http\Response

     */

    public function stripe()

    {

        return view('stripe');

    }

  

    /**

     * success response method.

     *

     * @return \Illuminate\Http\Response

     */

    public function stripePost(Request $request)

    {

        Stripe\Stripe::setApiKey(env('STRIPE_SECRET'));

        Stripe\Charge::create ([

                "amount" => 100 * 100,

                "currency" => "usd",

                "source" => $request->stripeToken,

                "description" => "Test payment from itsolutionstuff.com." 

        ]);

  

        Session::flash('success', 'Payment successful!');

          

        return back();

    }

}

Step 6: Create Blade File


In the final step, we create stripe.blade.php (resources / views / stripe.blade.php) for the design and enter the jquery code to get the stripe token here and enter the following code:

resources/views/stripe.blade.php

<!DOCTYPE html>

<html>

<head>

    <title>Laravel 6 - Stripe Payment Gateway Integration Example - ItSolutionStuff.com</title>

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" />

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

    <style type="text/css">

        .panel-title {

        display: inline;

        font-weight: bold;

        }

        .display-table {

            display: table;

        }

        .display-tr {

            display: table-row;

        }

        .display-td {

            display: table-cell;

            vertical-align: middle;

            width: 61%;

        }

    </style>

</head>

<body>

  

<div class="container">

  

    <h1>Laravel 6 - Stripe Payment Gateway Integration Example <br/> ItSolutionStuff.com</h1>

  

    <div class="row">

        <div class="col-md-6 col-md-offset-3">

            <div class="panel panel-default credit-card-box">

                <div class="panel-heading display-table" >

                    <div class="row display-tr" >

                        <h3 class="panel-title display-td" >Payment Details</h3>

                        <div class="display-td" >                            

                            <img class="img-responsive pull-right" src="http://i76.imgup.net/accepted_c22e0.png">

                        </div>

                    </div>                    

                </div>

                <div class="panel-body">

  

                    @if (Session::has('success'))

                        <div class="alert alert-success text-center">

                            <a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>

                            <p>{{ Session::get('success') }}</p>

                        </div>

                    @endif

  

                    <form 

                            role="form" 

                            action="{{ route('stripe.post') }}" 

                            method="post" 

                            class="require-validation"

                            data-cc-on-file="false"

                            data-stripe-publishable-key="{{ env('STRIPE_KEY') }}"

                            id="payment-form">

                        @csrf

  

                        <div class='form-row row'>

                            <div class='col-xs-12 form-group required'>

                                <label class='control-label'>Name on Card</label> <input

                                    class='form-control' size='4' type='text'>

                            </div>

                        </div>

  

                        <div class='form-row row'>

                            <div class='col-xs-12 form-group card required'>

                                <label class='control-label'>Card Number</label> <input

                                    autocomplete='off' class='form-control card-number' size='20'

                                    type='text'>

                            </div>

                        </div>

  

                        <div class='form-row row'>

                            <div class='col-xs-12 col-md-4 form-group cvc required'>

                                <label class='control-label'>CVC</label> <input autocomplete='off'

                                    class='form-control card-cvc' placeholder='ex. 311' size='4'

                                    type='text'>

                            </div>

                            <div class='col-xs-12 col-md-4 form-group expiration required'>

                                <label class='control-label'>Expiration Month</label> <input

                                    class='form-control card-expiry-month' placeholder='MM' size='2'

                                    type='text'>

                            </div>

                            <div class='col-xs-12 col-md-4 form-group expiration required'>

                                <label class='control-label'>Expiration Year</label> <input

                                    class='form-control card-expiry-year' placeholder='YYYY' size='4'

                                    type='text'>

                            </div>

                        </div>

  

                        <div class='form-row row'>

                            <div class='col-md-12 error form-group hide'>

                                <div class='alert-danger alert'>Please correct the errors and try

                                    again.</div>

                            </div>

                        </div>

  

                        <div class="row">

                            <div class="col-xs-12">

                                <button class="btn btn-primary btn-lg btn-block" type="submit">Pay Now ($100)</button>

                            </div>

                        </div>

                          

                    </form>

                </div>

            </div>        

        </div>

    </div>

      

</div>

  

</body>

  

<script type="text/javascript" src="https://js.stripe.com/v2/"></script>

  

<script type="text/javascript">

$(function() {

   

    var $form         = $(".require-validation");

   

    $('form.require-validation').bind('submit', function(e) {

        var $form         = $(".require-validation"),

        inputSelector = ['input[type=email]', 'input[type=password]',

                         'input[type=text]', 'input[type=file]',

                         'textarea'].join(', '),

        $inputs       = $form.find('.required').find(inputSelector),

        $errorMessage = $form.find('div.error'),

        valid         = true;

        $errorMessage.addClass('hide');

  

        $('.has-error').removeClass('has-error');

        $inputs.each(function(i, el) {

          var $input = $(el);

          if ($input.val() === '') {

            $input.parent().addClass('has-error');

            $errorMessage.removeClass('hide');

            e.preventDefault();

          }

        });

   

        if (!$form.data('cc-on-file')) {

          e.preventDefault();

          Stripe.setPublishableKey($form.data('stripe-publishable-key'));

          Stripe.createToken({

            number: $('.card-number').val(),

            cvc: $('.card-cvc').val(),

            exp_month: $('.card-expiry-month').val(),

            exp_year: $('.card-expiry-year').val()

          }, stripeResponseHandler);

        }

  

  });

  

  function stripeResponseHandler(status, response) {

        if (response.error) {

            $('.error')

                .removeClass('hide')

                .find('.alert')

                .text(response.error.message);

        } else {

            /* token contains id, last4, and card type */

            var token = response['id'];

               

            $form.find('input[type=text]').empty();

            $form.append("<input type='hidden' name='stripeToken' value='" + token + "'/>");

            $form.get(0).submit();

        }

    }

   

});

</script>

</html>


I hope This Could help you.....

0 comments:

Post a Comment

Please don't enter any spam link in the comment box.