带Apple的C#MDM Server,无法发送推送通知

时间:2012-07-18 13:32:13

标签: c# ios push apple-push-notifications mdm

我们正在为iOS设备开发MDM解决方案。

我们已经能够通过网站安装带有MDM-Payload的配置文件,我们已经收到了包含PushMagic,deviceToken和其他值的iOS设备发送的PUT请求。

我们使用此说明创建了一个COMPANY.pem SSL证书: http://www.softhinker.com/in-the-news/iosmdmvendorcsrsigning

我们尝试使用库push-sharp发送推送通知: https://github.com/Redth/PushSharp

我们使用MDM.p12文件构建这些命令

openssl pkcs12 -export -in ./COMPANY.pem -inkey ./customerPrivateKey.pem -certfile ./CertificateSigningRequest.certSigningRequest -out MDM.p12

发送此通知的程序不会抛出任何错误并正常退出。 但我们没有在我们的设备上收到任何推送通知,也没有通过反馈服务接收任何内容。

另外要提到的是,我们也尝试使用沙箱服务器和生产服务器。

以下是使用push-sharp库的代码:

    using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Text;
using PushSharp;
using PushSharp.Apple;


namespace PushSharp.Sample
{
    class Program
    {
        static void Main(string[] args)
        {

            //Create our service    
            PushService push = new PushService();

            //Wire up the events
            push.Events.OnDeviceSubscriptionExpired += new Common.ChannelEvents.DeviceSubscriptionExpired(Events_OnDeviceSubscriptionExpired);
            push.Events.OnDeviceSubscriptionIdChanged += new Common.ChannelEvents.DeviceSubscriptionIdChanged(Events_OnDeviceSubscriptionIdChanged);
            push.Events.OnChannelException += new Common.ChannelEvents.ChannelExceptionDelegate(Events_OnChannelException);
            push.Events.OnNotificationSendFailure += new Common.ChannelEvents.NotificationSendFailureDelegate(Events_OnNotificationSendFailure);
            push.Events.OnNotificationSent += new Common.ChannelEvents.NotificationSentDelegate(Events_OnNotificationSent);

            //Configure and start Apple APNS
            // IMPORTANT: Make sure you use the right Push certificate.  Apple allows you to generate one for connecting to Sandbox,
            //   and one for connecting to Production.  You must use the right one, to match the provisioning profile you build your
            //   app with!
            //var appleCert = File.ReadAllBytes("C:\\TEMP\\apns-mdm.p12");
            var appleCert = File.ReadAllBytes(@".\MDM.p12");

            //IMPORTANT: If you are using a Development provisioning Profile, you must use the Sandbox push notification server 
            //  (so you would leave the first arg in the ctor of ApplePushChannelSettings as 'false')
            //  If you are using an AdHoc or AppStore provisioning profile, you must use the Production push notification server
            //  (so you would change the first arg in the ctor of ApplePushChannelSettings to 'true')
            push.StartApplePushService(new ApplePushChannelSettings(true, appleCert, "PWD"));


            //String p12File = @".\apns-mdm.p12";
            //String p12Password = "PWD";
            String pushMagicString = "00454668-00B2-4122-A1DC-72ACD64E6AFB";
            //String deviceToken = "27asObngxvVNb3RvRMs3XVaEWC1DNa3TjFE12stKsig=";


            //Configure and start Android GCM
            //IMPORTANT: The SENDER_ID is your Google API Console App Project ID.
            //  Be sure to get the right Project ID from your Google APIs Console.  It's not the named project ID that appears in the Overview,
            //  but instead the numeric project id in the url: eg: https://code.google.com/apis/console/?pli=1#project:785671162406:overview
            //  where 785671162406 is the project id, which is the SENDER_ID to use!
            //push.StartGoogleCloudMessagingPushService(new GcmPushChannelSettings("785671162406", "AIzaSyC2PZNXQDVaUpZGmtsF_Vp8tHtIABVjazI", "com.pushsharp.test"));

            //Configure and start Windows Phone Notifications
            //push.StartWindowsPhonePushService(new WindowsPhone.WindowsPhonePushChannelSettings());

            //Fluent construction of a Windows Phone Toast notification
            //push.QueueNotification(NotificationFactory.WindowsPhone().Toast()
            //.ForEndpointUri(new Uri("http://sn1.notify.live.net/throttledthirdparty/01.00/AAFCoNoCXidwRpn5NOxvwSxPAgAAAAADAgAAAAQUZm52OkJCMjg1QTg1QkZDMkUxREQ"))
            //.ForOSVersion(WindowsPhone.WindowsPhoneDeviceOSVersion.MangoSevenPointFive)
            //.WithBatchingInterval(WindowsPhone.BatchingInterval.Immediate)
            //.WithNavigatePath("/MainPage.xaml")
            //.WithText1("PushSharp")
            //.WithText2("This is a Toast"));

            //Fluent construction of an iOS notification
            //IMPORTANT: For iOS you MUST MUST MUST use your own DeviceToken here that gets generated within your iOS app itself when the Application Delegate
            //  for registered for remote notifications is called, and the device token is passed back to you
            String test = "3d 58 64 4d 90 d3 18 09 22 5c 50 d2 12 16 b5 67 71 1e be 5c 13 6e 41 3c 3e 81 b5 52 30 68 09 a5";
            test = test.Replace(" ", string.Empty);
            Console.WriteLine("Device Token length is: " + test.Length);
            Console.WriteLine("DeviceToken is: " + test);
            Console.WriteLine("PushMagic is: " + pushMagicString);

            DateTime dayAfterTomorrow = DateTime.Now.AddDays(2);
            Console.WriteLine("Expiry date is: " + dayAfterTomorrow.ToString());

            push.QueueNotification(NotificationFactory.Apple()
                .ForDeviceToken(test).WithExpiry(dayAfterTomorrow).WithCustomItem("mdm", pushMagicString));


            //push.Events.RaiseNotificationSent(NotificationFactory.Apple()
            //    .ForDeviceToken(hex).WithCustomItem("mdm", pushMagicString));


            //Fluent construction of an Android GCM Notification
            //push.QueueNotification(NotificationFactory.AndroidGcm()
            //    .ForDeviceRegistrationId("APA91bG7J-cZjkURrqi58cEd5ain6hzi4i06T0zg9eM2kQAprV-fslFiq60hnBUVlnJPlPV-4K7X39aHIe55of8fJugEuYMyAZSUbmDyima5ZTC7hn4euQ0Yflj2wMeTxnyMOZPuwTLuYNiJ6EREeI9qJuJZH9Zu9g")
            //    .WithCollapseKey("NONE")
            //    .WithJson("{\"alert\":\"Alert Text!\",\"badge\":\"7\"}"));

            Console.WriteLine("Waiting for Queue to Finish...");

            //Stop and wait for the queues to drains
            push.StopAllServices(true);

            Console.WriteLine("Queue Finished, press return to exit...");
            Console.ReadLine();
        }

