C# 如何实现AppCenter推送API?

C# 如何实现AppCenter推送API?,c#,asp.net,xamarin,push-notification,visual-studio-app-center,C#,Asp.net,Xamarin,Push Notification,Visual Studio App Center,重要-微软很快就要退出AppCenter推送,您仍然可以按照我下面的答案来实施它。或者你也可以使用Firebase和Apple推送通知在上关注我的新帖子。多谢各位 我一直在互联网上阅读和寻找如何轻松实现这一点的例子,但没有发现任何有用的东西 我阅读并实现了这个 . 他的解决方案提供了一个很好的开端,但并不完整 因此,我将Andrew Hoefling的解决方案从上面改进为一个完整的工作版本,并认为在下面的答案中与fellows Xamarin成员分享是一件好事。公共类AppCenterPush

重要-微软很快就要退出AppCenter推送,您仍然可以按照我下面的答案来实施它。或者你也可以使用Firebase和Apple推送通知在上关注我的新帖子。多谢各位

我一直在互联网上阅读和寻找如何轻松实现这一点的例子,但没有发现任何有用的东西

我阅读并实现了这个 . 他的解决方案提供了一个很好的开端,但并不完整

因此,我将Andrew Hoefling的解决方案从上面改进为一个完整的工作版本,并认为在下面的答案中与fellows Xamarin成员分享是一件好事。

公共类AppCenterPush
public class AppCenterPush
{
    User receiver = new User();

    public AppCenterPush(Dictionary<Guid, string> dicInstallIdPlatform)
    {
        //Simply get all the Install IDs for the receipient with the platform name as the value
        foreach(Guid key in dicInstallIdPlatform.Keys)
        {
            switch(dicInstallIdPlatform[key])
            {
                case "Android":
                    receiver.AndroidDevices.Add(key.ToString());

                    break;

                case "iOS":
                    receiver.IOSDevices.Add(key.ToString());

                    break;
            }
        }
    }

    public class Constants
    {
        public const string Url = "https://api.appcenter.ms/v0.1/apps";
        public const string ApiKeyName = "X-API-Token";     
        
        //Push required to use this. Go to https://docs.microsoft.com/en-us/appcenter/api-docs/index for instruction
        public const string FullAccessToken = "{FULL ACCESS TOKEN}";   
        
        public const string DeviceTarget = "devices_target";
        public class Apis { public const string Notification = "push/notifications"; }

        //You can find your AppName and Organization/User name at your AppCenter URL as such https://appcenter.ms/users/{owner-name}/apps/{app-name}
        public const string AppNameAndroid = "{APPNAME_ANDROID}";
        public const string AppNameIOS = "{APPNAME_IOS}";

        public const string Organization = "{ORG_OR_USER}";
    }

    [JsonObject]
    public class Push
    {
        [JsonProperty("notification_target")]
        public Target Target { get; set; }

        [JsonProperty("notification_content")]
        public Content Content { get; set; }
    }

    [JsonObject]
    public class Content
    {
        public Content()
        {
            Name = "default";   //By default cannot be empty, must have at least 3 characters
        }

        [JsonProperty("name")]
        public string Name { get; set; }

        [JsonProperty("title")]
        public string Title { get; set; }

        [JsonProperty("body")]
        public string Body { get; set; }

        [JsonProperty("custom_data")]
        public IDictionary<string, string> CustomData { get; set; }
    }

    [JsonObject]
    public class Target
    {
        [JsonProperty("type")]
        public string Type { get; set; }

        [JsonProperty("devices")]
        public IEnumerable Devices { get; set; }
    }

    public class User
    {
        public User()
        {
            IOSDevices = new List<string>();
            AndroidDevices = new List<string>();
        }

        public List<string> IOSDevices { get; set; }
        public List<string> AndroidDevices { get; set; }
    }

