Exemplo n.º 1
0
        public async Task <IActionResult> Index()
        {
            var         httpClient = new HttpClient();
            ApnSettings settings   = new ApnSettings();

            settings.ServerType          = ApnServerType.Production;
            settings.TeamId              = "44KGXK85M8";
            settings.AppBundleIdentifier = "com.ultronnet.seekit24";
            settings.P8PrivateKey        = "MIGTAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBHkwdwIBAQQg8dK9Q2N3e4XfYW4e" +
                                           "fn5v5TCnv2MmMSU349XsxVCewJGgCgYIKoZIzj0DAQehRANCAATCm9YLSdOtPS3n" +
                                           "hhtYV2R7rjbUogF3cl4jD8evA3XHqRrH28YrOeLKFEt73ofFbxUKLvTkup0cNtTo" +
                                           "GJALzQMu";
            settings.P8PrivateKeyId = "QS47LJVNG3";

            var apn = new ApnSender(settings, httpClient);

            AppleNotification notification = new AppleNotification();

            notification.Aps          = new AppleNotification.ApsPayload();
            notification.ExperienceId = "@choby/seekit24";
            notification.Aps.Alert    = new AppleNotificationAlert
            {
                Title = "你有一条新的消息",
                Body  = "你屁股着火拉✅"
            };

            string deviceToken = "a0ba4576e8be019e88a3d9b4258eb04ebefdb7ad87f9d1fcc9dd727632760d06";
            var    response    = await apn.SendAsync(notification, deviceToken);


            return(Content($"ios push result:{response.IsSuccess.ToString()}"));
        }
        public async Task <IActionResult> SendNotificationMobile(string userId, string message)
        {
            // IActionResult OpmUserProvince = null;
            var mobileObj = _context.UserTokenMobiles
                            .Where(w => w.UserID == userId)
                            .ToArray();

            foreach (var item in mobileObj)
            {
                var p8privateKey = $"MIGTAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBHkwdwIBAQQgpaXr/CZEsUSHeky8aQQ6teO4cDSsLwVq3j7PWdpr6wOgCgYIKoZIzj0DAQehRANCAAQe9meUPmcbinwleRVTxlolByUcfJjX9uxhYie57KxZJZZEfYrM4/U/IAcDu3EiWWBoKYmsVtDMTBGbFTfVCUvo";
                if (item.DeviceType == "ios")
                {
                    using (var apn = new ApnSender(p8privateKey, "7D37LMN3C4", "RVLQ6T4Y33", "com.tot.inspec", ApnServerType.Production))
                    {
                        // await apn.SendAsync(item.Token,message );
                        await apn.SendAsync(new { alert = message }, item.Token);
                    }
                }
                else
                {
                    using (var fcm = new FcmSender("AAAAzLUSLHk:APA91bEPP7_VRyQf7nFxKPTpZ6BYZ_yk7A0sXEWTOo--4i8kykZpmZnxzneKB5jdkRj8hJIPGu7Nfsvtu81YM2bZ3zFGOS8oTV_QGPWMcuUimytm8GOOjA9OT6_4nxLLQ1oPZOEep8Jb", "879211195513"))
                    {
                        await fcm.SendAsync(item.Token, message);
                    }
                }
            }

            return(Ok(mobileObj));
        }
