Connect with us

How to Integrate Flutterwave Rave Payment System in your Laravel Applications

kizinho

Published

on

Follow
DEVELOPER PROGRAMMING: How to Integrate Flutterwave Rave Payment System in your Laravel Applications [New  Developer Programming] » Naijacrawl
Photo: Naijacrawl
site

Hi Folks, I know many laravel developers that have been using Paystack as their payment system have been finding it difficult to integrate Paystack Laravel Package from Laravel 6.0 - 7.0 versions. Today I have a beautiful solution by using Flutterwave Rave Payment System, this process will work on any laravel versions.

Requirements

  1. Running Exiting Project on Laravel
  2. Create Account on Flutterwave
  3. Then you are good to go

Lets Begin

composer require kingflamez/laravelrave

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

'providers' => [
 /* * Package Service Providers... */
 ... 
KingFlamez\Rave\RaveServiceProvider::class, 
...
]

Also add this to the aliases

'aliases' => [
 ... 
'Rave' => KingFlamez\Rave\Facades\Rave::class, 
...
]

Configuration

Publish the configuration file using this command:

php artisan vendor:publish
 --provider="KingFlamez\Rave\RaveServiceProvider"

Usage

Open your .env file and add your public key, secret key, environment variable and logo url like so:

RAVE_PUBLIC_KEY=FLWPUBK_TEST
-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-X
RAVE_SECRET_KEY=FLWSECK_TEST-xxxxxxxxxxxxxxx
xxxxxxxxxxxxxxx-XRAVE_TITLE="Naijacrawl"
RAVE_ENVIRONMENT="staging"
RAVE_LOGO="https://rave.flutterwave.com/
static/img/[email protected]"
RAVE_PREFIX="rave"
  • RAVE_PUBLIC_KEY - This is the api public key gotten from your dashboard (compulsory)
  • RAVE_SECRET_KEY - This is the api secret key gotten from your dashboard (compulsory)
  • RAVE_TITLE - This is the title of the modal (optional)
  • RAVE_ENVIRONMENT - This can be staging or live. Staging API keys can be gotten here while live API keys can be gotten here (compulsory)
  • RAVE_LOGO - This is a custom logo that will be displayed on the modal (optional)
  • RAVE_PREFIX - This is a the prefix added to your transaction reference generated for you (optional)
  • SECRET_HASH - This is the secret hash for your webhook, this is necessary if you are setting up a recurrent payment


1. Setup Routes


Route::post('/pay', '[email protected]')
->name('pay');
Route::post('/rave/callback',
 '[email protected]')->name('callback');


2. Grant CSRF Access to Rave Callback


Go to app/Http/Middleware/VerifyCsrfToken.php 

and add your callback url to the $except array

protected $except = [ 'rave/callback'];

A sample form from your frontend will look like so:

@php
$array = array(array(
'metaname' => 'color',
 'metavalue' => 'blue'),
 array('metaname' => 'size',
 'metavalue' => 'big'));
@endphp
"POST" action="{{ route('pay') }}" id="paymentForm"> {{ csrf_field() }} type="hidden" name="amount" value="500" />type="hidden" name="payment_method" value="both" />type="hidden" name="description" value="Beats by Dre. 2017" />type="hidden" name="country" value="NG" />type="hidden" name="currency" value="NGN" />type="hidden" name="email" value="[email protected]" />type="hidden" name="firstname" value="Oluwole" />type="hidden" name="lastname" value="Adebiyi" />type="hidden" name="metadata" value="{{ json_encode($array) }}" >type="submit" value="Buy" />

In this implementation, we are expecting a form encoded POST request to this script. The request will contain the following parameters.

  • payment_method Can be card, account, both
  • description Your transaction description
  • logo Your logo url
  • title Your transaction title
  • country Your transaction country
  • currency Your transaction currency
  • email Your customer's email
  • firstname Your customer's firstname
  • lastname Your customer's lastname
  • phonenumber Your customer's phonenumber
  • ref Your transaction reference.
  • It must be unique per transaction.
  • By default, the Rave class generates
  • a unique transaction reference for each
  • transaction. Pass this parameter only if
  • you uncommented the related section in
  • the script below.

3. Setup your Controller

Setup your controller to handle the routes. I created the RaveController.

