public virtual async Task SendNotification(NotificationJsonObj input) { try { var appKey = "AIzaSyA0CLo0JhmgpxTvphpUKDDIhaSTkGThtdY";// _configuration["PushNotification:AppKey"]; var fcmHost = "https://fcm.googleapis.com/fcm/send"; var allUsers = input.notification.UserIdList; foreach (var item in allUsers) { //save notification log now var logModel = new PushNotificationLog { UserId = item, IsRead = false, NotificationSentOn = DateTime.Now, NotificationContent = input.notification.body, NotificationBody = JsonConvert.SerializeObject(input) }; await _notificationLogRepository.InsertAsync(logModel); } var devices = await _deviceRepository.GetAll().Where(x => !x.IsDeleted && allUsers.Contains(x.UserID)).ToListAsync(); foreach (var device in devices) { var notificationId = string.Empty; var notification = await _notificationLogRepository.GetAll().OrderByDescending(x => x.CreationTime).FirstOrDefaultAsync(x => x.UserId == device.UserID); if (notification != null) { notificationId = notification.Id.ToString(); } using (var client = new WebClient()) { // Set the header so it knows we are sending JSON. client.Headers[HttpRequestHeader.ContentType] = "application/json"; client.Headers[HttpRequestHeader.Authorization] = "key=" + appKey; var jsonobj = new NotificationJsonObj(); jsonobj.to = device.RegID.ToString(); jsonobj.priority = "high"; if (device.PlatformType.ToString().Trim().ToLower() == "ios" || device.PlatformType.ToString().Trim().ToLower() == "web") { jsonobj.priority = "high"; var noti = new NotificaionBodyDto(); //noti.priority = "high"; noti.title = input.Title; noti.body = input.Message; noti.code = "PUSH_NOTIFICATION"; //notification.content_available = true; jsonobj.notification = noti; } var data = new NotificaionBodyDto(); data.title = input.Title; data.body = input.Message; data.ReferenceId = string.IsNullOrEmpty(input.notification.ReferenceId) ? "" : input.notification.ReferenceId.ToString(); data.NotificationLogId = string.IsNullOrEmpty(notificationId)? Guid.Empty : new Guid(notificationId); data.code = "PUSH_NOTIFICATION"; jsonobj.data = data; //for react like javascript framework -- send in the body jsonobj.data.custom_notification = new { title = input.Title, body = input.Message, sound = "default", priority = "high", show_in_foreground = true, targetScreen = "notification_detail", notificationId = string.IsNullOrEmpty(notificationId) ? Guid.Empty : new Guid(notificationId) }; //sent notification try { var body = JsonConvert.SerializeObject(jsonobj); var response = client.UploadString(fcmHost, body); } catch (Exception) { //try to sent notification for all users continue; } } } } catch (Exception ex) { throw ex; } }
public async Task <bool> SendPushNotification(string deviceToken, PushNotification notification, int badge = 0, bool testMode = false) { bool sent = false; // The Message should be sent to the News Topic: var message = new FcmMessage() { ValidateOnly = false, Message = new Message { Token = deviceToken, Data = notification.Data != null?notification.Data.GetDictionary() : null, AndroidConfig = new AndroidConfig { CollapseKey = notification.Data.ThreadId, Data = notification.Data != null?notification.Data.GetAndroidDictionary(notification.Title, notification.Body, badge) : null, }, ApnsConfig = new ApnsConfig { Payload = new ApnsConfigPayload { Aps = new Aps { Alert = new ApsAlert { Title = notification.Title, Body = notification.Body }, Badge = badge, Sound = "default", CustomData = notification.Data != null?notification.Data.GetData() : null, ThreadId = notification.Data.ThreadId } } } } }; var jsonBody = JsonConvert.SerializeObject(message); PushNotificationLog log = new PushNotificationLog { DeviceToken = deviceToken, Title = notification.Title, Body = notification.Body, DataJSON = jsonBody, CreatedAt = DateTime.UtcNow, Status = SendingStatus.Failed }; try { // Read the Service Account Key from a File, which is not under Version Control: var settings = FileBasedFcmClientSettings.CreateFromFile(_configuration["FCM:ProjectId"], _configuration["FCM:KeyPath"]); // Construct the Client: using (var client = new FcmClient(settings)) { // Finally send the Message and wait for the Result: CancellationTokenSource cts = new CancellationTokenSource(); // Send the Message and wait synchronously: var result = await client.SendAsync(message, cts.Token); log.Status = SendingStatus.Success; sent = true; } } catch (Exception ex) { _logger.LogError($"FCM Service: {ex}"); sent = false; if (testMode) { throw; } } finally { _unitOfWork.Repository <PushNotificationLog>().Insert(log); _unitOfWork.SaveChanges(); } return(sent); }