Firebase Cloud Messaging (FCM) is a cross-platform messaging solution that lets you reliably deliver messages at no cost.
Steps to get server key / SenderID
Steps to get server key / SenderID
- To get the keys, log in to Firebase account.
- Select the project from the list.
- Click on "Setting" gear icon and click "Project Settings".
- //Create the web request with fire base API
- WebRequest tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
- tRequest.Method = "post";
- //serverKey - Key from Firebase cloud messaging server
- tRequest.Headers.Add(string.Format("Authorization: key={0}", serverKey));
- //Sender Id - From firebase project setting
- tRequest.Headers.Add(string.Format("Sender: id={0}", senderId));
- tRequest.ContentType = "application/json";
- var payload = new {
- to = deviceId,
- priority = "high",
- content_available = true,
- notification = new {
- body = txtmsg,
- title = txttitle.Replace(":", ""),
- sound = "sound.caf",
- badge = badgeCounter
- },
- };
- var serializer = new JavaScriptSerializer();
- Byte[] byteArray = Encoding.UTF8.GetBytes(payload);
- tRequest.ContentLength = byteArray.Length;
- using(Stream dataStream = tRequest.GetRequestStream()) {
- dataStream.Write(byteArray, 0, byteArray.Length);
- using(WebResponse tResponse = tRequest.GetResponse()) {
- using(Stream dataStreamResponse = tResponse.GetResponseStream()) {
- if (dataStreamResponse != null) using(StreamReader tReader = new StreamReader(dataStreamResponse)) {
- String sResponseFromServer = tReader.ReadToEnd();
- result.Response = sResponseFromServer;
- }
- }
- }
- }
Subscribe Topics FCM :
The FCM JavaScript API lets you receive notification messages in web apps running in browsers.
Retrieve a messaging object
// Retrieve Firebase Messaging object.
const messaging = firebase.messaging();
// Add the public key generated from the console here.
messaging.usePublicVapidKey("XXXdd");
Request permission to receive notifications
messaging.requestPermission().then(function() {
console.log('Notification permission granted.');
// TODO(developer): Retrieve an Instance ID token for use with FCM.
// ...
}).catch(function(err) {
console.log('Unable to get permission to notify.', err);
});
Access the registration token
The messaging service requires a firebase-messaging-sw.js file. Unless you already have a firebase-messaging-sw.js file, create an empty file with that name and place it in the root of your domain before retrieving a token.
// Get Instance ID token. Initially this makes a network call, once retrieved
// subsequent calls to getToken will return from cache.
messaging.getToken().then(function(currentToken) {
if (currentToken) {
sendTokenToServer(currentToken);
updateUIForPushEnabled(currentToken);
} else {
// Show permission request.
console.log('No Instance ID token available. Request permission to generate one.');
// Show permission UI.
updateUIForPushPermissionRequired();
setTokenSentToServer(false);
}
}).catch(function(err) {
console.log('An error occurred while retrieving token. ', err);
showToken('Error retrieving Instance ID token. ', err);
setTokenSentToServer(false);
});
Receive Messaging :
When your app is in the foreground (the user is currently viewing your web page), you can receive data and notification payloads directly in the page.
// `messaging.setBackgroundMessageHandler` handler.
messaging.onMessage(function(payload) {
console.log('Message received. ', payload);
// ...
});
firebase-messaging-sw.js
// Note that you can only use Firebase Messaging here, other Firebase libraries // are not available in the service worker. importScripts('https://www.gstatic.com/firebasejs/4.8.1/firebase-app.js'); importScripts('https://www.gstatic.com/firebasejs/4.8.1/firebase-messaging.js'); // Initialize the Firebase app in the service worker by passing in the // messagingSenderId. firebase.initializeApp({ 'messagingSenderId': 'YOUR-SENDER-ID' }); // Retrieve an instance of Firebase Messaging so that it can handle background // messages. const messaging = firebase.messaging();
No comments:
Post a Comment