public string SendNotificationFromFirebaseCloud(AppNotification objAppNotification, bool ISAppUpdate = false) { // string deviceToken = "cIb5sbjgNo0:APA91bEB18OdXVxW4obSmkgXTKsl84OWg-dSgMVXO3gExgF2iZTVDYiS4axHJaUZgsKKMTN4GyYRfiLQO7-Yd4-oZmWDHeI_IWHmA6HSya6-ajFezXLqRwv22ovmcrgfYDeXsAsbWZpL"; string serverKey = ConfigurationManager.AppSettings["FCMServerKey"].ToString(); string senderId = ConfigurationManager.AppSettings["FCMsenderId"].ToString(); string FCMURL = ConfigurationManager.AppSettings["FCMAPIURL"].ToString(); string result = string.Empty; WebRequest tRequest = WebRequest.Create(FCMURL); tRequest.Method = "post"; tRequest.ContentType = "application/json"; var objNotification = new { to = objAppNotification.AllDeviceTokenID, data = new { status = ISAppUpdate == true?"AppUpdate":"AppNotification", title = "Title", body = objAppNotification.Message, } }; string jsonNotificationFormat = Newtonsoft.Json.JsonConvert.SerializeObject(objNotification); Byte[] byteArray = Encoding.UTF8.GetBytes(jsonNotificationFormat); tRequest.Headers.Add(string.Format("Authorization: key={0}", serverKey)); tRequest.Headers.Add(string.Format("Sender: id={0}", senderId)); tRequest.ContentLength = byteArray.Length; tRequest.ContentType = "application/json"; using (Stream dataStream = tRequest.GetRequestStream()) { dataStream.Write(byteArray, 0, byteArray.Length); using (WebResponse tResponse = tRequest.GetResponse()) { using (Stream dataStreamResponse = tResponse.GetResponseStream()) { using (StreamReader tReader = new StreamReader(dataStreamResponse)) { String responseFromFirebaseServer = tReader.ReadToEnd(); FCMResponse response = Newtonsoft.Json.JsonConvert.DeserializeObject <FCMResponse>(responseFromFirebaseServer); if (response.success == 1) { objAppNotification.Result = "success"; } else if (response.failure == 1) { objAppNotification.Result = "Failure"; } else { objAppNotification.Result = "Failure"; } } } } } return(result); }
public static string SendPushNotification(string deviceId, string msgBody, string msgTitle) { string response; try { //string photo = Reference.AdminLink + "/format/HeaderImages/logo.png"; // topic notification WebRequest tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send"); tRequest.Method = "post"; // tRequest.ContentType = "application/x-www-form-urlencoded;charset=UTF-8"; tRequest.ContentType = "application/json"; var data = new { to = deviceId, notification = new { body = msgBody, title = msgTitle, sound = "Enabled" } }; var serializer = new JavaScriptSerializer(); var json = serializer.Serialize(data); Byte[] byteArray = Encoding.UTF8.GetBytes(json); tRequest.Headers.Add(string.Format("Authorization: key={0}", serverKey)); tRequest.Headers.Add(string.Format("Sender: id={0}", senderId)); tRequest.ContentLength = byteArray.Length; using (Stream dataStream = tRequest.GetRequestStream()) { dataStream.Write(byteArray, 0, byteArray.Length); using (WebResponse tResponse = tRequest.GetResponse()) { using (Stream dataStreamResponse = tResponse.GetResponseStream()) { using (StreamReader tReader = new StreamReader(dataStreamResponse)) { string sResponseFromServer = tReader.ReadToEnd(); FCMResponse hresponse = Newtonsoft.Json.JsonConvert.DeserializeObject <FCMResponse>(sResponseFromServer); if (hresponse.success == 1) { response = "" + 200; } else { response = sResponseFromServer; } } } } } } catch (Exception ex) { response = ex.Message; } return(response); }
public void PushNoti_Vendor_Add(string DeviceType, string DeviceID) { try { //string DeviceID = string.Join("\",\"", FCMToken); string postData = string.Empty; string ApplicationID = Convert.ToString(ConfigurationSettings.AppSettings["ApplicationID"]); string SenderID = Convert.ToString(ConfigurationSettings.AppSettings["SenderID"]); //Title and Description var Description = "Description"; var Title = "Title"; WebRequest tRequest; tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send"); tRequest.Method = "post"; tRequest.ContentType = "application/json"; tRequest.Headers.Add(string.Format("Authorization: key={0}", ApplicationID)); tRequest.Headers.Add(string.Format("Sender: id={0}", SenderID)); if (DeviceType == "A") //Android { postData = "{\"to\":\"" + DeviceID + "\",\"collapse_key\":\"type_a\",\"data\": { \"body\" : " + "\"Description\",\"title\" : " + "\"" + Title + "\", \"message\" : " + "\"" + Description + "\",\"time\": " + "\"" + System.DateTime.Now.ToString() + "\"}}"; } else if (DeviceType == "I") //ios { postData = "{\"to\":\"" + DeviceID + "\",\"notification\": { \"title\" : \"AUTHENTICATOR\", \"body\" : " + "\"Approve Log in Envision request from " + Session["Email"].ToString().ToLower() + "\"}, \"priority\" : " + "\"high\"}"; } Byte[] byteArray = Encoding.UTF8.GetBytes(postData); tRequest.ContentLength = byteArray.Length; Stream dataStream = tRequest.GetRequestStream(); dataStream.Write(byteArray, 0, byteArray.Length); dataStream.Close(); WebResponse tResponse = tRequest.GetResponse(); dataStream = tResponse.GetResponseStream(); StreamReader tReader = new StreamReader(dataStream); //Get response from GCM server string sResponseFromServer = tReader.ReadToEnd(); FCMResponse response = Newtonsoft.Json.JsonConvert.DeserializeObject <FCMResponse>(sResponseFromServer); tReader.Close(); dataStream.Close(); tResponse.Close(); } catch (Exception oex) { } }
public bool EnviarAFCM(notificacion_mensaje mensaje) { WebRequest tRequest = createWebRequestPush(); string jsonNotificationFormat = crearParamsNotificaciones(mensaje); if (jsonNotificationFormat == "") { return(false); } else { Byte[] byteArray = Encoding.UTF8.GetBytes(jsonNotificationFormat); tRequest.ContentLength = byteArray.Length; using (Stream dataStream = tRequest.GetRequestStream()) { dataStream.Write(byteArray, 0, byteArray.Length); using (WebResponse tResponse = tRequest.GetResponse()) { using (Stream dataStreamResponse = tResponse.GetResponseStream()) { using (StreamReader tReader = new StreamReader(dataStreamResponse)) { String responseFromFirebaseServer = tReader.ReadToEnd(); //LogRepository.LOG_INFO((int)mensaje.doc_tipo, mensaje.doc_numero, responseFromFirebaseServer); FCMResponse fcmResponse = Newtonsoft.Json.JsonConvert.DeserializeObject <FCMResponse>(responseFromFirebaseServer); //como manda a muchos es dificil saber si ejecuto todos bien return(true); //return fcmResponse.success !=0; } } } } } }
public static bool SendPushNotification(string device_token, string body_data, Guid guid, int devicetype) { bool IsSendToFcm = false; try { FCMNotification fcmpush = new FCMNotification(); FCMResponse s = fcmpush.PushNotifyAsync(device_token, body_data, guid, devicetype); if (s.success > 0) { IsSendToFcm = true; } else { IsSendToFcm = false; } } catch (Exception ex) { throw ex; } return(IsSendToFcm); }
public IHttpActionResult push([FromBody] PushRequest request) { if (request.apiKey != API_KEY) { return(BadRequest("bad api key")); } double delay = 0; try { delay = double.Parse(request.delay); } catch (Exception) { } if (delay == 0) { string[] tokens = request.deviceToken.Split(','); if (request.categoryIdentifier == null || request.categoryIdentifier == "") { request.categoryIdentifier = "Chat"; } WebRequest tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send"); tRequest.Method = "post"; tRequest.ContentType = "application/json"; dynamic objNotification; if (string.IsNullOrEmpty(request.title) && string.IsNullOrEmpty(request.message)) { objNotification = new { registration_ids = tokens, content_available = true, categoryIdentifier = request.categoryIdentifier, priority = "high", data = new { data = request.data } }; } else { objNotification = new { registration_ids = tokens, priority = "high", notification = new { body = request.message, title = request.title, sound = "default", categoryIdentifier = request.categoryIdentifier, badge = request.badge }, data = new { data = request.data } }; } string jsonNotificationFormat = Newtonsoft.Json.JsonConvert.SerializeObject(objNotification); Byte[] byteArray = Encoding.UTF8.GetBytes(jsonNotificationFormat); tRequest.Headers.Add(string.Format("Authorization: key={0}", request.serverKey)); tRequest.Headers.Add(string.Format("Sender: id={0}", request.senderId)); tRequest.ContentLength = byteArray.Length; tRequest.ContentType = "application/json"; using (Stream dataStream = tRequest.GetRequestStream()) { dataStream.Write(byteArray, 0, byteArray.Length); using (WebResponse tResponse = tRequest.GetResponse()) { using (Stream dataStreamResponse = tResponse.GetResponseStream()) { using (StreamReader tReader = new StreamReader(dataStreamResponse)) { String responseFromFirebaseServer = tReader.ReadToEnd(); FCMResponse response = Newtonsoft.Json.JsonConvert.DeserializeObject <FCMResponse>(responseFromFirebaseServer); if (response.success == 1) { return(Ok("success")); } else if (response.failure == 1) { return(Ok(string.Format("Error sent from FCM server, after sending request : {0} , for following device info: {1}", responseFromFirebaseServer, jsonNotificationFormat))); } } } } } return(Ok()); } else { CancellationTokenSource source = new CancellationTokenSource(); var t = Task.Run(async delegate { await Task.Delay(TimeSpan.FromMilliseconds(delay), source.Token); string[] tokens = request.deviceToken.Split(','); if (request.categoryIdentifier == null || request.categoryIdentifier == "") { request.categoryIdentifier = "Chat"; } WebRequest tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send"); tRequest.Method = "post"; tRequest.ContentType = "application/json"; dynamic objNotification; if (string.IsNullOrEmpty(request.title) && string.IsNullOrEmpty(request.message)) { objNotification = new { registration_ids = tokens, content_available = true, categoryIdentifier = request.categoryIdentifier, priority = "high", data = new { data = request.data } }; } else { objNotification = new { registration_ids = tokens, priority = "high", notification = new { body = request.message, title = request.title, sound = "default", categoryIdentifier = request.categoryIdentifier, badge = request.badge }, data = new { data = request.data } }; } string jsonNotificationFormat = Newtonsoft.Json.JsonConvert.SerializeObject(objNotification); Byte[] byteArray = Encoding.UTF8.GetBytes(jsonNotificationFormat); tRequest.Headers.Add(string.Format("Authorization: key={0}", request.serverKey)); tRequest.Headers.Add(string.Format("Sender: id={0}", request.senderId)); tRequest.ContentLength = byteArray.Length; tRequest.ContentType = "application/json"; using (Stream dataStream = tRequest.GetRequestStream()) { dataStream.Write(byteArray, 0, byteArray.Length); } }); return(Ok()); } }
public static AndroidFCMPushNotificationStatus SendNotification(string deviceId, string msg, int userId, string title) { AndroidFCMPushNotificationStatus result = new AndroidFCMPushNotificationStatus(); try { result.Successful = false; result.Error = null; var serverApiKey = Convert.ToString(ConfigurationSettings.AppSettings["FcmServerApiKeyFO"]); var senderId = Convert.ToString(ConfigurationSettings.AppSettings["FcmsenderIdFO"]); //deviceId = "fiw592fD138:APA91bHqE4yzlcp3OVX3hHYBz3NE3oJBpz3b6JlFOXu2-wZPTajYLNyRD0BHPsvCG09pZv54zbNMVLW8rdJLArlg0aEHRDmB9z59ATQORy3FpVsnDTSgDh6XnMEjS7iDx_owcbPpSujs"; // var deviceId = "ae03efc8462cc55a"; WebRequest tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send"); tRequest.Method = "post"; // tRequest.ContentType = "application/x-www-form-urlencoded;charset=UTF-8"; tRequest.Headers.Add(string.Format("Authorization: key={0}", serverApiKey)); tRequest.Headers.Add(string.Format("Sender: id={0}", senderId)); // string postData = "collapse_key=score_update&time_to_live=108&delay_while_idle=1&data.message=" + value + "&data.time=" + System.DateTime.Now.ToString() + "®istration_id=" + deviceId + ""; //Byte[] byteArray = Encoding.UTF8.GetBytes(postData); tRequest.ContentType = "application/json"; // tRequest.UseDefaultCredentials = true; // tRequest.PreAuthenticate = true; // tRequest.Credentials = CredentialCache.DefaultCredentials; var data = new { to = deviceId, notification = new { body = msg, title = title } }; var serializer = new JavaScriptSerializer(); var json = serializer.Serialize(data); Byte[] byteArray = Encoding.UTF8.GetBytes(json); tRequest.ContentLength = byteArray.Length; using (Stream dataStream = tRequest.GetRequestStream()) { dataStream.Write(byteArray, 0, byteArray.Length); using (WebResponse tResponse = tRequest.GetResponse()) { using (Stream dataStreamResponse = tResponse.GetResponseStream()) { using (StreamReader tReader = new StreamReader(dataStreamResponse)) { String sResponseFromServer = tReader.ReadToEnd(); FCMResponse response = Newtonsoft.Json.JsonConvert.DeserializeObject <FCMResponse>(sResponseFromServer); if (response.success == 1) { var newTbl_NotifyLog = new NotifyLog(); newTbl_NotifyLog.FcmId = deviceId; newTbl_NotifyLog.AppKeyId = serverApiKey; newTbl_NotifyLog.Msg = msg; newTbl_NotifyLog.Status = "Success"; newTbl_NotifyLog.MsgId = response.results[0].message_id; newTbl_NotifyLog.CreatedDate = DateTime.Now.ToString(); newTbl_NotifyLog.CreatedBy = userId; new ReasonStatusDal().SaveNotifyLog(newTbl_NotifyLog); } else if (response.failure == 1) { var newTbl_NotifyLog = new NotifyLog(); newTbl_NotifyLog.FcmId = deviceId; newTbl_NotifyLog.AppKeyId = serverApiKey; newTbl_NotifyLog.Msg = msg; newTbl_NotifyLog.ErrorMsg = response.results[0].error; newTbl_NotifyLog.Status = "Failure"; newTbl_NotifyLog.CreatedDate = DateTime.Now.ToString(); newTbl_NotifyLog.CreatedBy = userId; new ReasonStatusDal().SaveNotifyLog(newTbl_NotifyLog); } result.Response = sResponseFromServer; } } } } } catch (Exception ex) { var newErrorLog = new ErrorLog(); newErrorLog.ControllerName = "Notification"; newErrorLog.ActionName = "SendNotification"; newErrorLog.Msg = ex.Message; newErrorLog.Type = title + " Console"; LogBal.ErrorLog("CommonBal", "SendNotification", ex.Message, 0); // new DataLayer().SaveErrorLog(newErrorLog); //result.Successful = false; //result.Response = null; //result.Error = ex; } return(result); }
public void sendData() { for (int i = 0; i < 10; i++) { String cultureName = "en-GB"; var cultureInfo = new CultureInfo(cultureName); DateTime localDate = DateTime.Now; WebRequest tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send"); tRequest.Method = "post"; tRequest.ContentType = "application/json"; var objNotification = new { to = "Fcm_Token", notification = new { //title = "notification: " + (i+1), title = localDate.ToString("HH:mm:ss"), body = "body" //icon = "/image/accept.png" }, data = new { bilgi = "id : " + (i + 1) } }; string jsonNotificationFormat = Newtonsoft.Json.JsonConvert.SerializeObject(objNotification); Byte[] byteArray = Encoding.UTF8.GetBytes(jsonNotificationFormat); tRequest.Headers.Add(string.Format("Authorization: key={0}", "Server_API_key")); tRequest.Headers.Add(string.Format("Sender: id={0}", "Sender_Id")); tRequest.ContentLength = byteArray.Length; tRequest.ContentType = "application/json"; Console.WriteLine(jsonNotificationFormat); using (Stream dataStream = tRequest.GetRequestStream()) { dataStream.Write(byteArray, 0, byteArray.Length); using (WebResponse tResponse = tRequest.GetResponse()) { using (Stream dataStreamResponse = tResponse.GetResponseStream()) { using (StreamReader tReader = new StreamReader(dataStreamResponse)) { String responseFromFirebaseServer = tReader.ReadToEnd(); FCMResponse response = Newtonsoft.Json.JsonConvert.DeserializeObject <FCMResponse>(responseFromFirebaseServer); if (response.success == 1) { Console.WriteLine("succeeded"); } else if (response.failure == 1) { Console.WriteLine("failed"); } } } } } } }
public Notification add(Notification notification) { logger.Info("Add message: "); try { if (notification == null) { throw new ArgumentNullException("message"); } List <Customer> customers = new List <Customer>(); if (notification.ids.Count() > 0) { foreach (var i in notification.ids) { // var olist = context.Customers.Where(x => x.fcmId != null && x.CustomerId == i.id && x.CreatedDate >= notification.From && x.CreatedDate <= notification.TO).SingleOrDefault(); var olist = context.Customers.Where(x => x.fcmId != null && x.CustomerId == i.id).SingleOrDefault(); customers.Add(olist); } } else { customers = context.Customers.Where(x => x.fcmId != null).ToList(); } context.AddNotification(notification); foreach (var item in customers) { if (item.fcmId != null) { //Registration Id created by Android App i.e. DeviceId. string regId; regId = item.Name; //API Key created in Google project var Key = "AIzaSyA67YsQd7_ZIOBYsAYDFbC4JBUDuDNU3MY"; //Project ID created in Google project. var id = "98292896656"; var varMessage = notification.Message; var ImageURL = "https://cdn4.iconfinder.com/data/icons/ionicons/512/icon-image-128.png"; WebRequest tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send") as HttpWebRequest; tRequest.Method = "post"; var objNotification = new { to = item.fcmId, notification = new { title = notification.title, body = notification.Message, icon = notification.Pic } }; string jsonNotificationFormat = Newtonsoft.Json.JsonConvert.SerializeObject(objNotification); Byte[] byteArray = Encoding.UTF8.GetBytes(jsonNotificationFormat); tRequest.Headers.Add(string.Format("Authorization: key={0}", Key)); tRequest.Headers.Add(string.Format("Sender: id={0}", id)); tRequest.ContentLength = byteArray.Length; tRequest.ContentType = "application/json"; using (Stream dataStream = tRequest.GetRequestStream()) { dataStream.Write(byteArray, 0, byteArray.Length); using (WebResponse tResponse = tRequest.GetResponse()) { using (Stream dataStreamResponse = tResponse.GetResponseStream()) { using (StreamReader tReader = new StreamReader(dataStreamResponse)) { String responseFromFirebaseServer = tReader.ReadToEnd(); FCMResponse response = Newtonsoft.Json.JsonConvert.DeserializeObject <FCMResponse>(responseFromFirebaseServer); if (response.success == 1) { Console.Write(response); try { DeviceNotification obj = new DeviceNotification(); obj.CustomerId = item.CustomerId; obj.DeviceId = item.fcmId; obj.title = notification.title; obj.Message = notification.Message; obj.ImageUrl = notification.Pic; obj.NotificationTime = DateTime.Now; context.DeviceNotificationDb.Add(obj); int Id = context.SaveChanges(); // return true; } catch (Exception ex) { logger.Error("Error in Add message " + ex.Message); return(null); } } else if (response.failure == 1) { } } } } } } } logger.Info("End Add message: "); return(notification); } catch (Exception ex) { logger.Error("Error in Add message " + ex.Message); return(null); } }
public FCMException(FCMResponse response) { Response = response; }
public FCMResponse PushNotifyAsync(string to, string message, Guid userid, int deviceType = 1) { FCMResponse res = new FCMResponse(); string response = string.Empty; try { WebRequest tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send"); tRequest.Method = "POST"; tRequest.ContentType = "application/json"; // create data object FCMRootObject dataObject = new FCMRootObject(); dataObject.priority = "high"; dataObject.content_available = true; dataObject.to = to; Notification NotificationBody = new Notification { body = message, title = "WEB RECHARGE", sound = "default" }; // if devicetype = 0 then IOS and 1 for android // so we are not passing NotificationBody to android if (deviceType == 0) { dataObject.notification = NotificationBody; } Data data = new Data { Description = message, NotificationTitle = "WEB RECHARGE", UserId = userid, }; // create data object end dataObject.data = data; string jsonNotificationFormat = Newtonsoft.Json.JsonConvert.SerializeObject(dataObject); Byte[] byteArray = Encoding.UTF8.GetBytes(jsonNotificationFormat); tRequest.Headers.Add(string.Format("Authorization: key={0}", ServerKey)); tRequest.Headers.Add(string.Format("Sender: id={0}", SenderID)); tRequest.ContentLength = byteArray.Length; tRequest.ContentType = "application/json"; using (Stream dataStream = tRequest.GetRequestStream()) { dataStream.Write(byteArray, 0, byteArray.Length); using (WebResponse tResponse = tRequest.GetResponse()) { using (Stream dataStreamResponse = tResponse.GetResponseStream()) { using (StreamReader tReader = new StreamReader(dataStreamResponse)) { response = tReader.ReadToEnd(); res = Newtonsoft.Json.JsonConvert.DeserializeObject <FCMResponse>(response); } } } } } catch (Exception ex) { response = ex.Message; } return(res); }