Exemplo n.º 3
0
        static async Task Main(string[] args)
        {
            var path = args.Length > 0 ? args[0] : Path.Combine(Directory.GetCurrentDirectory(), "apple.json");
            var json = JObject.Parse(File.ReadAllText(path));

            var p8privateKey        = json["p8privateKey"].ToString();
            var p8privateKeyId      = json["p8privateKeyId"].ToString();
            var teamId              = json["teamId"].ToString();
            var appBundleIdentifier = json["appBundleIdentifier"].ToString();
            var server              = json["server"].ToString().Equals("Development") ? CorePush.Apple.ApnServerType.Development : CorePush.Apple.ApnServerType.Production;
            var deviceToken         = json["deviceToken"].ToString();

            var settings = new ApnSettings
            {
                AppBundleIdentifier = appBundleIdentifier,
                P8PrivateKey        = p8privateKey,
                P8PrivateKeyId      = p8privateKeyId,
                TeamId     = teamId,
                ServerType = server,
            };

            var notification = json["payload"].ToObject <AppleNotification>();

            var apn      = new ApnSender(settings, http);
            var response = await apn.SendAsync(notification, deviceToken);

            Console.WriteLine($"Response: {JsonConvert.SerializeObject(response)}");
        }
Exemplo n.º 4
0
        public override bool SendMessage(SendMessage message)
        {
            if (apnSender == null)
            {
                var keyID             = SendCacheStore.GetSystemValue("barkKeyId");
                var teamID            = SendCacheStore.GetSystemValue("barkTeamId");
                var privateKey        = SendCacheStore.GetSystemValue("barkPrivateKey");
                var privateKeyContent = privateKey.Split('\n')[1];
                var apnSettings       = new ApnSettings()
                {
                    TeamId = teamID,
                    AppBundleIdentifier = "me.fin.bark",
                    P8PrivateKey        = privateKeyContent,
                    ServerType          = ApnServerType.Production,
                    P8PrivateKeyId      = keyID,
                };

                apnSender = new ApnSender(apnSettings, new HttpClient());
            }

            var payload = new AppleNotification(
                Guid.NewGuid(),
                message.Data,
                message.Title)
            {
                IsArchive         = Auth.IsArchive,
                AutoMaticallyCopy = Auth.AutoMaticallyCopy,
            };

            payload.Aps.Sound = Auth.Sound;

            var response = apnSender.Send(payload, Auth.DeviceToken);

            if (response.IsSuccess)
            {
                return(true);
            }
            return(false);
        }
