Push Notification from Web data to Mobile App usin

2019-08-28 00:48发布

So I have already set up the project and even tried testing it by adding sample notification from Cloud Messaging and receive that notification in my Android Emulator.

enter image description here

However, when there's changes from the web, I need that to push to the Mobile. So I tried this code in the web:

public void PushNotificationToFCM()
        {
            try
            {
                var applicationID = "AIzaSyDaWwl..........";
                var senderId = "487....";
                string deviceId = "1:487565223284:android:a3f0953e5fbdd790";
                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 = "sending to..",
                        title = "title-----"
                    }
                };
                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;
            }
        }

The response is:

{"multicast_id":7985385082196953522,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]}

Please help me. Thank you.

1条回答
老娘就宠你
2楼-- · 2019-08-28 01:38

I would suggest you check this amazing guide by Nico Bonoro on Medium which explains everything you need to do step by step to configure firebase with a .Net backend

Create a static class called PushNotificationLogic.cs with this method:

Add a static method called SendPushNotifications where these parameters are:

  • deviceTokens: An array of strings, each string represents an 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 a notification.
  • body: It represents “Message text” field of the Firebase SDK, this is the message you want to send to the users.
  • data: There is a dynamic object, it can be whatever you want because this object is going to be used as additional information you want to send to the app, it’s like hidden information. For example an action you want to execute when the user presses on the notification or id of some product.

For the method, I am going to suppose that all parameters are correct without bad values (you can add all the validations you want). The first thing we have to do is to create an object with all the data we need to send to the API

Add two classes as follows:

public class Message
{
  public string[] registration_ids { get; set; }
  public Notification notification { get; set; }
  public object data { get; set; }
}
  public class Notification
{
   public string title { get; set; }
   public string text { get; set; }
}

Then, just create a new object of type “Message” and serialize it as I did it here:

var messageInformation = new Message()
{
   notification = new Notification()
  {
    title = title,
    text = body
  },
  data = data,
  registration_ids = deviceTokens
 };
 //Object to JSON STRUCTURE => using Newtonsoft.Json;
 string jsonMessage = JsonConvert.SerializeObject(messageInformation);

Note: You will need NewtonSoft.Json added in your project

Now we just need a request to Firebase API and we’re done. The request has to be as a “Post” Method to the Firebase API-Url, we have to add a Header which is “Authorization” and use a value like “key={Your_Server_Key}”. Then we add the content (jsonMessage) and you are ready to hit the API.

// Create request to Firebase API
var request = new HttpRequestMessage(HttpMethod.Post, FireBasePushNotificationsURL);
request.Headers.TryAddWithoutValidation(“Authorization”, “key=” + ServerKey);
request.Content = new StringContent(jsonMessage, Encoding.UTF8, “application/json”);
HttpResponseMessage result;
using (var client = new HttpClient())
{
   result = await client.SendAsync(request);
}

Good luck feel free to revert in case of queries.

查看更多
登录 后发表回答