wayofdev / laravel-stripe-webhooks
Handle Stripe webhooks in a Laravel application with support of Cycle-ORM.
Fund package maintenance!
wayofdev
Installs: 1 957
Dependents: 0
Suggesters: 0
Security: 0
Stars: 1
Watchers: 1
Forks: 0
Open Issues: 12
Requires
- php: ^8.2
- cycle/database: ^2.8
- cycle/orm: ^2.7
- laravel/framework: ^v10.46
- stripe/stripe-php: ^14.0
- wayofdev/laravel-webhook-client: ^1.3
Requires (Dev)
- ergebnis/composer-normalize: ^2.42
- larastan/larastan: ^2.9
- orchestra/testbench: ^8.21
- pestphp/pest: ^2.34
- pestphp/pest-plugin-laravel: ^2.3
- phpstan/extension-installer: ^1.3
- phpstan/phpstan: ^1.10
- phpstan/phpstan-deprecation-rules: ^1.1
- phpstan/phpstan-phpunit: ^1.3
- phpstan/phpstan-strict-rules: ^1.5
- phpunit/phpunit: ^10.5
- roave/security-advisories: dev-latest
- wayofdev/cs-fixer-config: ^1.2
- dev-master
- v2.1.47
- v2.1.46
- v2.1.45
- v2.1.44
- v2.1.43
- v2.1.42
- v2.1.41
- v2.1.40
- v2.1.39
- v2.1.38
- v2.1.37
- v2.1.36
- v2.1.35
- v2.1.34
- v2.1.33
- v2.1.32
- v2.1.31
- v2.1.30
- v2.1.29
- v2.1.28
- v2.1.27
- v2.1.26
- v2.1.25
- v2.1.24
- v2.1.23
- v2.1.22
- v2.1.21
- v2.1.20
- v2.1.19
- v2.1.18
- v2.1.17
- v2.1.16
- v2.1.15
- v2.1.14
- v2.1.13
- v2.1.12
- v2.1.11
- v2.1.10
- v2.1.9
- v2.1.8
- v2.1.7
- v2.1.6
- v2.1.5
- v2.1.4
- v2.1.3
- v2.1.2
- v2.1.1
- v2.1.0
- v2.0.0
- v1.1.94
- v1.1.93
- v1.1.92
- v1.1.91
- v1.1.90
- v1.1.89
- v1.1.88
- v1.1.87
- v1.1.86
- v1.1.85
- v1.1.84
- v1.1.83
- v1.1.82
- v1.1.81
- v1.1.80
- v1.1.79
- v1.1.78
- v1.1.77
- v1.1.76
- v1.1.75
- v1.1.74
- v1.1.73
- v1.1.72
- v1.1.71
- v1.1.70
- v1.1.69
- v1.1.68
- v1.1.67
- v1.1.66
- v1.1.65
- v1.1.64
- v1.1.63
- v1.1.62
- v1.1.61
- v1.1.60
- v1.1.59
- v1.1.58
- v1.1.57
- v1.1.56
- v1.1.55
- v1.1.54
- v1.1.53
- v1.1.52
- v1.1.51
- v1.1.50
- v1.1.49
- v1.1.48
- v1.1.47
- v1.1.46
- v1.1.45
- v1.1.44
- v1.1.43
- v1.1.42
- v1.1.41
- v1.1.40
- v1.1.39
- v1.1.38
- v1.1.37
- v1.1.36
- v1.1.35
- v1.1.34
- v1.1.33
- v1.1.32
- v1.1.31
- v1.1.30
- v1.1.29
- v1.1.28
- v1.1.27
- v1.1.26
- v1.1.25
- v1.1.24
- v1.1.23
- v1.1.22
- v1.1.21
- v1.1.20
- v1.1.19
- v1.1.18
- v1.1.17
- v1.1.16
- v1.1.15
- v1.1.14
- v1.1.13
- v1.1.12
- v1.1.11
- v1.1.10
- v1.1.9
- v1.1.8
- v1.1.7
- v1.1.6
- v1.1.5
- v1.1.4
- v1.1.3
- v1.1.2
- v1.1.1
- v1.1.0
- v1.0.4
- v1.0.3
- v1.0.2
- v1.0.1
- v1.0.0
- dev-renovate/laravel-framework-10.x-lockfile
- dev-renovate/phpstan-packages
- dev-renovate/cycle-orm-2.x-lockfile
- dev-renovate/orchestra-testbench-8.x-lockfile
- dev-renovate/wayofdev-cs-fixer-config-1.x-lockfile
- dev-renovate/stripe-stripe-php-14.x-lockfile
- dev-renovate/lock-file-maintenance
- dev-renovate/laravel-framework-11.x
- dev-renovate/phpunit-phpunit-11.x
- dev-renovate/orchestra-testbench-9.x
- dev-renovate/wayofdev-laravel-webhook-client-1.x-lockfile
- dev-codesee-arch-diagram-workflow-1691510819028
This package is auto-updated.
Last update: 2024-12-20 16:40:27 UTC
README
Handle Stripe Webhooks in a Laravel application with Cycle-ORM integration
Stripe can notify your application of various events using webhooks. This package simplifies the process of handling those webhooks. Out of the box, it verifies the Stripe signature for all incoming requests.
Once verified, all valid webhook calls will be logged to the database using Cycle-ORM. You can effortlessly define jobs or events to be dispatched when certain events are received by your app.
However, please note that this package only manages the initial webhook request validation and the dispatching of corresponding jobs or events.
The subsequent actions (e.g., regarding payments) should be implemented separately by the developer. Before diving into this package, it's highly recommended to familiarize yourself with Stripe's comprehensive documentation on webhooks.
If you like/use this package, please consider starring it. Thanks!
๐ฟ Installation
โ Using Composer
Require as dependency:
$ composer req wayofdev/laravel-stripe-webhooks
The service provider will automatically register itself.
โ Configuring the Package
You must publish the config file with:
$ php artisan vendor:publish \ --provider="WayOfDev\StripeWebhooks\Bridge\Laravel\Providers\StripeWebhooksServiceProvider" \ --tag="config"
This is the contents of the config file that will be published at config/stripe-webhooks.php
:
<?php declare(strict_types=1); use WayOfDev\StripeWebhooks\Profile\StripeWebhookProfile; use WayOfDev\WebhookClient\Entities\WebhookCall; use WayOfDev\WebhookClient\Persistence\ORMWebhookCallRepository; return [ /* * Stripe will sign each webhook using a secret. You can find the used secret at the * webhook configuration settings: https://dashboard.stripe.com/account/webhooks. */ 'signing_secret' => env('STRIPE_WEBHOOK_SECRET'), /* * You can define a default job that should be run for all other Stripe event type * without a job defined in next configuration. * You may leave it empty to store the job in database but without processing it. */ 'default_job' => '', /* * You can define the job that should be run when a certain webhook hits your application * here. The key is the name of the Stripe event type with the `.` replaced by a `_`. * * You can find a list of Stripe webhook types here: * https://stripe.com/docs/api#event_types. */ 'jobs' => [ // 'source_chargeable' => \App\Jobs\StripeWebhooks\HandleChargeableSource::class, // 'charge_failed' => \App\Jobs\StripeWebhooks\HandleFailedCharge::class, ], /* * The classname of the entity to be used to store webhook calls. The class should * be equal or extend WayOfDev\WebhookClient\Entities\WebhookCall. */ 'entity' => WebhookCall::class, /* * The classname of the repository to be used to store webhook calls. The class should * implement WayOfDev\WebhookClient\Contracts\WebhookCallRepository. */ 'entity_repository' => ORMWebhookCallRepository::class, /* * This class determines if the webhook call should be stored and processed. */ 'profile' => StripeWebhookProfile::class, /* * Specify a connection and or a queue to process the webhooks */ 'connection' => env('STRIPE_WEBHOOK_CONNECTION'), 'queue' => env('STRIPE_WEBHOOK_QUEUE'), /* * When disabled, the package will not verify if the signature is valid. * This can be handy in local environments. */ 'verify_signature' => env('STRIPE_SIGNATURE_VERIFY', true), ];
In the signing_secret
key of the config file you should add a valid webhook secret. You can find the secret used at the webhook configuration settings on the Stripe dashboard.
โ Preparing the Database
By default, all webhook calls will get saved in the database.
To create the table for storing webhook calls:
-
Ensure you've already set up and are running the wayofdev/laravel-cycle-orm-adapter package in your Laravel project.
-
Modify the
cycle.php
config to include theWebhookCall
entity in search paths:// ... 'tokenizer' => [ /* * Directories to scan for entities. */ 'directories' => [ __DIR__ . '/../src/Domain', // Your current project Entities __DIR__ . '/../vendor/wayofdev/laravel-webhook-client/src/Entities', // Register new Entity ], // ... ],
-
After updating the config, run the command to generate migrations for the new entity:
$ php artisan cycle:orm:migrate
(Optional): To see a list of pending migrations:
$ php artisan cycle:migrate:status
-
Execute any outstanding migrations:
$ php artisan cycle:migrate
โ Configuring Webhook Routing
On the Stripe dashboard, specify the URL at which Stripe should send webhook requests. In your application's route file, map this URL using Route::stripeWebhooks
:
Route::stripeWebhooks('webhook-route-configured-at-the-stripe-dashboard');
Internally, this command registers a POST
route to a controller provided by this package. As Stripe can't retrieve a csrf-token, exclude this route from the VerifyCsrfToken
middleware:
protected $except = [ 'webhook-route-configured-at-the-stripe-dashboard', ];
๐ป Usage
Stripe dispatches webhooks for various event types. View the complete list of event types in Stripe's official documentation.
Stripe will sign all requests hitting the webhook url of your app. This package will automatically verify if the signature is valid. If it is not, the request was probably not sent by Stripe.
Unless something goes terribly wrong, this package will always respond with a 200
to webhook requests. Sending a 200
will prevent Stripe from resending the same event over and over again. Stripe might occasionally send a duplicate webhook request more than once. This package makes sure that each request will only be processed once. All webhook requests with a valid signature will be logged in the webhook_calls
table. The table has a payload
column where the entire payload of the incoming webhook is saved.
If the signature is invalid, the package will not log the request but will throw a WayOfDev\StripeWebhooks\Exceptions\WebhookFailed
exception. Any errors that occur during a webhook call will be recorded in the exception
column. If there's an error, a 500
response will be sent, otherwise a 200
response.
You can handle webhook requests in two ways with this package: by queuing a job or by listening to the package's events.
โ Handling Webhook Requests with Jobs
To take action when a specific event type is received, define a job. Here's a job example:
<?php declare(strict_types=1); namespace Infrastructure\Stripe\Webhooks\Jobs; use Illuminate\Bus\Queueable; use Illuminate\Queue\SerializesModels; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Contracts\Queue\ShouldQueue; use WayOfDev\WebhookClient\Entities\WebhookCall; class HandleChargeableSource implements ShouldQueue { use InteractsWithQueue, Queueable, SerializesModels; public WebhookCall $webhookCall; public function __construct(WebhookCall $webhookCall) { $this->webhookCall = $webhookCall; } public function handle() { // do your work here // you can access the payload of the webhook call with `$this->webhookCall->payload()` } }
To ensure prompt responses to webhook requests, consider making the job queueable. This allows for efficient handling of multiple Stripe webhook requests, reducing the chance of timeouts.
After creating the job, register it in the jobs
array of the stripe-webhooks.php
config file. The key should be the name of the stripe event type where but with the .
replaced by _
. The value should be the fully qualified classname.
// config/stripe-webhooks.php 'jobs' => [ 'source_chargeable' => \Infrastructure\Stripe\Webhooks\Jobs\HandleChargeableSource::class, ], // ...
In case you want to configure one job as default to process all undefined event, you may set the job at default_job
in the stripe-webhooks.php
config file. The value should be the fully qualified classname.
By default, the configuration is an empty string ''
, which will only store the event in database but without handling.
// config/stripe-webhooks.php 'default_job' => \Infrastructure\Stripe\Webhooks\Jobs\HandleOtherEvent::class, // ...
โ Handling Webhook Requests with Events
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 stripe-webhooks::<name-of-the-event>
event.
The payload of the events will be the instance of WebhookCall
that was created for the incoming request.
Let's take a look at how you can listen for such an event. In the EventServiceProvider
you can register listeners.
/** * The event listener mappings for the application. * * @var array */ protected $listen = [ 'stripe-webhooks::source.chargeable' => [ Infrastructure\Stripe\Listeners\ChargeSource::class, ], ];
Here's an example of such a listener:
<?php namespace Infrastructure\Stripe\Listeners; use Illuminate\Contracts\Queue\ShouldQueue; use WayOfDev\WebhookClient\Entities\WebhookCall; class ChargeSource implements ShouldQueue { public function handle(WebhookCall $webhookCall) { // do your work here // you can access the payload of the webhook call with `$webhookCall->payload()` } }
We highly recommend that you make the event listener queueable, as this will minimize the response time of the webhook requests. This allows you to handle more Stripe webhook requests and avoid timeouts.
To learn about other ways to handle events in Laravel, check out Laravel's official documentation on event handling.
โ๏ธ Advanced Usage
โ Retry Handling a Webhook
All incoming webhook requests are written to the database. This is incredibly valuable when something goes wrong while handling a webhook call. You can easily retry processing the webhook call, after you've investigated and fixed the cause of failure, like this:
use WayOfDev\WebhookClient\Contracts\WebhookCallRepository; use WayOfDev\StripeWebhooks\Bridge\Laravel\Jobs\ProcessStripeWebhookJob; class RetryWebhooks { public function __construct(private WebhookCallRepository $repository) { } public function handle() { dispatch(new ProcessStripeWebhookJob($repository->findById($id))); } }
โ Performing Custom Logic
You can add some custom logic that should be executed before and/or after the scheduling of the queued job by using your own entity. You can do this by specifying your own entity in the entity
key of the stripe-webhooks
config file. The class should extend WayOfDev\StripeWebhooks\Bridge\Laravel\Jobs\ProcessStripeWebhookJob
.
Here's an example:
use WayOfDev\StripeWebhooks\Bridge\Laravel\Jobs\ProcessStripeWebhookJob; class MyCustomStripeWebhookJob extends ProcessStripeWebhookJob { public function handle(): void { // do some custom stuff beforehand parent::handle(); // do some custom stuff afterwards } }
โ Determine if a Request Should be Processed
You may use your own logic to determine if a request should be processed or not. You can do this by specifying your own profile in the profile
key of the stripe-webhooks
config file. The class should implement WayOfDev\WebhookClient\Contracts\WebhookProfile
.
In this example we will make sure to only process a request if it wasn't processed before.
<?php declare(strict_types=1); namespace WayOfDev\StripeWebhooks\Profile; use Cycle\Database\Injection\Parameter; use Cycle\ORM\ORMInterface; use Illuminate\Http\Request; use WayOfDev\WebhookClient\Contracts\WebhookProfile; use WayOfDev\WebhookClient\Entities\WebhookCall; use WayOfDev\WebhookClient\Persistence\ORMWebhookCallRepository; class StripeWebhookProfile implements WebhookProfile { public function __construct(private readonly ORMInterface $orm) { } public function shouldProcess(Request $request): bool { /** @var ORMWebhookCallRepository $webhookCallsRepository */ $webhookCallsRepository = $this->orm->getRepository(WebhookCall::class); $exists = $webhookCallsRepository ->select() ->where(['name' => 'stripe']) ->andWhere("JSON_EXTRACT(payload, '$.id')", '=', new Parameter(['payloadId' => $request->get('id')])) ->count(); return 0 === $exists; } }
โ Handling Multiple Signing Secrets
When using Stripe Connect you might want to the package to handle multiple endpoints and secrets. Here's how to configurate that behaviour.
If you are using the Route::stripeWebhooks
macro, you can append the configKey
as follows:
Route::stripeWebhooks('webhook-url/{configKey}');
Alternatively, if you are manually defining the route, you can add configKey
like so:
Route::post( 'webhook-url/{configKey}', \WayOfDev\StripeWebhooks\Bridge\Laravel\Http\Controllers\StripeWebhooksController::class, );
If this route parameter is present the verify middleware will look for the secret using a different config key, by appending the given the parameter value to the default config key. E.g. If Stripe posts to webhook-url/my-named-secret
you'd add a new config named signing_secret_my-named-secret
.
Example config for Connect might look like:
// secret for when Stripe posts to webhook-url/account 'signing_secret_account' => 'whsec_abc', // secret for when Stripe posts to webhook-url/connect 'signing_secret_connect' => 'whsec_123',
โ Transforming the Webhook Payload into a Stripe Object
You can transform the Webhook payload into a Stripe object to assist in accessing its various methods and properties.
To do this, use the Stripe\Event::constructFrom($payload)
method with the WebhookCall
's payload:
use Stripe\Event; // ... public function handle(WebhookCall $webhookCall) { /** @var \Stripe\StripeObject|null */ $stripeObject = Event::constructFrom($webhookCall->payload())->data?->object; }
For example, if you have setup a Stripe webhook for the invoice.created
event, you can transform the payload into a StripeInvoice
object:
/** @var \Stripe\StripeInvoice|null */ $stripeInvoice = Event::constructFrom($webhookCall->payload())->data?->object; // $stripeInvoice->status // $stripeInvoice->amount_due // $stripeInvoice->amount_paid // $stripeInvoice->amount_remaining foreach ($stripeInvoice->lines as $invoiceLine) { // ... }
โก๏ธSequence Diagram
๐งช Running Tests
โ PHPUnit Tests
To run tests, run the following command:
$ make test
โ Static Analysis
Code quality using PHPStan:
$ make lint-stan
โ Coding Standards Fixing
Fix code using The PHP Coding Standards Fixer (PHP CS Fixer) to follow our standards:
$ make lint-php
๐ค License
๐งฑ Credits and Useful Resources
This repository is based on the spatie/laravel-stripe-webhooks work.
๐๐ผโโ๏ธ Author Information
Created in 2023 by lotyp / 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