Exemplo n.º 5
0
        //[HttpGet]
        //[Route("AppleNotificaion")]
        private async Task ApplePushNotification(string deviceToken, Notification notification)
        {
            try
            {
                HttpClient  httpClient  = new HttpClient();
                ApnSettings apnSettings = new ApnSettings()
                {
                    AppBundleIdentifier = "com.nextleveltraining", P8PrivateKey = "MIGTAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBHkwdwIBAQQgZ1ugPXE4Hhh3L1embZmjfUdYBij8HbsrolZnzfR49X6gCgYIKoZIzj0DAQehRANCAARbCwj0VnMCOzw/Tyx4GsS4W+QN4LLCe6RRgIR/LZBJQqKi0q4XWg/p4Qa6JQAdKOZziemK4/dJZaqH/EFijM1S", P8PrivateKeyId = "FQ6ZXC7U8L", ServerType = ApnServerType.Production, TeamId = "Y77A2C426U"
                };
                AppleNotification appleNotification = new AppleNotification();
                appleNotification.Aps.AlertBody = notification.Text;
                appleNotification.Notification  = JsonConvert.SerializeObject(notification);
                var apn    = new ApnSender(apnSettings, httpClient);
                var result = await apn.SendAsync(appleNotification, deviceToken.Trim());

                if (!result.IsSuccess)
                {
                    ApnSettings devApnSettings = new ApnSettings()
                    {
                        AppBundleIdentifier = "com.nextleveltraining", P8PrivateKey = "MIGTAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBHkwdwIBAQQgZ1ugPXE4Hhh3L1embZmjfUdYBij8HbsrolZnzfR49X6gCgYIKoZIzj0DAQehRANCAARbCwj0VnMCOzw/Tyx4GsS4W+QN4LLCe6RRgIR/LZBJQqKi0q4XWg/p4Qa6JQAdKOZziemK4/dJZaqH/EFijM1S", P8PrivateKeyId = "FQ6ZXC7U8L", ServerType = ApnServerType.Development, TeamId = "Y77A2C426U"
                    };
                    AppleNotification appleNotificationDev = new AppleNotification();
                    appleNotificationDev.Aps.AlertBody = notification.Text;
                    appleNotificationDev.Notification  = JsonConvert.SerializeObject(notification);
                    var apnDev    = new ApnSender(devApnSettings, httpClient);
                    var resultDev = await apnDev.SendAsync(appleNotificationDev, deviceToken.Trim());

                    if (!resultDev.IsSuccess)
                    {
                        var    notificationError = result.Error.Reason;
                        var    device_Token      = deviceToken;
                        var    user    = _unitOfWork.UserRepository.FindOne(x => x.DeviceToken.ToLower() == device_Token.ToLower());
                        string path    = Directory.GetCurrentDirectory();
                        var    num     = string.IsNullOrEmpty(user.MobileNo) ? "" : user.MobileNo.ToString();
                        var    email   = string.IsNullOrEmpty(user.EmailID) ? "" : user.EmailID.ToString();
                        string newPath = path + "\\wwwroot\\ErrorLogFile\\AppleErrorDevices.txt";
                        using (StreamWriter writer = new StreamWriter(newPath, true))
                        {
                            writer.WriteLine("-----------------------------------------------------------------------------");
                            writer.WriteLine("Email : " + email.ToString());
                            writer.WriteLine("Mobile_No : " + num);
                            writer.WriteLine("Device_Token : " + device_Token.ToString());
                            writer.WriteLine("Error : " + notificationError.ToString());
                            writer.WriteLine("Mode : Development");
                            writer.WriteLine("-----------------------------------------------------------------------------");
                            writer.WriteLine();
                        }
                    }
                    else
                    {
                        var    notificationError = result.Error.Reason;
                        var    device_Token      = deviceToken;
                        var    user    = _unitOfWork.UserRepository.FindOne(x => x.DeviceToken.ToLower() == device_Token.ToLower());
                        string path    = Directory.GetCurrentDirectory();
                        var    num     = string.IsNullOrEmpty(user.MobileNo) ? "" : user.MobileNo.ToString();
                        var    email   = string.IsNullOrEmpty(user.EmailID) ? "" : user.EmailID.ToString();
                        string newPath = path + "\\wwwroot\\ErrorLogFile\\AppleWorkingDevices.txt";
                        using (StreamWriter writer = new StreamWriter(newPath, true))
                        {
                            writer.WriteLine("-----------------------------------------------------------------------------");
                            writer.WriteLine("Email : " + email.ToString());
                            writer.WriteLine("Mobile_No : " + num);
                            writer.WriteLine("Device_Token : " + device_Token.ToString());
                            writer.WriteLine("Mode : Development");
                            writer.WriteLine("-----------------------------------------------------------------------------");
                            writer.WriteLine();
                        }
                    }
                }
                else
                {
                    var    device_Token = deviceToken;
                    var    user         = _unitOfWork.UserRepository.FindOne(x => x.DeviceToken.ToLower() == device_Token.ToLower());
                    string path         = Directory.GetCurrentDirectory();
                    var    num          = string.IsNullOrEmpty(user.MobileNo) ? "" : user.MobileNo.ToString();
                    var    email        = string.IsNullOrEmpty(user.EmailID) ? "" : user.EmailID.ToString();
                    string newPath      = path + "\\wwwroot\\ErrorLogFile\\AppleWorkingDevices.txt";
                    using (StreamWriter writer = new StreamWriter(newPath, true))
                    {
                        writer.WriteLine("-----------------------------------------------------------------------------");
                        writer.WriteLine("Email : " + email);
                        writer.WriteLine("Mobile_No : " + num);
                        writer.WriteLine("Device_Token : " + device_Token.ToString());
                        writer.WriteLine("Mode : Production");
                        writer.WriteLine("-----------------------------------------------------------------------------");
                        writer.WriteLine();
                    }
                }
            }
            catch (Exception ex)
            {
                string path    = Directory.GetCurrentDirectory();
                string newPath = path + "\\wwwroot\\ErrorLogFile\\ErrorLogs.txt";
                using (StreamWriter writer = new StreamWriter(newPath, true))
                {
                    writer.WriteLine("-----------------------------------------------------------------------------");
                    writer.WriteLine("Message : " + ex.Message.ToString());
                    writer.WriteLine("Eception : " + ex.ToString());
                    writer.WriteLine("-----------------------------------------------------------------------------");
                    writer.WriteLine();
                }
            }
        }
