Firebase Cloud Messaging click_action not working - firebase

I am sending notification from Firebase console to web application (Firebase). When I am sending a POST request from POSTMAN, I am able to navigate to the URL when I click on the notification. But when I am sending it from Firebase console I am not able to open the URL. Also, I need to add my logo as my Icon to the notification.
POSTMAN
{
"notification": {
"title": "Push notification test",
"body": "It works! 🎉",
"icon": "https://soft-ing.info/img/firebase.png",
"click_action": "https://google.com"
},
"to": "dLXCbmVCh5Y:APA91bGmFN7BUsKqwWFokyoBsoph6k4EhBQEflwJLFrPaUzTceYhAPYfFf8LqTRBVJGCA0gWS_0k0DUCeJBa7jdopIyjFQNprtp3lkQgLmUNRUibLIIMxAuBZeXuHTqaU-BA4QwbekN6"
}
Service Worker File Code
messaging.setBackgroundMessageHandler(function(payload) {
console.log('[firebase-messaging-sw.js] Received background message ', payload);
// Customize notification here
const notificationTitle = payload.data.title;//'Background Message Title';
const notificationOptions = {
body: payload.data.body,//'Background Message body.',
icon: payload.data.icon,
image : payload.data.image,
data:{
time: new Date(Date.now()).toString(),
click_action : payload.data.click_action
}
};
return self.registration.showNotification(notificationTitle,notificationOptions);
});
self.addEventListener("notificationclick", (event) => {
event.waitUntil(async function () {
const allClients = await clients.matchAll({
includeUncontrolled: true
});
let chatClient;
let appUrl = 'https://www.google.com';
for (const client of allClients) {
//here appUrl is the application url, we are checking it application tab is open
if(client['url'].indexOf(appUrl) >= 0)
{
client.focus();
chatClient = client;
break;
}
}
if (!chatClient) {
chatClient = await clients.openWindow(appUrl);
}
}());
});

There's some discrepancy in the above two snippets you shared.
In your case body: payload.data.body should be body: payload.notification.body, you need to do similarly for other places in service worker since that's how you are sending the request.

Related

Notification via rest api in react native

I am trying to send notification in react native via rest api. In response i'm getting success :1. The problem here is i'm not getting notification in emulator.
const token = await firebase.messaging().getToken();
console.log("token in sendNotification ",token)
const FIREBASE_API_KEY = "firebaseApiKey";
const message = {
to :token,
notification: {
title: "This is a Notification",
boby: "This is the body of the Notification",
vibrate: 1,
sound: 1,
show_in_foreground: true,
priority: "high",
content_available: true,
}
}
let headers = new Headers({
"Content-Type" : "application/json",
Authorization: "key=" + FIREBASE_API_KEY,
})
try {
let response = await fetch ("https://fcm.googleapis.com/fcm/send",{
method: "POST",
headers,
body: JSON.stringify(message),
})
response = await response.json();
console.log("response ", response);
} catch (error) {
console.log("error ", error);
}
https://firebase.google.com/docs/cloud-messaging/js/receive
You can follow the incoming message documentation
// Handle incoming messages. Called when:
// - a message is received while the app has a focus
// - the user clicks on an app notification created by a service worker
// `messaging.setBackgroundMessageHandler` handler.
messaging.onMessage((payload) => {
console.log('Message received. ', payload);
// ...
});
In useEffect of App.js
import React,{useEffect} from 'react'
import{View,Text} from 'react-native';
async function onDisplayNotification() {
// Create a channel
const channelId = await notifee.createChannel({
id: 'default',
name: 'Default Channel',
});
// Display a notification
await notifee.displayNotification({
title: 'Notification Title',
body: 'Main body content of the notification',
android: {
channelId,
smallIcon: 'ic_launcher', // optional, defaults to 'ic_launcher'.
},
});
}
const App=()=> {
useEffect(() => {
// Assume a message-notification contains a "type" property in the data payload of the screen to open
messaging().onMessage((payload) => {
console.log('Message received. ', payload);
onDisplayNotification();
// ...
});
messaging().onNotificationOpenedApp(remoteMessage => {
console.log(
'Notification caused app to open from background state:',
remoteMessage.notification,
);
alert("Notification");
});
// Check whether an initial notification is available
messaging()
.getInitialNotification()
.then(remoteMessage => {
if (remoteMessage) {
console.log(
'Notification caused app to open from quit state:',
remoteMessage.notification,
);
}
});
}, []);
return (
<View>
</View>
)
}
export default App;

