After you set up the environment in your app and make it able to receive push notifications, here we’ll see how to send these push notifications using the FCM features with C#.

Here a simple snippet to send text push notifications to a single device:

public string SendMessage()
{
    string serverKey = "myServerKey";

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

        var regID  = "phoneRegID";

        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\": \"" + regID + "\",\"notification\": {\"title\": \"New deal\",\"body\": \"20% deal!\"},\"priority\":10}";
            //registration_ids, array of strings -  to, single recipient
            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)
    {
        Console.WriteLine(ex.ToString());
        return "err";
    }
}

Edit the json to be send to reach multiple recipients:

string json = "{\"registration_ids\": [\"" + regID1 + "\", \"" + regID2 + "\" \"" + regIDN + "\"],\"notification\": {\"title\": \"New deal\",\"body\": \"20% deal!\"},\"priority\":10}";

The two snippets above will create a queue of notification in the recipient phone. If you prefer to show only the last received notification, use this json (use to ins:

string json = "{\"registration_ids\": [\"" + regID + "\"],\"data\": {\"message\": \"20% deal today!!\",}}";
Advertisements