Exemplo n.º 6
0
        private async Task SendNotificationsForDevices(List <Device> devices, string message, string type, Dictionary <string, string> payload)
        {
            if (devices.Count == 0)
            {
                return;
            }

            var iosPayload = new AppleNotification
            {
                Aps = new ApsPayload
                {
                    Alert = message,
                },
                Type   = type,
                Params = payload,
            };

            var androidPayload = new FirebaseNotification
            {
                Android = new FirebaseAndroidPayload
                {
                    Notification = new FirebaseAndroidNotification
                    {
                        Body      = message,
                        ChannelId = "GENERAL"
                    },
                    Priority = 10,
                    Data     = new FirebasePayload
                    {
                        Type   = type,
                        Params = payload
                    }
                },
                Notification = new FirebaseNotificationInfo
                {
                    Body = message
                }
            };

            var iOSDevices = devices.Where(d => d.Platform == 1).ToList();

            using var apn = new ApnSender(
                      settings.Connection.ApplePushKey,
                      settings.Connection.ApplePushKeyId,
                      settings.Connection.ApplePushTeamId,
                      settings.Connection.ApplePushBundleId,
                      ApnServerType.Production
                      );

            await Task.WhenAll(iOSDevices.Select(device => Policy
                                                 .HandleResult <ApnsResponse>(r => !r.IsSuccess)
                                                 .WaitAndRetryAsync(new[]
            {
                TimeSpan.FromSeconds(2),
                TimeSpan.FromSeconds(4),
                TimeSpan.FromSeconds(8)
            }, (exception, timeSpan) =>
            {
                var time = timeSpan.ToString("h'h 'm'm 's's'", CultureInfo.CurrentCulture);
                Logger.LogWarning($"Failed to send iOS notification to device id {device.Token} in {time}: {exception?.Result?.Error?.Reason}");
            })
                                                 .ExecuteAsync(() => apn.SendAsync(iosPayload, device.Token))
                                                 ).ToArray())
            .ConfigureAwait(false);

            var androidDevices = devices.Where(d => d.Platform == 2).ToList();

            using var fcm = new FcmSender(settings.Connection.FirebaseServerKey, settings.Connection.FirebaseSenderId);
            await Task.WhenAll(androidDevices.Select(device => Policy
                                                     .HandleResult <FcmResponse>(r => r.Failure > 0)
                                                     .WaitAndRetryAsync(new[]
            {
                TimeSpan.FromSeconds(2),
                TimeSpan.FromSeconds(4),
                TimeSpan.FromSeconds(8)
            }, (_, timeSpan) =>
            {
                var time = timeSpan.ToString("h'h 'm'm 's's'", CultureInfo.CurrentCulture);
                Logger.LogWarning($"Failed to send Android notification to device id {device.Token} in {time}");
            })
                                                     .ExecuteAsync(() => fcm.SendAsync(device.Token, androidPayload))
                                                     ).ToArray())
            .ConfigureAwait(false);
        }
Exemplo n.º 7
0
 public async Task PostNotification(string apns, Notification notification)
 {
     ApnSettings apnSettings = _apiSettings.APNSSettings.ConvertToAPNSettings();
     var         apn         = new ApnSender(apnSettings, new System.Net.Http.HttpClient());
     await apn.SendAsync(notification, apns);
 }