    public async Task<bool> Notify(string title, string message, Dictionary<string, string> customData = default(Dictionary<string, string>))
    {
        try
        {
            //title, message length cannot exceed 100 char
            if (title.Length > 100)
                title = title.Substring(0, 95) + "...";

            if (message.Length > 100)
                message = message.Substring(0, 95) + "...";

            if (!receiver.IOSDevices.Any() && !receiver.AndroidDevices.Any())
                return false; //No devices to send

            //To make sure in Android, title and message is retain when click from notification. Else it's lost when app is in background
            if (customData == null)
                customData = new Dictionary<string, string>();

            if (!customData.ContainsKey("Title"))
                customData.Add("Title", title);

            if (!customData.ContainsKey("Message"))
                customData.Add("Message", message);

            //custom data cannot exceed 100 char 
            foreach (string key in customData.Keys)
            {
                if(customData[key].Length > 100)
                {
                    customData[key] = customData[key].Substring(0, 95) + "...";
                }
            }

            var push = new Push
            {
                Content = new Content
                {
                    Title = title,
                    Body = message,
                    CustomData = customData
                },
                Target = new Target
                {
                    Type = Constants.DeviceTarget
                }
            };

            HttpClient httpClient = new HttpClient();

            //Set the content header to json and inject the token
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            httpClient.DefaultRequestHeaders.Add(Constants.ApiKeyName, Constants.FullAccessToken);

            //Needed to solve SSL/TLS issue when 
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

            if (receiver.IOSDevices.Any())
            {
                push.Target.Devices = receiver.IOSDevices;

                string content = JsonConvert.SerializeObject(push);

                HttpContent httpContent = new StringContent(content, Encoding.UTF8, "application/json");

                string URL = $"{Constants.Url}/{Constants.Organization}/{Constants.AppNameiOS}/{Constants.Apis.Notification}";

                var result = await httpClient.PostAsync(URL, httpContent);
            }

            if (receiver.AndroidDevices.Any())
            {
                push.Target.Devices = receiver.AndroidDevices;

                string content = JsonConvert.SerializeObject(push);

                HttpContent httpContent = new StringContent(content, Encoding.UTF8, "application/json");

                string URL = $"{Constants.Url}/{Constants.Organization}/{Constants.AppNameAndroid}/{Constants.Apis.Notification}";

                var result = await httpClient.PostAsync(URL, httpContent);
            }

            return true;
        }
        catch(Exception ex)
        {
            Console.WriteLine(ex.ToString());

            return false;
        }
    }
}
{ 用户接收器=新用户(); 公共AppCenterPush(Dictionary dicInstallIdPlatform) { //只需以平台名称作为值获取Receipent的所有安装ID即可 foreach(dicsinstallidplatform.Keys中的Guid键) { 开关(DIC安装平台[键]) { 案例“Android”: receiver.AndroidDevices.Add(key.ToString()); 打破 案例“iOS”: receiver.IOSDevices.Add(key.ToString()); 打破 } } } 公共类常量 { 公用常量字符串Url=”https://api.appcenter.ms/v0.1/apps"; public const string ApiKeyName=“X-API-Token”; //需要按此按钮才能使用此功能。请转到https://docs.microsoft.com/en-us/appcenter/api-docs/index 请示 public const string FullAccessToken=“{FULL ACCESS TOKEN}”; public const string DeviceTarget=“设备\目标”; 公共类API{public const string Notification=“push/notifications”;} //您可以在AppCenter URL中找到您的AppName和组织/用户名https://appcenter.ms/users/{owner name}/apps/{app name} public const字符串appnameadroid=“{APPNAME_ANDROID}”; 公用常量字符串AppNameIOS=“{APPNAME_IOS}”; public const string Organization=“{ORG\u或_USER}”; } [JsonObject] 公共类推送 { [JsonProperty(“通知对象”)] 公共目标目标{get;set;} [JsonProperty(“通知内容”)] 公共内容{get;set;} } [JsonObject] 公开课内容 { 公共内容() { Name=“default”//默认情况下不能为空,必须至少有3个字符 } [JsonProperty(“名称”)] 公共字符串名称{get;set;} [JsonProperty(“所有权”)] 公共字符串标题{get;set;} [JsonProperty(“主体”)] 公共字符串体{get;set;} [JsonProperty(“自定义数据”)] 公共IDictionary自定义数据{get;set;} } [JsonObject] 公共类目标 { [JsonProperty(“类型”)] 公共字符串类型{get;set;} [JsonProperty(“设备”)] 公共IEnumerable设备{get;set;} } 公共类用户 { 公共用户() { IOSDevices=新列表(); AndroidDevices=新列表(); } 公共列表设备{get;set;} 公共列表AndroidDevices{get;set;} } 公共异步任务通知(字符串标题、字符串消息、字典customData=default(字典)) { 尝试 { //标题,消息长度不能超过100个字符 如果(标题长度>100) title=title.子字符串(0,95)+“…”; 如果(message.Length>100) message=message.Substring(0,95)+“…”; 如果(!receiver.IOSDevices.Any()&&!receiver.AndroidDevices.Any()) 返回false;//没有要发送的设备 //为了确保在安卓系统中,当从通知中单击时,标题和消息将被保留。否则,当应用程序位于后台时,标题和消息将丢失 if(customData==null) customData=新字典(); 如果(!customData.ContainsKey(“标题”)) 添加(“标题”,标题); 如果(!customData.ContainsKey(“消息”)) customData.Add(“Message”,Message); //自定义数据不能超过100个字符 foreach(customData.Keys中的字符串键) { 如果(自定义数据[键]。长度>100) { customData[key]=customData[key]。子字符串(0,95)+“…”; } } var push=新推送 { 内容=新内容 { 头衔, Body=消息, CustomData=CustomData }, 目标=新目标 { 类型=常量。设备目标 } }; HttpClient HttpClient=新HttpClient(); //将内容头设置为json并注入令牌 httpClient.DefaultRequestHeaders.Accept.Add(新的MediaTypeWithQualityHeaderValue(“应用程序/json”); httpClient.DefaultRequestHeaders.Add(Constants.ApiKeyName、Constants.FullAccessToken); //需要在以下情况下解决SSL/TLS问题: ServicePointManager.SecurityProtocol=SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; if(receiver.IOSDevices.Any()) { push.Target.Devices=receiver.ios设备; string content=JsonConvert.SerializeObject(推送); HttpContent HttpContent=新的StringContent(content,Encoding.UTF8,“application/json”); 字符串URL=$“{Constants.URL}/{Constants.Organization}/{Constants.AppNameiOS}/{Constants.api.Notification}”; var result=wait-httpClient.PostAsync(URL,httpContent); } 如果(接收端)
 var receiptInstallID = new Dictionary<string, string>
    {
        { "XXX-XXX-XXX-XXX", "Android" },
        { "YYY-YYY-YYY-YYY", "iOS" }
    };

AppCenterPush appCenterPush = new AppCenterPush(receiptInstallID);

await appCenterPush.Notify("{YOUR_TITLE}", "{YOUR_MESSAGE}", null);
string URL = $"{Constants.Url}/{Constants.Organization}/Constants.AppNameiOS}/{Constants.Apis.Notification}";
string URL = $"{Constants.Url}/{Constants.Organization}/{Constants.AppNameIOS}/{Constants.Apis.Notification}";
var receiptInstallID = new Dictionary<Guid, string>
using Newtonsoft.Json;  
using System;  
using System.Collections;  
using System.Collections.Generic;  
using System.Linq;  
using System.Net;  
using System.Net.Http;  
using System.Net.Http.Headers;  
using System.Text;  
using System.Threading.Tasks;  
 public class AppCenterPush
{
    User receiver = new User();

    public AppCenterPush(Dictionary<string, string> dicInstallIdPlatform)
    {
        //Simply get all the Install IDs for the receipient with the platform name as the value
        foreach (string key in dicInstallIdPlatform.Keys)
        {
            switch (dicInstallIdPlatform[key])
            {
                case "Android":
                    receiver.AndroidDevices.Add(key.ToString());

                    break;

                case "iOS":
                    receiver.IOSDevices.Add(key.ToString());

                    break;
            }
        }
    }

    public class Constants
    {
        public const string Url = "https://api.appcenter.ms/v0.1/apps";
        public const string ApiKeyName = "X-API-Token";

        //Push required to use this. Go to https://docs.microsoft.com/en-us/appcenter/api-docs/index for instruction
        public const string FullAccessToken = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";

        public const string DeviceTarget = "devices_target";
        public const string UserTarget = "user_ids_target";
        public class Apis { public const string Notification = "push/notifications"; }

        //You can find your AppName and Organization/User name at your AppCenter URL as such https://appcenter.ms/users/{owner-name}/apps/{app-name}
        public const string AppNameAndroid = "XXXXXX";
        public const string AppNameIOS = "XXXXXX";

        public const string Organization = "XXXXXXX";
    }

    [JsonObject]
    public class Push
    {
        [JsonProperty("notification_target")]
        public Target Target { get; set; }

        [JsonProperty("notification_content")]
        public Content Content { get; set; }
    }

    [JsonObject]
    public class Content
    {
        public Content()
        {
            Name = "default";   //By default cannot be empty, must have at least 3 characters
        }

        [JsonProperty("name")]
        public string Name { get; set; }

        [JsonProperty("title")]
        public string Title { get; set; }

        [JsonProperty("body")]
        public string Body { get; set; }

        [JsonProperty("custom_data")]
        public IDictionary<string, string> CustomData { get; set; }
    }

    [JsonObject]
    public class Target
    {
        [JsonProperty("type")]
        public string Type { get; set; }

        [JsonProperty("user_ids")]
        public IEnumerable Users { get; set; }
    }

    public class User
    {
        public User()
        {
            IOSDevices = new List<string>();
            AndroidDevices = new List<string>();
        }

        public List<string> IOSDevices { get; set; }
        public List<string> AndroidDevices { get; set; }
    }

    public async Task<bool> Notify(string title, string message, Dictionary<string, string> customData = default(Dictionary<string, string>))
    {
        try
        {
            //title, message length cannot exceed 100 char
            if (title.Length > 100)
                title = title.Substring(0, 95) + "...";

            if (message.Length > 100)
                message = message.Substring(0, 95) + "...";

            if (!receiver.IOSDevices.Any() && !receiver.AndroidDevices.Any())
                return false; //No devices to send

            //To make sure in Android, title and message is retain when click from notification. Else it's lost when app is in background
            if (customData == null)
                customData = new Dictionary<string, string>();

            if (!customData.ContainsKey("Title"))
                customData.Add("Title", title);

            if (!customData.ContainsKey("Message"))
                customData.Add("Message", message);

            //custom data cannot exceed 100 char 
            foreach (string key in customData.Keys)
            {
                if (customData[key].Length > 100)
                {
                    customData[key] = customData[key].Substring(0, 95) + "...";
                }
            }

            var push = new Push
            {
                Content = new Content
                {
                    Title = title,
                    Body = message,
                    CustomData = customData
                },
                Target = new Target
                {
                    Type = Constants.UserTarget
                }
            };

            HttpClient httpClient = new HttpClient();

            //Set the content header to json and inject the token
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            httpClient.DefaultRequestHeaders.Add(Constants.ApiKeyName, Constants.FullAccessToken);

            //Needed to solve SSL/TLS issue when 
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

            if (receiver.IOSDevices.Any())
            {
                push.Target.Users = receiver.IOSDevices;

                string content = JsonConvert.SerializeObject(push);

                HttpContent httpContent = new StringContent(content, Encoding.UTF8, "application/json");

                string URL = $"{Constants.Url}/{Constants.Organization}/{Constants.AppNameIOS}/{Constants.Apis.Notification}";

                var result = await httpClient.PostAsync(URL, httpContent);
            }

            if (receiver.AndroidDevices.Any())
            {
                push.Target.Users = receiver.AndroidDevices;

                string content = JsonConvert.SerializeObject(push);

                HttpContent httpContent = new StringContent(content, Encoding.UTF8, "application/json");

                string URL = $"{Constants.Url}/{Constants.Organization}/{Constants.AppNameAndroid}/{Constants.Apis.Notification}";

                var result = await httpClient.PostAsync(URL, httpContent);
            }

            return true;
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());

            return false;
        }
    }
}
public async void PushNotification()
    {
        var receiptInstallID = new Dictionary<string, string>
                {
                    {"17593989838", "Android" }
                };

        var customData = new Dictionary<string, string>
                {
                    {"taskId", "1234" }
                };

        AppCenterPush appCenterPush = new AppCenterPush(receiptInstallID);

        await appCenterPush.Notify("Hello", "How are you?", customData);

    }