I am working on a Firebase push notification functionality on Laravel Vue project. I was able to send the notifications from laravel successfully but was not able to receive them on client side.
When I trigger push notification from laravel I get a successful response as below
{"message":"Push notification sent successfully!!","response":{"name":"projects/paseo-307906/messages/3877998254258475769"}}
The Related function is
public function sendPushNotification()
{
try {
// Initialize Firebase Messaging with the service account credentials
$firebase = (new Factory)->withServiceAccount(base_path('google/firebase_credentials.json'));
$messaging = $firebase->createMessaging();
$message = CloudMessage::fromArray([
'notification' => [
'title' => 'Hello from Firebase!',
'body' => 'This is a test notification.'
],
'topic' => 'global'
]);
// Send the message
$response = $messaging->send($message);
// Optionally, you can log the response or process it as needed
// $response will contain information about the sent message
// Return a success response
return response()->json(['message' => 'Push notification sent successfully!!', 'response' => $response]);
} catch (Exception $e) {
// Handle the exception and return an error response
return response()->json(['error' => 'Failed to send push notification', 'details' => $e->getMessage()], 500);
}
}
For now I am setting the ‘topic’ => ‘global’ to test the functionality.
But I don’t receive any notification on the client side (vue js)
Here is the related code on vue js side
The content of firebase-messaging-sw.js file placed in root folder
importScripts('https://www.gstatic.com/firebasejs/8.2.7/firebase-app.js')
importScripts('https://www.gstatic.com/firebasejs/8.2.7/firebase-messaging.js')
const firebaseConfig = {
--configs here--
};
const app = firebase.initializeApp(firebaseConfig)
The content of firebase.js file
import firebase from 'firebase/app'
import 'firebase/firebase-messaging'
const firebaseConfig = {
--Cofigs here---
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig)
export default firebase.messaging()
This file is imported in app.js and as below
import firebaseMessaging from './firebase'
Vue.prototype.$messaging = firebaseMessaging
As now the messaging can be used globally, I am using it in my vue component as below
In the mounted hook a am calling
this.notificationPermission(this.$messaging);
In the methods
notificationPermission(messaging){
try{
Notification.requestPermission().then(permission => {
if (permission === "granted") {
messaging.getToken( { vapidKey: process.env.MIX_FIREBASE_VAPID_KEY }).then((currentToken) => {
if (currentToken) {
console.log('client token', currentToken);
messaging.onMessage((payload) => {
console.log('Message received. ', payload);
const noteTitle = payload.notification.title;
const noteOptions = {
body: payload.notification.body,
icon: payload.notification.icon,
};
new Notification(noteTitle, noteOptions);
});
this.saveFCMToken(currentToken);
} else {
console.log('No registration token available. Request permission to generate one.');
}
}).catch((err) => {
console.log('An error occurred while retrieving token. ', err);
});
} else {
console.log("Unable to get permission to notify.");
}
});
}catch(e){
console.log('the notificationPermission error is ', e);
}
},
saveFCMToken(token){
try{
var apiUrl = this.baseUrl + 'api/save-fpm-token';
axios.post(apiUrl,{
user_id: this.user_id,
fcm_token: token,
device_type:'web'
},{headers: this.headers}).then(res => {
if(res.data.status === true){
console.log(the user toke aginst id ${this.user_id} was saved successfully);
}else{
console.log('could not save user token due to',res.data.message);
}
});
}catch(e){
console.log('save token exception is ', e);
}
},
From the console output I can see the token is generated and saved in database correctly, but I never see the console.log(‘Message received. ‘, payload); or the browser notification message when I send the notification from laravel end.