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-…


This content originally appeared on DEV Community and was authored by Nasrul Hazim Bin Mohamad

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-client --git --jet --stack=livewire 
php artisan queue:table
php artisan migrate

Install & Configure the Package

And install the package:

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

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' => [],
];

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),

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
],

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

QUEUE_CONNECTION=database

The Syntax

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

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

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:

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();
    });
}

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,
    ]);
});

Then we need to disable the Verify CSRF Token:

protected $except = [
    'webhook/handler'
];

Testing the Webhook

Now, let's test the webhook:

# Run in first terminal
php artisan serve
# Run in second terminal
php artisan queue:work

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 (
    ),
  )),
)  

Congratulations! You have successfully setup the Webhook Server!

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


This content originally appeared on DEV Community and was authored by Nasrul Hazim Bin Mohamad


Print Share Comment Cite Upload Translate Updates
APA

Nasrul Hazim Bin Mohamad | Sciencx (2022-07-12T04:46:14+00:00) Webhook – Part II. Retrieved from https://www.scien.cx/2022/07/12/webhook-part-ii/

MLA
" » Webhook – Part II." Nasrul Hazim Bin Mohamad | Sciencx - Tuesday July 12, 2022, https://www.scien.cx/2022/07/12/webhook-part-ii/
HARVARD
Nasrul Hazim Bin Mohamad | Sciencx Tuesday July 12, 2022 » Webhook – Part II., viewed ,<https://www.scien.cx/2022/07/12/webhook-part-ii/>
VANCOUVER
Nasrul Hazim Bin Mohamad | Sciencx - » Webhook – Part II. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/07/12/webhook-part-ii/
CHICAGO
" » Webhook – Part II." Nasrul Hazim Bin Mohamad | Sciencx - Accessed . https://www.scien.cx/2022/07/12/webhook-part-ii/
IEEE
" » Webhook – Part II." Nasrul Hazim Bin Mohamad | Sciencx [Online]. Available: https://www.scien.cx/2022/07/12/webhook-part-ii/. [Accessed: ]
rf:citation
» Webhook – Part II | Nasrul Hazim Bin Mohamad | Sciencx | https://www.scien.cx/2022/07/12/webhook-part-ii/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.