Push notifications with firebase

I'm getting this error when i test with token which I got from firebase
Error -The request's Authentication (Server-) Key contained an invalid or malformed FCM-Token (a.k.a. IID-Token)
these are the codes that i used to get token from firebase.
async getToken() {
let fcmToken = await AsyncStorage.getItem('fcmToken');
console.log("before fcmToken: ", fcmToken);
if (!fcmToken) {
fcmToken = await firebase.messaging().getToken();
if (fcmToken) {
console.log("after fcmToken: ", fcmToken);
await AsyncStorage.setItem('fcmToken', fcmToken);
}
}
}
async requestPermission() {
firebase.messaging().requestPermission()
.then(() => {
this.getToken();
})
.catch(error => {
console.log('permission rejected');
});
}
async checkPermission() {
firebase.messaging().hasPermission()
.then(enabled => {
if (enabled) {
console.log("Permission granted");
this.getToken();
} else {
console.log("Request Permission");
this.requestPermission();
}
});
}`
But I got this Error 401 when I test with APNS & GCM Tester Online
https://pushtry.com/
Please may I have any methods to get push notification for react native android application?
You can use postman. Make a post request to this url "https://fcm.googleapis.com/fcm/send".
you need to send an object like this:
{
"data":
{
"title": "your title",
"body": "your body"
},
"notification": {
"title": "your title",
"body": "your body"
},
"registration_ids" : ["czf_nv_t1JA:APA91bGOyY3lTSG9b7Nr71xVo_Xn5RrxOIOwVfnKDv2OBanQjx1eQQyqdM3PFOd1Pjapm_DWn1R327iDyEwEeXjflJ3DyaGFF4iXmqot-OsyDt-Iz99Lu3MZZTvOSFIPiYgiaGHP5ByO"]
}
and registration_ids is your token.Also you need to set a header for your request with key Authorization and it's value comes from firebase console.for finding that you can check this https://developer.clevertap.com/docs/find-your-fcm-sender-id-fcm-server-api-key
Make sure in Authorization value is as per your firebase cloud messaging server key.
Reference link:- https://www.djamware.com/post/5c6ccd1f80aca754f7a9d1ec/push-notification-using-ionic-4-and-firebase-cloud-messaging

notification click render only my domain url not my click_action key url in as i pass in my payload for mobile devices onmessage event

onmessgae event code --
messaging.onMessage(function(payload) {
const notificationTitle = payload.notification.title;
const notificationOptions = {
body: payload.notification.body,
icon: payload.notification.icon,
data: payload.notification.click_action,
};
navigator.serviceWorker.register('firebase-messaging-sw.js');
if (Notification.permission === "granted") {
// If it's okay let's create a notification
navigator.serviceWorker.ready.then(function (registration) {
registration.showNotification(notificationTitle, notificationOptions);
})
}
})
my notification click event -
self.addEventListener('notificationclick', function (event) {
var default_val = 0;
console.log(event.notification)
event.notification.close();
try{
url = event.notification.data.FCM_MSG.notification.click_action
console.log("check1")
console.log("true")
}
catch (err) {
url = event.notification.data
console.log("check2")
}
//url = event.notification.data
if (default_val ==0) {
default_val = default_val+1
event.waitUntil(self.clients.openWindow(url));
}
})
my payload ---
{"notification":
{"body": "testing", "click_action": "/order1/", "icon": "http://localhost:8000/static/Logo/fcm_logo.jpg", "mutable-content": 1, "title": "hi "},
i am implementing fcm services for my project ,as i maintain in my titile i am getting a problem with my onmessage event in mobile devices .i sharing some code ,my setBackgroundMessageHandler event is working fine for both mobile or desktop version ...but issue with on message event in mobile devices

send push notification using lambda with aws sns for single device

I did lot rnd for send push (ios) using aws SNS. I manually create a platform application and then add deviceToken and then push. It works well.
But I want to add the device to application Platform in lambda runtime and send push to that device token. Can any help me? Thanks in advance.
function sendPushMessage(deviecToken, pushMessage)
{
var SNS = require('sns-mobile'),EVENTS = SNS.EVENTS;
var SNS_KEY_ID = 'AWS_USER_AWSAccessKeyId',
SNS_ACCESS_KEY = 'AWS_USER_AWSSecretKey',
IOS_ARN = "SNS_APPLICATION_ARN";
var iosApp = new SNS({
platform: SNS.SUPPORTED_PLATFORMS.IOS,
region: 'us-west-1',
apiVersion: '2010-03-31',
accessKeyId: SNS_ACCESS_KEY,
secretAccessKey: SNS_KEY_ID,
platformApplicationArn: IOS_ARN,
sandbox: true
});
// Add a user, the endpointArn is their unique id
// endpointArn is required to send messages to the device
iosApp.addUser(deviecToken, JSON.stringify({
some: 'extra data'
}), function(err, endpointArn) {
if (err) {
// callback(null, err);
}
else{
let endpp = endpointArn;
// Send a simple String or data to the client
iosApp.sendMessage(endpp, pushMessage, function(err, messageId) {
if (err) {
// callback(null, err);
}
else{
// callback(null, messageId);
}
});
}
});
}
let response;
let test = (event, context, callback) => {
let deviceToken = "YOUR DEVICE TOKEN";
let apnPayload = { aps: { alert: { title: "Hello", body: "This is the content of our push notification." }, badge: 6 } };
let msg = {
"APNS_SANDBOX": JSON.stringify(apnPayload)
};
sendPushMessage(deviceToken, msg);
};
module.exports = test;
Note : First you have to " npm install sns-mobile " this package. Then create test lambda and copy paste this code. i m using this code and working well.

Send push notifications using Firebase and OneSignal

Not sure if this is possible, but I have an existing Ionic 3 app which uses Firebase as a backend. Maybe it's just me, I'm not able to integrate Google login, Facebook login and push notifications in the same app. Been trying for a few days now.
I was able to install OneSignal and send push notifications to an Android device, but I want to send them programatically using tokens which are saved for each device, not from the OneSignal dashboard.
This is what I use in Firebase Cloud Functions to send notifications. Can it be modified to send the notification to OneSignal and then to each device?
`function sendFcm(userID, eventSnapshot, eventID) {
const getDeviceTokensPromise = admin.database().ref(`/fcmTokens/${userID}/`).once('value');
return Promise.all([getDeviceTokensPromise]).then(result => {
const tokensSnapshot = result[0];
const payload = {
"notification": {
"title": "Your invitation has arrived",
"body": eventSnapshot.name,
"sound": "default",
// "click_action": "FCM_PLUGIN_ACTIVITY",
"icon": "fcm_push_icon"
},
"data": {
"eventId": eventID,
"uid": userID,
"eventObj": JSON.stringify(eventSnapshot),
"notificationType": "newEventNotification"
}
};
const tokens = Object.keys(tokensSnapshot.val());
console.log(tokens);
// Send notifications to all tokens.
return admin.messaging().sendToDevice(tokens, payload).then(response => {
// For each message check if there was an error.
const tokensToRemove = [];
response.results.forEach((result, index) => {
console.log(tokens[index]);
const error = result.error;
if (error) {
console.error('Failure sending notification to', tokens[index], error);
// Cleanup the tokens which are not registered anymore.
if (error.code === 'messaging/invalid-registration-token' ||
error.code === 'messaging/registration-token-not-registered') {
tokensToRemove.push(tokensSnapshot.ref.child(tokens[index]).remove());
}
}
});
return Promise.all(tokensToRemove);
});
})
}`
After searching a bit, I found the OneSignal API. Seems that I just need to save the player id and send it or mutiple in an array to onesignal.com/api/v1/notifications. More details here: https://documentation.onesignal.com/reference#section-send-based-on-onesignal-playerids-create-notification

Resources