I want to implement push notifications in node js with the OneSignal package.
You can implement OneSignal Push Notifications in Nodejs by following below steps:
1- First implement your OneSignal Push Notifications on the frontend side e.g (React Native, Reactjs, Flutter).
2- Then test those Push Notifications by sending manual notifications from One Signal website.
Link for manual testing: https://dashboard.onesignal.com/apps/fade543c-d12e-422c-8e15-66afa731e2fe/notifications/new
3- If manual notifications are working then we are good to go on the Nodejs side. First Install "onesignal-node" package in your node App.
4- And use the below code to send notifications
const sendPushNotificationsToAll = async (request, response) => {
\\you can find app id and api key in your one signal
application settings
const client = new OneSignal.Client(
process.env.ONE_SIGNAL_APP_ID,
process.env.ONE_SIGNAL_API_KEY
);
const notification = {
headings: { en: title }, ***title of notification***
contents: {
en: description, ***description of notification***
},
included_segments: ["Subscribed Users"], ***target audience***
large_icon: "http://www.logo.com", ***notification large logo***
big_picture: "http://www.bigpicture.com",
data: {
postId: postId, ***fields data***
},
};
try {
const res = await client.createNotification(notification);
response.status(200).json("Notification created successfully");
} catch (error) {
response.status(500).json(error);
}
};
Related
I have Angular application with Capacitor (without Ionic) and I need to send push notifications to the user app from Node.js backend. How would I do that? Any article, source or example would be much appreciable?
Here is capacitor.config.ts file
import { CapacitorConfig } from '#capacitor/cli';
const config: CapacitorConfig = {
appId: 'xxx.xxxxxxx.xxx',
appName: 'ABC',
webDir: 'dist/abc',
bundledWebRuntime: false,
plugins: {
PushNotifications: {
presentationOptions: ["badge", "sound", "alert"],
},
},
};
export default config;
I have seen many artcles etc. on push notifications with Capacitor and Firebase but couldn't find a single source on my requirement.
The best and easiest solution so far is to implement it with firebase. There are primarily two parts to this entire setup
Configure Capacitor and Firebase to be able to receive notifications
For this I suggest you follow this tutorial word by word.
Code the nodejs implementation to send push notifications from the server
For this, follow the firebase official documentation
As a reference, here is how you can handle the nodejs part, this triggers push notifications successfully.
const admin = require("firebase-admin");
admin.initializeApp({
credential: admin.credential.applicationDefault(),
databaseURL: <Your-Firebase-DB-URL>
});
async function sendNotification(tokens, title, body, data = {}) {
message = {
notification: {
title: title,
body: body,
},
data: data
}
options = {
priority: 'high'
}
result = await admin.messaging().sendToDevice(tokens, message, options)
return result;
}
module.exports = { sendNotification };
This might be very simple, but I cannot find any reference regarding this.
I integrated the chat bot in the web app using direct line API; I’m using this API to generate conversation id:
POST: https://directline.botframework.com/v3/directline/conversations
I’m trying to get the generated conversation id from the above API (from web app code) to the chatbot code (NodeJS). Is there a way or any reference to do this?
one way as per this issue comment is to send data to bot before starting the conversation using:
var params = BotChat.queryParams(location.search);
var my_token = params['my_token'];
var botConnection = new BotChat.DirectLine({
secret: 'DIRECTLINE_SECRET'
});
BotChat.App({
botConnection: botConnection
,user: { id: 'USER_ID', name: 'User' } // user.id auto updates after first user message
}, document.getElementById("bot"));
botConnection.connectionStatus$.subscribe(function (status) {
if (status == 2) { // wait for connection is 'OnLine' to send data to bot
var convID = botConnection.conversationId;
botConnection.postActivity({
from: { id: convID } // because first time user ID == conversation ID
,type: 'event'
,name: 'registerUserData' // event name as we need
,value: my_token // data attached to event
}).subscribe(function (activityId) {
// This subscription is a MUST
// If I remove this handler the postActivity not reaches the bot
});
}
});
Here you subscribe to the botConnection.connectionStatus$ and when the status is equal to 2, you get the conversation ID from the botConnection object.
Then, you can add this middleware code in the bot code to get the data:
bot.use({ receive: function(event, next) {
if (!!event && !!event.address && event.name == 'registerUserData') {
var message = new builder.Message().address(event.address).text('my_token:' + event.value);
bot.send(message, function (err) {}); // simulate proactive message to user
}
next();
} });
Hope this helps.
I resolve it using Botframework Web Chat back channel, here's the link for reference:
https://github.com/Microsoft/BotFramework-WebChat
After I generated the conversation id using directline API:
POST: https://directline.botframework.com/v3/directline/conversations
I send data from the web app to the chatbot via backchannel.
<div id="webchat"></div>
<script>
(async function () {
// We are using a customized store to add hooks to connect event
const store = window.WebChat.createStore({}, ({ dispatch }) => next => action => {
if (action.type === 'DIRECT_LINE/CONNECT_FULFILLED') {
// When we receive DIRECT_LINE/CONNECT_FULFILLED action, we will send an event activity using WEB_CHAT/SEND_EVENT
dispatch({
type: 'WEB_CHAT/SEND_EVENT',
payload: {
name: 'webchat/join',
value: { conversation_id: conversationID }
}
});
}
return next(action);
});
window.WebChat.renderWebChat({
directLine: window.WebChat.createDirectLine({ token }),
store
}, document.getElementById('webchat'));
document.querySelector('#webchat > *').focus();
})().catch(err => console.error(err));
//Note: conversationID and token is generated in the backend code of the web app.
</script>
I'm trying to get my FCM web notifications to contain a clickable link to my site, using the firebase admin SDK (version 7.0.0) for node.js. As far as I can tell I'm following the documentation to a T, but I'm unable to get the link working. To clarify, my notifications are working fine otherwise, it's just the link that I haven't got to work.
The documentation states:
For notification messages sent from the app server, the FCM JavaScript API supports the fcm_options.link key. Typically this is set to a page in your web app
I've included webpush.fcm_options.link inside my notification message. I've made sure to include an explicit notification payload in my message, as the documentation states that data messages don't support fcm_options.link.
Here's the structure of my message currently:
{
notification: {
title: 'Title',
body: 'Body',
},
data: {
// my data here
},
webpush: {
notification: {
requireInteraction: true,
icon: '/icons/notification.png'
},
fcm_options: {
link: 'https://example.com/'
}
},
// android: {},
// apns: {},
topic: 'sometopic'
};
Here's the function I'm using to send the message:
const admin = require('firebase-admin')
const sendMessage = message => {
admin
.messaging()
.send(message)
.then(response => {
console.log(response)
})
.catch(error => {
console.log(error)
});
};
The link property should be working according to the documentation: my url includes https and my notification is being sent from the app server, and includes an explicit notification payload. At the moment, clicking on the notification just makes it disappear, with nothing else happening.
UPDATE: I worked out what the issue was - my service worker was using the importScripts function, but I was using an out-of-date version of the firebase script that didn't support fcm_options.link. I changed it to my current version of firebase (5.8.5) and it works. All sorted!
in notification try This
"notification":{
"title":"IssA",
"body":"Lafi",
"icon": "Icon URL",
"click_action": "Your URL here"
}
In the last version, using firebase admin in node js, this is the right configuration:
var message = {
notification: {
title: "",
body: ""
},
webpush: {
fcmOptions: {
link: "https://yourlink.web.app"
}
}
};
I am building cloud notifications based on Firebase. We are currently working on creating a server as node js and controlling cloud notifications.
However, I have searched a lot of data, and most of the above data is transmitted to only one person by receiving the token value when sending notifications.
Of course, i can use mysql to send it to a large number of people, but is it possible to send it to all users who have the app installed as a user segment like the Firebase console?
Here is the site I referenced. I made it using the script provided here.
https://www.npmjs.com/package/fcm-node
but is it possible to send it to all users who have the app installed as a user segment like the Firebase console?
Not possible out of box. You need a user's registration token to do any sort of messaging. If you do not have all your user's registration tokens, then you'll need to retrieve it for each user. Remember to verify the tokens before persisting them to your database: https://firebase.google.com/docs/auth/admin/verify-id-tokens
And as the readme states for fcm-node:
Warning: on February 2, 2017, the Firebase Team released the admin.messaging() service to their node.js admin module. This new service makes this module kind of deprecated
With that said, you have two options:
Send notifications to multiple users via their registration token:
-
const registrationTokens = [
'abc',
'efg',
'123'
];
const message = {
data: {
score: '850'
},
token: registrationToken
};
const promises = [];
registrationTokens.forEach(token => {
const promise = admin.messaging().send(message);
promises.push(promise);
});
Promise.all(promises)
.then(results => console.log(results))
.catch(err => console.error(err));
Or better yet, use Topic Messaging on a "user segment". You'll need to subscribe users to their respective topic. For example, Android documentation on how to do that can be found here
-
const message = {
data: {
score: '850'
},
topic: 'myUserSegmentTopic'
};
admin.messaging().send(message)
.then(res => console.log(res))
.error(err => console.error(err));
What are the procedures to follow in using GCM for a node based application?
Are there specific codes required on both server side(Node js) and client side(Android/iOS)?
Android device should sent a device token to the server to be able to receive notifications. Here an example how to do it.
Get gcm key to send pushes from server.
Send push with node-gcm package from npm with node.js app.
Basic example:
const gcm = require('node-gcm'); //Google Cloud Messaging
const gcmKey = ''; // Your gcm key in quotes
const deviceToken = ''; // Receiver device token
const sender = new gcm.Sender(gcmKey);
var message = new gcm.Message();
message.addData({
title: 'Push',
body: 'This is push notification',
otherProperty: true,
});
sender.send(message, {registrationIds: [token]}, (err) => {
if (err) {
console.error(err);
}
else {
console.log('Sent');
}
});