How to integrate Paystack payment gateway in Laravel

Laravel Logo Laravel Logo Paystack Image

What is Paystack?

Paystack is an African payment gateway used by enterprises. It is one of the most popular payment gateways in Africa, especially in Nigeria. It assists most E-commerce platforms to accept payment from their customers.

To seamlessly integrate Paystack into Laravel, we must ensure our environment has the following in place:

  • PHP 5.4+
  • Composer

Let’s now integrate Paystack step by step.

To get the latest version of the Paystack package installed into your application, we need to require it using a composer command on the command line. It will be better if we use Visual Studio Code for this integration.

Step 1

composer require unicodeveloper/laravel-paystack

At the composer.json file, you can add:

unicodeveloper/laravel-paystack": "1.0.*

Step 2

Run composer install or composer update to download it and have the autoloader updated.

Step 3

Once installed, open up config/app.php and add the following to the providers key to register the service provider.

'providers' => [
    ...
    Unicodeveloper\Paystack\PaystackServiceProvider::class,
    ...
]

Step 4

Register the Facade like so:

'aliases' => [
    ...
    'Paystack' => Unicodeveloper\Paystack\Facades\Paystack::class,
    ...
]

Step 5

It’s now time to make some configuration. Run the below command to publish the configuration:

php artisan vendor:publish --provider="Unicodeveloper\Paystack\PaystackServiceProvider"

Step 6

At the config directory, you will see a paystack.php configuration:

<?php

return [

 
    'publicKey' => 'pk_test_******************************',

    
    'secretKey' => 'sk_test_******************************',

    
    'paymentUrl' => 'https://api.paystack.co',

    
    'merchantEmail' => 'yourmail.com',

];

The above is done in situations where you don’t want to make use of the .env, so the configuration values were entered directly.

Step 7

Let’s understand the payment flow.

  1. The end-user is redirected to the payment provider (the process is handled elegantly), as we will see in Step 9.

  2. The end-user pays Paystack.

  3. The end-user gets redirected back to your site.

Head over to your Paystack dashboard to make sure you have /payment/callback registered in Paystack Dashboard. Image

Step 8

Let’s configure the route. Enter the code in your web.php file in the route directory, as follows.

// Laravel 5.1.17
Route::post('/pay', 'PaymentController@redirectToGateway')->name('pay');
// Laravel 8
Route::post('/pay', [App\Http\Controllers\PaymentController::class, 'redirectToGateway'])->name('pay');

Route::get('/payment/callback', [App\Http\Controllers\PaymentController::class, 'handleGatewayCallback'])->name('payment');

We are done with route. Let’s now create our PaymentController to handle the processes, with a typical example where I process student payment.

Step 9

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Redirect;
use Paystack;// Paystack package
use Auth;
use App\Student; // Student Model
use App\Payment; // Payment Model
use App\User; // User model
class PaymentController extends Controller
{
/**
* Redirect the User to Paystack Payment Page
* @return Url
*/
public function redirectToGateway(Request $request)
{
try{
return Paystack::getAuthorizationUrl()->redirectNow();
}catch(\Exception $e) {
return Redirect::back()->withMessage(['msg'=>'The paystack token has expired. Please refresh the page and try again.', 'type'=>'error']);
}
}
/**
* Obtain Paystack payment information
* @return void
*/
public function handleGatewayCallback()
{
//Getting authenticated user
$id = Auth::id();
// Getting the specific student and his details
$student = Student::where('user_id',$id)->first();
$class_id = $student->class_id;
$section_id = $student->section_id;
$level_id = $student->level_id;
$student_id = $student->id;
$paymentDetails = Paystack::getPaymentData(); //this comes with all the data needed to process the transaction
// Getting the value via an array method
$inv_id = $paymentDetails['data']['metadata']['invoiceId'];// Getting InvoiceId I passed from the form
$status = $paymentDetails['data']['status']; // Getting the status of the transaction
$amount = $paymentDetails['data']['amount']; //Getting the Amount
$number = $randnum = rand(1111111111,9999999999);// this one is specific to application
$number = 'year'.$number;
// dd($status);
if($status == "success"){ //Checking to Ensure the transaction was succesful
Payment::create(['student_id' => $student_id,'invoice_id'=>$inv_id,'amount'=>$amount,'status'=>1]); // Storing the payment in the database
Student::where('user_id', $id)
->update(['register_no' => $number,'acceptance_status' => 1]);
return view('student.studentFees');
}
// Now you have the payment details,
// you can store the authorization_code in your DB to allow for recurrent subscriptions
// you can then redirect or do whatever you want
}
}

We are done with controller. Let’s now head over to the view, where we will send the form values.

There are other ways to go about it, but this is just one of those ways.

<form method="POST" action="{{ route('pay') }}" accept-charset="UTF-8" class="form-horizontal d-none" role="form">
<input type="hidden" name="metadata" value="{{ json_encode($array = ['invoiceId' => $fee->id]) }}" >
<input type="hidden" name="email" value="{{Auth::user()->email}}"> {{-- required --}}
<input type="hidden" name="orderID" value="345">
<input type="hidden" name="amount" value="{{$fee->total}}"> {{-- required in kobo --}}
<input type="hidden" name="currency" value="NGN">
<input type="hidden" name="reference" value="{{ Paystack::genTranxRef() }}">
{{ csrf_field() }}
<button class="btn btn-success btn-lg btn-block" type="submit" value="Pay Now!">
<i class="fa fa-plus-circle fa-lg"></i> Pay Now!</button>
</form>

Summary

Integrating the Paystack payment gateway is a game-changer for your application and an entry into African E-commerce. Follow the above judiciously, and you will be able to integrate Paystack easily.

Free Resources