You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

71 lines
2.9 KiB

1 year ago
  1. using Common;
  2. using log4net;
  3. using System;
  4. using System.Configuration;
  5. using System.IO;
  6. using System.Net;
  7. using System.Text;
  8. using System.Web.Script.Serialization;
  9. namespace PushNotification
  10. {
  11. public static class FcmNotifier
  12. {
  13. private static readonly ILog Log = LogManager.GetLogger(typeof(FcmNotifier));
  14. public static void Notify(string fcmToken, string body, string title, bool isGroup = false, object data = null)
  15. {
  16. if (string.IsNullOrEmpty(fcmToken))
  17. {
  18. Log.Debug("Fcm device id is empty: " + fcmToken);
  19. return;
  20. }
  21. PushNotificationPayload payload = new PushNotificationPayload();
  22. payload.to = isGroup == true ? "/topics/" + fcmToken : fcmToken;
  23. payload.notification = new Notification { body = body, title = title };
  24. payload.data = data;
  25. try
  26. {
  27. Log.Debug("Server is firing push notification" + fcmToken);
  28. WebRequest tRequest = WebRequest.Create(ConfigurationManager.AppSettings["GoogleFcm"].ToString());
  29. tRequest.Method = "POST";
  30. tRequest.ContentType = "application/json";
  31. var serializer = new JavaScriptSerializer();
  32. var json = serializer.Serialize(payload);
  33. Byte[] byteArray = Encoding.UTF8.GetBytes(json);
  34. tRequest.Headers.Add(string.Format("Authorization: key={0}", ConfigurationManager.AppSettings["FcmAuthorizationHeader"].ToString()));
  35. tRequest.Headers.Add(string.Format("Sender: id={0}", ConfigurationManager.AppSettings["fcmSenderId"].ToString()));
  36. tRequest.ContentLength = byteArray.Length;
  37. using (Stream dataStream = tRequest.GetRequestStream())
  38. {
  39. dataStream.Write(byteArray, 0, byteArray.Length);
  40. using (WebResponse tResponse = tRequest.GetResponse())
  41. {
  42. using (Stream dataStreamResponse = tResponse.GetResponseStream())
  43. {
  44. using (StreamReader tReader = new StreamReader(dataStreamResponse))
  45. {
  46. String sResponseFromServer = tReader.ReadToEnd();
  47. string str = sResponseFromServer;
  48. // Log.Info($"Google FCM Api call success: {str}");
  49. Log.Info(serializer.Serialize( new FireBaseLogResponseViewModel() { Response = str, Data = json }));
  50. }
  51. }
  52. }
  53. }
  54. }
  55. catch (Exception ex)
  56. {
  57. Log.Error(ex.Message, ex);
  58. Log.ErrorFormat("Google FCM Api call failed Exception {0}:", ex.Message);
  59. }
  60. }
  61. }
  62. }