Solución:
Actualización 2019
Hay un nuevo SDK de administrador de .NET que le permite enviar notificaciones desde su servidor. Instalar a través de Nuget
Install-Package FirebaseAdmin
Luego, deberá obtener la clave de la cuenta de servicio descargándola siguiendo las instrucciones que se dan aquí y luego hacer referencia a ella en su proyecto. He podido enviar mensajes inicializando el cliente de esta manera
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);
}
//...
}
Después de inicializar la aplicación, ahora puede crear notificaciones y mensajes de datos y enviarlos a los dispositivos que desee.
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
}
….. en su colección de servicios puede agregarlo …
services.AddSingleton<IMobileMessagingClient, MobileMessagingClient >();
C# Código del lado del servidor Para Firebase Mensajería en la nube
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 y senderId, se obtiene aquí ——— como sigue (debajo de las imágenes) (vaya a su aplicación firebase)
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;
}
}
¡Haz clic para puntuar esta entrada!
(Votos: 0 Promedio: 0)