forked from Praveent696/FCMSharp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFCMSharp.cs
More file actions
102 lines (93 loc) · 3.34 KB
/
FCMSharp.cs
File metadata and controls
102 lines (93 loc) · 3.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
using FCMSharp.DataObject;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
namespace FCMSharp
{
public class FCMSharp
{
private string appID = "";
private string senderID = "";
public void ConfigureFCMSharp(FCMConfig config)
{
appID = config.ApplicationID;
senderID = config.SenderID;
}
public bool SendToSingle(FCMDevice fcmdevice)
{
bool status = SendNotification(fcmdevice);
return status;
}
public bool SendToMultiple(List<FCMDevice> fcmdevices)
{
bool status = false;
foreach (var device in fcmdevices)
{
status = SendNotification(device);
}
return status;
}
private bool SendNotification(FCMDevice fcmdevices)
{
bool status = true;
try
{
var applicationID = appID;
var senderId = senderID;
WebRequest tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
tRequest.Method = "post";
tRequest.ContentType = "application/json";
var data = new
{
to = fcmdevices.DeviceToken,
priority = fcmdevices.Priority,
notification = new
{
body = fcmdevices.Message,
title = fcmdevices.Title
}
};
var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(data);
Byte[] byteArray = Encoding.UTF8.GetBytes(json);
tRequest.Headers.Add(string.Format("Authorization: key={0}", applicationID));
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();
JObject sResponse = JObject.Parse(sResponseFromServer);
if (Convert.ToInt32(sResponse["success"]) == 1)
{
status = true;
}
else
{
status = false;
}
}
}
}
}
}
catch (Exception ex)
{
status = false;
}
return status;
}
}
}