firevel / webhook-gateway-laravel-client
Laravel 的 Webhook 网关客户端
Requires
- guzzlehttp/guzzle: ^6.3|^7.0
- illuminate/support: ~5.5.0|~5.6.0|~5.7.0|~5.8.0|^6.0|^7.0|^8.0|^9.0|^10.0
README
Laravel 的 Webhook 网关客户端
此软件包的开发目的是在微服务之间和第三方集成之间共享事件。
安装
使用 Composer 安装
composer require firevel/webhook-gateway-laravel-client
发布配置
php artisan vendor:publish --provider="Firevel\WebhookGatewayLaravelClient\Providers\WebhookGatewayClientServiceProvider" --tag="config"
客户端
客户端负责从 Webhook 网关接收事件并将它们作为内部 Laravel 事件分发。
设置
- 在 Webhook 网关上使用客户端 URL(默认为
https://[HOST]/events
)创建客户端帐户。 - 在
config/webhookgateway.php
或WEBHOOKGATEWAY_CLIENT_SECRET
环境变量中设置客户端密钥。
用法
在 Webhook 网关订阅者部分设置您想要监听的频道。事件总是以服务开头,例如 billing.invoice.created
。
Event::listen('billing.invoice.created', function ($invoice) { PaymentService::payInvoice($invoice); });
您还可以使用 Laravel 事件监听器。
protected $listen = [ 'billing.invoice.created' => [ 'App\Listeners\InvoiceCreated', ], ];
事件包括包含方法的 WebhookEvent $event
负载数据
$event->getData(); // Get event data array. $event->getData('user.email'); // Get event data using "dot" annotation. $event->getChannel(); // Get event channel name. $event->getMeta(); // Get event meta data array. $event->getMeta('role.id'); // Get meta data using "dot" annotation. $event->getId(); // Get event id. $event->getSubscription(); // Get event subscription array.
您可以在 webhookgateway.event_class
配置中设置自定义的 Webhook 事件类。
服务
使用服务配置将 Laravel 事件与 Webhook 网关和其他微服务共享。
设置
- 在 Webhook 网关中创建一个新的服务并设置服务名称和服务密钥。
- 在
config/webhookgateway.php
中设置 Webhook 网关服务名称和密钥。 - 使用
webhookgateway.channels
配置选择您想要与 Webhook 网关共享的事件。
用法
共享事件
匹配 webhookgateway.channels
模式的事件将被与其他订阅了配置中使用的命名空间微服务共享。Webhook 网关将自动为每个分发的事件添加服务前缀。
例如,如果您使用服务名称 billing
并设置频道
'invoice.created' => [ 'eloquent.created: App/Models/Invoice', ]
发票模型的每个保存事件将被分发为 billing.invoice.created
。
Eloquent 事件
默认情况下,Eloquent 模型使用 (array) $model
转换为数组。如果您想自定义事件格式,请将以下代码添加到您的模型中
/** * Get the event data array for the model. * * @return array */ public function toEventArray() { return [ // Your code here... ]; }
您还可以通过添加到您的模型中来为每个事件附加元数据
/** * Get the event meta data array. * * @return array */ public function eventMetadata() { // Your code here... }
Laravel 事件
要共享 Laravel 事件与事件网关,您可以使用常规的 webhookgateway.channels
配置,例如
'user.suspended' => [ 'App\Events\UserSuspended' ],
您可以使用 toEventArray
和 eventMetadata
方法来自定义负载或元数据。
常见问题解答
我可以用 WebHook 网关作为事件广播驱动程序吗?
您需要构建自定义驱动程序(请检查 Illuminate\Contracts\Broadcasting
)。广播驱动程序不是此软件包的一部分,因为 Laravel 广播是为其他目的开发的(WebSockets)。
鸣谢
- SpringboardVR 对初始实现做出的贡献。