FCM (Firebase Cloud Messaging) Push Notification with Asp.Net - android

I have already push the GCM message to google server using asp .net in following method,
GCM Push Notification with Asp.Net
Now i have planned upgrade to FCM method, anyone have idea about this or developing this in asp .net let me know..

2019 Update
There's a new .NET Admin SDK that allows you to send notifications from your server.
Install via Nuget
Install-Package FirebaseAdmin
You'll then have to obtain the service account key by downloading it by following the instructions given here, and then reference it in your project. I've been able to send messages by initializing the client like this
using FirebaseAdmin;
using FirebaseAdmin.Messaging;
using Google.Apis.Auth.OAuth2;
...
public class MobileMessagingClient : IMobileMessagingClient
{
private readonly FirebaseMessaging messaging;
public MobileMessagingClient()
{
var app = FirebaseApp.Create(new AppOptions() { Credential = GoogleCredential.FromFile("serviceAccountKey.json").CreateScoped("https://www.googleapis.com/auth/firebase.messaging")});
messaging = FirebaseMessaging.GetMessaging(app);
}
//...
}
After initializing the app you are now able to create notifications and data messages and send them to the devices you'd like.
private Message CreateNotification(string title, string notificationBody, string token)
{
return new Message()
{
Token = token,
Notification = new Notification()
{
Body = notificationBody,
Title = title
}
};
}
public async Task SendNotification(string token, string title, string body)
{
var result = await messaging.SendAsync(CreateNotification(title, body, token));
//do something with result
}
..... in your service collection you can then add it...
services.AddSingleton<IMobileMessagingClient, MobileMessagingClient >();

C# Server Side Code For Firebase Cloud Messaging
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Script.Serialization;
namespace Sch_WCFApplication
{
public class PushNotification
{
public PushNotification(Plobj obj)
{
try
{
var applicationID = "AIza---------4GcVJj4dI";
var senderId = "57-------55";
string deviceId = "euxqdp------ioIdL87abVL";
WebRequest tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
tRequest.Method = "post";
tRequest.ContentType = "application/json";
var data = new
{
to = deviceId,
notification = new
{
body = obj.Message,
title = obj.TagMsg,
icon = "myicon"
}
};
var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(data);
Byte[] byteArray = Encoding.UTF8.GetBytes(json);
tRequest.Headers.Add(string.Format("Authorization: key={0}", applicationID));
tRequest.Headers.Add(string.Format("Sender: id={0}", senderId));
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())
{
using (StreamReader tReader = new StreamReader(dataStreamResponse))
{
String sResponseFromServer = tReader.ReadToEnd();
string str = sResponseFromServer;
}
}
}
}
}
catch (Exception ex)
{
string str = ex.Message;
}
}
}
}
APIKey and senderId , You get is here---------as follow(Below Images)
(go to your firebase App)

public class Notification
{
private string serverKey = "kkkkk";
private string senderId = "iiddddd";
private string webAddr = "https://fcm.googleapis.com/fcm/send";
public string SendNotification(string DeviceToken, string title ,string msg )
{
var result = "-1";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Headers.Add(string.Format("Authorization: key={0}", serverKey));
httpWebRequest.Headers.Add(string.Format("Sender: id={0}", senderId));
httpWebRequest.Method = "POST";
var payload = new
{
to = DeviceToken,
priority = "high",
content_available = true,
notification = new
{
body = msg,
title = title
},
};
var serializer = new JavaScriptSerializer();
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = serializer.Serialize(payload);
streamWriter.Write(json);
streamWriter.Flush();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
return result;
}
}

