custom-d / webhook-registry
用于管理 Laravel 项目中 webhooks 的 webhook 注册表
Requires
- php: ^8.1
- illuminate/support: ^9.0|^10.0|^11.0
- spatie/laravel-webhook-server: ^3.1
Requires (Dev)
- orchestra/testbench: ^7.0|^8.0|^9.0
- phpunit/phpunit: ^9.3.0|^10.0
README
这是一个用于提供简单灵活的 webhook 注册表的包装器,它允许您将任何 Laravel 事件暴露为 webhook,并提供开箱即用的 webhook 结果日志。
安装
使用 composer 安装
composer require custom-d/webhook-registry
发布配置文件
php artisan vendor:publish --provider="CustomD\WebhookRegistry\ServiceProvider" --tag="config"
用法
1. 通过事件触发已注册的 webhook
在任意 Laravel 事件上实现 CustomD\WebhookRegistry\Contracts\ShouldDeliverWebhooks
合约,您就可以注册将在该事件上触发的 webhook。
此合约定义了需要在您的事件上定义的几个方法,这将有助于提供负载详情。
您的负载必须定义一个 body
,但也可以定义 tags 和 meta 信息,以便传递给 Spatie\WebhookServer\WebhookCall
。
/** * Get the payload for this webhook event */ public function getWebhookPayload(): array { return [ 'body' => [ 'status' => $this->status, ] ]; }
2. 注册 webhook
直接使用 CustomD\WebhookRegistry\Models\WebhookEndpoint
模型创建 webhook 端点,或使用外观 WebhookRegistry::registerEndpoint
。
$endpoint = WebhookRegistry::registerEndpoint( 'https://webhook.site/custom/endpoint', 'My webhook endpoint name' );
默认情况下,我们将验证 outgoing webhook 连接的 SSL 证书。如果您想禁用 SSL 验证,可以将 false
传递给 registerEndpoint
函数。
$endpoint = WebhookRegistry::registerEndpoint( 'https:///webhook-test', 'My insecure endpoint', false );
3. 将事件绑定到端点
使用 CustomD\WebhookRegistry\Model\WebhookEvent
模型或外观 WebhookRegistry::registerEvent
将 webhook 事件与端点关联。
$event = WebhookRegistry::registerEvent($webhook->id, 'App\Events\MyEvent');
模型
自定义 WebhookEvent 模型以添加有关事件何时应触发的逻辑。在 config/webhook-registry.php
中,您将看到在 models
-> events
中使用的模型。您可以通过实现适当的合约并更新配置文件来创建自己的模型。
WebhookEndpoint extends Model implements CustomD\WebhookRegistry\Models\Contracts\WebhookEndpointContract
WebhookEvent extends Model implements CustomD\WebhookRegistry\Models\Contracts\WebhookEventContract
如果您需要修改 WebhookRequest
记录表,请注意它不需要合约,可以根据需要覆盖,但请确保原始字段存在,或定义适当的属性映射。
自定义 'dispatchable' 逻辑
为了确定在给定的执行中哪些事件是可分发的,您必须在 WebhookEvent
模型上设置一个 scopeWhereDispatchable
。当查找应触发的事件时将使用此作用域。
默认情况下,此作用域不执行任何过滤。
安全
如果您发现任何与安全相关的问题,请通过电子邮件而不是使用问题跟踪器。
致谢
本软件包在 melihovv/laravel-package-generator 的帮助下启动。