Fcm Notifications push android/IOS nodejs - android

I am looking for to send a notification from a Nodejs server, but I am getting some errors that I don't know how solve it. Could someone help me? I found this possible solution on Internet --> URL
This is my code in nodejs
var FCM = require('fcm-push');
function sendNotification (){
var serverKey = 'AAAAJnK3Ing:AP-(more caracters)AwAlBL_CvXIkFM2UufYZHYkvhC7FP3Tu16mlI';
var fcm = new FCM(serverKey);
var message = {
to: 'd2b2v(more caracters token)DUmAXqU-uHptJJLRPXukl',
/*data: {
your_custom_data_key: 'your_custom_data_value'
},*/
notification: {
title: 'notification',
body: 'This is a notification from node'
}
};
//callback style
fcm.send(message, function(err, response){
if (err) {
console.log("****************************************************")
console.log(message)
console.log("Something has gone wrong!");
} else {
console.log("Successfully sent with response: ", response);
}
});
//promise style
fcm.send(message)
.then(function(response){
console.log("Successfully sent with response: ", response);
})
.catch(function(err){
console.log("----------------------------------------------------")
console.log("Something has gone wrong!");
console.error(err);
})
}
module.exports = {
sendNotification
}
I am getting this error

Try to check if your firewall allow to connect on 443 port. It seems like it can't create the connection.

Related

Sending a notification using firebase cloud Messaging sometimes sends the notification with image and sometime not

I have an issue with firebase cloud messaging notification. I have implemented function that sends specific title, message and imageUrl and I made sure that the image size is less than 1mb as the documentation. But sometimes I see the image and sometime I don't see the image in the notification
and when I debug to check the notification object, it contains the imageUrl.
Here is my Implementation:
const notification = {
title: data.title,
body: data.message,
...(imageUrl && { imageUrl }),
};
exports.notificationWithImg = async (registrationToken, notification) => {
try {
const response = await admin.messaging().sendMulticast({
tokens: registrationToken,
notification,
});
console.log("Notificatin response:", JSON.stringify(response));
if (response.successCount > 0) {
return {
statusMessage: "SUCCESS",
message: "Sent Successfully",
statusCode: 200,
};
}
if (response.failureCount > 0) {
return {
statusMessage: "ERROR",
message: "Falure",
statusCode: 400,
};
}
} catch (error) {
console.log("Error", error);
return {
statusMessage: "ERROR",
message: "SERVER ERROR",
statusCode: 400,
};
}
};
Frontend
using react-native-push-notification
PushNotification.localNotification({
message: remoteMessage.notification.body,
title: remoteMessage.notification.title,
picture: remoteMessage.notification.android.imageUrl,
priority: 'high',
bigPictureUrl: remoteMessage.notification.android.imageUrl,
smallIcon: remoteMessage.notification.android.imageUrl,
});

How to feed FirebaseInstanceID Token to observer on NodeJS server from Android application?

I'm trying to send notifications to my android app.
I have a NodeJS backend with Firesbase as my DB and my client is an Android app.
This is my observer on my NodeJS:
var observer = db.collection(‘bookings’)
.onSnapshot(querySnapshot => {
querySnapshot.docChanges.forEach(change => {
if (change.type === ‘added’) {
// This registration token comes from the client FCM SDKs.
var registrationToken = ‘YOUR_REGISTRATION_TOKEN’; //can't find this
// See documentation on defining a message payload.
var message = {
data: {
score: ‘850’,
time: ‘2:45’
},
token: registrationToken
};
// Send a message to the device corresponding to the provided
// registration token.
admin.messaging().send(message)
.then((response) => {
// Response is a message ID string.
console.log(‘Successfully sent message:’, response);
})
.catch((error) => {
console.log(‘Error sending message:’, error);
});
console.log(‘New booking: ’, change.doc.data());
}
else if (change.type === ‘modified’) {
console.log(‘Modified booking: ’, change.doc.data());
}
else if (change.type === ‘removed’) {
console.log(‘Removed booking: ’, change.doc.data());
}
});
});
I am unable to figured out how to persist the FirebaseInstanceID Token somewhere in the server or DB?

Cloud Function executed successfully but notification not showing android

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...

How to handle FCM upstream message in Node server?

I am using node-xcs module to create XMPP CCS server in NodeJs, But in that module there is no method to send ACK message which is required to send back to FCM.
do you use fcm-node package for get FCM token . using that we can register device look at my full coding i have use it for send notification to mobile
var FCM = require('fcm-node');
exports.SendNotification = function(msg,title,type,id,user_id,api_token)
{
var fcm = new FCM(constants.serverKey);
var message = {
registration_ids : api_token,
notification: {
title: title,
body:msg
},
data: {
type: type,
id:id,
user_id:user_id
}
};
fcm.send(message, function(err, response){
if (err)
{
console.log("Error for Send Notification",err);
return;
}
else
{
console.log("Successfully sent Notification", response);
return;
}
});
}
and than call this function like this
msg='new notification for you'
title='Hello'
id='34'
user_id='34'
result='api_token'//save this token in database and retrive using user_id
SendNotification(msg,title,'START_APPOINTMENT',id,user_id,result);

Ionic Push using $http not working for android (Push Error Code 101)

push: function (tokens, message) {
var privateKey = 'xxx';
var appId = 'xxx';
var auth = btoa(privateKey + ':');
var req = {
method: 'POST',
url: 'https://push.ionic.io/api/v1/push',
headers: {
'Content-Type': 'application/json',
'X-Ionic-Application-Id': appId,
'Authorization': 'basic ' + auth
},
data: {
"tokens": tokens,
"notification": {
"alert": message
}
}
};
// Make the API call
$http(req).success(function (resp) {
// Handle success
console.log(tokens);
console.log(resp);
}).error(function (error) {
// Handle error
console.log("Ionic Push: Push error...");
});
}
I am using the above code to push notifications. It gets into the
success handler and prints the token used and message id, to the console. But when i check the status with the message id, its saying Push Error Code 101.
When i use the same token using Ionic.io website for one time notification screen, it works !
How can i make this working using angular code ?
Thanks !

Categories

Resources