使用FCM将通知从Web数据推送到Mobile App [英] Push Notification from Web data to Mobile App using FCM

查看:322
本文介绍了使用FCM将通知从Web数据推送到Mobile App的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我已经设置了项目,甚至尝试通过从Cloud Messaging添加示例通知来对其进行测试,并在我的Android仿真器中接收该通知.

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.

但是,当网络上发生变化时,我需要将其推送到移动设备上. 因此,我在网络上尝试了以下代码:

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

响应为:

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

请帮助我.谢谢.

推荐答案

我建议您查看Nico Bonoro在Medium上写的这本令人惊奇的指南,其中介绍了您逐步进行

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

使用此方法创建一个名为PushNotificationLogic.cs的静态类:

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

添加一个名为SendPushNotifications的静态方法,其中这些参数为:

Add a static method called SendPushNotifications where these parameters are:

  • deviceTokens:字符串数组,每个字符串代表Firebase在每次安装应用程序时提供的FCM令牌.这将是通知将要发送的应用程序安装的列表.
  • 标题:这是通知的粗体部分.
  • 正文:代表Firebase SDK的消息文本"字段,这是您要发送给用户的消息.
  • 数据:有一个动态对象,它可以是您想要的任何对象,因为该对象将用作要发送到应用程序的其他信息,就像隐藏的信息一样.例如,当用户按下某些产品的通知或ID时要执行的操作.

对于该方法,我将假设所有参数正确且没有错误值(您可以添加所需的所有验证).我们要做的第一件事是创建一个包含所有需要发送到API的数据的对象

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

添加以下两个类:

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

然后,只需创建一个类型为"Message"的新对象,并按照我在此处进行的操作对其进行序列化即可:

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

注意:您将需要 NewtonSoft.Json 添加到您的项目中

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

现在,我们只需要对Firebase API的请求就可以了.该请求必须作为Firebase API-Url的发布"方法,我们必须添加一个标头,即授权",并使用"key = {Your_Server_Key}"之类的值.然后我们添加内容(jsonMessage),您就可以使用API​​.

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

如有查询,祝您好运.

这篇关于使用FCM将通知从Web数据推送到Mobile App的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