        static void Events_OnDeviceSubscriptionIdChanged(Common.PlatformType platform, string oldDeviceInfo, string newDeviceInfo)
        {
            //Currently this event will only ever happen for Android GCM
            Console.WriteLine("Device Registration Changed:  Old-> " + oldDeviceInfo + "  New-> " + newDeviceInfo);
        }

        static void Events_OnNotificationSent(Common.Notification notification)
        {
            Console.WriteLine("Sent: " + notification.Platform.ToString() + " -> " + notification.ToString());
        }

        static void Events_OnNotificationSendFailure(Common.Notification notification, Exception notificationFailureException)
        {
            Console.WriteLine("Failure: " + notification.Platform.ToString() + " -> " + notificationFailureException.Message + " -> " + notification.ToString());
        }

        static void Events_OnChannelException(Exception exception)
        {
            Console.WriteLine("Channel Exception: " + exception.ToString());
        }

        static void Events_OnDeviceSubscriptionExpired(Common.PlatformType platform, string deviceInfo)
        {
            Console.WriteLine("Device Subscription Expired: " + platform.ToString() + " -> " + deviceInfo);
        }
    }
}

我们使用此网站编码收到的deviceToken: http://home.paulschou.net/tools/xlate/ 从base64到HEX。

我们还在iOS设备上使用APS / PC Logging配置文件,通过IPCU提供的调试控制台获得更多输出。

6 个答案:

答案 0 :(得分:3)

发送到推送通知服务的消息不得包含aps密钥。该消息应仅包含PushMagic字符串作为mdm键的值。例如,使用您定义为pushMagicString的值,推送通知服务的消息应如下所示:

{"mdm":"00454668-00B2-4122-A1DC-72ACD64E6AFB"}

