Laravel stripe payment gateway integration

Stripe is the best platform to collection payment online. In this tutorial, we’ll learn Stripe integration with Laravel and create a demo. Let’s see Stripe payment gateway integration with laravel

To get started we must have a laravel setup ready. If you don’t know how to setup laravel project click here

Install Stripe Package

To communicate with the stripe payment gateway we need a laravel package for stripe.

Go to the root directory of your project and run the below command to install the package

composer require cartalyst/stripe-laravel

Please make sure you have install the correct version of package.

After installing the package, open your Laravel config file located at config/app.php and add the following lines.

In the $providers array add the following service provider for this package.

Cartalyst\Stripe\Laravel\StripeServiceProvider::class

In the $aliases array add the following facade for this package.

'Stripe' => Cartalyst\Stripe\Laravel\Facades\Stripe::class

Now you need to setup the Stripe API key, to do this open or create the config/services.php file, and add or update the 'stripe' array:

<?php

return [

    'stripe' => [
        'secret' => 'your-stripe-key-here',
    ],

];

Here your-stripe-key-hereis your stripe public key, You can get this key from the stripe dashboard. Login or register on stripe then go to the Developer then Api Keys . Here you can see the Publishable key copy this key and replace with the above your-stripe-key-here

Create Controller

Next, We will create controller named StripeController this will contain two method, one for the view where we will create payment button and second where we will capture the payment. Run the below command to create the controller

php artisan make:controller StripeController

Next, Open StripeController and put the below method on this

<?php
   
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Redirect,Response,Stripe;
   
class StripeController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('stripe');
    }
    
   
    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {

        $stripe = Stripe::charges()->create([
            'source' => $request->get('tokenId'),
            'currency' => 'USD',
            'amount' => $request->get('amount') * 100
        ]);

        return $stripe;
    }
}

Here you may noticed that we have two methods

The index method is to load the view for the payment. and store method is to capture the payment

Create Route

Next, We will add routes in web.php file as like below.

Route::get('stripe', '[email protected]');
Route::post('stripe', '[email protected]');

Create View

Next, We will create view named stripe.blade.php

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <meta name="csrf-token" content="{{ csrf_token() }}">
  <title>W3path | laravel Stripe Payment Gateway Integration - W3path.com</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />
  <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
  <style>
   .container{
    padding: 0.5%;
   } 
</style>
</head>
<body>
  <div class="container">
    <h2 style="margin-top: 12px;" class="alert alert-success">laravel Stripe Payment Gateway Integration - <a href="https://www.w3path.com" target="_blank" >W3path</a></h2><br>  

    <div class="row">
      <div class="col-md-12"><pre id="token_response"></pre></div>
    </div>
    <div class="row">
      <div class="col-md-4">
        <button class="btn btn-primary btn-block" onclick="pay(10)">Pay $10</button>
      </div>
      <div class="col-md-4">
        <button class="btn btn-success btn-block" onclick="pay(50)">Pay $50</button>
      </div>
      <div class="col-md-4">
        <button class="btn btn-info btn-block" onclick="pay(100)">Pay $100</button>
      </div>
    </div>
</div>



<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<script src="https://checkout.stripe.com/checkout.js"></script>

<script type="text/javascript">
  $(document).ready(function () {  
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
  });

  function pay(amount) {
    var handler = StripeCheckout.configure({
      key: 'pk_test_aeUUjYYcx4XNfKVW60pmHTtI',
      locale: 'auto',
      token: function (token) {
        // You can access the token ID with `token.id`.
        // Get the token ID to your server-side code for use.
        console.log('Token Created!!');
        console.log(token)
        $('#token_response').html(JSON.stringify(token));

        $.ajax({
          url: '{{ url("stripe") }}',
          method: 'post',
          data: { tokenId: token.id, amount: amount },
          success: (response) => {

            console.log(response)

          },
          error: (error) => {
            console.log(error);
            alert('Oops! Something went wrong')
          }
        })
      }
    });
 
    handler.open({
      name: 'Demo Site',
      description: '2 widgets',
      amount: amount * 100
    });
  }
</script>
</body>
</html>

Here, We are using Stripe JS library to create token

When user hit any of the above buttons our pay()function will called and here we will initialize stripe object and open the stripe popup. The popup will be default popup of stripe. You need not to worry about the validation and security stripe will handle everything for you.

The StripeCheckout.configure method has a property called token the stripe will give callback after the token created then you can use this token to capture the payment.

If you have any questions or thoughts to share, use the comment form below to reach us.

3 Comments

  1. sirgliofrei said:

    I have not checked in here for some time because I thought it was getting boring, but the last few posts are great quality so I guess I¦ll add you back to my daily bloglist. You deserve it my friend 🙂

    October 8, 2019
    Reply
  2. Greggraido said:

    Интересно!

    October 17, 2019
    Reply
  3. Zak said:

    Hi thanks for your tutorial! just one problem though, when I fill the form it returns back the alert saying ‘Oops! Somthing went wrong’, could you help me with that please?

    November 13, 2019
    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *