DEV Community

devbalop
devbalop

Posted on

"Laravel: Real-time Application Data Issue Export Directly To A Slack Channel"

User interaction is vital for an application's success. With more users, chances of use case issues arises, thereby creating bad data in your application's db. Addressing these in real-time is crucial. Imagine if your app could proactively report defects or bad data to the team before clients notice.

In this article, I'll show you how to integrate direct reporting to Slack via a Slack app, streamlining the process.

In this article, I will cover;

  • Creating A Slack App

  • Creating sample command that handles recognising failed payments with reference to a simple E-commerce payment system

Creating a slack app
To get started, go to Slack and click on the "Create New App" button. Then, select the first option as shown in the image below.

Image description

Enter the application name, choose a workspace, and then press the "Create App" button to save the form.

Image description

After creating our app, choose the "Incoming Webhooks" option and toggle it on the next screen.

Image description

Navigate to the bottom of the page and select "Add New Webhook to Workspace." Then, on the following screen, pick a channel and click "Allow."

Image description

Slack will generate a webhook URL. Copy it and paste it into your app's .env file as shown below.

FAILED_PAYMENT_SLACK_WEBHOOK_URL=https://hooks.slack.com/services/xxxxxxxxxx
Enter fullscreen mode Exit fullscreen mode

Creating sample command

In Laravel, commands are custom, reusable scripts that perform specific tasks within the application. They can be executed via the command line interface (CLI) and are useful for automating tasks, such as database migrations, scheduled jobs, and custom operations.

In Laravel, custom commands are typically stored in the app/Console/Commands directory. You can create a new command using the Artisan CLI or by manually creating a new PHP file in that directory.

Here's an example of a basic command:

  1. Creating a Command

You can create a command using Artisan. Open your terminal and run:

php artisan make:command ExportFailedPayments

This will generate a new command file named ExportFailedPayments.php in the app/Console/Commands directory.

  1. Sample Command Code

Open the generated ExportFailedPayments.php file and you'll find something like this:

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;

class ExportFailedPayments extends Command
{
    protected $signature = 'export:failed-payments';
    protected $description = 'Export failed payments to CSV and send to server';

    public function handle()
    {
        // Generate CSV data (replace this with your actual logic)
        $csvData = [
            ['order_id', 'payment_id', 'status'],
            [1, 101, 'failed'],
            [2, 102, 'failed'],
            // Add more rows as needed
        ];

        $csvFilePath = storage_path('app/failed_payments.csv');
        $file = fopen($csvFilePath, 'w');

        foreach ($csvData as $row) {
            fputcsv($file, $row);
        }

        fclose($file);

        $message = "Daily Failed Payment Report:\n
        File: <" . file_get_contents($csvFilePath) . "|Download CSV>";

        $data = [
            'text' => $message,
        ];

        Http::post(env('FAILED_PAYMENT_SLACK_WEBHOOK_URL'), $data); // Replace with your actual slack webhook url.


        // Clean up: Delete the local CSV file
        unlink($csvFilePath);
    }
}
Enter fullscreen mode Exit fullscreen mode
  1. Using the Command

You can now execute this command in the terminal using its signature:

php artisan export:failed-payments
Enter fullscreen mode Exit fullscreen mode

This will trigger the handle method, and any logic you place there will be executed.

Remember, this is a basic example. Commands can perform a wide range of tasks, from database operations to complex data processing. But we are only referencing a failed payment export instance in this article.

In E-commerce, it is important to reconcile failed payment as early as possible, so in this article, I will show you how to create a cron job that schedules this command above to run as often as you want it to.

To schedule this command to run at e.g (5pm every day), you'll need to add an entry to your Laravel scheduler. Open the App\Console\Kernel.php file and add the following code to the $commands array:

protected $commands = [
    // ... other commands ...
    Commands\ExportFailedPayments::class,
];
Enter fullscreen mode Exit fullscreen mode

Next, in the schedule method of the same file, add the following line to schedule the command:

protected function schedule(Schedule $schedule)
{
    // ... other scheduled tasks ...

    $schedule->command('export:failed-payments')
             ->dailyAt('17:00'); // This will run the command at 5:00 PM
}
Enter fullscreen mode Exit fullscreen mode

Now, your ExportFailedPayments command will be scheduled to run at 5:00 PM every day. Make sure your server is correctly configured to handle Laravel's scheduled tasks (using cron or task scheduler depending on your server environment).

Below, you'll find an example of the report based on the focus of this article.

Image description

I hope this was helpful. Thanks for dropping by!

Top comments (1)

Collapse
 
dotmarn profile image
Kasim Ridwan

You don't need to add the command class within $commands array since you are using the command signature within the schedule method