Laravel SES Webhooks Client

Overview

Laravel SES Webhooks Client

Packagist GitHub-tag License Downloads GH-Actions codecov

Handle AWS SES webhook in Laravel php framework.

Installation

You can install the package via composer:

composer require "ankurk91/laravel-ses-webhooks"

The service provider will automatically register itself.

You must publish the config file with:

php artisan vendor:publish --provider="Ankurk91\SesWebhooks\SesWebhooksServiceProvider"

Next, you must publish the migration with:

php artisan vendor:publish --provider="Spatie\WebhookClient\WebhookClientServiceProvider" --tag="webhook-client-migrations"

After the migration has been published you can create the webhook_calls table by running the migrations:

php artisan migrate

Next, for routing, add this line to your routes/web.php

Route::sesWebhooks('/webhooks/ses');

Behind the scenes this will register a POST route to a controller provided by this package. Next, you must add that route to the except array of your VerifyCsrfToken middleware:

protected $except = [
    '/webhooks/*',
];

Prepare your AWS console for SES webhooks

  • Assuming that you have SES service up and running in your app already
  • Create a configuration set
  • Choose SNS as event destination
  • Choose HTTP as delivery method for that newly created SNS topic
  • Specify the webhook URL as ${APP_URL}/webhooks/ses
  • This package should auto confirm the subscription
  • You need to specify the configuration set name in your config/services.php
 'ses' => [
        'key' => env('AWS_ACCESS_KEY_ID'),
        'secret' => env('AWS_SECRET_ACCESS_KEY'),
        'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
        'options' => [
            'ConfigurationSetName' => env('AWS_SES_CONFIGURATION_SET'),
        ],
    ],

Usage

There are 2 way to handle incoming webhooks via this package.

1 - Handling webhook requests using jobs

If you want to do something when a specific event type comes in; you can define a job for that event. Here's an example of such job:



namespace App\Jobs\Webhooks\SES;

use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Arr;
use Spatie\WebhookClient\Models\WebhookCall;

class BounceHandler implements ShouldQueue
{
    use SerializesModels;

    public function __construct(public WebhookCall $webhookCall)
    {
        //
    }

    public function handle()
    {
        $message = $this->webhookCall->payload['Message'];
        
        if (Arr::get($message, 'bounce.bounceType') !== 'Permanent') return;

        foreach ($message['bounce']['bouncedRecipients'] as $recipient) {
            // todo do something with $recipient['emailAddress']
        }
    }
}

After having created your job you must register it at the jobs array in the config/ses-webhooks.php config file. The key should be lowercase and spaces should be replaced by _. The value should be a fully qualified classname.



return [
     'jobs' => [
          'bounce' => \App\Jobs\Webhooks\SES\BounceHandler::class,
     ],
];

2 - Handling webhook requests using events and listeners

Instead of queueing jobs to perform some work when a webhook request comes in, you can opt to listen to the events this package will fire. Whenever a valid request hits your app, the package will fire a ses-webhooks:: event.

The payload of the events will be the instance of WebhookCall that was created for the incoming request.

You can listen for such event by registering the listener in your EventServiceProvider class.

protected $listen = [
    'ses-webhooks::complaint' => [
        App\Listeners\SES\ComplaintListener::class,
    ],
];

Here's an example of such listener class:



namespace App\Listeners\SES;

use Illuminate\Contracts\Queue\ShouldQueue;
use Spatie\WebhookClient\Models\WebhookCall;

class ComplaintListener implements ShouldQueue
{
    public function handle(WebhookCall $webhookCall)
    {
        $message = $webhookCall->payload['Message'];
        
        foreach ($message['complaint']['complainedRecipients'] as $recipient) {
            // todo do something with $recipient['emailAddress']
        }
    }
}

Pruning old webhooks (opt-in)

You can schedule the artisan command to remove old webhooks from database like:


namespace App\Console;

use Illuminate\Console\Scheduling\Schedule; 
use Illuminate\Database\Console\PruneCommand;
use Ankurk91\SesWebhooks\SesWebhookCall;

class Kernel extends ConsoleKernel
{
    protected function schedule(Schedule $schedule)
    {
        $schedule->command(PruneCommand::class, [
            '--model' => [SesWebhookCall::class]
        ])
        ->onOneServer()
        ->daily()
        ->description('Prune webhook_calls for SES.');
    }
    
    //...
}

By default, the package is configured to keep past 30 days records only. You can adjust the duration in config/ses-webhooks.php file.

Changelog

Please see CHANGELOG for more information what has changed recently.

Testing

composer test

Security

If you discover any security issue, please email pro.ankurk1[at]gmail[dot]com instead of using the issue tracker.

Useful Links

Acknowledgment

This package is highly inspired by:

License

This package is licensed under MIT License.

You might also like...
Generator-hedley - Scaffold a headless Drupal backend, Angular app client, and Behat tests

