How to use FraudLabs Pro API to validate order in Bagisto?

How to use FraudLabs Pro API to validate order in Bagisto

Bagisto is an open source e-commerce framework that blends the power of Laravel and Vue.js. Bagisto aimed to help entrepreneurs to set up their online stores in a simple and efficient way. To cater the business’s needs, whether it’s big or small, Bagisto offers extensive features to the businessman. With its extensive community support and developer-friendly design, Bagisto is quickly becoming a go-to choice for modern e-commerce needs.

In addition to the pre-built functionality and extensions, Bagisto also allowed users to extend its capabilities by using various methods. For example, users can create a custom listener to listen on a pre-defined event, and customize the functionality they want. However, Bagisto currently lacks a built-in security feature to protect the merchants from the potential frauds. As a result, they will be exposed to the financial loss due to the fraudulent activity. Fortunately, the FraudLabs Pro API provides a reliable solution, empowering merchants with robust fraud detection and prevention tools.

In this tutorial, we are going to show how to call the FraudLabs Pro Screen Order API to validate the order in real-time, and also flag the order as fraud in the status so that the admin can be aware of the fraud order when reviewing the order history. If you are interested to get more information about the API, you can always refer to its documentation.

Before we get started, make sure that you have a FraudLabs Pro API key with you. If you don’t, you can always register for a free API key to get started. This tutorial will also assume that you have already installed and set up the Bagisto in your machine. If you haven’t, the simplest way to get it is to follow their installation instructions in their documentation to get started.

Steps to use FraudLabs Pro API in Bagisto

  1. Navigate to your Bagisto project in the command prompt, and run the following commands to generate two listeners files:
php artisan make:listener ValidateOrder
php artisan make:listener UpdateOrderStatus
  1. After that, open the app/Listeners/ValidateOrder.php file, and replace the content with the following code:
<?php

namespace App\Listeners;

use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Http;

use Illuminate\Support\Facades\Session;

class ValidateOrder
{
    /**
     * Create the event listener.
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     */
    public function handle($event): void
    {
        $apiKey = config('services.fraudlabspro.key');
        $order_id = $event['cart_id'] ?? '';

        // Prepare the payload
        $payload = [
            'key'               => $apiKey, // API Key from .env
            'ip'                 => request()->ip(),
            'email'              => $event['customer_email'] ?? '',
            'first_name' => $event['customer_first_name'] ?? '',
            'last_name'  => $event['customer_last_name'] ?? '',
            'user_phone'    => $event['billing_address']['phone'] ?? '',
            'bill_addr'    => $event['billing_address']['address'] ?? '',
            'bill_city'       => $event['billing_address']['city'] ?? '',
            'bill_state'      => $event['billing_address']['state'] ?? '',
            'bill_zip_code'   => $event['billing_address']['postcode'] ?? '',
            'bill_country'    => $event['billing_address']['country'] ?? '',
            'ship_first_name'=> $event['shipping_address']['first_name'] ?? '',
            'ship_last_name' => $event['shipping_address']['last_name'] ?? '',
            'ship_addr'   => $event['shipping_address']['address'] ?? '',
            'ship_city'      => $event['shipping_address']['city'] ?? '',
            'ship_state'     => $event['shipping_address']['state'] ?? '',
            'ship_zip_code'  => $event['shipping_address']['postcode'] ?? '',
            'ship_country'   => $event['shipping_address']['country'] ?? '',
            'amount'             => $event['grand_total'] ?? 0,
            'quantity'             => $event['total_qty_ordered'] ?? 0,
            'currency'           => $event['order_currency_code'] ?? 'USD',
            'order_id'           => $order_id,
            'user_agent'         => request()->userAgent(),
        ];

        // Send the payload to FraudLabs Pro API
        $response = Http::post('https://api.fraudlabspro.com/v2/order/screen', $payload);

        if ($response->ok()) {
            $validationResult = $response->json();

            // Log the validation result
            Log::info('FraudLabs Pro Validation Result:', $validationResult);

            if (isset($validationResult['fraudlabspro_status']) && $validationResult['fraudlabspro_status'] === 'REJECT') {
                Log::warning('Fraud detected. Halting order processing.');
                Session::put('fraud_detected', true);
            } else {
                Session::put('fraud_detected', false);
            }
        } else {
            // Log any HTTP errors
            Log::channel('custom')->error('FraudLabs Pro API Error', [
                'status' => $response->status(),
                'body'   => $response->body(),
            ]);
        }
    }
}
  1. Then, open the app/Listeners/UpdateOrderStatus.php file, and replace the content with the following code:
<?php

namespace App\Listeners;

use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Session;

class UpdateOrderStatus
{
    /**
     * Create the event listener.
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     */
    public function handle(object $event): void
    {
        if (Session::get('fraud_detected', false)) {
            Log::warning('Skipping order processing because fraud was detected.');
            $event->status = 'fraud';
            $event->save(); // Persist changes to the database
        }
    }
}
  1. Next, open the app/Providers/EventServiceProvider.php file, and change the variable $listen to the following code:
    protected $listen = [
        'checkout.order.save.before' => [
            \App\Listeners\ValidateOrder::class,
        ],
        'checkout.order.save.after' => [
            \App\Listeners\UpdateOrderStatus::class,
        ],
     ];
  1. Remember to save your FraudLabs Pro API key in your .env file like this: FRAUDLABSPRO_API_KEY=YOUR_API_KEY. Finally, open your config/services.php file, and place the following code as the last order in the array:
    'fraudlabspro' => [
        'key' => env('FRAUDLABSPRO_API_KEY'),
    ],
  1. Now the API shall be set up in your e-commerce site, and once the API detected any fraud order, you shall see the order had been flagged as fraud in your admin dashboard, for example, here is how it may looks like:

Fortify Your Business Against Fraud

Streamline your works with our fraud detection API now!

Was this article helpful?