Register device on Azure notifications hub - azure

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

Related

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.

Push notifications using Firebase Cloud Function iOS

Trying to send remote push notifications through firebase cloud functions. Resources I've been following achieves this through sendToDevice method, which takes a String as an argument. A resource from GitHub says its a "device notification token" that is retrieved when user agrees to receive notifications in app. Firebase says its a "registration token that comes from the client FCM SDKs". What should be the input here, and how to I retrieve it?
// Send notification to device via firebase cloud messaging.
// https://firebase.google.com/docs/cloud-messaging/admin/send-messages
// https://github.com/firebase/functions-samples/blob/master/fcm-notifications/functions/index.js
//
admin.messaging().sendToDevice(request.query.tokenId, payload).then(response => {
response.results.forEach((result, index) => {
const error = result.error
if (error) {
console.log("Failure sending notification.")
}
});
});
You need to integrate FCM into your iOS app. Pay attention to the part about receiving the current registration token.
Registration tokens are delivered via the FIRMessagingDelegate method
messaging:didReceiveRegistrationToken:. This method is called
generally once per app start with an FCM token. When this method is
called, it is the ideal time to:
If the registration token is new, send it to your application server (it's recommended to implement server logic to determine whether the
token is new).
Subscribe the registration token to topics. This is required only for new subscriptions or for situations where the user has
re-installed the app.
So, you'll have to get a hold of this token in your app, store it somewhere that the Cloud Function can get a hold of (traditionally, Realtime Database), and query for it at the time the function runs.

Twillio SMS support in The Netherlands

I want to test an Azure Logic app that uses a service like Twillio to send SMS messages. Unfortunately Twillio doesn't offer SMS support in The Netherlands. What alternatives could we choose to solve this?
I used messagebird.com for this and build their API into a custom API App that I embedded in a Logic App flow:
Client client = Client.CreateDefault("[API KEY]" , null);
Message messageResponse = client.SendMessage(message.Sender,
message.MessageText, new[] { long.Parse(message.Number) });
This could also be implemented in an Azure Function to simplify deployment.

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.

Issue with sending Notification to Windows Store app using Service bus

I use Notification Hubs to send Notifications to IPhone and Windows Store app. The IPhone is working perfectly fine, but there is some issue with Windows Store when sending the notification.
Error: The Push Notification System handle for the registration is invalid.
Template:
String WindowsTemplateStr = #"<toast><visual><binding template=""ToastImageAndText03""><image id=""1"" src=""https://"" alt=""Customer""/><text id=""1"">$(headlineText)</text><text id=""2"">$(bodyText)</text></binding></visual></toast>";
I use this code to register:
registration = await hubClient.CreateWindowsTemplateRegistrationAsync(userDeviceInformation.ChannelUri, Templates.WindowsNotificationTemplate,
new string[]
{
userDeviceInformation.InstallationId,
userDeviceInformation.UserName
});
The registration goes through fine and I can see the tags properly associated using "Service Bus Explorer".
When I try to send the Notification this is what I do:
notification.Add("src", ImageUrl);
notification.Add("headlineText", String.Format("Message from {0}", fullName));
notification.Add("bodyText", String.Format("Message {0}", message));
When the notification is sent, nothing is received on the device; and I see the registration is also being deleted.
I can't seem to find what is causing this behavior.
Any ideas ?
If WNS returns invalid handle then the corresponding registration will be removed from the notification hubs.
You can use test send to check the error details:
http://msdn.microsoft.com/en-us/library/microsoft.servicebus.notifications.notificationhubclient.enabletestsend.aspx

Resources