Forked from rbravo/Expo_Push_Notifications_Helper.cs
Created
August 17, 2018 22:38
-
-
Save dp-la/0fb73738f018f5367040acd748c40e68 to your computer and use it in GitHub Desktop.
Expo.io Push Notifications Send Through C#
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ExpoPushHelper | |
{ | |
public class MyWebClient : WebClient | |
{ | |
protected override WebRequest GetWebRequest(Uri address) | |
{ | |
HttpWebRequest request = base.GetWebRequest(address) as HttpWebRequest; | |
request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip; | |
return request; | |
} | |
} | |
internal class UnderscoreContractResolver : DefaultContractResolver | |
{ | |
protected override string ResolvePropertyName(string propertyName) | |
{ | |
return Regex.Replace(propertyName, "(?<=[a-z])[A-Z]", m => "_" + m).ToLower(); | |
} | |
} | |
public class ExpoResponseData | |
{ | |
public ExpoResponse Data { get; set; } | |
} | |
public class ExpoResponseBulkData | |
{ | |
public List<ExpoResponse> Data { get; set; } | |
} | |
public class ExpoResponse | |
{ | |
public string Status { get; set; } | |
public string Message { get; set; } | |
public DetailsError Details { get; set; } | |
} | |
public class DetailsError | |
{ | |
public string Error { get; set; } | |
} | |
public static dynamic SendPushNotification(string ExpoToken) | |
{ | |
dynamic body = new | |
{ | |
to = ExpoToken, | |
title = "hello", | |
body = "world", | |
sound = "default", | |
data = new { some = "daaaata" } | |
}; | |
string response = null; | |
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; | |
using (MyWebClient client = new MyWebClient()) | |
{ | |
client.Encoding = System.Text.Encoding.UTF8; | |
client.Headers.Add("accept", "application/json"); | |
client.Headers.Add("accept-encoding", "gzip, deflate"); | |
client.Headers.Add("Content-Type", "application/json"); | |
response = client.UploadString("https://exp.host/--/api/v2/push/send", JsonExtensions.ToJson(body)); | |
} | |
ExpoResponseData results = JsonConvert.DeserializeObject<ExpoResponseData>(response, | |
new JsonSerializerSettings { ContractResolver = new UnderscoreContractResolver() }); | |
if (results.Data.Status.ToLower() == "ok") | |
return "ok"; | |
else if (response.ToLower().Contains("devicenotregistered")) | |
{ | |
//remove this key in your DB | |
//await DeleteRegistrationExpoAsync(expoToken); | |
} | |
else if (response.ToLower().Contains("unable to retrieve the fcm server key")) | |
{ | |
//await DeleteRegistrationExpoAsync(expoToken); | |
return "FCM server key error, removing"; | |
} | |
return response; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment