Laravel

How to implement Paystack payment gateway in laravel application

How to implement Paystack payment gateway in laravel application

Paystack is the most popular payment gateway in Africa. Paystack has supported ZAR currencies.

It’s very simple to implement in your laravel application

Install package

				
					composer require unicodeveloper/laravel-paystack
				
			

Once Laravel Paystack is installed, you need to register the service provider. Open up config/app.php and add the following to the providers key.

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

Register the Facade

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

Note: Make sure you have /payment/callback registered in Paystack Dashboard  https://dashboard.paystack.co/#/settings/developer

Set Paystack credentials into config/paystack.php

				
					 return [

    /**
     * Public Key From Paystack Dashboard
     */
    'publicKey' => 'PAYSTACK KEY',

    /**
     * Secret Key From Paystack Dashboard
     */
    'secretKey' => 'PAYSTACK SECRET KEY',

    /**
     * Paystack Payment URL
     */
    'paymentUrl' => 'https://api.paystack.co',

    /**
     * Optional email address of the merchant
     */
    'merchantEmail' => 'EMAIL ADDRESS',

 ];
				
			

Configure the route. Enter the code in your web.php file in the route directory

				
					 //Paystack Route
 Route::get('paystack-onboard', [PaystackController::class, 'redirectToGateway'])->name('paystack.init');
 Route::get('paystack-payment-success',
    [PaystackController::class, 'handleGatewayCallback'])->name('paystack.success');
				
			

Then after create one controller PaystackController.php

				
					 public function redirectToGateway(Request  $request)
     {
         try{
             $request->request->add([
                 "email"    => "Your email address",
                 "orderID"  => "123456", // anything 
                 "amount"   => 150 * 100,
                 "quantity" => 1,                
                 "currency" => "ZAR", // change as per need
                 "reference"=> Paystack::genTranxRef(),
                 "metadata" => json_encode(['key_name' => 'value']), // this should be related data
             ]);

             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']);
         }
     }

    public function handleGatewayCallback(Request  $request)
     {
         $paymentDetails = Paystack::getPaymentData();

 dd($paymentDetails);
 }
				
			

That’s it. Enjoy.

Share On: