ThakurCoder

Webhooks in laravel: when sending and receiving messages, make sure both ends are aligned

·4 min read
laravel
best practices

Ever tried getting two systems to play nice with each other? It’s like trying to get two cats to share a sunbeam—tricky but totally worth it. Webhooks are the digital equivalent of sending a friendly nudge to say, “Hey, something’s happening over here!” And when it comes to setting this up in Laravel, Spatie’s got your back with not one but two nifty packages: laravel-webhook-client and laravel-webhook-server. Let's dive in and hook up your apps with a touch of humor and a splash of Laravel magic!

The Webhook Tango: Two Steps to Success

In this dance, you’ve got two partners: App A (the sender) and App B (the receiver). App A will be sending out the webhook requests like a digital carrier pigeon, while App B will be catching and processing them with open arms.

Setting Up App B: The Webhook Receiver

Install the Webhook Client Package

First things first, App B needs to be ready to catch those webhooks. Install the Spatie Webhook Client package with:

composer require spatie/laravel-webhook-client

Publish the Configuration

Next, give App B a configuration file to work with:

php artisan vendor:publish --provider="Spatie\WebhookClient\WebhookClientServiceProvider"

Configure the Webhook Client

Open config/webhook-client.php and set the stage for receiving webhooks:

return [
'webhook_url' => env('WEBHOOK_URL'),

'signature_header_name' => 'X-Signature',

'webhook' => [
    'secret' => env('WEBHOOK_SECRET'),
],

];

And in your .env file, make sure to set the URL and secret key:

WEBHOOK_URL=http://app-b.example.com/webhook
WEBHOOK_SECRET=your_secret_key

Set Up Webhook Handling

Create a controller to handle incoming webhooks:

php artisan make:controller WebhookController

In app/Http/Controllers/WebhookController.php:

namespace App\Http\Controllers;
use Illuminate\Http\Request;
class WebhookController extends Controller
{
public function handle(Request $request)
{
// Validate the webhook signature
$request->validate([
'X-Signature' => 'required',
]);
    // Process the incoming data
    $data = $request->all();
    // Handle the data (e.g., store it in the database)

    return response()->json(['status' => 'success']);
}

}

Add the route for the webhook in routes/web.php:

use App\Http\Controllers\WebhookController;

Route::post('/webhook', [WebhookController::class, 'handle']);

Setting Up App A: The Webhook Sender

Install the Webhook Server Package

Now, let’s get App A ready to send those webhooks. Install the Spatie Webhook Server package:

composer require spatie/laravel-webhook-server

Publish the Configuration

Publish the configuration file:

php artisan vendor:publish --provider="Spatie\WebhookServer\WebhookServerServiceProvider"

Configure the Webhook Server

Update config/webhook-server.php:

return [
    'webhook_url' => env('WEBHOOK_URL'),
    'webhook_secret' => env('WEBHOOK_SECRET'),
];

And add the following to your .env file:

WEBHOOK_URL=http://app-b.example.com/webhook
WEBHOOK_SECRET=your_secret_key

Send a Webhook

Create a service to send the webhook:

// app/Services/WebhookService.php
namespace App\Services;
use Spatie\WebhookServer\WebhookCall;
class WebhookService
{
protected $webhookUrl;
public function __construct()
{
    $this->webhookUrl = config('webhook-server.webhook_url');
}

public function send($data)
{
    WebhookCall::create()
        ->url($this->webhookUrl)
        ->payload($data)
        ->useSecret(config('webhook-server.webhook_secret'))
        ->dispatch();
}

}

Use this service in a controller:

// app/Http/Controllers/ExampleController.php
namespace App\Http\Controllers;
use App\Services\WebhookService;
class ExampleController extends Controller
{
protected $webhookService;
public function __construct(WebhookService $webhookService)
{
    $this->webhookService = $webhookService;
}

public function triggerWebhook()
{
    $data = [
        'key' => 'value',
        'another_key' => 'another_value',
    ];

    try {
        $this->webhookService->send($data);
        return response()->json(['status' => 'Webhook sent successfully']);
    } catch (\Exception $e) {
        return response()->json(['status' => 'Error sending webhook', 'message' => $e->getMessage()], 500);
    }
}

}

Add the route for triggering the webhook in routes/web.php:

use App\Http\Controllers\ExampleController;

Route::post('/trigger-webhook', [ExampleController::class, 'triggerWebhook']);

Conclusion: Webhooks Done Right

And there you have it! With Spatie’s laravel-webhook-client and laravel-webhook-server, you’re all set to get your Laravel apps talking to each other. It’s like setting up a digital hotline between App A and App B—no more shouting across the room, just seamless communication. Remember, setting up webhooks is like making a fine wine—patience and precision make all the difference. Cheers to making your applications work together in perfect harmony!

Feel free to reach out if you have any more questions or need further assistance. Happy hooking!