Mitesh Makwana

Mitesh Makwana's Posts

Sr Laravel Developer

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.

January 26, 20231 minuteMitesh MakwanaMitesh Makwana
Some Laravel tips that we must need to know

1) Null safe operator

From PHP 8 you can use Null Safe Operator

How we are doing null checking code in PHP < 8.0

 $country =  null;

 if ($session !== null) {
     $user = $session->user;

     if ($user !== null) {
         $address = $user->getAddress();

         if ($address !== null) {
             $country = $address->country;
         }
     }
 }

PHP 8 allows you to write this:

 $country = $session?->user?->getAddress()?->country;

2) Ternary condition

We have used this ternary condition for checking null value

 isset($user->image) ? $user->image : null

We can short above condition like this

 $user->image ?? null

3) Clone a model

You can clone a model using replicate(). It will create a copy of the model into a new, non-existing instance.

 $user = App\User::find(1);
 $newUser = $user->replicate();
 $newUser->save();

4) Default Relationship Models

Laravel provides a handy withDefault() method on the belongsTo relationship that will return a model object even when the relationship doesn't actually exist.

 class Post extends Model
 {
     public function user()
     {
         return $this->belongsTo(User::class)->withDefault();
     }
 }

Now, if we try to access the $post->user relationship, we'll still get a User object even when it does exist in the database. This is known as the "null object" pattern and helps eliminate some of those if ($post->user) conditional statements.

For more information read Laravel withDefault() doc.

5) Save models and relationships

You can save a model and its corresponding relationships using the push() method.

 class User extends Model
 {
     public function phone()
     {
         return $this->hasOne('App\Phone');
     }
 }
 $user = User::first();
 $user->name = "Peter";
 $user->phone->number = '1234567890';
 $user->push(); // This will update both user and phone record in DB

Hope it will be helpful.

Thanks

December 30, 20221 minuteMitesh MakwanaMitesh Makwana
How to implement Laravel impersonate

What is user impersonate and why we use it in projects?

  • User Impersonate is useful when we want to login on behalf of admin user.
  • When we are a super-admin and we want to know about our users what they do in their account then this package is useful to check their activity.
  • If you implemented impersonate in your project then you need to maintain it because it may cause a security issue as well as user's privacy issue.

Here is a full documentation of laravel impersonate: https://github.com/404labfr/laravel-impersonate

So let's start with installing impersonate on your project copy the below code where we will install this package using composer.

 composer require lab404/laravel-impersonate

Add the service provider at the end of your config/app.php:

 'providers' => [
     // ...
     Lab404\Impersonate\ImpersonateServiceProvider::class,
  ],

Add the trait Lab404\Impersonate\Models\Impersonate to your User model.

Using the built-in controller

In your routes file, under web middleware, you must call the impersonate route macro.

 Route::impersonate();

 // Where $id is the ID of the user you want impersonate
 route('impersonate', $id)

 // Or in case of multi guards, you should also add `guardName` (defaults to `web`)
 route('impersonate', ['id' => $id, 'guardName' => 'admin'])

 // Generate an URL to leave current impersonation
 route('impersonate.leave')

Blade

There are three Blade directives available.

When the user can impersonate

 @canImpersonate($guard = null)
     <a href="{{ route('impersonate', $user->id) }}">Impersonate this user</a>
 @endCanImpersonate

When the user can be impersonated

 @canBeImpersonated($user, $guard = null)
     <a href="{{ route('impersonate', $user->id) }}">Impersonate this user</a>
 @endCanBeImpersonated

When the user is impersonated

 @impersonating($guard = null)
     <a href="{{ route('impersonate.leave') }}">Leave impersonation</a>
 @endImpersonating

That's it. Enjoy.

October 15, 20221 minuteMitesh MakwanaMitesh Makwana