turanct/webhooks

从您的项目触发WebHooks

1.0.1 2018-02-20 16:14 UTC

This package is auto-updated.

Last update: 2024-08-28 22:40:35 UTC


README

Travis CI

目标

创建一个非常简单且易于使用的库,用于触发WebHooks。

基本用法

此包提供的接口是WebHooks接口。它提供了一个方法send(),该方法接受一个WebHook实例并发送它。然后您可以根据需要配置您的依赖注入容器或服务定位器来构建该接口的具体实现。让我们看看如何在模拟控制器中使用它。

<?php

use Turanct\WebHooks\WebHooks;
use Turanct\WebHooks\WebHook;
use Turanct\WebHooks\WebHookId;
use Turanct\WebHooks\WebHookWasNotSent;

final class DummyController
{
    private $webhooks;

    public function __construct(WebHooks $webhooks)
    {
        $this->webhooks = $webhooks;
    }

    /**
     * @route /send-webhook
     */
    public function sendWebhook()
    {
        $webhook = new WebHook(
            WebHookId::generate(),
            'https://example.com/webhooks',
            'verification string',
            array('foo' => 'bar', 'baz' => 'qux')
        );

        try {
            $this->webhooks->send($webhook);
        } catch (WebHookWasNotSent $e) {
            return new Response('something went wrong', 500);
        }

        return new Response('webhook was sent', 200);
    }
}

现在,每次我们访问应用程序上的url /send-webhook,就会触发一个WebHooks,它将我们上面指定的有效载荷发送到https://example.com/webhooks。当发生错误时,将抛出WebHookWasNotSent异常,正如上面的示例中所看到的,我们可以catch它。

使用哪种实现?

在编写本文档时,推荐的WebHooks接口实现是WebHooksGeneric类。您可以在依赖注入容器中这样实例化它:

$app['webhooks_service'] = function () {
    $httpclient = ... ; // you can implement the `Turanct\WebHooks\HttpClient`
                        // interface yourself, there is no implementation
                        // supplied with this package. You can use the HTTP
                        // client that you're already using in your app by
                        // writing a small implementation of the interface.

    $formatter = new FormatterJSON();
    $signer = new SignerSHA256();

    $webhooks = new WebHooksGeneric(
        $httpclient,
        $formatter,
        $signer
    );

    return $webhooks;
};

现在,WebHooks服务已在依赖注入容器中注册(例如,Pimple中的示例)。

为什么选择HttpClient接口以及如何使用它?

我们选择不提供默认的HTTP客户端实现,以便能够与所有现有的HTTP客户端包一起使用。我们只是提供了一个非常小的接口,您可以为所选的HTTP客户端轻松实现。然后,您可以将该实现打包在单独的包中,并将此包放入您的包的composer require语句中。这样,依赖关系就会以正确的方向解析(具体依赖于抽象)。

您的实现应确保:

  • 它有一个execute()方法,该方法接受一个HttpRequest并返回一个HttpResponse
  • 它捕获所有来自底层HTTP客户端的异常,并在无法恢复的情况下将它们包装在HttpClientException中。

关于重试和异步实现怎么办?

它们正在制作中。已在此存储库中创建相关的问题。