none
Apple APNS WebRequest

    Question

  • Hello,

    does anyone know how a webrequest for Apple APNS using a certificate Looks like?

    All examples found by Google are useless. The documentation is useless as well. Google and Windows Push is already working fine, but Apple is a nightmare... PushSharp is not an Option.

    Regards,

    Marcus

    private EventLog eventLog;
            private X509Certificate2 serverCertificate;
    
            public ApplePusher(EventLog eventLog)
            { 
                this.eventLog = eventLog;
                serverCertificate = new X509Certificate2(String.Format("{0}TicketPusher-Sandbox.p12", AppDomain.CurrentDomain.BaseDirectory));
            }
    
            public void SendNotification(string deviceToken, string notification)
            {
                var payload = JObject.Parse("{\"aps\":{\"alert\":\"" + notification + "\"}}");
    
                try
                {
                    HttpWebRequest request = HttpWebRequest.Create("api.development.push.apple.com:443") as HttpWebRequest;
                    request.ClientCertificates.Add(serverCertificate);
                    request.Method = "POST";
                    request.Headers.Add("path:/3/device/" + deviceToken);
                    using (Stream requestStream = request.GetRequestStream()) requestStream.Write(payloadBytes, 0, payloadBytes.Length);
                }
                catch (Exception ex)
                {
                    eventLog.WriteEntry(ex.Message);
                }
            }


    Thursday, April 13, 2017 3:00 PM

Answers

  • using System;
    using System.Diagnostics;
    using System.IO;
    using System.Linq;
    using System.Net.Security;
    using System.Net.Sockets;
    using System.Security.Authentication;
    using System.Security.Cryptography.X509Certificates;
    
    namespace Pusher
    {
        public class ApplePusher
        {
            private EventLog eventLog;
    
            public ApplePusher(EventLog eventLog)
            {
                this.eventLog = eventLog;
            }
    
            public void SendNotification(string deviceToken, string notification)
            {
                int port = 2195;
                string hostname = "gateway.sandbox.push.apple.com";
                //string hostname = "gateway.push.apple.com";
                string certificatePath = @"apns-certificate.p12";
                X509Certificate2 clientCertificate = new X509Certificate2(File.ReadAllBytes(certificatePath), "");
                X509Certificate2Collection certificatesCollection = new X509Certificate2Collection(clientCertificate);
                TcpClient tcpClient = new TcpClient(hostname, port);
                SslStream sslStream = new SslStream(tcpClient.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
                try
                {
                    sslStream.AuthenticateAsClient(hostname, certificatesCollection, SslProtocols.Tls, false);
                    MemoryStream memoryStream = new MemoryStream();
                    BinaryWriter writer = new BinaryWriter(memoryStream);
                    writer.Write((byte)0);
                    writer.Write((byte)0);
                    writer.Write((byte)32);
                    writer.Write(HexStringToByteArray(deviceToken.ToUpper()));
                    string payload = "{\"aps\":{\"alert\":\"" + notification + "\",\"badge\":1,\"sound\":\"default\"}}";
                    writer.Write((byte)0);
                    writer.Write((byte)payload.Length);
                    byte[] payloadBytes = System.Text.Encoding.UTF8.GetBytes(payload);
                    writer.Write(payloadBytes);
                    writer.Flush();
                    byte[] memoryStreamAsBytes = memoryStream.ToArray();
                    sslStream.Write(memoryStreamAsBytes);
                    sslStream.Flush();
                    tcpClient.Close();
                }
                
                catch (Exception ex)
                {
                    eventLog.WriteEntry(ex.Message, EventLogEntryType.Error);
                    tcpClient.Close();
                }
            }
    
            private byte[] HexStringToByteArray(string hexString)
            {
                return Enumerable.Range(0, hexString.Length)
                         .Where(x => x % 2 == 0)
                         .Select(x => Convert.ToByte(hexString.Substring(x, 2), 16))
                         .ToArray();
            }
    
            private bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
            {
                if (sslPolicyErrors == SslPolicyErrors.None) return true;
                return false;
            }
        }
    }

    • Marked as answer by Marcus Runge Thursday, April 20, 2017 2:02 PM
    Thursday, April 20, 2017 2:02 PM

All replies

  • Hi Marcus Runge,

    Thank you for posting here.

    For your question is more related to Apple APNS, our forum provide support for Microsoft products. We do not have scenario to test the code. You could post a new thread in Apple Developer Forums.

    The Visual C# discuss and ask the C# programming language, IDE, libraries, samples and tools about Microsoft products.

    If you have some grammar or code errors, please feel free to contact us. We will try our best to give you a solution.

    Thanks for your understanding and cooperation.

    Best Regards,

    Wendy


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.


    Friday, April 14, 2017 6:38 AM
    Moderator
  • using System;
    using System.Diagnostics;
    using System.IO;
    using System.Linq;
    using System.Net.Security;
    using System.Net.Sockets;
    using System.Security.Authentication;
    using System.Security.Cryptography.X509Certificates;
    
    namespace Pusher
    {
        public class ApplePusher
        {
            private EventLog eventLog;
    
            public ApplePusher(EventLog eventLog)
            {
                this.eventLog = eventLog;
            }
    
            public void SendNotification(string deviceToken, string notification)
            {
                int port = 2195;
                string hostname = "gateway.sandbox.push.apple.com";
                //string hostname = "gateway.push.apple.com";
                string certificatePath = @"apns-certificate.p12";
                X509Certificate2 clientCertificate = new X509Certificate2(File.ReadAllBytes(certificatePath), "");
                X509Certificate2Collection certificatesCollection = new X509Certificate2Collection(clientCertificate);
                TcpClient tcpClient = new TcpClient(hostname, port);
                SslStream sslStream = new SslStream(tcpClient.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
                try
                {
                    sslStream.AuthenticateAsClient(hostname, certificatesCollection, SslProtocols.Tls, false);
                    MemoryStream memoryStream = new MemoryStream();
                    BinaryWriter writer = new BinaryWriter(memoryStream);
                    writer.Write((byte)0);
                    writer.Write((byte)0);
                    writer.Write((byte)32);
                    writer.Write(HexStringToByteArray(deviceToken.ToUpper()));
                    string payload = "{\"aps\":{\"alert\":\"" + notification + "\",\"badge\":1,\"sound\":\"default\"}}";
                    writer.Write((byte)0);
                    writer.Write((byte)payload.Length);
                    byte[] payloadBytes = System.Text.Encoding.UTF8.GetBytes(payload);
                    writer.Write(payloadBytes);
                    writer.Flush();
                    byte[] memoryStreamAsBytes = memoryStream.ToArray();
                    sslStream.Write(memoryStreamAsBytes);
                    sslStream.Flush();
                    tcpClient.Close();
                }
                
                catch (Exception ex)
                {
                    eventLog.WriteEntry(ex.Message, EventLogEntryType.Error);
                    tcpClient.Close();
                }
            }
    
            private byte[] HexStringToByteArray(string hexString)
            {
                return Enumerable.Range(0, hexString.Length)
                         .Where(x => x % 2 == 0)
                         .Select(x => Convert.ToByte(hexString.Substring(x, 2), 16))
                         .ToArray();
            }
    
            private bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
            {
                if (sslPolicyErrors == SslPolicyErrors.None) return true;
                return false;
            }
        }
    }

    • Marked as answer by Marcus Runge Thursday, April 20, 2017 2:02 PM
    Thursday, April 20, 2017 2:02 PM