juststeveking/laravel-webhooks

Laravel的简单webhook实现。

0.0.51 2023-05-31 08:48 UTC

This package is auto-updated.

Last update: 2024-08-30 01:38:32 UTC


README

Latest Version Software License Run Tests PHP Version Total Downloads

Laravel的简单webhook实现。

安装

composer require juststeveking/laravel-webhooks

发布配置

要发布此包的配置文件,请运行以下Artisan命令

php artisan vendor:publish --provider="JustSteveKing\Webhooks\Providers\PackageServiceProvider" --tag="webhooks"

配置文件查找以下环境变量,您可以根据需要进行设置

  • WEBHOOK_HEADER - 发送签名时要使用的header键,默认为Signature
  • WEBHOOK_SIGNING_KEY - 您的webhook签名密钥。
  • WEBHOOK_USER_AGENT - 您想在请求中设置的user agent,默认为Laravel_Webhooks
  • WEBHOOK_TIMEOUT - 发送webhook时要设置的请求超时,默认为15秒。

用法

使用webhook外观,您只需要传递要发送webhook的URL。

use JustSteveKing\Webhooks\Facades\Webhook;

$webhook = Webhook::to(
    url: 'https://your-url.com/',
)

这将返回一个PendingWebhook,您可以使用它。这将从您的配置中加载签名密钥。

如果您需要/想要为每个webhook设置签名密钥,您需要自己实例化PendingWebhook

use JustSteveKing\Webhooks\Builder\PendingWebhook;
use JustSteveKing\Webhooks\Signing\WebhookSigner;

$webhook = new PendingWebhook(
    url: 'https://your-url.com/',
    signer: new WebhookSigner(
        key: 'your-signing-key',
    ),
);

在构造函数中,Pending Webhook具有以下属性

  • url - 您要发送webhook的URL。
  • signer - 您要使用的webhook签名器实例。这必须实现SigningContract
  • payload - 您可以预先传递您想在webhook中发送的有效负载。这应该是一个array
  • signed - 您可以预先传递是否希望此webhook被签名,默认为true .- signature - 您可以预先传递您想要用于签名Webhook的签名。
  • request - 您可以预先传递一个您想要用于发送webhook的PendingRequest,这在您需要将API令牌附加到Webhook时很有用。

一个简单的示例

在下面的示例中,我们向https://your-url.com/发送一个webhook,并发送我们找到的第一个Post模型。

use JustSteveKing\Webhooks\Facades\Webhook;

Webhook::to('https://your-url.com/')
    ->with(Post::query()->first()->toArray())
    ->send();

一个更复杂的示例

在这个例子中,我们想要向https://your-url.com/发送一个webhook,再次传递第一个Post模型。然而,这次我们想要拦截请求的创建来附加Bearer令牌进行身份验证。然后我们想要将发送此webhook的任务派遣到队列中。

use Illuminate\Http\Client\PendingRequest;
use JustSteveKing\Webhooks\Facades\Webhook;

Webhook::to('https://your-url.com/')
    ->with(Post::query()->first()->toArray())
    ->intercept(fn (PendingRequest $request) => $request
        ->withToken('YOUR-BEARER-TOKEN'),
    )->queue('my-queue-name');

不签名webhook

如果您不需要签名webhook。

use JustSteveKing\Webhooks\Facades\Webhook;

Webhook::to('https://your-url.com/')->with(
    Post::query()->first()->toArray()
)->notSigned()->send();

测试

要运行测试

composer run test

致谢

许可证

MIT许可证(MIT)。请参阅许可证文件获取更多信息。