lenderspender/laravel-webhook-channel

通过用户定义的webhooks发送通知

3.1.0 2024-03-29 15:38 UTC

README

Laravel webhook chanel 允许您将 JsonResource 对象作为通知发送给您的用户。

安装

您可以通过 composer 安装此包

composer require lenderspender/laravel-webhook-channel

安装

在您希望接收webhooks的模型上实现 ReceivesWebhooks

<?php

declare(strict_types=1);

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;
use LenderSpender\LaravelWebhookChannel\Receiver\ReceivesWebhooks;
use LenderSpender\LaravelWebhookChannel\Receiver\WebhookData;

class User extends Model implements ReceivesWebhooks
{
    use Notifiable;
    
    public function routeNotificationForWebhook() : ?WebhookData
    {
        return new WebhookData('https://example.com/webhooks/', 'users-webhook-secret');
    }
}

创建webhook通知

要允许您的通知发送webhook数据,您只需实现 WebhookNotification。它接受 Eloquent: API Resources

<?php

declare(strict_types=1);

namespace App\Notifications;

use Illuminate\Notifications\Notifiable;
use Illuminate\Notifications\Notification;
use LenderSpender\LaravelWebhookChannel\Receiver\ReceivesWebhooks;use LenderSpender\LaravelWebhookChannel\Receiver\WebhookMessage;use LenderSpender\LaravelWebhookChannel\WebhookNotification;

class StatusUpdatedNotification extends Notification implements WebhookNotification
{
    use Notifiable;
    
    public function routeNotificationForWebhook(ReceivesWebhooks $notifiable) : WebhookMessage
    {
        $resource = new UserResource($notifiable);
        
        return new WebhookMessage('foo_was_updated', $resource);
    }
}

通知

<?php

declare(strict_types=1);

namespace App\Http\Controllers;

class NotificationController
{
    public function __invoke()
    {
        auth()->user()->notify(new StatusUpdatedNotification());
    }
}

查看

每个webhook调用都存储在WebhookNotificationMessage模型中。在您想要查看webhook消息的模型上实现HasWebhookNotificationMessages

<?php

declare(strict_types=1);

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;
use LenderSpender\LaravelWebhookChannel\Receiver\HasWebhookNotificationMessages;
use LenderSpender\LaravelWebhookChannel\Receiver\ReceivesWebhooks;

class User extends Model implements ReceivesWebhooks
{
    use Notifiable;
    use HasWebhookNotificationMessages;
}

重试发送webhooks

可以通过在WebhookNotificationMessage模型上调用callWebhook方法来重试WebhookNotificationMessages。