Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/wayofdev/laravel-webhook-client
Receive webhooks in Laravel apps with support of Cycle-ORM.
https://github.com/wayofdev/laravel-webhook-client
cycle cycle-orm http laravel payments php php8 spatie stripe webhooks
Last synced: about 2 months ago
JSON representation
Receive webhooks in Laravel apps with support of Cycle-ORM.
- Host: GitHub
- URL: https://github.com/wayofdev/laravel-webhook-client
- Owner: wayofdev
- License: mit
- Created: 2023-08-06T22:45:16.000Z (over 1 year ago)
- Default Branch: master
- Last Pushed: 2024-05-28T18:16:03.000Z (8 months ago)
- Last Synced: 2024-05-29T02:34:01.304Z (8 months ago)
- Topics: cycle, cycle-orm, http, laravel, payments, php, php8, spatie, stripe, webhooks
- Language: PHP
- Homepage: https://wayof.dev
- Size: 1.06 MB
- Stars: 1
- Watchers: 1
- Forks: 0
- Open Issues: 11
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- Funding: .github/FUNDING.yml
- License: LICENSE
- Code of conduct: .github/CODE_OF_CONDUCT.md
Awesome Lists containing this project
README
# Receive webhooks in Laravel apps
Webhooks offer a mechanism for one application to inform another about specific events, typically using a straightforward HTTP request.
The [wayofdev/laravel-webhook-client](https://github.com/wayofdev/laravel-webhook-client) package facilitates the reception of webhooks in a Laravel application, leveraging the power of cycle-orm. Features include verifying signed calls, storing payload data, and processing the payloads in a queued job.
This package is inspired by and re-written from the original [spatie/laravel-webhook-client](https://github.com/spatie/laravel-webhook-client) to incorporate [Cycle-ORM](https://cycle-orm.dev) support.
## ๐ฟ Installation
### โ Using composer
Require as dependency:
```bash
$ composer req wayofdev/laravel-webhook-client
```### โ Configuring the package
You can publish the config file with:
```bash
php artisan vendor:publish \
--provider="WayOfDev\WebhookClient\Bridge\Laravel\Providers\WebhookClientServiceProvider" \
--tag="config"
```This is the contents of the file that will be published at `config/webhook-client.php`:
```php
[
[
/*
* This package supports multiple webhook receiving endpoints. If you only have
* one endpoint receiving webhooks, you can use 'default'.
*/
'name' => 'default',/*
* We expect that every webhook call will be signed using a secret. This secret
* is used to verify that the payload has not been tampered with.
*/
'signing_secret' => env('WEBHOOK_CLIENT_SECRET'),/*
* The name of the header containing the signature.
*/
'signature_header_name' => 'Signature',/*
* This class will verify that the content of the signature header is valid.
*
* It should implement \WayOfDev\WebhookClient\Contracts\SignatureValidator
*/
'signature_validator' => DefaultSignatureValidator::class,/*
* This class determines if the webhook call should be stored and processed.
*/
'webhook_profile' => ProcessEverythingWebhookProfile::class,/*
* This class determines the response on a valid webhook call.
*/
'webhook_response' => DefaultRespondsTo::class,/*
* The classname of the entity to be used to store webhook calls. The class should
* be equal or extend WayOfDev\WebhookClient\Entities\WebhookCall.
*/
'webhook_entity' => WebhookCall::class,/*
* The classname of the repository to be used to store webhook calls. The class should
* implement WayOfDev\WebhookClient\Contracts\WebhookCallRepository.
*/
'webhook_entity_repository' => ORMWebhookCallRepository::class,/*
* In this array, you can pass the headers that should be stored on
* the webhook call entity when a webhook comes in.
*
* To store all headers, set this value to `*`.
*/
'store_headers' => [
'*',
],/*
* The class name of the job that will process the webhook request.
*
* This should be set to a class that extends \WayOfDev\WebhookClient\Jobs\ProcessWebhookJob.
*/
'process_webhook_job' => '',
],
],/*
* The integer amount of days after which database records should be deleted.
*
* 7 deletes all records after 1 week. Set to null if no database records should be deleted.
*/
'delete_after_days' => 30,
];
```In the `signing_secret` key of the config file, you should add a valid webhook secret. This value should be provided by the app that will send you webhooks.
This package will try to store and respond to the webhook as fast as possible. Processing the payload of the request is done via a queued job. It's recommended to not use the `sync` driver but a real queue driver. You should specify the job that will handle processing webhook requests in the `process_webhook_job` of the config file. A valid job is any class that extends `WayOfDev\WebhookClient\Bridge\Laravel\Jobs\ProcessWebhookJob` and has a `handle` method.
### โ Preparing the database
By default, all webhook calls will get saved in the database.
To create the table that holds the webhook calls:
1. You must have already configured and running [wayofdev/laravel-cycle-orm-adapter](https://github.com/wayofdev/laravel-cycle-orm-adapter) package in your Laravel project.
2. Edit `cycle.php` config to add WebhookCall entity to search paths:
```php
// ...
'tokenizer' => [
/*
* Where should class locator scan for entities?
*/
'directories' => [
__DIR__ . '/../src/Domain', // Your current project Entities
__DIR__ . '/../vendor/wayofdev/laravel-webhook-client/src/Entities', // Register new Entity
],
// ...
],
```3. After editing config, run command to generate new migrations from newly appeared entity:
```bash
$ php artisan cycle:orm:migrate
```**(Optional):** To view list of migrations, to be executed:
```bash
$ php artisan cycle:migrate:status
```4. Run outstanding migrations using command:
```bash
$ php artisan cycle:migrate
```### โ Taking care of routing
Finally, let's take care of the routing. At the app that sends webhooks, you probably configure an URL where you want your webhook requests to be sent. In the routes file of your app, you must pass that route to `Route::webhooks`. Here's an example:
```php
Route::webhooks('webhook-receiving-url');
```Behind the scenes, by default this will register a `POST` route to a controller provided by this package. Because the app that sends webhooks to you has no way of getting a csrf-token, you must add that route to the `except` array of the `VerifyCsrfToken` middleware:
```php
protected $except = [
'webhook-receiving-url',
];
```
## ๐ป Usage
Once you've completed the installation, here's a comprehensive breakdown of how the package functions:
1. **Signature Verification:**
* The package initiates by verifying the incoming request's signature.
* If the signature doesn't pass the verification, an exception is thrown, the `InvalidSignatureEvent` event is fired, and the request isn't saved to the database.
2. **Webhook Profile Evaluation:**
* Each incoming request interacts with a webhook profile, which is essentially a class that evaluates if a request should be both saved and processed within your application.
* This profile enables filtering of specific webhook requests based on the app's requirements.
* [Your own custom webhook profile](#-determining-which-webhook-requests-should-be-stored-and-processed) can be created, to change or extend this logic.
3. **Storage & Processing:**
* If the profile gives the go-ahead, the request is first saved in the `webhook_calls` table.
* Subsequently, a queued job handles the `WebhookCall` entity.
* Webhooks usually expect a fast response, so by queuing jobs, we can respond quickly.
* Configuration for the job processing the webhook is found under the `process_webhook_job` in the `webhook-client` config file.
* If any issues arise during job queuing, the package logs the exception within the `exception` field of the `WebhookCall` entity.
4. **Webhook Response:**
* Once the job is dispatched, a webhook response takes charge. This class determines the HTTP response for the request.
* By default, a `200` status code with an 'ok' message is returned. However, you can also craft a custom webhook response. Learn how to easily [create your own webhook response](#-creating-your-own-webhook-response).### โ Verifying the signature of incoming webhooks
This package assumes that an incoming webhook request has a header that can be used to verify the payload has not been tampered with. The name of the header containing the signature can be configured in the `signature_header_name` key of the config file. By default, the package uses the `DefaultSignatureValidator` to validate signatures. This is how that class will compute the signature.
```php
$computedSignature = hash_hmac(
'sha256',
$request->getContent(),
$configuredSigningSecret
);
```If the `$computedSignature` does match the value, the request will be [passed to the webhook profile](#-determining-which-webhook-requests-should-be-stored-and-processed). If `$computedSignature` does not match the value in the signature header, the package will respond with a `500` and discard the request.
### โ Creating your own signature validator
A signature validator is any class that implements `WayOfDev\WebhookClient\Contracts\SignatureValidator`. Here's what that interface looks like.
```php
webhookCall // contains an instance of `WebhookCall`// perform the work here
}
}
```You should specify the class name of your job in the `process_webhook_job` of the `webhook-client` config file.
### โ Creating your own webhook response
A webhook response is any class that implements `\WayOfDev\WebhookClient\Contracts\RespondsToWebhook`. This is what that interface looks like:
```php
[
[
'name' => 'webhook-sending-app-1',
'signing_secret' => 'secret-for-webhook-sending-app-1',
'signature_header_name' => 'Signature-for-app-1',
'signature_validator' => DefaultSignatureValidator::class,
'webhook_profile' => ProcessEverythingWebhookProfile::class,
'webhook_response' => DefaultRespondsTo::class,
'webhook_entity' => WebhookCall::class,
'webhook_entity_repository' => ORMWebhookCallRepository::class,
'process_webhook_job' => '',
],
[
'name' => 'webhook-sending-app-2',
'signing_secret' => 'secret-for-webhook-sending-app-2',
'signature_header_name' => 'Signature-for-app-2',
'signature_validator' => DefaultSignatureValidator::class,
'webhook_profile' => ProcessEverythingWebhookProfile::class,
'webhook_response' => DefaultRespondsTo::class,
'webhook_entity' => WebhookCall::class,
'webhook_entity_repository' => ORMWebhookCallRepository::class,
'process_webhook_job' => '',
],
],
];
```When registering routes for the package, you should pass the `name` of the config as a second parameter.
```php
Route::webhooks('receiving-url-for-app-1', 'webhook-sending-app-1');
Route::webhooks('receiving-url-for-app-2', 'webhook-sending-app-2');
```### โ Change route method
Being an incoming webhook client, there are instances where you might want to establish a route method other than the default `post`. You have the flexibility to modify the standard post method to options such as `get`, `put`, `patch`, or `delete`.
```php
Route::webhooks('receiving-url-for-app-1', 'webhook-sending-app-1', 'get');
Route::webhooks('receiving-url-for-app-1', 'webhook-sending-app-1', 'put');
Route::webhooks('receiving-url-for-app-1', 'webhook-sending-app-1', 'patch');
Route::webhooks('receiving-url-for-app-1', 'webhook-sending-app-1', 'delete');
```### โ Using the package without a controller
If you don't want to use the routes and controller provided by your macro, you can programmatically add support for webhooks to your own controller.
`WayOfDev\WebhookClient\WebhookProcessor` is a class that verifies the signature, calls the web profile, stores the webhook request, and starts a queued job to process the stored webhook request. The controller provided by this package also uses that class [under the hood](https://github.com/wayofdev/laravel-webhook-client/blob/56167f0be276f41b947cc6c7a5bd30230b8a08d6/src/Bridge/Laravel/Http/Controllers/WebhookController.php#L25).
It can be used like this:
```php
use WayOfDev\WebhookClient\Entities\WebhookCall;
use WayOfDev\WebhookClient\Persistence\ORMWebhookCallRepository;
use WayOfDev\WebhookClient\Profile\ProcessEverythingWebhookProfile;
use WayOfDev\WebhookClient\Response\DefaultRespondsTo;
use WayOfDev\WebhookClient\SignatureValidator\DefaultSignatureValidator;
use WayOfDev\WebhookClient\Config;
use WayOfDev\WebhookClient\WebhookProcessor;$webhookConfig = new Config([
'name' => 'webhook-sending-app-1',
'signing_secret' => 'secret-for-webhook-sending-app-1',
'signature_header_name' => 'Signature',
'signature_validator' => DefaultSignatureValidator::class,
'webhook_profile' => ProcessEverythingWebhookProfile::class,
'webhook_response' => DefaultRespondsTo::class,
'webhook_entity' => WebhookCall::class,
'webhook_entity_repository' => ORMWebhookCallRepository::class,
'process_webhook_job' => '',
]);(new WebhookProcessor($request, $webhookConfig))->process();
```### โ Deleting entities
Whenever a webhook comes in, this package will store as a `WebhookCall` entity. After a while, you might want to delete old entities.
@todo Laravel version uses mass-prunable trait, so, entity deletion logic should be re-written using laravel console commands or by committing to cycle-orm.
In this example all entities will be deleted when older than 30 days.
```php
return [
'configs' => [
// ...
],'delete_after_days' => 30,
];
```
## ๐งช Running Tests
### โ PHPUnit tests
To run tests, run the following command:
```bash
$ make test
```### โ Static Analysis
Code quality using PHPStan:
```bash
$ make lint-stan
```### โ Coding Standards Fixing
Fix code using The PHP Coding Standards Fixer (PHP CS Fixer) to follow our standards:
```bash
$ make lint-php
```
## ๐ค License
[![Licence](https://img.shields.io/github/license/wayofdev/laravel-webhook-client?style=for-the-badge&color=blue)](./LICENSE)
## ๐งฑ Credits and Useful Resources
This repository is based on the [spatie/laravel-webhook-client](https://github.com/spatie/laravel-webhook-client) work.
## ๐๐ผโโ๏ธ Author Information
Created in **2023** by [lotyp / wayofdev](https://github.com/wayofdev)
## ๐ Want to Contribute?
Thank you for considering contributing to the wayofdev community! We are open to all kinds of contributions. If you want to:
- ๐ค Suggest a feature
- ๐ Report an issue
- ๐ Improve documentation
- ๐จโ๐ป Contribute to the code