Laravel 12 Hướng dẫn config FCM

Laravel 12 Hướng dẫn config FCM

Điều đầu tiên bạn cần lấy thông tin từ firebase như video 

Ta phải thêm fcm.js vào public/js/fcm.js

// Khởi tạo Firebase
const firebaseConfig = {
    apiKey: "xxxmY1plcU2hEXhREyTTTFIYhbaTCBHYrY",
    authDomain: "xxx-3eb09.firebaseapp.com",
    projectId: "xxx-3eb09",
    storageBucket: "xxx-3eb09.firebasestorage.app",
    messagingSenderId: "xxx",
    appId: "1:xxx:web:180e66a9a8c2d70c4230fc"
};
firebase.initializeApp(firebaseConfig);

if ('serviceWorker' in navigator) {
    navigator.serviceWorker.register('/firebase-messaging-sw.js')
        .then(async (registration) => {
            console.log('Service Worker registered:', registration);

            // Khởi tạo messaging
            const messaging = firebase.messaging();

            // Yêu cầu quyền thông báo
            const permission = await Notification.requestPermission();
            if (permission !== 'granted') {
                console.warn('Bạn từ chối quyền nhận thông báo');
                alert('Bạn từ chối quyền nhận thông báo');
                return;
            }

            // Lấy token
            const currentToken = await messaging.getToken({
                vapidKey: 'BP8nJ0RMcmghWAboBRo44OBIpp5retAcNqYWy43_XYofiicTGKfngIca79J7g7DpG4-dq0lDsv6YyTcAO_rNzn4',
                serviceWorkerRegistration: registration,
            });

            if (currentToken) {
                console.log('FCM Token:', currentToken);
                const fingerprint = document.querySelector('meta[name="fingerprint"]').getAttribute('content');
                console.log('fingerprint', fingerprint)
                // TODO: Gửi token về server nếu cần
            } else {
                console.warn('Không thể lấy token');
            }
        })
        .catch((err) => {
            console.error('Service Worker registration or token error:', err);
        });
} else {
    console.error('Trình duyệt không hỗ trợ Service Worker');
}

Ở trang chủ ta gọi đến fcm.js

    <!-- Firebase SDK -->
    <script src="https://www.gstatic.com/firebasejs/10.10.0/firebase-app-compat.js"></script>
    <script src="https://www.gstatic.com/firebasejs/10.10.0/firebase-messaging-compat.js"></script>
    <script src="{{ asset('js/fcm.js') }}"></script>

Tiếp theo vào file  : public/firebase-messaging-sw.js

// public/firebase-messaging-sw.js

importScripts('https://www.gstatic.com/firebasejs/10.10.0/firebase-app-compat.js');
importScripts('https://www.gstatic.com/firebasejs/10.10.0/firebase-messaging-compat.js');

// Khởi tạo Firebase
firebase.initializeApp({
    apiKey: "AIzaSyBumY1plcU2hEXhREyTTTFIYhbaTCBHYrY",
    authDomain: "truyenvideo-3eb09.firebaseapp.com",
    projectId: "truyenvideo-3eb09",
    storageBucket: "truyenvideo-3eb09.firebasestorage.app",
    messagingSenderId: "22119134901",
    appId: "1:22119134901:web:180e66a9a8c2d70c4230fc"
});

const messaging = firebase.messaging();

// Nhận thông báo khi ở chế độ nền
messaging.onBackgroundMessage((payload) => {
    // console.log('[firebase-messaging-sw.js] Received background message ', payload);
});

// Nhận push từ server
self.addEventListener('push', function(event) {
    const payload = event.data?.json() ?? {};

    const notificationOptions = {
        body: payload.body ?? 'Bạn có một thông báo mới!',
        image: payload.image,
        icon: payload.icon ?? 'https://truyenvideo.com/images/logo_notification.png',
        badge: payload.badge ?? 'https://truyenvideo.com/images/logo_notification.png',
        data: payload.data ?? {},
        actions: [
            { action: 'open', title: '🔗 Xem chi tiết' },
            { action: 'dismiss', title: '❌ Đóng' }
        ]
    };

    event.waitUntil(
        self.registration.showNotification(payload.title ?? '🔥 Thông báo mới!', notificationOptions)
    );
});

// Xử lý sự kiện khi người dùng tương tác với thông báo
self.addEventListener('notificationclick', function(event) {
    event.notification.close();

    let url = event.notification.data?.url || 'https://truyenvideo.com';

    if (event.action === 'open' || !event.action) {
        event.waitUntil(clients.openWindow(url));
    }
});

Oke vậy là chúng ta đã làm xong phần client đăng kí tiếp theo chúng ta sẽ viết controller gửi 

<?php

namespace App\Services;

use Google\Client;
use Illuminate\Support\Facades\Http;

class FcmService
{
    public function sendFcmNotification($targetToken)
    {
        // 1. Load credentials
        $client = new  Client();
        $client->setAuthConfig(storage_path('firebase-adminsdk.json'));
        $client->addScope('https://www.googleapis.com/auth/firebase.messaging');
        $accessToken = $client->fetchAccessTokenWithAssertion()["access_token"];

        // 2. Gửi notification
        $projectId = 'truyenvideo-xxxx'; // Project ID trong Firebase

        $url = "https://fcm.googleapis.com/v1/projects/{$projectId}/messages:send";

        $data = [
            'message' => [
                'token' => $targetToken,
                'notification' => [
                    'title' => 'Xin chào đây là title',
                    'body'  => 'Demo nhé',
                    'image'=> 'https://i3.ytimg.com/vi/My5pjyoTOps/maxresdefault.jpg',
                ],
                'data' => [ // Nếu bạn cần gửi thêm payload
                    'url' => 'https://www.youtube.com/watch?v=xxxxx',
                    'key2' => 'key2data',
                ]
            ]
        ];

        $response = Http::withToken($accessToken)
            ->post($url, $data);
        return $response->json();
    }
}

File firebase-adminsdk.json được lưu ở storage_path được download ở đây https://console.firebase.google.com/project/truyenvideo-3eb09/settings/serviceaccounts/adminsdk?hl=vi .Vậy là bây giờ bạn chỉ cần gọi đến là có thể chuyển oke