Hướng dẫn notification to slack laravel

  • December 6, 2020
  • 1920

Hướng dẫn gửi notification to slack sử dụng laravel từ a đến z nhé ae! Yêu cầu chức năng khi có người dùng đặt 1 đơn hàng thì sẽ có notification về slack nhé.

Create notification

Để sử dụng notification to slack bạn cần cài laravel/slack-notification-channel package sử dụng commannd sau:


composer require laravel/slack-notification-channel

Ngoài ra bạn cũng cần chuẩn bị slack web hook và channel mà mình muốn nhận notification nhé, phần này sẽ được khai báo trong file config/notification.php. Sau đó bắt tay vào code ngay thôi nào.

Laravel hỗ trợ command để tạo 1 notification chúng ta chỉ việc gõ lệnh để tạo ra 1 notification


php artisan make:notification Ordered

Lệnh trên sẽ tạo ra một class notification trong thư mục app/Notifications có tên là Ordered.


Thiết lập code để gửi notification to slack

Chúng ta cùng thiết lập class Ordered để gửi notification to slack nhé


<?php

namespace App\Notifications;

use App\Models\Order;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\SlackMessage;
use Illuminate\Notifications\Messages\SlackAttachment;

class Ordered extends Notification implements ShouldQueue
{
    use Queueable;

    /**
     * Get the notification's delivery channels.
     *
     * @param Order $order
     * @return array
     */
    public function via(Order $order)
    {
        return ['slack'];
    }

    /**
     * Get the Slack representation of the notification.
     *
     * @param Order $order
     * @return SlackMessage
     */
    public function toSlack(Order $order)
    {
        $url = config('app.admin_url') . '/orders/' . $order->id;
        return (new SlackMessage())
            ->to(config('notification.slack.alert_channel'))
            ->content('Has one order')
            ->attachment(function (SlackAttachment $attachment) use ($order, $url) {
                $attachment->color('#fcda00');
                $attachment->title('Detail', $url);
                $attachment->fields([
                    'order_id' => $order->order_id,
                    'price' => $order->price,
                    'address' => $order->address,
                    'phone' => $order->phone,
                    'email' => $order->email,
                ]);
                $attachment->footer('SMILE bot :interrobang: ');
            });
    }
}


Thêm file config/notification.php


<?php

return [
    'slack' => [
        // Slack webhook
        'alert_webhook_url' => env('SLACK_ALERT_WEBHOOK_URL'),
        // Channel nhận notification
        'alert_channel' => env('SLACK_ALERT_CHANNEL', ''),
    ],
];

Khai báo method routeNotificationForSlack trong model


<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;
use App\Notifications\Ordered;

class Order extends Model
{
    use Notifiable;

    /**
     * Route notifications for the Slack channel.
     *
     * @param  Ordered  $notification
     * @return string
     */
    public function routeNotificationForSlack(Ordered $notification)
    {
        return config('notification.slack.alert_webhook_url');
    }
}

Khai báo trên giúp gọi function send notification từ entity model Order ở bất cứ đâu. Giờ việc gửi notification chỉ đơn giản là từ controller mỗi khi 1 order được tạo mình sẽ gọi hàm gửi notification $order->notify() là xong.


<?php

namespace App\Http\Controllers;

use App\Models\Order;
use App\Requests\StoreOrderRequest;
use App\Notifications\Ordered;
use Exception;

class OrderController extends Controller
{
    public function store(StoreOrderRequest $request)
    {
        try {
            $data = $request->all();
            $order = Order::create($data);
            // Send notification to slack
            $order->notify((new Ordered())->onQueue('api'));
        } catch (Exception $e) {
            return $this->error($e->getMessage(), $e->getCode());
        }
    }
}

Lưu ý, code trên mình đang sử dụng laravel queue nhé, vì vậy nên bạn cần setup laravel queue trước, or bỏ tính năng notification sử dụng queue là được nhé. Chúc các bạn gửi được message to slack.