Sending Laravel Slack Notifications with a webhook URL

Laravel Notifications support a number of channels, such as email, SMS and Slack. If you follow their documentation for sending Slack notifications you’ll need to setup a bot user with an OAuth token.

If you were creating a new Slack ‘app’ to receive messages this would be the way to go. In my case though I was refactoring some Logging which used the Slack channel with a webhook URL setup. The Slack interface didn’t allow me to setup or find the bot user/OAuth token for an existing App.

In order to use the Notifications class with a webhook I needed to send a simpler message structure than what you see in the docs and use slightly different service configuration.

Slack Service Config

In config/services.php

<?php

return [
    'slack' => [
        'webhook_url' => env('LOG_SLACK_WEBHOOK_URL'),

        /*
       Use a webhook_url instead of the bot_user_oauth_token structure

        'notifications' => [
             'bot_user_oauth_token' => env('SLACK_BOT_USER_OAUTH_TOKEN'),
             'channel' => env('SLACK_BOT_USER_DEFAULT_CHANNEL'),
        ],
       */
    ],
];

Instead of calling the text, headerBlock, contextBlock type methods I just called content()

<?php

namespace App\Notifications;

use Illuminate\Notifications\Messages\SlackMessage;
use Illuminate\Notifications\Notification;

class CafeNotification extends Notification
{
    public function via(object $notifiable): array
    {
        return ['slack'];
    }

    public function toSlack(object $notifiable): SlackMessage
    {
        return (new SlackMessage)
            ->content($theMessageGoesHere)
            ->unfurlLinks(false);
    }
}

This was enough to get simple notifications going without having to recreate my Slack app in order to setup a bot user and token.

Leave a Reply

Your email address will not be published. Required fields are marked *