generator-hedley Scaffold a headless Drupal backend, Angular app client, and Behat tests Hedley is a yeoman generator that scaffolds a headless Drupal

PHP API for GeoIP2 webservice client and database reader

GeoIP2 PHP API Description This package provides an API for the GeoIP2 and GeoLite2 web services and databases. Install via Composer We recommend inst

Hashtopolis is a multi-platform client-server tool for distributing hashcat tasks to multiple computers.
Hashtopolis is a multi-platform client-server tool for distributing hashcat tasks to multiple computers.

Hashtopolis is a multi-platform client-server tool for distributing hashcat tasks to multiple computers. The main goals for Hashtopolis's development are portability, robustness, multi-user support, and multiple groups management.

Symfony bundle that provides Cross Site Request Forgery (CSRF or XSRF) protection for client-side applications

CSRF Cookie Bundle This Symfony bundle provides Cross Site Request Forgery (CSRF or XSRF) protection for client-side applications requesting endpoints

A simple pure PHP RADIUS client supporting Standard and Vendor-Specific Attributes in single file

BlockBox-Radius A simple pure PHP RADIUS client supporting Standard and Vendor-Specific Attributes in single file Author: Daren Yeh [email protected]

PHP API for GeoIP2 webservice client and database reader

GeoIP2 PHP API Description This package provides an API for the GeoIP2 and GeoLite2 web services and databases. Install via Composer We recommend inst

List of 77 languages for Laravel Framework 4, 5, 6, 7 and 8, Laravel Jetstream , Laravel Fortify, Laravel Breeze, Laravel Cashier, Laravel Nova and Laravel Spark.

Laravel Lang In this repository, you can find the lang files for the Laravel Framework 4/5/6/7/8, Laravel Jetstream , Laravel Fortify, Laravel Cashier

⚡ Laravel Charts — Build charts using laravel. The laravel adapter for Chartisan.
⚡ Laravel Charts — Build charts using laravel. The laravel adapter for Chartisan.

What is laravel charts? Charts is a Laravel library used to create Charts using Chartisan. Chartisan does already have a PHP adapter. However, this li

Laravel Kickstart is a Laravel starter configuration that helps you build Laravel websites faster.

Laravel Kickstart What is Laravel Kickstart? Laravel Kickstart is a Laravel starter configuration that helps you build Laravel websites faster. It com

Owner
Ankur Kumar
Open Source Fanatic | Tinkerer | Spotify Addict
Ankur Kumar
Mollie API client wrapper for Laravel & Mollie Connect provider for Laravel Socialite

Mollie for Laravel Laravel-Mollie incorporates the Mollie API and Mollie Connect into your Laravel or Lumen project. Accepting iDEAL, Apple Pay, Banco

Mollie 289 Nov 24, 2022
A REST client inside your Laravel app

Laravel Compass is an elegant REST assistant for the Laravel framework that you can use to test API calls and create API documentation. it provides automatically endpoints for GET, POST, PUT/PATCH, DELETE, various auth mechanisms, and other utility endpoints based on Laravel routes in your project.

David H. Sianturi 1.2k Dec 31, 2022
Dashboard to view your http client requests in laravel application

Laravel Blanket is a package with wraps laravel http client requests and provide logs for request and response, also give option to retry any request from dashboard and more...

Ahmed waleed 215 Dec 29, 2022
Websockets-Client (Sample) laravel

About Laravel Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experie

Filimantaptius Gulo 1 Mar 8, 2022
This is a laravel 4 package for the server and client side of datatables at http://datatables.net/

Datatable Important This package will not receive any new updates! You can still use this package, but be preparared that there is no active developme

Nils Plaschke 388 Dec 30, 2022
Minimal GraphQL client for Laravel.

Minimal GraphQL Laravel Client Minimal GraphQL client for Laravel. Requirements Composer 2+ Installation Install Package (Composer 2+) composer requir

David Gutierez Bendeck 20 Dec 7, 2022
Laravel Abdal Detector - Find info about IP , OS and web browser from your client

Laravel Abdal Detector - Find info about IP , OS and web browser from your client

 Abdal Security Group 1 Mar 24, 2022
A OpenID connect client for Laravel framework.

Introduction A OpenID connect client for Laravel framework. Install composer require package/oidc:^1.0 Configuration php artisan vendor:publish --tag=

Betterde 2 Sep 17, 2022
PHP client library for reCAPTCHA, a free service to protect your website from spam and abuse.

reCAPTCHA PHP client library reCAPTCHA is a free CAPTCHA service that protects websites from spam and abuse. This is a PHP library that wraps up the s

Google 3.3k Dec 23, 2022
Shared code for the MaxMind Web Service PHP client APIs

Common Code for MaxMind Web Service Clients This is not intended for direct use by third parties. Rather, it is for shared code between MaxMind's vari

MaxMind 264 Jan 3, 2023