bfg/web-hooker

安装: 21

依赖项: 0

建议者: 0

安全: 0

星标: 0

关注者: 2

分支: 1

开放问题: 0

类型:bfg-app

2.2.2 2022-09-15 08:49 UTC

This package is auto-updated.

Last update: 2024-09-15 12:45:29 UTC


README

安装

composer require bfg/web-hooker

描述

简单的 Laravel WebHook 核心库,适合入门使用

用法

重要!您应该有队列来处理钩子。

发布

迁移

php artisan vendor:publish --tag=web-hooker-migrations

配置

php artisan vendor:publish --tag=web-hooker-config

迁移

创建数据库表是必须的步骤,因此发布迁移后,将启动它们。

php artisan migrate

HTTP 请求类型

您需要确保 type.http_request 设置在 config/webhooker.php 文件中的值为 true

在使用之前,您应该在要用于钩子的模型上使用该特质

<?php

namespace App\Models;

use Bfg\WebHooker\Traits\WebHooked;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use WebHooked;
}

创建您自己的事件,这是 Laravel 的标准功能。

php artisan make:event YouEvent

在事件的构造函数中,您可以接受 Hook 模型和有效载荷。

...
    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct(
        public WebHook $hook,
        public array $payload,
    ) {
        //
    }
...

通过使用 Bfg\WebHooker\WebHookOrganizerInterface 接口创建组织者类

<?php

namespace App\WebHook\Organizers;

use Bfg\WebHooker\Models\WebHook;
use Bfg\WebHooker\WebHookOrganizerInterface;

class YouOrganizer implements WebHookOrganizerInterface
{
    /**
     * Generate the event for hook emit
     * @param  WebHook  $hook
     * @return string
     */
    function event(WebHook $hook): string
    {
        return YouEvent::class;
    }

    /**
     * Method for remote subscribe
     *  
     * To return the truth if the subscription was successful, 
     * otherwise there will be a repeated request for the next iteration.
     *
     * @param  WebHook  $hook
     * @return bool
     */
    public function subscribe(WebHook $hook): bool
    {
        // Request to subscribe
        // Link for request: $hook->route_response
        return true;
    }

    /**
     * Method for remote unsubscribe
     *
     * To return the truth if the unsubscription was successful, 
     * otherwise there will be a repeated request for the next iteration.
     * 
     * @param  WebHook  $hook
     * @return bool
     */
    public function unsubscribe(WebHook $hook): bool
    {
        // Request to unsubscribe
        return true;
    }
}

或者您可以使用命令来创建组织者

php artisan make:organizer YouOrganizer

要获取钩子的请求链接,您可以使用 $hook->route_response 参数。

现在您可以为数据库中的一些单独条目或模型创建桥梁。

$webhook = \App\Models\User::first()->assignBridge(
    organizer: YouOrganizer::class,
    settings: [] // Optional
): \Bfg\WebHooker\Models\WebHook;

或者

$webhook = \App\Models\User::assignBridgework(
    organizer: YouOrganizer::class,
    settings: [] // Optional
): \Bfg\WebHooker\Models\WebHook;

如果您想延迟签名一段时间,您可以使用 subscribeDelay 方法

/** @var \Bfg\WebHooker\Models\WebHook $webhook */
$webhook->subscribeDelay(
    now()->addHour()
);

如果您想指示取消订阅的时间,您也可以通过 unsubscribeDelay 方法进行指示

/** @var \Bfg\WebHooker\Models\WebHook $webhook */
$webhook->unsubscribeDelay(
    now()->addHours(2)
);

要启动订阅和取消订阅程序,您需要配置 webhook:associate 命令的调度,间隔为1分钟

$schedule->command('webhook:associate')->everyMinute();

开放签名类型

您需要确保 type.websocket_open_signature 设置在 config/webhooker.php 文件中的值为 true

如果您安装了 beyondcode/laravel-websockets 包,您就有机会创建快速钩子,可以获取套接字上的数据。要使用此类型,您需要这样做

composer require beyondcode/laravel-websockets

创建组织者

php artisan make:organizer YouOrganizer

创建特殊桥梁

$webhook = \App\Models\User::assignBridgework(
    organizer: YouOrganizer::class,
    settings: []
)->setTypeWebsocketOpenSignature(): \Bfg\WebHooker\Models\WebHook;

服务器

php artisan websockets:serve

客户端

const hookSocket = new WebSocket("ws://0.0.0.0:6001/hook/{PUSHER_APP_KEY}/{WEBHOOK_HASH}");
hookSocket.send('Any data');

开放客户端类型

您需要确保 type.websocket_open_client 设置在 config/webhooker.php 文件中的值为 true

此类型设计为客户端,与异步 TCP(WebSocket 服务器)创建本地客户端连接。

创建组织者

php artisan make:organizer BinanceOrganizer --client

仔细研究组织者是如何构建的,没有它,客户端的服务器将忽略此钩子

<?php

namespace App\WebHook\Organizers;

use Bfg\WebHooker\Models\WebHook;
use Bfg\WebHooker\WebHookOrganizerAbstract;

class BinanceOrganizer extends WebHookOrganizerAbstract
{
    /**
     * Generate the event for hook emit
     * @param  WebHook  $hook
     * @return string
     */
    function event(WebHook $hook): string
    {
        return YouEvent::class;
    }

    /**
     * The websocket host for connection
     * @param  WebHook  $hook
     * @return string
     */
    function host(WebHook $hook): string
    {
        return "wss://stream.binance.com:9443/ws/btcusdt@depth";
    }
}

在指示服务器链接后,您可以稍微自定义您的组织者

...
    /**
     * Send a message when creating the first connection
     *
     * @param  WebHook  $hook
     * @return array
     */
    public function onConnectMessage(WebHook $hook): array
    {
        return [
            'method' => 'SUBSCRIBE',
            'params' => [
                'btcusdt@aggTrade',
                'btcusdt@depth'
            ],
            'id' => $hook->id
        ];
    }
    
    /**
     * Send message when disconnect from server
     *
     * @param  WebHook  $hook
     * @return array
     */
    public function onDisconnectMessage(WebHook $hook): array
    {
        return [
            'method' => 'UNSUBSCRIBE',
            'params' => [
                'btcusdt@aggTrade',
                'btcusdt@depth'
            ],
            'id' => $hook->id
        ];
    }
    
    /**
     * Send message when add hook to client’s server
     *
     * @param  WebHook  $hook
     * @return array
     */
    public function onAddMessage(WebHook $hook): array
    {
        return [];
    }
    
    /**
     * Checks an incoming message for authenticity for this hook
     *
     * @param  WebHook  $hook
     * @param  array  $payload
     * @return bool
     */
    public function isSelfMessage(WebHook $hook, array $payload): bool
    {
        return true;
    }

为了准备您的有效载荷,您可以在您的组织者中声明 preparePayload 方法

...    
    public function preparePayload(WebHook $hook, array $payload): array
    {
        return $payload;
    }
...

创建特殊桥梁

$webhook = \App\Models\User::assignBridgework(
    organizer: BinanceOrganizer::class,
    settings: []
)->setTypeWebsocketOpenClient(): \Bfg\WebHooker\Models\WebHook;

运行客户端连接服务器

php artisan webhook:open-client

监督者

[program:webhook-open-client]
directory=/path/to/you/project
command=php artisan webhook:open-client
autostart=true
autorestart=true
user=root
numprocs=1
redirect_stderr=true
stdout_logfile=/path/to/you/project/webhook-open-client.log