How to implement shift4 payment gateway in laravel?

This guide provides a step-by-step process on how to integrate the Shift4 payment gateway into a PHP or a Laravel application using shift4 package, I prefer to use laravel but this process will work in PHP aswell. If you do not have credentails for Shift4 Payment Gateway then please read our post on How to get API Keys of Shift4 Payment Gateway?


We will use shift4 package, To install shift4 package please run this command. 

composer require shift4/shift4-php
Step 1 : Create a controller.

To create a controller use the command below.

php artisan make:controller PaymentController
Step 2 : Create a function to generate checkout token.

In the context of Shift4 Payment Gateway, a checkout token is part of the checkout request object that you sign with your secret key, Token will be generated using amount and currency.


So we will create a function in PaymentController.php

use Shift4\Request\CheckoutRequest;
use Shift4\Request\CheckoutRequestCharge;
use Shift4\Shift4Gateway;


public function checkoutToken($data)
{
    $key = 'secret_key';

    $shiftGateway = new Shift4Gateway($key);

    $checkoutCharge = new CheckoutRequestCharge();
    $checkoutCharge->amount($data['amount'] * 100)->currency($data['currency']);

    $checkoutRequest = new CheckoutRequest();
    $checkoutRequest->charge($checkoutCharge);

    $shift_checkout_token = $shiftGateway->signCheckoutRequest($checkoutRequest);

    return $shift_checkout_token;
}
Step 3 : Create a payment form.

Now we will create a payment form so you can ask user for the detials and conformation you need, So first lets create a route in web.php

//PAYMENT FORM
Route::get('payment-form', [\App\Http\Controllers\PaymentController::class, 'index'])->name('payment-form');

Now create a function named index in PaymentController.php

public function index()
{
    $data = [
        'amount' => 19,
        'currency' => 'USD'
    ];
    $shift_checkout_token = $this->checkoutToken($data);
    return view('shift4.payment-form',compact('data','shift_checkout_token'));
}

Now create a payment form,


resources/views/shift4/payment-form.blade.php 


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Shift4 Payment Gateway</title>

    <!-- BOOTSTRAP -->
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />

    <!-- Styles -->
    <style>
        body {
            background: #f7f7f7;
        }

        .form-box {
            max-width: 500px;
            margin: auto;
            padding: 50px;
            background: #ffffff;
            border: 10px solid #f2f2f2;
            margin-top: 100px;
        }

        h1, p {
            text-align: center;
        }

        input, textarea {
            width: 100%;
        }
    </style>
</head>
<body>
<div class="form-box">
    <h1>Pay with Shift4</h1>
    <form action="{{ route('shift4-callback') }}" method="post" style="text-align: center;margin-top: 50px;">
        @csrf
        <script src="https://dev.shift4.com/checkout.js"
                class="shift4-button"
                data-class="btn btn-primary"
                data-key="public_id_here"
                data-checkout-request="{{ $shift_checkout_token }}"
                data-name="Shift4"
                data-description="Test Payment of Shit4"
                data-checkout-button="Pay {{ $data['amount'] }}$">
        </script>
    </form>
</div>
</body>
</html>
Step 4 : Create a callback function.

Now we will create a callback function, So first lets create callback route in web.php

//CALLBACK ROUTE
Route::post('shift4-callback', [\App\Http\Controllers\PaymentController::class, 'callback'])->name('shift4-callback');
Step 5 : Usage.

Now when you click on pay button (which is auto generated by shit4 js), You will get a shift4 generated popup checkout, Which will look like this :



For test purpose use :

Email : Any

Card Number : 4242 4242 4242 4242

Expiry : Any future date

CVV : 111


When payment is successfull you will recive this data in callback, Remember you will get data in POST method.

//CALLBACK RESPONSE 
array:5 [▼ // Callback : PaymentController.php
  "_token" => "QYIXhuWFc3xOGZJWHep4xoqbLPCRKpw598oGCtHo" // CSRF
  "securionpayEmail" => "test@example.com" // Customer email
  "securionpayCustomerId" => "cust_****************************" // Can use to retrive customer details
  "securionpayChargeId" => "char_******************************" // Can use to retrive payment details
  "securionpaySubscriptionId" => null
]
Step 6 : Verifying Payment.

In callback function we will verify our payment and we can add details in database if payment is success or redirect if payment fails.

public function callback(Request $request)
{
    $key = 'secret_key';
    $charge_id = $request->securionpayChargeId;

    $shiftGateway = new Shift4Gateway($key);
    $chargeDetails = $shiftGateway->retrieveCharge($charge_id);

    if ($chargeDetails->get('status') == 'successful' && $chargeDetails->get('captured')) 
    {
        //PAYMENT IS A SUCCESS
        //HERE YOU CAN ADD DETAILS INTO DATABASE
    } 
    else
     {
        //HANDLE YOUR ERROR MESSAGE HERE
        //YOU WILL GET PAYMENT STATUS IN THIS : $chargeDetails->get('status')
    }
}