Webhook - Part II
Tags: webhook, integration
Published: 2022-07-12 04:46:14

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](https://github.com/spatie/laravel-webhook-server).

### Create New Laravel Project

Let's create a new Laravel project:

```bash
laravel new webhook-client --git --jet --stack=livewire 
php artisan queue:table
php artisan migrate
```

### Install & Configure the Package

And install the package:

```bash
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
<?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:

```php
'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:

```php
'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:

```php
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:

```php
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`

```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:

```php
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.