Unable to register device to azure notification hub using nodejs packages - azure

We are trying to send push notification dynamically to all registered devices (android) using azure push notification. when we are trying to register the device using device token received from flutter mobile app. it is not getting registered.
For reference: https://learn.microsoft.com/en-us/azure/notification-hubs/notification-hubs-nodejs-push-notification-tutorial
In the above documentation, there is no step to register device using their device token to notification hub. So tried to check on some tech forums and got a sample way to proceed on registering device. Code is below for reference.
notificationHubService.gcm.createTemplateRegistration(
'replacing device token',
'tag', {
'aps': {
'alert': '$(message)',
'badge': '#(count)',
'sound': 'default'
}
},
function (e, r) {
if (e) {
console.log(e);
} else {
console.log({
id: r.RegistrationId,
deviceToken: r.DeviceToken,
expires: r.ExpirationTime
});
}
}
);
Response
{
id: '1294571364808236565-5460521645299605787-1',
deviceToken: undefined,
expires: '9999-12-31T23:59:59.999'
}
device token is always returning as undefined.

Please refer to this sample of how to use the Azure-SB SDK here.
Using this example, you can set the GCM_REGISTRATION_ID which is the device token from the Android device such as you would get from here.
This has the usage of GCM/Firebase here in registering, which is using the REST-API method of create registration under the covers: Create a registration | Microsoft Docs

Related

Register device on Azure notifications hub

I'm developing an application using Ionic & capacitor. My backend is Azure functions (nodejs) javascript, i'm able to get the device token using the below code:
PushNotifications.addListener(
'registration',
(token: PushNotificationToken) => {
alert('Push registration success, token: ' + token.value);
},
);
This token I send to my backend, but i don't know how to save it in Azure Notifications Hub?
Typically this is stored on your app backend. Please see this document for more information.
Let me know if there are further questions on this matter.
Was able to use azure-sb to successfully register the device and send notifications, sample code here: https://github.com/mpodwysocki/azure-notificationhubs-node-sample/blob/main/src/index.ts

How to send push notifications in Flutter android app?

I developed a flutter android app. and my database is MongoDB. I use Node.js API to connect my flutter app with the MongoDB. I want to send push notifications when a new data record is coming to MongoDB. How can I do that?
The simplest way is to use Firebase Cloud Messaging. Especially since Google is deprecating GCM which was previously used for Android. Also Firebase cloud messaging is free and can be used for both iOS and Android. Apple's APN service will require a setup as well though and a paid developer account.
Create a Firebase project if you haven't already and enable cloud messaging.
To set up your Node.js server so that it can send push notifications to your android and IOS devices. Click on the Project Overview, Settings and service accounts and follow the directions to generate a private key for your project and follow the instructions for setup. Also npm install "firebase-admin".
Once you have firebase setup refer to these docs for how to send messages. https://firebase.google.com/docs/cloud-messaging/send-message
There are several ways to send messages. You can send messages directly.
with this code
// This registration token comes from the client FCM SDKs.
var registrationToken = 'YOUR_REGISTRATION_TOKEN';
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);
});
You can also create topics for devices to subscribe to as well if you are sending out mass notifications. More examples once again are within the docs. Now if you are wondering what the token is that is the next step.
The token comes from the unique device that is connecting to your platform. You can get the token by installing the Firebase Messaging sdk from https://pub.dev/packages/firebase_messaging and following the instructions to add the necessary dependencies to your pubsec.yaml and properly configure your Android manifest and iOS files for the changes.
This package will give you methods to grab your communicate and to receive the notifications that you have sent form your Node.JS server.
Here is an example of grabbing the token from your device on the frontend in flutter.
final FirebaseMessaging _firebaseMessaging = FirebaseMessaging();
bool _initialized = false;
Future<void> init() async {
if (!_initialized) {
// For iOS request permission first.
_firebaseMessaging.requestNotificationPermissions();
_firebaseMessaging.configure(onMessage: (Map<String, dynamic> `enter code here`message) {
print('onMessage: $message');
Platform.isAndroid
? showNotification(message['notification'])
: showNotification(message['aps']['alert']);
return;
}, onResume: (Map<String, dynamic> message) {
print('onResume: $message');
return;
}, onLaunch: (Map<String, dynamic> message) {
print('onLaunch: $message');
return;
});
// For testing purposes print the Firebase Messaging token
String token = await _firebaseMessaging.getToken();
print("FirebaseMessaging token: $token");
_initialized = true;
}
}
At this point you would most likely save the token to your MongoDB database and associate the token with your user and that specific device. Of course you would have to also install the firebase core and for Flutter as well and do all of the necessary configurations.
You are still able to maintain your NodeJS API and MongoDB database and use free cloud messaging service to push your notifications for your server to your device.

Duplicate registrations in Azure Notification Hub with Xamarin Android

