DEV Community

Nasrul Hazim Bin Mohamad
Nasrul Hazim Bin Mohamad

Posted on • Updated on

Webhook - Part II

Continue from previous post, let's build our first Webhook Provider.

We going to build using Laravel, and a package from Spatie, Laravel Webhook Server.

Create New Laravel Project

Let's create a new Laravel project:

laravel new webhook-server --git --jet --stack=livewire 
# Skip following if running on Laravel 11
php artisan queue:table
php artisan migrate
Enter fullscreen mode Exit fullscreen mode

Install & Configure the Package

And install the package:

composer require spatie/laravel-webhook-server
php artisan vendor:publish --provider="Spatie\WebhookServer\WebhookServerServiceProvider"
Enter fullscreen mode Exit fullscreen mode

By default, Spatie already pre-configured your Webhook, as in config/webhook-server.php:

<?php

return [
    'queue' => 'default',
    'connection' => null,
    'http_verb' => 'post',
    'signer' => \Spatie\WebhookServer\Signer\DefaultSigner::class,
    'signature_header_name' => 'Signature',
    'headers' => [
        'Content-Type' => 'application/json',
    ],
    'timeout_in_seconds' => 3,
    'tries' => 3,
    'backoff_strategy' => \Spatie\WebhookServer\BackoffStrategy\ExponentialBackoffStrategy::class,
    'verify_ssl' => env('WEBHOOK_VERIFY_SSL', false),
    'throw_exception_on_failure' => false,
    'tags' => [],
];
Enter fullscreen mode Exit fullscreen mode

As for development, the verify_ssl, I want to turn it off - you can make it configurable by set as following:

'verify_ssl` = env('WEBHOOK_VERIFY_SSL', false),
Enter fullscreen mode Exit fullscreen mode

So by default, verify SSL is optional - unless in production I recommended to turn it on.

Another configuration that you might interested is setting the headers. This allow you to have some sort of identifier, that the payload is coming from you. I would suggest to add:

'headers' => [
    'Content-Type' => 'application/json',
    'X-App' => env('APP_NAME'),
    'X-Version' => 1.0
],
Enter fullscreen mode Exit fullscreen mode

Next, we going to use database queue, update the .env:

QUEUE_CONNECTION=database
Enter fullscreen mode Exit fullscreen mode

The Syntax

Now the fun part, send the payload. Sending the payload is a straightforward setup, as per in the documentation:

use Spatie\WebhookServer\WebhookCall;

WebhookCall::create()
   ->url('https://other-app.com/webhooks')
   ->payload(['key' => 'value'])
   ->useSecret('sign-using-this-secret')
   ->dispatch();
Enter fullscreen mode Exit fullscreen mode

As you can see here, it's just a few line of codes. Let's describe it a little bit.

The url() method, you need to provide the Webhook Consumer endpoint that receiving the data / information / payload from the Webhook Provider.

The payload() accept an array of data, which all the information you want to share with your Webhook Consumer.

The useSecret() is a secret key that your Webhook Consumer will share with you. So that, when Webhook Consumer receiving the payload, they will check against the signature sent by the Webhook Provider.

The dispatch(), basically send the payload to the queue job, to send the information to Webhook consumer. By default, the package will use the default queue. You can configure this in the config/webhook-server.php.

Sending the Payload

For this post, let's send to a Webhook Consumer, which need to know any newly created user from Webhook Provider.

Let's keep it simple, in your app/Models/User.php, add the following code snipppet:

use Spatie\WebhookServer\WebhookCall;
...
public static function boot() {

    parent::boot();

    static::created(function(User $model) {
        WebhookCall::create()
            ->url(url('webhook/handler'))
            ->payload($model->toArray())
            ->throwExceptionOnFailure()
            ->useSecret('sign-using-this-secret')
            ->dispatch();
    });
}
Enter fullscreen mode Exit fullscreen mode

What above code does, basically to call send information about the newly created user to the url('webhook/handler'), using the secret key provided and we set to throw an exception in case sending to Webhook Consumer is failed.

That's all for sending the data to Webhook Consumer.

Handling the Payload

For the sake of demonstrate that this Webhook Provide works, we going to receive the payload in the same Laravel app.

Create new route, in routes/web.php

Route::post('webhook/handler', function(Request $request) {
    logger()->info([
        'payload' => $request->all(),
        'headers' => $request->headers,
    ]);
});
Enter fullscreen mode Exit fullscreen mode

Then we need to disable the Verify CSRF Token.

For Laravel 10 and below, update your app/Http/Middleware/VerifyCsrfToken.php:

protected $except = [
    'webhook/handler'
];
Enter fullscreen mode Exit fullscreen mode

For Laravel 11, update your bootstrap/app.php:

<?php

use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        api: __DIR__.'/../routes/api.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware) {
        $middleware->validateCsrfTokens(except: [
            'webhook/handler',
        ]);
    })
    ->withExceptions(function (Exceptions $exceptions) {
        //
    })->create();
Enter fullscreen mode Exit fullscreen mode

Testing the Webhook

Now, let's test the webhook:

# Run in first terminal
php artisan serve
Enter fullscreen mode Exit fullscreen mode
# Run in second terminal
php artisan queue:work
Enter fullscreen mode Exit fullscreen mode

Visit the URL http://localhost:8000, then do the registration.

Once completed the registration, open up the storage/logs/laravel.log. You should see something like following:

[2022-07-12 03:03:17] local.INFO: array (
  'payload' => 
  array (
    'name' => 'Kirby Porter',
    'email' => 'sava@mailinator.com',
    'updated_at' => '2022-07-12T02:59:03.000000Z',
    'created_at' => '2022-07-12T02:59:03.000000Z',
    'id' => 5,
    'profile_photo_url' => 'https://ui-avatars.com/api/?name=K+P&color=7F9CF5&background=EBF4FF',
  ),
  'headers' => 
  Symfony\Component\HttpFoundation\HeaderBag::__set_state(array(
     'headers' => 
    array (
      'host' => 
      array (
        0 => '127.0.0.1:8000',
      ),
      'user-agent' => 
      array (
        0 => 'GuzzleHttp/7',
      ),
      'content-type' => 
      array (
        0 => 'application/json',
      ),
      'x-app' => 
      array (
        0 => 'Laravel',
      ),
      'x-version' => 
      array (
        0 => '1',
      ),
      'signature' => 
      array (
        0 => '665fcd8bd35088d46d577865ad1e2aa5e6ac51c8e1ea7cdc83cc700eec0d19c2',
      ),
      'content-length' => 
      array (
        0 => '240',
      ),
    ),
     'cacheControl' => 
    array (
    ),
  )),
)  
Enter fullscreen mode Exit fullscreen mode

Congratulations! You have successfully setup the Webhook Server!

Next, we going to setup the Webhook Consumer application. Read more at Webhook: Part III.

Top comments (0)