To hit Firebase API we need some information from Firebase, we need the API URL (https://fcm.googleapis.com/fcm/send) and unique keys that identify our Firebase project for security reasons.
We can use this method to send notifications from .NET Core backend:
public async Task<bool> SendNotificationAsync(string token, string title, string body)
{
using (var client = new HttpClient())
{
var firebaseOptionsServerId = _firebaseOptions.ServerApiKey;
var firebaseOptionsSenderId = _firebaseOptions.SenderId;
client.BaseAddress = new Uri("https://fcm.googleapis.com");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization",
$"key={firebaseOptionsServerId}");
client.DefaultRequestHeaders.TryAddWithoutValidation("Sender", $"id={firebaseOptionsSenderId}");
var data = new
{
to = token,
notification = new
{
body = body,
title = title,
},
priority = "high"
};
var json = JsonConvert.SerializeObject(data);
var httpContent = new StringContent(json, Encoding.UTF8, "application/json");
var result = await _client.PostAsync("/fcm/send", httpContent);
return result.StatusCode.Equals(HttpStatusCode.OK);
}
}
These parameters are:
token: string represents a FCM token provided by Firebase on each app-installation. This is going to be the list of app-installations that the notification is going to send.
title: It’s the bold section of notification.
body: It represents “Message text” field of the Firebase SDK, this is the message you want to send to the users.
To find your Sender ID and API key you have to:
Login to the Firebase Developer Console and go to your Dashboard
Click on the “gear” icon and access “project settings”
Go to the
“Cloud Messaging Section” and you will have access to the sender ID
and the API Key.

