Stripe Payment Integration with Laravel

December 17, 2018

In this tutorial we will see how to integrate Stripe payment system with Laravel

1 Create the shopping cart
2 Create the checkout page with payment form and get token
3 Charging the customer

Create the shopping cart

I am going to create the shopping cart now and add some product to it. I will hard code the product in HTML file and this cart is only for demonstration purpose only. What we consider here only the total values of the shopping cart

I will create the resources\view\cart.blade.php and it will have the following code

@extends('layouts.app')

@section('content')
My Cart
{{ csrf_field() }}

Product Name Unit price Qty Price
GoPro – HERO5 Black 4K Action Camera $299 1 $299
SanDisk – Extreme PLUS 64GB microSDXC UHS-I Memory Card $39 1 $39
TOTAL $338
@endsection

Next I am going to create CartController using artisan command

php artisan make:controller CartController

Now I will create the show() method to display the cart

This is the route in routes\web.php to display the cart

Route::get('/cart', 'CartController@show');

Now you can start the server using following command

 php artisan serve --port=8001

You can view the cart at http://127.0.0.1:8001/cart

Create the checkout page

Now I am going to create the checkout page. To create the payment form I am using Stripe Element which is pre-built UI component from the Stripe

We need route, action and view to implement checkout.
So our route should be like this

Route::post('/cart/checkout', 'CartController@checkout')->name('cart.checkout');

Then your action checkout should be like this

 public function checkout(){
    	return view("checkout");
    }

Now you can create the views\checkout.blade.php to start the checkout page code
You need following code in your file

@extends('layouts.app')

@section('content')
 
{{ csrf_field() }}

@endsection

@section('script')

@endsection

On the top of the file we have the Javascript code https://js.stripe.com/v3/ from stripe. Then we have the form which is a Stripe Element.
So Stripe Element will be inserted automatically and it will show the error messages when you enter the details to the form. All the work are handled by the Stripe Javascript code.

To make a payment via Stripe, you need to follow two steps.
1 Get the token from the Stripe server
2 Send back token, amount etc to the Stripe server for charging the amout

So to get the token you need some javascript code. I am going to do that code in public\js\stripe-checkout.js file

var stripe = Stripe('pk_test_0i3MPhnul2126bQ9HqdyCmr3');
var elements = stripe.elements();


// Custom styling can be passed to options when creating an Element.
var style = {
  base: {
    // Add your base input styles here. For example:
    fontSize: '16px',
    color: "#32325d",
  }
};

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

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


card.addEventListener('change', function(event) {
  var displayError = document.getElementById('card-errors');
  if (event.error) {
    displayError.textContent = event.error.message;
  } else {
    displayError.textContent = '';
  }
});

First you have to get the public key from the Stripe.com website.

Then you can make reference to the element. You can create the style which can be used when you create the element. Finally you can mount the card.

To show the Card Errors I have used the change event of the card element.

Now you can add the following code to generate the token from the server

// Create a token or display an error when the form is submitted.
var form = document.getElementById('payment-form');
form.addEventListener('submit', function(event) {
  event.preventDefault();

  stripe.createToken(card).then(function(result) {
    if (result.error) {
      // Inform the customer that 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);
    }
  });
});


function stripeTokenHandler(token) {
  // Insert the token ID into the form so it gets submitted to the server
  var form = document.getElementById('payment-form');
  var hiddenInput = document.createElement('input');
  hiddenInput.setAttribute('type', 'hidden');
  hiddenInput.setAttribute('name', 'stripeToken');
  hiddenInput.setAttribute('value', token.id);
  form.appendChild(hiddenInput);

  // Submit the form
  form.submit();
}

Now you can see the following screen

When you hit the Submit Payment button it will run the above JavaScript code and get the token from Strip and It will be passed to stripeTokenHandler() function. Finally it will call the form submission.

3 Charging the customer

Once you get the Token form will be submit to make a charge.
So we need to make the action of the form. You can add following php code to routes\
web.php file

Route::post('/cart/charge', 'CartController@charge')->name('cart.charge');

You need to install stripe/php code to make the charge from the Laravel. You can go to terminal and run the following command

composer require stripe/stripe-php

Then you can add the following code to CartController

public function charge(){
    	\Stripe\Stripe::setApiKey("sk_test_rHjOdqU5sokYSnU973P2DCnr");

			// Token is created using Checkout or Elements!
			// Get the payment token ID submitted by the form:
			$token = $_POST['stripeToken'];

			// Charge the user's card:
			$charge = \Stripe\Charge::create(array(
			  "amount" => 1000,
			  "currency" => "usd",
			  "description" => "Example charge",
			  "source" => $token,
			));
    }

You can get the Api key from the API section of the stripe.com

These are the completed code to make the Stripe payment. Once you make the payment you can see it on stripe.com