My application is simply order app and I want admin get notification when new order is placed.
So to do that I send notification to device with token Id by using firebase functions.
'use-strict'
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotification = functions.database.ref('admin/{user_id}/notification/{notification_id}').onCreate((snapshot, context) => {
console.log("hehehehehehehehe");
const user_id=context.params.user_id;
const getDeviceTokensPromise = admin.database().ref(`admin/${user_id}`).once('value');
//let tokensSnapshot;
//let tokes;
return Promise.all([getDeviceTokensPromise]).then(result => {
//const registrationToken= result[0].tokenid.val();
//console.log(registrationToken);
const payload = {
notification: {
title: 'You have a new follower!',
body: 'Yeni sifaris var',
}
};
return admin.messaging().sendToDevice('fOCU86Rhhb4:APA91bHwJZInZYGp9cIDc7PyCw48QcEvvMOMuFepYcCTvkxlCJp8_Ieq1Ikwd9xNoU2rfTA9paRqCTLAuhUlZgF952AvpBstGdGRWMK8lCR2MHgHn6xzbvyxFEu-auRYexnPYmOnlTB1',payload).then((response) => {
return console.log('Successfully sent message:', response);
}).catch((error) => {
return console.log('Error sending message:', error);
});
});
});
Although I got the success response message in console log, my android phone couldn't get any notification.
Successfully sent message: { results: [ { messageId: '0:1542910779596746%095eb9af095eb9af' } ],
canonicalRegistrationTokenCount: 0,
failureCount: 0,
successCount: 1,
multicastId: 6551370257673400000 }
What is wrong with my code. I am new to firebase. I need your help.
Related
I wrote a node.js function which sends notification on to an Android device by payload. I've deployed the index.js(file that content the function) on to Firebase Cloud Messaging.
After sending a message the log shows that the notification is sent at the same time it shows error, and I'm not able to receive notification on targeted device.
Here's my index.js file that content the function:
'use-strict'
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotification = functions.firestore.document("Users/{user_id}/notifMessages/{notification_id}").onWrite((change, context) => {
const user_id = context.params.user_id;
const notification_id = context.params.notification_id;
return admin.firestore().collection("Users").doc(user_id).collection("notifMessages").doc(notification_id).get().then(queryResult => {
const from_user_id = queryResult.data().fromUser;
const from_message = queryResult.data().message;
const from_data = admin.firestore().collection("Users").doc(from_user_id).get();
const to_data = admin.firestore().collection("Users").doc(user_id).get();
return Promise.all([from_data, to_data]).then(result => {
const from_name = result[0].data().nom;
const to_name = result[1].data().nom;
const tokenId = result[1].data().tokenId;
const payload = {
notification: {
title : "Notification from : "+from_name,
body : from_message,
icon : "default",
click_action: "mr.pharma_proche.TARGETNOTIFICATION"
},
data: {
message : from_message,
from_user_id : from_user_id
}
};
return admin.messaging().sendToDevice(tokenId, payload).then(result => {
console.log("Notification sent : "+from_name+" to : "+to_name+" Token : "+tokenId);
return results;
}).catch((error) => {
console.log("error, message not sent");
});
});
});
});
I have not more experience of Android and almost have no idea in javascript coding, I followed a tutorial to create a firebase function and now firebase function change beta to stable and my code is showing me error :
this is my code --->
'use strict'
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.sendNotification = functions.database.ref('/notifications/{user_id}/{notification_id}').onWrite((change, context)=> {
const user_id = context.params.user_id;
const notification_id = context.params.notification_id;
console.log('We have a notification from : ', user_id);
if (!event.data.exists()) {
return console.log('A Notification has been deleted from the database : ', notification_id);
}
const fromUser = admin.database().ref(`/notifications/${user_id}/${notification_id}`).once('value');
return fromUser.then(fromUserResult => {
const from_user_id = fromUserResult.val().from;
console.log('You have new notification from : ', from_user_id);
const userQuery = admin.database().ref(`Users/${from_user_id}/name`).once('value');
const deviceToken = admin.database().ref(`/Users/${user_id}/device_token`).once('value');
return Promise.all([userQuery, deviceToken]).then(result => {
const userName = result[0].val();
const token_id = result[1].val();
const payload = {
notification: {
title : "New Friend Request",
body: `${userName} has sent you request`,
icon: "default",
click_action : "in.tvac.akshaye.lapitchat_TARGET_NOTIFICATION"
},
data : {
from_user_id : from_user_id
}
};
return admin.messaging().sendToDevice(token_id, payload).then(response => {
console.log('This was the notification Feature');
});
});
});
});
and this is my database ---->
notifications
BOhvOUJG8sWgIyTD7JLuSOgfv9v1
aqTdCWJYfvQiw188MqldsDtlLFf2
-LLO14ghpMruZtqwK7CR from: "rrajSiL7SFd7WQydkA7jwxi26s63" type: "request"
-LLOQ2WsWHymJvdOxrx5 from: "rrajSiL7SFd7WQydkA7jwxi26s63" type: "request"
-LLfVM43o8Rt-1A55r28
-LLfxudlktvk3ysxvype
i am getting this error --->
ReferenceError: event is not defined
at exports.sendNotification.functions.database.ref.onWrite (/user_code/index.js:15:7)
at cloudFunctionNewSignature (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:105:23)
at cloudFunction (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:135:20)
at /var/tmp/worker/worker.js:733:24
at process._tickDomainCallback (internal/process/next_tick.js:135:7)
Please check if you have defined the event or not
I need help, I've been searching for solutions all day but I can't fix my issue, the code below won't read the device tokens.
Below contains my db structure. I manage to receive the log: 'We have a new News for you.' When I added a new post but I received the log "There are no notification tokens to send to." Which means it cannot detect the device tokens even though there is already ones. What am I doing wrong?
{
"Newsv2" : {
"All" : {
"-Ktr7ZkuChCjsUIMb_4f" : {
"title" : "",
"type" : "",
}
},
"Usersv2" : {
"h0RzzpdO7nZVLpAR4fi7xRWUqsT2" : {
"device_token" : "",
"name" : "",
"user_no" : ""
}
},
}
/--News
--All
--name
--desc
/--Usersv2
--{userID}
--device_token
exports.sendNotif = functions.database.ref('/Newsv2/All/{newsID}').onWrite(event => {
const newsID = event.params.newsID;
const userID = event.params.userID;
if (!event.data.val()) {
return console.log('News! ', newsID);
}
console.log('We have a new News for you!',newsID);
// Get the list of device notification tokens.
const getDeviceTokensPromise = admin.database().ref(`/Usersv2/${userid}/device_token`).once('value');
return Promise.all([getDeviceTokensPromise]).then(results => {
const tokensSnapshot = results[0];
//const follower = results[1];
// Check if there are any device tokens.
if (!tokensSnapshot.hasChildren()) {
return console.log('There are no notification tokens to send to.');
}
console.log('There are', tokensSnapshot.numChildren(), 'tokens to send notifications to.');
//console.log('Fetched follower profile', follower);
// Notification details.
const payload = {
notification: {
title: 'Test Message',
body: '',
icon: ''
}
};
// Listing all tokens.
const tokens = Object.keys(tokensSnapshot.val());
// 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) => {
const error = result.error;
if (error) {
console.error('Failure sending notification to', tokens[index], error);
// Cleanup the tokens who 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);
});
});
});
To get the device token I store it in my firebase DB when a user registers or logs in.
private DatabaseReference mUserDatabase;
mUserDatabase = FirebaseDatabase.getInstance().getReference().child("Users/");
//and if the login/register is successful
mUserDatabase.child("device_token").setValue(deviceToken).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Intent intent = new Intent(application.getApplicationContext(), MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |Intent.FLAG_ACTIVITY_NEW_TASK);
application.startActivity(intent);
}
});
as for my firebase funciton:
const deviceToken = admin.database().ref(`/Users/${unique_id}/device_token`).once('value');
Below code is my firebase function index.js file
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotification = functions.database.ref("Notifications/{userId}")
.onWrite(event => {
var request = event.data.val();
var payload = {
data: {
title: "Welcome to ChitChat Group",
message: "You may have new messages"
}
};
admin.messaging().sendToDevice(request.token, payload)
.then(function (response) {
console.log("Successfully sent message: ", response);
})
.catch(function (error) {
console.log("Error sending message: ", error);
})
});
below code contains where i crate token when user get registered
String uid = (String) firebaseAuth.getCurrentUser().getUid();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Notifications/"+uid);
reference.child("token").setValue(FirebaseInstanceId.getInstance().getToken());
You can make all your users subscribe to one big topic like registration on newMembers then send notification to the topic :
var message = {
to: '/topics/newMembers',
notification: {
title: 'title',
body: 'body'
},
};
In an android app, I am using FCM for sending notifications, the cloud function executed successfully, as shown in the firebase console log, but in my device its not showing any notification, what could be the reason ?
Below is the code for my index.js
let functions = require('firebase-functions');
let admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.sendNotification = functions.database.ref('/notifications/messages/{pushId}')
.onWrite(event => {
console.log('notifying start1');
const message = event.data.current.val();
const senderUid = message.from;
const receiverUid = message.to;
console.log('SenderId '+senderUid + ' Receiver Id '+receiverUid);
const promises = [];
console.log('notifying start2');
if (senderUid == receiverUid) {
//if sender is receiver, don't send notification
promises.push(event.data.current.ref.remove());
return Promise.all(promises);
}
console.log('notifying start3');
const getInstanceIdPromise = admin.database().ref(`/users/${receiverUid}/accessToken`).once('value');
console.log('notifying start4');
const getReceiverUidPromise = admin.auth().getUser(receiverUid);
console.log('notifying start5');
return Promise.all([getInstanceIdPromise, getReceiverUidPromise]).then(results => {
const accessToken = results[0].val();
const receiver = results[1];
console.log('notifying ' + receiverUid + ' about ' + message.body + ' from ' + senderUid);
const payload = {
notification: {
title: 'Firebase Notification',
body: message.body,
}
};
admin.messaging().sendToDevice(accessToken, payload)
.then(function (response) {
console.log("Successfully sent message:", response);
})
.catch(function (error) {
console.log("Error sending message:", error);
});
});
});
Kindly help! Thanks in advance.
Had the same problem and couldn't understand what was wrong since the error details were not shown i.e. { error: [Object] }
Successfully sent message: { results: [ { error: [Object] } ],
canonicalRegistrationTokenCount: 0,
failureCount: 1,
successCount: 0,
multicastId: 5487635521698134000
}
So changed/added a log in the cloud function code to access the error details i.e. console.log(response.results[0].error);.
code (in the cloud function):
admin.messaging().sendToDevice(registrationToken, payload)
.then(function(response) {
console.log("Successfully sent message:", response);
console.log(response.results[0].error);
})
.catch(function(error) {
console.log("Error sending message:", error);
});
error details:
{ Error: The provided registration token is not registered. A previously valid registration token can be unregistered for a variety of reasons. See the error documentation for more details. Remove this registration token and stop using it to send messages.
at FirebaseMessagingError.Error (native)
at FirebaseMessagingError.FirebaseError [as constructor] (/user_code/node_modules/firebase-admin/lib/utils/error.js:25:28)
at new FirebaseMessagingError (/user_code/node_modules/firebase-admin/lib/utils/error.js:130:23)
at Function.FirebaseMessagingError.fromServerError (/user_code/node_modules/firebase-admin/lib/utils/error.js:154:16)
at /user_code/node_modules/firebase-admin/lib/messaging/messaging.js:80:63
at Array.forEach (native)
at mapRawResponseToDevicesResponse (/user_code/node_modules/firebase-admin/lib/messaging/messaging.js:76:26)
at /user_code/node_modules/firebase-admin/lib/messaging/messaging.js:223:24
at process._tickDomainCallback (internal/process/next_tick.js:135:7)
errorInfo:
{ code: 'messaging/registration-token-not-registered',
message: 'The provided registration token is not registered. A previously valid registration token can be unregistered for a variety of reasons. See the error documentation for more details. Remove this registration token and stop using it to send messages.' } }
Not sure if you have the same error I do...