Use the Rave facade.


Example


namespaceApp\Http\Controllers;
use Illuminate\Http\Request;
//use the Rave Facadeuse Rave;class RaveController extends Controller{ 
/** * Initialize Rave payment process * @return void */ 
public function initialize() {
 //This initializes payment and redirects to the payment gateway 
//The initialize method takes the parameter of the redirect URL
 Rave::initialize(route('callback')); 
} 
/** * Obtain Rave callback information 
* @return void */public function callback() {
 $data =Rave::verifyTransaction(request()->txref);
dd($data); 
// view the data response 
 if ($data->status == 'success') {
 //do something to your database
}else
 {
//return invalid payment
}
 }
}



site


kizinho

I am a software developer, like meeting people and love blogging, that's why I developed naijacrawl because that's what I love doing.

Continue Reading
Click To Comment

BE First To Comment


    Leave a Reply

    Your email address will not be published. Required fields are marked *

    How to solve This page isn’t working HTTP ERROR 500 in Laravel

    kizinho

    Published

    on

    DEVELOPER PROGRAMMING: How to solve This page isn’t working HTTP ERROR 500 in Laravel [New  Developer Programming] » Naijacrawl
    Photo: Naijacrawl

    In case you ran into this problem This page isn’t working www.example.com is currently unable to handle this request HTTP ERROR here is the cause and how to fix it. First, it must not be an error from your code, it is an error from querying large data from your database. So request ran out of memory, to fix it follow this step.

    In your Laravel root project folder locate this file

    vendor/laravel/framework/src/Illuminate/
    Database/Connection.php.
    

    Insert this line of code after line 324 

    ini_set('memory_limit', '-1'); 
    

    or follow the code snippet or image below:


     public function select($query, $bindings = [], $useReadPdo = true)    {        return $this->run($query, $bindings, function ($query, $bindings) use ($useReadPdo) {            if ($this->pretending()) {                return [];            }            // For select statements, we'll simply execute the query and return an array            // of the database result set. Each element in the array will be a single            // row from the database table, and will either be an array or objects.            ini_set('memory_limit', '-1');         
    
       $statement = $this->prepared($this->getPdoForSelect($useReadPdo)                              ->prepare($query));            $this->bindValues($statement, $this->prepareBindings($bindings));            $statement->execute();            return $statement->fetchAll();        });    }
    


    Continue Reading

    How to use the same Guard name in WEB and API Using Laravel Spatie Permission

    kizinho

    Published

    on

    NEWS: How to use the same Guard name in WEB and API Using Laravel Spatie Permission [New  Developer] » Naijacrawl
    Photo: Naijacrawl

    Hi, Folks will show how to use the same guard name on your Laravel application using Laravel Spatie Permission without creating multiple guards for your web and API when building your real projects.


    Spatie Permission comes with guard name it is used to authenticate user role and permission in your laravel app. But what if you have Role and Permission with Guard Name Web, it means only web can use this permission or role, when you want to use it for API to Authorize user Permission or Role, this would not work and you will always get user don't have permission to access this page.


    In this article, you can now use a single Guard name for both Web and API.


    Guard name depends on your application usage, guard name can be admin,user, but i prefer to use guard name as web or API, so that i don't have to create each role and permission for different guard name, and it saves time to use single guard name in all your applications. So let's start


    Go to this file vendor/spatie/laravel-permission/src/Models/Role and add protected $guard_name = 'web' .

    You can change the $guard_name to whatever you want to use as your guard name.


    See Full Code

    namespace Spatie\Permission\Models;
    
    
    use Spatie\Permission\Guard;
    use Illuminate\Database\Eloquent\Model;
    use Spatie\Permission\Traits\HasPermissions;
    use Spatie\Permission\Exceptions\RoleDoesNotExist;
    use Spatie\Permission\Exceptions\GuardDoesNotMatch;
    use Spatie\Permission\Exceptions\RoleAlreadyExists;
    use Spatie\Permission\Contracts\Role as RoleContract;
    use Spatie\Permission\Traits\RefreshesPermissionCache;
    use Illuminate\Database\Eloquent\Relations\MorphToMany;
    use Illuminate\Database\Eloquent\Relations\BelongsToMany;
    
    
    class Role extends Model implements RoleContract {
    
    
        use HasPermissions;
        use RefreshesPermissionCache;
    
    
        protected $guarded = ['id'];
        protected $guard_name = 'web';
    
    
        public function __construct(array $attributes = []) {
            $attributes['guard_name'] = $attributes['guard_name'] ?? config('auth.defaults.guard');
    
    
            parent::__construct($attributes);
    
    
            $this->setTable(config('permission.table_names.roles'));
        }
    
    
        public static function create(array $attributes = []) {
            $attributes['guard_name'] = $attributes['guard_name'] ?? Guard::getDefaultName(static::class);
    
    
            if (static::where('name', $attributes['name'])->where('guard_name', $attributes['guard_name'])->first()) {
                throw RoleAlreadyExists::create($attributes['name'], $attributes['guard_name']);
            }
    
    
            if (isNotLumen() && app()::VERSION < '5.4') {
                return parent::create($attributes);
            }
    
    
            return static::query()->create($attributes);
        }
    
    
        /**
         * A role may be given various permissions.
         */
        public function permissions(): BelongsToMany {
            return $this->belongsToMany(
                            config('permission.models.permission'), config('permission.table_names.role_has_permissions'), 'role_id', 'permission_id'
            );
        }
    
    
        /**
         * A role belongs to some users of the model associated with its guard.
         */
        public function users(): MorphToMany {
            return $this->morphedByMany(
                            getModelForGuard($this->attributes['guard_name']), 'model', config('permission.table_names.model_has_roles'), 'role_id', config('permission.column_names.model_morph_key')
            );
        }
    
    
        /**
         * Find a role by its name and guard name.
         *
         * @param string $name
         * @param string|null $guardName
         *
         * @return \Spatie\Permission\Contracts\Role|\Spatie\Permission\Models\Role
         *
         * @throws \Spatie\Permission\Exceptions\RoleDoesNotExist
         */
        public static function findByName(string $name, $guardName = null): RoleContract {
            $guardName = $guardName ?? Guard::getDefaultName(static::class);
    
    
            $role = static::where('name', $name)->where('guard_name', $guardName)->first();
    
    
            if (!$role) {
                throw RoleDoesNotExist::named($name);
            }
    
    
            return $role;
        }
    
    
        public static function findById(int $id, $guardName = null): RoleContract {
            $guardName = $guardName ?? Guard::getDefaultName(static::class);
    
    
            $role = static::where('id', $id)->where('guard_name', $guardName)->first();
    
    
            if (!$role) {
                throw RoleDoesNotExist::withId($id);
            }
    
    
            return $role;
        }
    
    
        /**
         * Find or create role by its name (and optionally guardName).
         *
         * @param string $name
         * @param string|null $guardName
         *
         * @return \Spatie\Permission\Contracts\Role
         */
        public static function findOrCreate(string $name, $guardName = null): RoleContract {
            $guardName = $guardName ?? Guard::getDefaultName(static::class);
    
    
            $role = static::where('name', $name)->where('guard_name', $guardName)->first();
    
    
            if (!$role) {
                return static::query()->create(['name' => $name, 'guard_name' => $guardName]);
            }
    
    
            return $role;
        }
    
    
        /**
         * Determine if the user may perform the given permission.
         *
         * @param string|Permission $permission
         *
         * @return bool
         *
         * @throws \Spatie\Permission\Exceptions\GuardDoesNotMatch
         */
        public function hasPermissionTo($permission): bool {
            $permissionClass = $this->getPermissionClass();
    
    
            if (is_string($permission)) {
                $permission = $permissionClass->findByName($permission, $this->getDefaultGuardName());
            }
    
    
            if (is_int($permission)) {
                $permission = $permissionClass->findById($permission, $this->getDefaultGuardName());
            }
    
    
            if (!$this->getGuardNames()->contains($permission->guard_name)) {
                throw GuardDoesNotMatch::create($permission->guard_name, $this->getGuardNames());
            }
    
    
            return $this->permissions->contains('id', $permission->id);
        }
    
    
    }
    


    Go to this file again vendor/spatie/laravel-permission/src/Models/Permission and add protected $guard_name = 'web' .

    Full Code


    namespace Spatie\Permission\Models;
    
    
    use Spatie\Permission\Guard;
    use Illuminate\Support\Collection;
    use Spatie\Permission\Traits\HasRoles;
    use Illuminate\Database\Eloquent\Model;
    use Spatie\Permission\PermissionRegistrar;
    use Spatie\Permission\Traits\RefreshesPermissionCache;
    use Illuminate\Database\Eloquent\Relations\MorphToMany;
    use Spatie\Permission\Exceptions\PermissionDoesNotExist;
    use Illuminate\Database\Eloquent\Relations\BelongsToMany;
    use Spatie\Permission\Exceptions\PermissionAlreadyExists;
    use Spatie\Permission\Contracts\Permission as PermissionContract;
    
    
    class Permission extends Model implements PermissionContract {
    
    
        use HasRoles;
        use RefreshesPermissionCache;
    
    
        protected $guarded = ['id'];
        protected $guard_name = 'web';
    
    
        public function __construct(array $attributes = []) {
            $attributes['guard_name'] = $attributes['guard_name'] ?? config('auth.defaults.guard');
    
    
            parent::__construct($attributes);
    
    
            $this->setTable(config('permission.table_names.permissions'));
        }
    
    
        public static function create(array $attributes = []) {
            $attributes['guard_name'] = $attributes['guard_name'] ?? Guard::getDefaultName(static::class);
    
    
            $permission = static::getPermissions(['name' => $attributes['name'], 'guard_name' => $attributes['guard_name']])->first();
    
    
            if ($permission) {
                throw PermissionAlreadyExists::create($attributes['name'], $attributes['guard_name']);
            }
    
    
            if (isNotLumen() && app()::VERSION < '5.4') {
                return parent::create($attributes);
            }
    
    
            return static::query()->create($attributes);
        }
    
    
        /**
         * A permission can be applied to roles.
         */
        public function roles(): BelongsToMany {
            return $this->belongsToMany(
                            config('permission.models.role'), config('permission.table_names.role_has_permissions'), 'permission_id', 'role_id'
            );
        }
    
    
        /**
         * A permission belongs to some users of the model associated with its guard.
         */
        public function users(): MorphToMany {
            return $this->morphedByMany(
                            getModelForGuard($this->attributes['guard_name']), 'model', config('permission.table_names.model_has_permissions'), 'permission_id', config('permission.column_names.model_morph_key')
            );
        }
    
    
        /**
         * Find a permission by its name (and optionally guardName).
         *
         * @param string $name
         * @param string|null $guardName
         *
         * @throws \Spatie\Permission\Exceptions\PermissionDoesNotExist
         *
         * @return \Spatie\Permission\Contracts\Permission
         */
        public static function findByName(string $name, $guardName = null): PermissionContract {
            $guardName = $guardName ?? Guard::getDefaultName(static::class);
            $permission = static::getPermissions(['name' => $name, 'guard_name' => $guardName])->first();
            if (!$permission) {
                throw PermissionDoesNotExist::create($name, $guardName);
            }
    
    
            return $permission;
        }
    
    
        /**
         * Find a permission by its id (and optionally guardName).
         *
         * @param int $id
         * @param string|null $guardName
         *
         * @throws \Spatie\Permission\Exceptions\PermissionDoesNotExist
         *
         * @return \Spatie\Permission\Contracts\Permission
         */
        public static function findById(int $id, $guardName = null): PermissionContract {
            $guardName = $guardName ?? Guard::getDefaultName(static::class);
            $permission = static::getPermissions(['id' => $id, 'guard_name' => $guardName])->first();
    
    
            if (!$permission) {
                throw PermissionDoesNotExist::withId($id, $guardName);
            }
    
    
            return $permission;
        }
    
    
        /**
         * Find or create permission by its name (and optionally guardName).
         *
         * @param string $name
         * @param string|null $guardName
         *
         * @return \Spatie\Permission\Contracts\Permission
         */
        public static function findOrCreate(string $name, $guardName = null): PermissionContract {
            $guardName = $guardName ?? Guard::getDefaultName(static::class);
            $permission = static::getPermissions(['name' => $name, 'guard_name' => $guardName])->first();
    
    
            if (!$permission) {
                return static::query()->create(['name' => $name, 'guard_name' => $guardName]);
            }
    
    
            return $permission;
        }
    
    
        /**
         * Get the current cached permissions.
         */
        protected static function getPermissions(array $params = []): Collection {
            return app(PermissionRegistrar::class)
                            ->setPermissionClass(static::class)
                            ->getPermissions($params);
        }
    
    
    }
    


    Next go to your Model where you use HasRoles and Paste this code , eg I used HasRoles in my User Model , will use the code on my user

    Copy this code


     public function hasPermissionTo($permission, $guardName = 'web'): bool {
    
    
            $permissionClass = $this->getPermissionClass();
    
    
            if (is_string($permission)) {
                $permission = $permissionClass->findByName(
                        $permission, $guardName ?? $this->getDefaultGuardName()
                );
            }
    
    
            if (is_int($permission)) {
                $permission = $permissionClass->findById(
                        $permission, $guardName ?? $this->getDefaultGuardName()
                );
            }
    
    
            return $this->hasDirectPermission($permission) || $this->hasPermissionViaRole($permission);
        }
    
    
        protected function getDefaultGuardName(): string {
            return 'web';
        }
    


    Now all web and API can use the same guard name to check user role and permission

    See complete Code on my user model


    namespace App\Models\User;
    
    
    use Laravel\Passport\HasApiTokens;
    use Illuminate\Foundation\Auth\User as Authenticatable;
    use Illuminate\Database\Eloquent\SoftDeletes;
    use Spatie\Permission\Traits\HasRoles;
    
    
    class User extends Authenticatable implements MustVerifyEmail {
    
    
        use HasApiTokens,
            SoftDeletes,
            HasRoles,
           ;
    
    
        public function hasPermissionTo($permission, $guardName = 'web'): bool {
    
    
            $permissionClass = $this->getPermissionClass();
    
    
            if (is_string($permission)) {
                $permission = $permissionClass->findByName(
                        $permission, $guardName ?? $this->getDefaultGuardName()
                );
            }
    
    
            if (is_int($permission)) {
                $permission = $permissionClass->findById(
                        $permission, $guardName ?? $this->getDefaultGuardName()
                );
            }
    
    
            return $this->hasDirectPermission($permission) || $this->hasPermissionViaRole($permission);
        }
    
    
        protected function getDefaultGuardName(): string {
            return 'web';
        }
    
    
        /**
         * The attributes that are mass assignable.
         *
         * @var array
         */
        protected $fillable = [
            'id', 'slug', 'username', 'email', 'email_verified_at', 'created_at', 'password',
        ];
    
    
        /**
         * The attributes that should be hidden for arrays.
         *
         * @var array
         */
        protected $hidden = [
            'password', 'remember_token',
        ];
    
    
        /**
         * The attributes that should be cast to native types.
         *
         * @var array
         */
      
    
        protected $casts = [
            'email_verified_at' => 'datetime',
        ];
    
    
    
    }
    


    If this article help you kindly share , thanks for reading

    Continue Reading

    Laravel 7 comes with Easy Implicit Route Model Binding

    kizinho

    Published

    on

    NEWS: Laravel 7 comes with Easy Implicit Route Model Binding [New  Developer] » Naijacrawl
    Photo: Naijacrawl

    Laravel 7 will be out 2020 with new awesome features. You can clean the way routing is been done with one line of code.

    But you can try the dev version by running this code

    laravel new example --dev
    


    In laravel 7 you can bind routes like this:


    Route::get('/posts/{post:slug}', function (Post $post) {
        // ...
    });
    
    


    Currently, Laravel 6 and below requires you to define a getRouteKeyName() method on the model like so:

    <?php
    
    class Post extends Model
    {
        /**
         * Get the route key for the model.
         *
         * @return string
         */
        public function getRouteKeyName()
        {
            return 'slug';
        }
    }
    


    You can use the below route binding when you have multiple routes that you want to bind differently.

    For example, the frontend route uses slugs to display posts and backend admin uses ids to manage posts:


    Route::get('/posts/{post:slug}', function (Post $post) {
        // ...
    });
    
    // Or you could use the default `{post}` here...
    Route::get('/admin/posts/{post:id}/edit', function (Post $post) {
        // ...
    });
    


    Thanks for reading.



    Continue Reading

    Latest