I am using Azure Notification Hub with Xamarin Android. It works fine in normal scenario and I am able to get push notifications on my registered tags but on update of tag or reregistering the hub it creates duplicate registrations. Also the tags which were removed post registration still gets the notification. Below is the sample snippet for the same
try
{
Hub.UnregisterAll(registrationId);
}
catch (Exception ex)
{
}
var tags = getting active tags
try
{
var hubregistration = Hub.Register(registrationId, tags);
}
catch (Exception ex)
{
}
AFAIK, the Registration Token (registrationId) issued by GCM is used to identity the client app, and it may be the same when re-register from GCM without unregistering from GCM. Based on your code, you are using the Registrations model. Hub.UnregisterAll(registrationId) would try to un-register the registrations with the same Registration Token (pnsHandle) from your azure notification hub.
I would recommend you capturing the exception when you call UnregisterAll. Also, you could leverage Server Explorer from Visual Studio, choose your notification hub, then view and manage all the registrations in your hub as follows to narrow this issue:
Note: You could check with your device registrations and try to find whether you could retrieve the duplicated registrations (same PNS Identifier (Registration Token), different tags / Azure Registration ID or different PNS Identifier (Registration Token) for the same client app, etc.).
If you find different PNS Identifier (Registration Token) for the same client app, I assume that your client app need to store the previous Registration Token and compare with the latest Registration Token, UnregisterAll the old Registration Token if not match firstly, then register the new Registration Token with your notification hub.
Additionally, the Installations model could avoid the duplicate registrations. For more details, you could refer to Registration management.
This is my working methods for Register and UnRegister from azure hub
void unregister ()
{
try {
NotificationHub hub = new NotificationHub (Constants.NotificationHubName, Constants.ListenConnectionString, this);
hub.UnregisterAll (FirebaseInstanceId.Instance.Token);
} catch (Exception ex) {
}
}
void register ()
{
try {
NotificationHub hub = new NotificationHub (Constants.NotificationHubName, Constants.ListenConnectionString, this);
var tags = new List<string> () { ... };
hub.Register (FirebaseInstanceId.Instance.Token, tags.ToArray ());
} catch (Exception ex) {
}
}
based on this documentation https://learn.microsoft.com/en-us/azure/notification-hubs/xamarin-notification-hubs-push-notifications-android-gcm

Requesting a New Registration Id and Creating a Tag for the Azure Notification Hub with NodeJs

How to get a new registration Id for the Azure Notification Hub with JavaScript (NodeJS) and how to create the tag afterwards? The tutorial provided by the Azure documentation misses this part - it sends to all devices (null).
https://azure.microsoft.com/en-us/documentation/articles/notification-hubs-nodejs-how-to-use-notification-hubs/
var payload={
alert: 'Hello!'
};
notificationHubService.apns.send(null, payload, function(error){
if(!error){
// notification sent
}
});
Thanks!
The Notification Hub apns object also has a createNativeRegistration(token, tags, options, callback) function.
var token='abcd1234......'; // token from iOS device
var tags = ['mynewtag', 'myoldtag'];
notificationHubService.apns.createNativeRegistration(token, tags, {success:newRegistrationCompleteCallback, error:newRegistrationErrorCallback});
If you are using the npm you can read the source for it since the documentation is pretty incomplete.
If you are using Mobile Services' Node.js backend, see also the documentation for the built-in push apns object, which seems to be using the same library.

How to register devices to Azure Notification Hub from server side(with NodeJS sdk) ?

I am developing a windows phone 8.1 App (RT), I am trying to push notification with Azure Notification Hub. I am able to do it with the client side SDK available. But I want to do the device registration, tagging etc. from the server side. I see a good guide for .Net backend at http://blogs.msdn.com/b/azuremobile/archive/2014/04/08/push-notifications-using-notification-hub-and-net-backend.aspx . I am using NodeJS in the backend server side. Can anyone help me in the same, with a sample code or so.
I want to register devices from server side (iPhone, Android & Windows Phone), actually I have the device tokens available at the servicer side which is sent from the device via API call.
I want to update multiple tags for each devices time to time.
I want to unregister the devices when user request to do so.
I want to send push notification to specific tags, using the template.
The steps to register the device token and sending out the notification using the Notification Hub in node.js are as follows:
Create a Registration ID
Create Registration
Send Notification
This is server side code, once the device token is received. Note that the registration ID, Device Token, Tag and Callback function are required parameters for notificationHubService.apns.send call.
Here is the code snippet:
var azure = require('azure');
var notificationHubService = azure.createNotificationHubService('<Hub Name>','<Connection String>');
var payload={
alert: 'Hello!'
};
notificationHubService.createRegistrationId(function(error, registrationId, response){
if(!error){
console.log(response);
console.log(registrationId);
//RegistrationDescription registration = null;
//registration.RegistrationId = registrationId;
//registration.DeviceToken = req.body.token;
notificationHubService.apns.createOrUpdateNativeRegistration(registrationId, req.body.token, req.token.upn, function(error, response){
if(!error){
console.log('Inside : createOrUpdateNativeRegistration' + response);
notificationHubService.apns.send(null, payload, function(error){
if(!error){
// notification sent
console.log('Success: Inside the notification send call to Hub.');
}
});
}
else{
console.log('Error in registering the device with Hub' + error);
}
});
}
else{
console.log('Error in generating the registration Id' + error);
}
});
Look at open source SDK for server side. I've never tried it out, but should be OK because any SDK is just a wrapper for REST API.

Resources