首页 > 解决方案 > Laravel Slack 按需通知;在哪里设置 webhook?

问题描述

根据 Laravel 文档,我可以在控制器中进行按需通知,如下所示:

use Notification;
use App\Notifications\TradeSuccessful;

$trada_data = array( 'title' => 'test', 'amount' => 123.45 )

Notification::route('slack', '#test')->notify(new TradeSuccessful($trade_data));

TradeSuccessful(示例代码)中:

public function toSlack($notifiable)
    {
        return (new SlackMessage)
            ->success()
            ->content('One of your invoices has been paid!')
            ->attachment(function ($attachment) use ($trade_data) {
                $attachment->title('Invoice 1322')
                    ->fields([
                    'Title' => $trade_data['title],
                    'Amount' => $trade_data['amount]
                ]);
            });
    }

主要问题:当我使用这样的通知(按需)时,我在哪里设置 Slack webhook?因为在他们使用的文档中:

public function routeNotificationForSlack($notification)
    {
        return 'https://hooks.slack.com/services/...';
    }

但是该功能是在模型上定义的,当使用按需通知时,模型上没有定义任何内容。

标签: phplaravellaravel-5slacklaravel-5.8

解决方案


文档中:

按需通知

有时您可能需要向未存储为应用程序“用户”的人发送通知。使用该 Notification::route方法,您可以在发送通知之前指定 ad-hoc 通知路由信息:

Notification::route('mail', 'taylor@example.com')
            ->route('nexmo', '5555555555')
            ->notify(new InvoicePaid($invoice));

对于 Slack,您指定的路由需要是 web-hook:

use Notification;
use App\Notifications\TradeSuccessful;

$trada_data = array( 'title' => 'test', 'amount' => 123.45 );

$slack_webhook = 'my-slack-webhook-url'; // <---

Notification::route('slack', $slack_webhook)->notify(new TradeSuccessful($trade_data));
                             ^^^^^^^^^^^^^^

当然,您应该将其存储为env()密钥,但您明白了。


推荐阅读