Laravel 5.7 - Stripe Payment Gateway Integration Example

Step 1: Install Laravel 5.8
I am going to explain step by step from scratch so, we need to get fresh Laravel 5.7 application using bellow command, So open your terminal OR command prompt and run bellow command:
composer create-project --prefer-dist laravel/laravel blog
Step 2: Install stripe-php Package
In this step we need to install stripe-php via the Composer package manager, so one your terminal and fire bellow command:
composer require stripe/stripe-php
Step 3: Set Stripe API Key and SECRET
Now, we need to set stripe key and secret. so first you can go on Stripe website and create development stripe account key and secret and add bellow:
.env
STRIPE_KEY=pk_test_reFxwbsm9cdCKASdTfxAR
STRIPE_SECRET=sk_test_oQMFWteJiPd4wj4AtgApY
Step 4: Create Routes
In this step, we will create two routes for get request and another for post request. So, let's add new route on that file.
routes/api.php
<?php
Route::get('/stripe/{order}', 'Backend\StripePaymentController@stripe')->name('stripe'); Route::post('stripe', 'Backend\StripePaymentController@stripePost')->name('stripe.post');
Step 5: Create Controller File
in next step, now we have create new controller as StripePaymentController and write both method on it like as bellow, So let's create both controller:
app/Http/Controllers/StripePaymentController.php
<?php namespace App\Http\Controllers\Backend; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Auth; use Session; use Validator; use App\Order; class StripePaymentController extends Controller { /** * success response method. * * @return \Illuminate\Http\Response */ public function stripe($id) { $order = Order::find($id); return view('backend.stripe.stripe', compact('order')); } /** * success response method. * * @return \Illuminate\Http\Response */ public function stripePost(Request $request) { $input = $request->except('_token'); $order = Order::find($request->order_id); $validator = Validator::make($request->all(), [ 'card_no' => 'required', 'cc_expiry_month' => 'required', 'cc_expiry_year' => 'required', 'cvc' => 'required', ]); if ($validator->fails()) { return redirect(route('stripe', $order->id))->withErrors($validator); } else { $stripe = \Stripe\Stripe::setApiKey(env('STRIPE_SECRET')); try { $charge = \Stripe\Charge::create([ 'source' => $request->stripeToken, 'currency' => 'USD', 'amount' => $order->total*100, 'description' => 'wallet', ]); if($charge['status'] == 'succeeded') { $order = Order::find($order->id); $order->update(['order_status_id' => 3, 'pay_by' => 'stripe']); return redirect()->route('orders.edit', $order->id)->with('message', 'Thank you! We have received you order. We will contact you shortly with free quotation.'); } else { Session::put('error','Payment failed!!'); return redirect()->route('stripe', $order->id)->with('message', 'A error has occurred, and you have not been charged. Please try again.'); } } catch (Exception $e) { Session::put('error', $e->getMessage()); return redirect()->route('stripe', $order->id)->with('message', 'A error has occurred, and you have not been charged. Please try again.'); } catch(\Cartalyst\Stripe\Exception\CardErrorException $e) { Session::put('error', $e->getMessage()); return redirect()->route('stripe', $order->id)->with('message', 'A error has occurred, and you have not been charged. Please try again.'); } catch(\Cartalyst\Stripe\Exception\MissingParameterException $e) { Session::put('error', $e->getMessage()); return redirect()->route('stripe', $order->id)->with('message', 'A error has occurred, and you have not been charged. Please try again.'); } return redirect()->route('stripe', $order->id)->with('message', 'A error has occurred, and you have not been charged. Please try again.'); } } }
Step 6: Create Blade File
In Last step, let's create stripe.blade.php(resources/views/stripe.blade.php) for layout and write code of jquery to get token from stripe here and put following code:
resources/views/stripe.blade.php
@extends('layouts.common') @section('title') Pay by Credit Card @endsection @section('content') <div class="container"> <div class="row"> <div class="col-0 col-sm-2 col-md-3"></div> <div class="col-12 col-sm-8 col-md-6"> <div class="card card-default credit-card-box mb-5"> <div class="card-header display-table" > <div class="row display-tr" > <h3 class="card-title display-td" >Payment Details</h3> <div class="display-td" > <img class="img-responsive float-right" src="http://i76.imgup.net/accepted_c22e0.png"> </div> </div> </div> <div class="card-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 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 <input type="hidden" name="order_id" value="{{ $order->id }}" /> <div class='form-group required'> <label for="name" >Name on Card</label> <input class='form-control card' id="name" name="name" size='4' type='text' autofocus required> @error('name') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror </div> <div class='form-group required'> <label for="car-no">Card Number</label> <input autocomplete='off' class='form-control card-number' id="card-no" name="card_no" size='20' type='text' required> @error('card_no') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror </div> <div class='row'> <div class='col-12 col-md-4 form-group cvc required'> <label class='control-label'>CVC</label> <input autocomplete='off' class='form-control card-cvc' name="cvc" placeholder='ex. 311' size='4' type='text' required> @error('cvc') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror </div> <div class='col-12 col-md-4 form-group expiration required'> <label class='control-label'>Expiration Month</label> <input class='form-control card-expiry-month' name="cc_expiry_month" placeholder='MM' size='2' type='text' required> @error('cc_expiry_month') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror </div> <div class='col-12 col-md-4 form-group expiration required'> <label class='control-label'>Expiration Year</label> <input class='form-control card-expiry-year' name="cc_expiry_year" placeholder='YYYY' size='4' type='text' required> @error('cc_expiry_year') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror </div> </div> <div class='row'> <div class='col-12 error form-group d-none'> <div class='alert-danger alert'>Please correct the errors and try again.</div> </div> </div> <div class="row"> <div class="col-12"> <button type="submit" class="btn btn-primary btn-lg w-100">Pay Now (${{ $order->total }})</button> </div> </div> </form> </div> </div> </div> </div> </div> @endsection @section('style') <style> .display-table { display: table; } .display-tr { display: table-row; } .display-td { display: table-cell; vertical-align: middle; width: 61%; } </style> @endsection @section('script') <script type="text/javascript" src="https://js.stripe.com/v2/"></script> <script> $(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('d-none'); $('.has-error').removeClass('has-error'); $inputs.each(function(i, el) { var $input = $(el); if ($input.val() === '') { $input.parent().addClass('has-error'); $errorMessage.removeClass('d-none'); e.preventDefault(); } }); if (!$form.data('cc-on-file')) { e.preventDefault(); Stripe.setPublishableKey("{{ env('STRIPE_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('d-none') .find('.alert') .text(response.error.message); } else { // token contains id, last4, and card type var token = response['id']; // insert the token into the form so it gets submitted to the server $form.find('input[type=text]').empty(); $form.append("<input type='hidden' name='stripeToken' value='" + token + "'/>"); $form.get(0).submit(); } } }); </script> @endsection
Now you can check with following card details:
Name: Test
Number: 4242 4242 4242 4242
CSV: 123
Expiration Month: 12
Expiration Year: 2024

Labels: , ,

© copyright-2020 Rejaul