Here is my VbScript sample for who prefers vb:
//Create Json body
posturl="https://fcm.googleapis.com/fcm/send"
body=body & "{ ""notification"": {"
body=body & """title"": ""Your Title"","
body=body & """text"": ""Your Text"","
body=body & "},"
body=body & """to"" : ""target Token""}"
//Set Headers :Content Type and server key
set xmlhttp = server.Createobject("MSXML2.ServerXMLHTTP")
xmlhttp.Open "POST",posturl,false
xmlhttp.setRequestHeader "Content-Type", "application/json"
xmlhttp.setRequestHeader "Authorization", "Your Server key"
xmlhttp.send body
result= xmlhttp.responseText
//response.write result to check Firebase response
Set xmlhttp = nothing

2020/11/28
download this file from Firebase -> Settings -> Service accounts -> Firebase Admin SDK
Move the downloaded file to Your dotnet Core Root folder then change it's name to key.json for example .
then add this code to your .csproj file: YourProjectName.csproj in your project root folder :
<ItemGroup>
<None Update="key.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
then add this code to your Program.cs in Main function :
var defaultApp = FirebaseApp.Create(new AppOptions()
{
Credential =
GoogleCredential.FromFile(Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
"key.json")),
});
Last thing is the code that will push notification :
public async Task SendNotificationAsync(string DeviceToken, string title ,string body){
var message = new Message()
{
Notification = new FirebaseAdmin.Messaging.Notification
{
Title = title,
Body = body
},
Token = DeviceToken,
};
var messaging = FirebaseMessaging.DefaultInstance;
var result = await messaging.SendAsync(message);
}
Put it in any Controller then u can call it to send notification ...
that is what i did to push notificaion and it is working very well and fast ...

Use CorePush lib
It's very lightweight. I use it across all my projects to send Firebase Android, WebPush and Apple iOS push notifications. Useful links:
NuGet package
Documentation
The interface is very simple and minimalistic:
Send APN message:
var apn = new ApnSender(settings, httpClient);
await apn.SendAsync(notification, deviceToken);
Send FCM message:
var fcm = new FcmSender(settings, httpClient);
await fcm.SendAsync(deviceToken, notification);

I don't believe there is any change in the way you are sending push notifications. In FCM also, you are going to make HTTP POST Request the same way you did for GCM:
https://fcm.googleapis.com/fcm/send
Content-Type:application/json
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA
{ "data": {
"score": "5x1",
"time": "15:10"
},
"to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1..."
}
Read about FCM Server for more information.
The only change I could see now, is the target Url. Period.

Related

how to add buttons to firebase messaging notification?

I am newbie to flutter, I am using firebase-Messaging to send notification to device we use web API that send request to firebase to send notification and firebase send notification to the android.
I want under the notification title and body show two buttons (accept and reject) like watts app notification "mark as read" option I want some thing like that.
Android manifest file I added:
<intent-filter>
<action android:name="FLUTTER_NOTIFICATION_CLICK" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
flutter Code
final FirebaseMessaging _firebaseMessaging = FirebaseMessaging();
if(user != null)
{
Navigator.push(context,
MaterialPageRoute(builder: (context) => InitialPage()));
_firebaseMessaging.onTokenRefresh.listen(sendTokenToServer);
_firebaseMessaging.getToken();
// _firebaseMessaging.subscribeToTopic('all');
_firebaseMessaging.configure(
onMessage: (Map<String, dynamic> message) async {
print("onMessage: $message");
final notification = message['data'];
},
onLaunch: (Map<String, dynamic> message) async {
print("onLaunch: $message");
},
onResume: (Map<String, dynamic> message) async {
print("onResume: $message");
},
);
_firebaseMessaging.requestNotificationPermissions(
const IosNotificationSettings(sound: true, badge: true, alert: true));
}
web api service code
public class NotificationController : ApiController
{
//api/user
public IHttpActionResult GetUsers()
{
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}", "xxxxxxxxxxxxxxxxxxxxxx"));
//Sender Id - From firebase project setting
tRequest.Headers.Add(string.Format("Sender: id={0}", "123456"));
tRequest.ContentType = "application/json";
var payload = new
{
to = "wwwwwwwwwwww",
priority = "high",
content_available = true,
notification = new
{
body = "test body",
title = "Test title",
badge = 1,
},
data = new
{
key1 = "value1",
key2 = "value2"
}
};
string postbody = JsonConvert.SerializeObject(payload).ToString();
Byte[] byteArray = Encoding.UTF8.GetBytes(postbody);
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;
}
}
}
}
return Ok("test service");
}
}
Firebase Cloud Messaging service for push notifications doesn’t provide an option to add action buttons to the notification layouts. So in order to add the action button to notifications, the only way we have now is to create the notification in native and integrate it with Flutter.
Check this medium post

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);

Authenticate with OneDrive SDK in Xamarin Android App

I use the onedrive SDK in a Cross Plattform app. On Windows the Authentication works via the OneDriveClientExtensions.GetClientUsingWebAuthenticationBroker.
Now I'm trying to login on Android. I tried it with this:
oneDriveClient = OneDriveClient.GetMicrosoftAccountClient(
appId: MSA_CLIENT_ID,
returnUrl: RETURN_URL,
scopes: scopes,
clientSecret: MSA_CLIENT_SECRET);
await oneDriveClient.AuthenticateAsync();
But get an error that no valid token could be received. Do I have to implement a own AuthenticationProvider inhereting from WebAuthenticationBrokerAuthenticationProvider who shows a browser for the oauth? Or what would be the way to go here?
I solved this using the Xamarin Auth Component. Heres the code who calls the webview with the login:
private const string RETURN_URL = #"https://login.live.com/oauth20_desktop.srf";
private void ShowWebView()
{
var auth = new OAuth2Authenticator(
clientId: MSA_CLIENT_ID,
scope: string.Join(",", scopes),
authorizeUrl: new Uri(GetAuthorizeUrl()),
redirectUrl: new Uri(RETURN_URL));
auth.Completed += (sender, eventArgs) =>
{
if (eventArgs.IsAuthenticated)
{
//Do Something
}
};
var intent = auth.GetUI(Application.Context);
intent.SetFlags(ActivityFlags.NewTask);
Application.Context.StartActivity(intent);
}
private string GetAuthorizeUrl()
{
var requestUriStringBuilder = new StringBuilder();
requestUriStringBuilder.Append("https://login.live.com/oauth20_authorize.srf");
requestUriStringBuilder.AppendFormat("?{0}={1}", Constants.Authentication.RedirectUriKeyName, RETURN_URL);
requestUriStringBuilder.AppendFormat("&{0}={1}", Constants.Authentication.ClientIdKeyName, MSA_CLIENT_ID);
requestUriStringBuilder.AppendFormat("&{0}={1}", Constants.Authentication.ScopeKeyName,
string.Join("%20", scopes));
requestUriStringBuilder.AppendFormat("&{0}={1}", Constants.Authentication.ResponseTypeKeyName,
Constants.Authentication.TokenResponseTypeValueName);
return requestUriStringBuilder.ToString();
}

Integrate Parse with Pusher

As per the Pusher docs, for a client to subscribe to a private channel he needs to undergo some authorization process. Could someone guide me on how to achieve this using Parse? I already have integrated Facebook login with Parse for my android application. Im not too familiar with web development code so had difficulty in understand this
HttpAuthorizer authorizer = new HttpAuthorizer(http://example.com/some_auth_endpoint);
PusherOptions options = new PusherOptions().setAuthorizer(authorizer);
Pusher pusher = new Pusher( YOUR_APP_KEY, options );
Somebody has written a Parse module that offers authentication functionality: https://github.com/kashif/pusher-parse
The auth example from the README is:
app.post('/authorise', function(req, res) {
var socketId = req.body.socket_id;
var channel = req.body.channel_name;
var user_id = channel.split("-")[1];
var user = Parse.Object.extend("User");
var query = new Parse.Query(user);
query.get(user_id, {
success: function(userAgain) {
var presenceData = {
user_id: userAgain.id,
user_info: {
username: userAgain.get("username"),
email: userAgain.get("email")
}
};
var auth = pusher.authenticate( socketId, channel, presenceData );
res.send(auth);
},
error: function(model, error) {
res.status(403);
res.send('Forbidden');
}
});
});

How to create push notifications in django?

I'd like to implement push notifications in android ?
I prefer not to use an existing plugins
would someone give me an example of code on how to send a message
have been struggling since a week none of my tries have been successfull
This is my last try:
gcm.py
import requests
import json
def send_gcm_message(api_key, regs_id, data, collapse_key=None):
"""
Send a GCM message for one or more devices, using json data
api_key: The API_KEY from your console (https://code.google.com/apis/console, locate Key for Server Apps in
Google Cloud Messaging for Android)
regs_id: A list with the devices which will be receiving a message
data: The dict data which will be send
collapse_key: A string to group messages, look at the documentation about it:
http://developer.android.com/google/gcm/gcm.html#request
"""
values = {
'registration_ids': regs_id,
'collapse_key': collapse_key,
'data': data
}
values = json.dumps(values)
headers = {
'UserAgent': "GCM-Server",
'Content-Type': 'application/json',
'Authorization': 'key=' + api_key,
}
response = requests.post(url="https://android.googleapis.com/gcm/send",
data=values,
headers=headers)
return response.content
views.py
import settings
from .gcm import send_gcm_message
#render_to("push/envoyer_message.html")
def send_message(request):
if not request.user.is_authenticated():
return HttpResponseRedirect('/client/login')
else:
if request.method == 'POST':
form = MessageForm(request.POST)
if form.is_valid():
form.save()
reg_id='APA91bFSIEHPOeT2I7ddCqnYtnJ-iAEQfCiR3HArUIz0t5lQUVfIOGhlEIUJCJLY7SWEdwiJCHedLNaSFi6oVqbnsci9-HmpBNiZAa86KD3349AIWMesweUqF2YbfpSBRot1tNLCITRFbYH9g5AO514s8Zzs4ABumA'
msg='test'
send = send_gcm_message(api_key = settings.GCM_APIKEY, regs_id=[reg_id], data={'msg': msg},collapse_key="message")
messages.success(request, _(u'Formulaire envoyé avec succès.'))
return HttpResponseRedirect(reverse("push-confirmation-envoi"))
else:
form = MessageForm()
return locals()
EDIT:
This is the error I get :
Field "data" must be a JSON array: test www
SOLVED
regs_id = list()
for device in devices_a :
regs_id.append(device.token_string)
message = json.dumps(message)
values = {
'registration_ids': regs_id,
'collapse_key': "message" ,
'data': {"message":str(msg.message)}
}
headers = {
'UserAgent': "GCM-Server",
'Content-Type': 'application/json',
'Authorization': 'key=' + settings.GCM_APIKEY,
}
response = requests.post(url="https://android.googleapis.com/gcm/send",data=json.dumps(values), headers=headers)
r = json.loads(response.content)
msg.nbr_android_recieved = r["success"]

Categories

Resources