Click here to Skip to main content
15,886,069 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
I am trying to use FCM for pushing notifications to Android device but it seems that I am missing something. These are steps that I've followed

1- Using normal google account, I created new project in https://console.firebase.google.com
2- From Settings -> Cloud Messaging tab, I got Server key and Sender Id
3- I used the bellow code

I always get Mismatch Sender Id error. Am I missing any steps? or do I have to do something on mobile app to match sender id?

What I have tried:

<pre lang="c#">
var regId = "device id";
string SERVER_API_KEY = "Firebase Server key";
        var SENDER_ID = "Sender ID";
        var value = "Test Notification";
        WebRequest tRequest;
        tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
        tRequest.Method = "post";
        tRequest.ContentType = " application/x-www-form-urlencoded;charset=UTF-8";
        tRequest.Headers.Add(string.Format("Authorization: key={0}", SERVER_API_KEY));

        tRequest.Headers.Add(string.Format("Sender: id={0}", SENDER_ID));

        string postData = "collapse_key=score_update&time_to_live=108&delay_while_idle=1&data.message=" + value + "&data.time=" + System.DateTime.Now.ToString() + "®istration_id=" + regId + "";
        Console.WriteLine(postData);
        byte[] byteArray = Encoding.UTF8.GetBytes(postData);
        tRequest.ContentLength = byteArray.Length;

        Stream dataStream = tRequest.GetRequestStream();
        dataStream.Write(byteArray, 0, byteArray.Length);
        dataStream.Close();

        WebResponse tResponse = tRequest.GetResponse();

        dataStream = tResponse.GetResponseStream();

        StreamReader tReader = new StreamReader(dataStream);

        string sResponseFromServer = tReader.ReadToEnd();


        tReader.Close();
        dataStream.Close();
        tResponse.Close();
Posted
Updated 25-Sep-17 3:30am
v2

I found the error. As a back-end developer I worked on C# part only. There is one more step to be done from mobile application side. Mobile app should allow receiving messages from list of Sender Ids so the one that I use in my C# code must be allowed from mobile app side. Once I did that it worked
 
Share this answer
 
Comments
giangcs 17-May-17 1:00am    
Hi Ahmedfci_90,
Can you share me code example after you fix your problem.
I want to push notification from C# and receive from ionic app but not successful.
T Thamaraiselvan 1-Jun-18 3:12am    
If so, can you send the code what you done on mobile app side?
You can try following method. I have tested with android .

C#
static void SendMessage()
{
    string serverKey = "Your Server key";

    try
    {
        var result = "-1";
        var webAddr = "https://fcm.googleapis.com/fcm/send";

        var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
        httpWebRequest.ContentType = "application/json";
        httpWebRequest.Headers.Add("Authorization:key=" + serverKey);
        httpWebRequest.Method = "POST";

        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
            string json = "{\"to\": \"Your device token\",\"data\": {\"message\": \"This is a Firebase Cloud Messaging Topic Message!\",}}";
            streamWriter.Write(json);
            streamWriter.Flush();
        }

        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            result = streamReader.ReadToEnd();
        }

       // return result;
    }
    catch (Exception ex)
    {
      //  Response.Write(ex.Message);
    }
}
 
Share this answer
 
Comments
Member 13370016 29-Aug-17 1:39am    
Am getting invalid registration. Am giving the server key as Server key. Kindly clarify whether i have to give "Server key" or "legacy server key"
T Thamaraiselvan 1-Jun-18 3:10am    
Hi, you have to provide Registration Token in the place of 'Your device token' string in code below.

string json = "{\"to\": \"Your device token\",\"data\": {\"message\": \"This is a Firebase Cloud Messaging Topic Message!\",}}";
Korlakunta 10-Oct-18 8:26am    
its worked for me with "Server key" and if you get unauthorized exception then you have to do following way:

Please try to delete server key in Cloud Messaging section in Firebase console and add it with "Add Server key" button and use new "Serverkey" try to execute the above code.
like that its worked for me
Er. Sushant Shinde 23-Jul-18 9:26am    
I use that code, it gives me below response---
"{\"multicast_id\":5620607393159798425,\"success\":0,\"failure\":1,\"canonical_ids\":0,\"results\":[{\"error\":\"NotRegistered\"}]}"

I use correct device token and server api key then it gives me failure response?
public static String SendNotificationFromFirebaseCloud()
{
var result = "-1";
var webAddr = "https://fcm.googleapis.com/fcm/send";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Headers.Add("Your_Server_Key");
httpWebRequest.Method = "POST";

using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{\"to\": \"/topics/news\",\"notification\": {\"body\": \"New news added in application!\",\"title\":\"" + Your_Notif_Title+ "\",}}";
streamWriter.Write(json);
streamWriter.Flush();
}

var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
return result;
}
 
Share this answer
 
v2
 public static String SendNotificationFromFirebaseCloud()
        {
            var result = "-1";
            var webAddr = "https://fcm.googleapis.com/fcm/send";
            var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
            httpWebRequest.ContentType = "application/json";
            httpWebRequest.Headers.Add(HttpRequestHeader.Authorization,"key=Your Key");
            httpWebRequest.Method = "POST";

            using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            {
                string strNJson = @"{
                    ""to"": ""/topics/ServiceNow"",
                    ""data"": {
                        ""ShortDesc"": ""This is sample"",
                        ""IncidentNo"": ""INC0010438"",
                        ""Description"": ""This is sample""
  },
  ""notification"": {
                ""title"": ""ServiceNow"",
    ""text"": ""Click me to open an Activity!"",
""sound"":""default""
  }
        }";
                streamWriter.Write(strNJson);
                streamWriter.Flush();
            }

            var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                result = streamReader.ReadToEnd();
            }
            return result;
        }
 
Share this answer
 
v2
Comments
Anoob KD 25-Sep-17 0:17am    
Am getting error : System.Net.WebException: 'The remote server returned an error: (401) Unauthorized.'
..plz help me
Korlakunta 10-Oct-18 8:20am    
Please try to delete server key in Cloud Messaging section in Firebase console and add it with "Add Server key" button and use new "Serverkey" try to execute the above code.
like that its worked for me
Can you please share your code or mail me.
httpWebRequest.Headers.Add(HttpRequestHeader.Authorization,"key=Your Key");

you have to write key=xxxxxxxx, where xxxxxxxx is your server key.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900