Search code examples
c#.netfirebasefirebase-cloud-messagingandroid-push-notification

Sending Push Notification on Android Device using Firebase (FCM)


I am trying to send push notification on android device with FCM in C#.Net, but I am getting "InvalidRegistration" error message.

I have used the same from Postman and R-Client as well, but still getting same error.

   public String SendNotificationFromFirebaseCloud()
    {
        string DeviceToken = "RegToken";           
        string YOUR_FIREBASE_SERVER_KEY = "ServerKey";
        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=" + YOUR_FIREBASE_SERVER_KEY);
        httpWebRequest.Headers.Add(string.Format("Sender: id={0}", "MySenderId"));
        httpWebRequest.Method = "POST";

        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
            string json = "{\"to\":\"" + DeviceToken + "\",\"data\":{\"message\": \"Welcome\"}}";               
            streamWriter.Write(json);
            streamWriter.Flush();
        }

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

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


Solution

  • "invalid registration" indicates that the device token is incorrect, does not point to an existing device.

    Mind that this does not mean a device that's turned off, it means that no device (currently) uses that token at all.

    In other words it's an indication of a bad recipient address, effectively the equivalent of an HTTP 404 error.