我没有使用你正在使用的push-sharp库。但是,我简要地查看了代码,似乎AppleNotificationPayload.ToJson方法总是在消息中添加aps密钥。我建议评论第114行然后尝试它。以下是注释掉行的ToJson方法:

    public string ToJson()
    {
        JObject json = new JObject();

        JObject aps = new JObject();

        if (!this.Alert.IsEmpty)
        {
            if (!string.IsNullOrEmpty(this.Alert.Body)
                && string.IsNullOrEmpty(this.Alert.LocalizedKey)
                && string.IsNullOrEmpty(this.Alert.ActionLocalizedKey)
                && (this.Alert.LocalizedArgs == null || this.Alert.LocalizedArgs.Count <= 0)
                && !this.HideActionButton)
            {
                aps["alert"] = new JValue(this.Alert.Body);
            }
            else
            {
                JObject jsonAlert = new JObject();

                if (!string.IsNullOrEmpty(this.Alert.LocalizedKey))
                    jsonAlert["loc-key"] = new JValue(this.Alert.LocalizedKey);

                if (this.Alert.LocalizedArgs != null && this.Alert.LocalizedArgs.Count > 0)
                    jsonAlert["loc-args"] = new JArray(this.Alert.LocalizedArgs.ToArray());

                if (!string.IsNullOrEmpty(this.Alert.Body))
                    jsonAlert["body"] = new JValue(this.Alert.Body);

                if (this.HideActionButton)
                    jsonAlert["action-loc-key"] = new JValue((string)null);
                else if (!string.IsNullOrEmpty(this.Alert.ActionLocalizedKey))
                    jsonAlert["action-loc-key"] = new JValue(this.Alert.ActionLocalizedKey);

                aps["alert"] = jsonAlert;
            }
        }

        if (this.Badge.HasValue)
            aps["badge"] = new JValue(this.Badge.Value);

        if (!string.IsNullOrEmpty(this.Sound))
            aps["sound"] = new JValue(this.Sound);

        if (this.ContentAvailable.HasValue)
            aps["content-available"] = new JValue(this.ContentAvailable.Value);

        //json["aps"] = aps;

        foreach (string key in this.CustomItems.Keys)
        {
            if (this.CustomItems[key].Length == 1)
                json[key] = new JValue(this.CustomItems[key][0]);
            else if (this.CustomItems[key].Length > 1)
                json[key] = new JArray(this.CustomItems[key]);
        }

        string rawString = json.ToString(Newtonsoft.Json.Formatting.None, null);

        StringBuilder encodedString = new StringBuilder();
        foreach (char c in rawString)
        {
            if ((int)c < 32 || (int)c > 127)
                encodedString.Append("\\u" + String.Format("{0:x4}", Convert.ToUInt32(c)));
            else
                encodedString.Append(c);
        }
        return rawString;// encodedString.ToString();
    }

答案 1 :(得分:2)

您是否确保在MDM注册期间,您提供的MDM有效负载(PayloadType = com.apple.mdm)具有正确的主题?

即。在您从apple下载的APN推送证书中,您会看到类似的内容 CN = com.apple.mgmt.external。[GUID]。这需要与MDM注册期间提供给IOS设备的值相同。

如果APN在邮件上传过程中没有出现任何错误,或者反馈服务未返回指示设备不可用的deviceID,则表示它将正确传送到设备。下一阶段是确定IOS设备是否设置为通过该主题收听APN消息。

您可以尝试将设备连接到XCode或IPCU,在控制台日志中,它将包含指示APN是否能够使用商定的主题成功传递此消息的日志。

这里还有一篇关于APN故障排除的文章 http://developer.apple.com/library/ios/#technotes/tn2265/_index.html

上面的文章中有一个可下载的配置文件,您可以将其加载到您的设备以进行其他详细的日志记录。

答案 2 :(得分:0)

Push-sharp库似乎是为应用程序通知而设计的。要使其适用于MDM通知,您可以通过

修复AppleNotificationPayload.ToJson函数,第114行
if (aps.HasValues == true)
{
    json["aps"] = aps;
}

此修复程序将确保仅包含应用程序通知的“aps”键。该库可用于MDM通知和应用程序通知。

答案 3 :(得分:0)

ios会忽略“aps”键。您可以看到屏幕截图日志。它忽略“aps”并成功执行clearpasscode命令。

答案 4 :(得分:0)

Unable to send iOS MDM Push Notification using Push Sharp

这个答案很有效

var pushService = new PushService();
// attach event listeners

// override the production/development auto-detection as it doesn't
// work for MDM certificates
var cert = null; // load your push client certificate
var channel = new ApplePushChannelSettings(true, cert, true);
pushService.StartApplePushService(channel);

// create and send the notification
var notification = NotificationFactory
    .Apple()
    .ForDeviceToken("your-device-token-received-from-checkin")
    .WithExpiry(DateTime.UtcNow.AddDays(1))
    .WithCustomItem("mdm", "your-push-magic-received-in-checkin");
pushService.QueueNotification(notification);

答案 5 :(得分:0)

我也遵循了相同的流程和命令。我在你的代码中注意到你已经评论过来自&#34; MessageType:TokenUpdate&#34;

//String deviceToken = "27asObngxvVNb3RvRMs3XVaEWC1DNa3TjFE12stKsig=";

您正在使用以下变量&#34; test&#34;作为设备令牌,发送推送通知。

String test = "3d 58 64 4d 90 d3 18 09 22 5c 50 d2 12 16 b5 67 71 1e be 5c 13 6e 41 3c 3e 81 b5 52 30 68 09 a5";
test = test.Replace(" ", string.Empty);

当我使用来自&#34; MessageType:TokenUpdate&#34 ;;的设备令牌时pushsharp给我错误

  

APNS NotificationFailureException - &gt; 8:无效令牌

编辑:

我认为我们需要将byte[]转换为十六进制字符串;使用以下方法:

public static string ByteArrayToString(byte[] ba) 
{ 
    StringBuilder hex = new StringBuilder(ba.Length * 2); 
    foreach (byte b in ba) 
        hex.AppendFormat("{0:x2}", b); 

    return hex.ToString(); 
}