.NET Backend Sample


Send push notifications to your users with this .NET code sample.

The following code will send a push notification to devices with {message: "Hello World!"} as the payload.

public static void SendSamplePush()
{
    // Prepare array of target device tokens
    List<string> deviceTokens = new List<string>();

    // Add your device tokens here
    deviceTokens.Add("cdd92f4ce847efa5c7f");

	// Convert to string[] array
	string[] to = deviceTokens.toArray();

	// Optionally, send to a publish/subscribe topic instead
    // string to = '/topics/news';
    
    // Set payload (it can be any object)
    var payload = new Dictionary<string, string>();

    // Add message parameter to dictionary
    payload.Add("message", "Hello World!");

    // iOS notification fields
    var notification = new Dictionary<string, object>();

    notification.Add("badge", 1);
    notification.Add("sound", "ping.aiff");
    notification.Add("title", "Test Notification");
    notification.Add("body", "Hello World \u270c");

    // Prepare the push HTTP request
    PushyPushRequest push = new PushyPushRequest(payload, to, notification);

    try
    {
        // Send the push notification
        PushyAPI.SendPush(push);
    }
    catch (Exception exc)
    {
        // Write error to console
        Console.WriteLine(exc);
    }
}

Create a file named PushyAPI.cs and paste the following code inside it:

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace Pushy
{
    class PushyAPI
    {
        // Insert your Secret API Key here
        public static readonly string SECRET_API_KEY = "SECRET_API_KEY";

        public static void SendPush(PushyPushRequest push)
        {
            // Create an HTTP request to the Pushy API
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api.pushy.me/push?api_key=" + SECRET_API_KEY);

            // Send a JSON content-type header
            request.ContentType = "application/json";

            // Set request method to POST
            request.Method = "POST";

            // Convert request post body to JSON (using JSON.NET package from Nuget)
            string postData = JsonConvert.SerializeObject(push);

            // Convert post data to a byte array
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);

            // Set the ContentLength property of the WebRequest
            request.ContentLength = byteArray.Length;

            // Get the request stream
            Stream dataStream = request.GetRequestStream();

            // Write the data to the request stream
            dataStream.Write(byteArray, 0, byteArray.Length);

            // Close the stream
            dataStream.Close();
            
            // Proceed with caution
            WebResponse response;

            try
            {
                // Execute the request
                response = request.GetResponse();
            }
            catch (WebException exc)
            {
                // Get returned JSON error as string
                string errorJSON = new StreamReader(exc.Response.GetResponseStream()).ReadToEnd();

                // Parse into object
                PushyAPIError error = JsonConvert.DeserializeObject<PushyAPIError>(errorJSON);

                // Throw error
                throw new Exception(error.error);
            }

            // Open the stream using a StreamReader for easy access
            StreamReader reader = new StreamReader(response.GetResponseStream());

            // Read the response JSON for debugging
            string responseData = reader.ReadToEnd();

            // Clean up the streams
            reader.Close();
            response.Close();
            dataStream.Close();
        }
    }

    class PushyPushRequest
    {
        public object to;
        public object data;
        public object notification;

        public PushyPushRequest(object data, object to, object notification)
        {
            this.to = to;
            this.data = data;
            this.notification = notification;
        }
    }

    class PushyAPIError
    {
        public string error;

        public PushyAPIError(string error)
        {
            this.error = error;
        }
    }
}

Note: Make sure to replace SECRET_API_KEY with your app's Secret API Key, available in the Pushy Dashboard (Click your app -> API Authentication tab). This is a backend API endpoint. Never expose your application's Secret API Key in your client code.