Tạo web push notifications trong laravel với firebase

Laravel web push notification firebase
5/5 - (1 vote)

Hiển thị thông báo cho của web ra màn hình hay web push notifications là cách giúp bạn thông báo đến người dùng website của mình.

Nếu bạn viết một website tin tức thì bạn có thể báo cho người dùng biết mỗi khi có một bài viết mới hoặc ví như bạn viết một ứng dụng chấm công thì có thể giúp thông báo đến bạn khi có một nhân viên nào đó thực hiện thao tác chấm công và dễ dàng theo dõi họ.

Có rất nhiều plugin hỗ trợ cho web push notifications nhưng với phương châm miễn phí trường tồn nên chúng ta sẽ cùng tìm hiểu về cách tạo web push notifications với firebase của google.

Đăng ký firebase để tạo web push notifications trong laravel

Bạn truy cập vào đường lịnk https://console.firebase.google.com/u/0/ để tạo một project.

web push notifications firebase project

Bạn nhập nhập tên project mà mình muốn và hoàn thành từng bước theo yêu cầu để tạo một project mới.

web push notification trong laravel với firebase

Copy đoạn code firebaseConfig như hình vào thay thế vào đoạn code bên dưới.

tạo desktop web push notifications trong laravel với firebase

Và vào tab Cloud Messaging để lấy server key rồi thay vào server_api_key trong phần Tạo class để gửi thông báo đến người dùng

Browser web push notification laravel with firebase

Thiết lập firebase trong file blade

Việc đầu tiên chúng ta cần làm đó là thêm firebase vào trong file blade mà bạn mong muốn thông báo của bạn sẽ hoạt động.

<script src="https://www.gstatic.com/firebasejs/7.23.0/firebase.js"></script>
<script>
  
    var firebaseConfig = {
          apiKey: "your_apikey",
          authDomain: "",
          projectId: "",
          storageBucket: "",
          messagingSenderId: "",
          appId: ""
    };//change by your SDKs for firebase
      
    firebase.initializeApp(firebaseConfig);
    const messaging = firebase.messaging();
  
    function initFirebaseMessagingRegistration() {
            messaging
            .requestPermission()
            .then(function () {
                return messaging.getToken()
            })
            .then(function(token) {
                console.log(token);
                $.ajax({
                    url: '{{ route("save-token") }}',
                    type: 'POST',
                    data: {
                        _token: '{{ csrf_token() }}',
                        token: token
                    },
                    dataType: 'JSON',
                    success: function (response) {
                        //alert('Token saved successfully.');
                    },
                    error: function (err) {
                        console.log('User Chat Token Error'+ err);
                    },
                });
  
            }).catch(function (err) {
                console.log('User Chat Token Error'+ err);
            });
     }  
      initFirebaseMessagingRegistration();
    messaging.onMessage(function(payload) {
        const noteTitle = payload.notification.title;
        const noteOptions = {
            body: payload.notification.body,
            icon: payload.notification.icon,
        };
        new Notification(noteTitle, noteOptions);
    });
   
</script>

Bạn nhớ thay đoạn code màu đỏ ở trên bằng đoạn code trong firebase console của bạn nhé.

Lưu device token cho web push notification trong laravel

Để có thể gửi thông báo đến một người dùng nào đó thì chúng ta phải dựa vào device token, chính vì vậy mà đoạn script ở phần trên chúng ta có thấy đoạn ajax. Đoạn ajax này nhằm mục đích giúp ta lưu trữ device token vào database mỗi khi người dùng trung cập vào trang mà có chứa nó.

Trước hết trong bảng users ta thêm một column và đặt tên cho nó là “device_token”. Tiếp đến bạn đặt đoạn code dưới đây vào trong controller bất kỳ mà bạn muốn.

public function saveToken(Request $request)
    {
        auth()->user()->update(['device_token'=>$request->token]);
        return response()->json(['token saved successfully.']);
    }

Và bạn tiếp tục mở file web.php trong routes để khai báo route cho nó. Ví dụ tôi để function trên vào HomeController thì tôi sẽ khai báo như dưới đây.

Route::post('save-token', [HomeController::class, 'saveToken'])->name('save-token');

Tạo class để gửi thông báo đến người dùng

Để web push notifications có thể hiển thị thông báo trên màn hình người dùng thì chúng ta phải gửi thông tin đến project trên firebase thông qua CURL. Để tái sử dụng nó ở bất cứ đâu thì chúng ta sẽ đưa nó vào class để có thể gọi lại khi cần. Và để gọi class thì chúng ta sử dụng DesktopNotify::sendNotification('$title',$body);

<?php
namespace App\Classes;
use DB;

class DesktopNotification
{
    public static function sendNotification($title,$body)
    {
        $firebaseToken = DB::table('users')->whereNotNull('device_token')->pluck('device_token')->all();
          
        $SERVER_API_KEY = 'server_key_trong_project_firebase_của_bạn';
  
        $data = [
            "registration_ids" => $firebaseToken,
            "notification" => [
                "title" => $title,
                "body" => $body,  
                "icon" => 'https://hanhtinhcongnghe.comlogo.jpg'
            ]
        ];
        $dataString = json_encode($data);
    
        $headers = [
            'Authorization: key=' . $SERVER_API_KEY,
            'Content-Type: application/json',
        ];
    
        $ch = curl_init();
      
        curl_setopt($ch, CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send');
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
               
        $response = curl_exec($ch);
        //dd($response);
    }
}

Đừng quên khai báo use App\Classes\tên_thu_mục_chứa_class; ở trong controller mà bạn đặt đoạn code gọi class nhé.

Vậy là bạn đã có thể tạo được web push notification cho laravel bằng firebase

Để lại bình luận

Email của bạn sẽ được bảo mật.