jpush.net 封装jpush的封装
1 using Beyova.JPush; 2 using Beyova.JPush.V3; 3 using Beyova; 4 using Newtonsoft.Json; 5 using System; 6 using System.Collections.Generic; 7 using System.Configuration; 8 using System.Text; 9 using System.Net; 10 11 namespace JinLi.Mobile.API.Bll.Quartz 12 { 13 14 /// <summary> 15 ///三种推送方式 16 ///1.根据在极光官方注册的ID推送 17 /// 2.根据别名推送 18 ///3.根据标签或者标签组合推送 19 /// </summary> 20 public class JPushHelper 21 { 22 #region fields 23 private static JPushClientV3 jpushClient; 24 private static JPushInfo jpushInfo = null; 25 protected const string reportBaseUrlFormat = "https://report.jpush.cn/v2/"; 26 #endregion 27 #region ctor 28 static JPushHelper() 29 { 30 jpushInfo = new JPushInfo 31 { 32 AppKey = ConfigurationManager.AppSettings["AppKey"], 33 MasterSecret = ConfigurationManager.AppSettings["MasterSecret"] 34 }; 35 } 36 private static void Init() 37 { 38 jpushClient = new JPushClientV3(jpushInfo.AppKey, jpushInfo.MasterSecret); 39 } 40 #endregion 41 42 #region methods 43 /// <summary> 44 ///根据多个指定 注册ID推送 45 ///[ "4312kjklfds2", "8914afd2", "45fdsa31" ] 46 /// </summary> 47 /// <param name="registrationId">极光官网注册ID数组</param> 48 /// <param name="notification"></param> 49 /// <param name="customizedValues"></param> 50 /// <returns></returns> 51 public static OperationResult DoPushByRegistrationId( List<string> registrationIds, NotificationInfo notification) 52 { 53 if (jpushClient == null) 54 { 55 Init(); 56 } 57 58 Audience audience = new Audience(); 59 audience.Add(PushTypeV3.ByRegistrationId, registrationIds); 60 61 var response = jpushClient.SendPushMessage(new PushMessageRequestV3 62 { 63 Audience = audience, 64 Platform = PushPlatform.AndroidAndiOS, 65 IsTestEnvironment = true, 66 AppMessage = new AppMessage 67 { 68 Content = notification.Alert, 69 CustomizedValue = notification.CustomizedValues, 70 Title = notification.Title 71 }, 72 Notification = new Notification 73 { 74 AndroidNotification = new AndroidNotificationParameters 75 { 76 Title = notification.Title, 77 Alert = notification.Alert, 78 CustomizedValues = notification.CustomizedValues, 79 80 }, 81 iOSNotification = new iOSNotificationParameters 82 { 83 //新同志的条数 小红点 84 Badge =0, 85 Alert = notification.Alert, 86 Sound = "default", 87 CustomizedValues = notification.CustomizedValues 88 } 89 } 90 }); 91 var res = response.ResponseCode.ToString(); 92 if (res == "Succeed") 93 { 94 //System.Threading.Thread.Sleep(10000); 95 //发送成功 96 List<string> idToCheck = new List<string>(); 97 idToCheck.Add(response.MessageId); 98 99 var statusList =new JPushHelper().QueryPushMessageStatus(idToCheck); 100 if (statusList != null) 101 { 102 //foreach (var one in statusList) 103 //{ 104 // Console.WriteLine(string.Format("Id: {0}, Android: {1}, iOS: {2}", one.MessageId, one.AndroidDeliveredCount, one.ApplePushNotificationDeliveredCount)); 105 //} 106 return new OperationResult(OperationResultType.Success, "推送成功", statusList); 107 } 108 return new OperationResult(OperationResultType.Success, "推送成功", null); 109 } 110 return new OperationResult(OperationResultType.Success, "推送失败", null); 111 } 112 113 /// <summary> 114 /// 根据多个别名推送 115 /// [ "4314", "892", "4531" ] 116 /// </summary> 117 /// <param name="alias">别名数组</param> 118 /// <param name="notification"></param> 119 /// <param name="customizedValues"></param> 120 /// <returns></returns> 121 public static OperationResult DoPushByAlias( List<string> alias, NotificationInfo notification) 122 { 123 if (jpushClient == null) 124 Init(); 125 126 Audience audience = new Audience(); 127 audience.Add(PushTypeV3.ByTagWithinOr, alias); 128 audience.Add(PushTypeV3.ByAlias, alias); 129 130 var response = jpushClient.SendPushMessage(new PushMessageRequestV3 131 { 132 Audience = audience, 133 Platform = PushPlatform.All, 134 //AppMessage = new AppMessage 135 //{ 136 // Content = notification.Alert, 137 // CustomizedValue = notification.CustomizedValues, 138 // Title = notification.Title 139 //}, 140 Notification = new Notification 141 { 142 AndroidNotification = new AndroidNotificationParameters 143 { 144 Title = notification.Title, 145 Alert = notification.Alert, 146 CustomizedValues = notification.CustomizedValues 147 }, 148 iOSNotification = new iOSNotificationParameters 149 { 150 Badge = 1, 151 Alert = notification.Alert, 152 //Sound = "YourSound",//default 153 CustomizedValues = notification.CustomizedValues 154 } 155 }, 156 LifeTime = 86400, 157 IsTestEnvironment = true 158 }); 159 var res = response.ResponseCode.ToString(); 160 if (res == "Succeed") 161 { 162 //发送成功 163 List<string> idToCheck = new List<string>(); 164 int parseVal; 165 if (Int32.TryParse(response.MessageId, out parseVal)) 166 { 167 idToCheck.Add(response.MessageId); 168 } 169 else 170 { 171 return new OperationResult(OperationResultType.Success, "推送成功", null); 172 } 173 174 var statusList = new JPushHelper().QueryPushMessageStatus(idToCheck); 175 if (statusList != null) 176 { 177 //foreach (var one in statusList) 178 //{ 179 // Console.WriteLine(string.Format("Id: {0}, Android: {1}, iOS: {2}", one.MessageId, one.AndroidDeliveredCount, one.ApplePushNotificationDeliveredCount)); 180 //} 181 return new OperationResult(OperationResultType.Success, "推送成功", statusList); 182 } 183 return new OperationResult(OperationResultType.Success, "推送成功", null); 184 } 185 return new OperationResult(OperationResultType.Success, "推送失败", null); 186 } 187 188 /// <summary> 189 /// 根据多个标签推送(or关系) 190 /// "tag" : [ "深圳", "广州", "北京" ] 191 /// </summary> 192 /// <param name="tags">and标签数组</param> 193 /// <param name="notification"></param> 194 /// <param name="customizedValues"></param> 195 /// <returns></returns> 196 public static OperationResult DoPushByTagOr( List<string> tags, NotificationInfo notification) 197 { 198 if (jpushClient == null) 199 Init(); 200 201 Audience audience = new Audience(); 202 audience.Add(PushTypeV3.ByTagWithinOr, tags); 203 204 var response = jpushClient.SendPushMessage(new PushMessageRequestV3 205 { 206 Audience = audience, 207 Platform = PushPlatform.AndroidAndiOS, 208 IsTestEnvironment = true, 209 AppMessage = new AppMessage 210 { 211 Content = notification.Alert, 212 CustomizedValue = notification.CustomizedValues, 213 Title = notification.Title 214 }, 215 Notification = new Notification 216 { 217 AndroidNotification = new AndroidNotificationParameters 218 { 219 Title = notification.Title, 220 Alert = notification.Alert, 221 CustomizedValues = notification.CustomizedValues 222 }, 223 iOSNotification = new iOSNotificationParameters 224 { 225 Badge = 1, 226 Alert = notification.Alert, 227 //Sound = "YourSound",//default 228 CustomizedValues = notification.CustomizedValues 229 } 230 } 231 }); 232 var res = response.ResponseCode.ToString(); 233 if (res == "Succeed") 234 { 235 //发送成功 236 List<string> idToCheck = new List<string>(); 237 idToCheck.Add(response.MessageId); 238 239 var statusList =new JPushHelper().QueryPushMessageStatus(idToCheck); 240 if (statusList != null) 241 { 242 //foreach (var one in statusList) 243 //{ 244 // Console.WriteLine(string.Format("Id: {0}, Android: {1}, iOS: {2}", one.MessageId, one.AndroidDeliveredCount, one.ApplePushNotificationDeliveredCount)); 245 //} 246 return new OperationResult(OperationResultType.Success, "推送成功", statusList); 247 } 248 return new OperationResult(OperationResultType.Success, "推送成功", null); 249 } 250 return new OperationResult(OperationResultType.Success, "推送失败", null); 251 } 252 253 254 /// <summary> 255 /// 根据多个标签推送(And关系) 256 /// 可同时推送指定多类推送目标:在深圳或者广州,并且是 “女” “会员” 257 /// "tag" : [ "深圳", "广州" ] 258 /// "tag_and" : [ "女", "会员"] 259 /// </summary> 260 /// <param name="alias">or标签数组</param> 261 /// <param name="tagsAnd">and 标签数组</param> 262 /// <param name="notification">推送notif信息</param> 263 /// <param name="customizedValues"></param> 264 /// <returns></returns> 265 public static OperationResult DoPushByTagAndTag( List<string> tags, List<string> tagsAnd, NotificationInfo notification) 266 { 267 if (jpushClient == null) 268 Init(); 269 270 Audience audience = new Audience(); 271 audience.Add(PushTypeV3.ByTagWithinOr, tags); 272 audience.Add(PushTypeV3.ByTagWithinAnd, tagsAnd); 273 274 var response = jpushClient.SendPushMessage(new PushMessageRequestV3 275 { 276 Audience = audience, 277 Platform = PushPlatform.AndroidAndiOS, 278 IsTestEnvironment = true, 279 AppMessage = new AppMessage 280 { 281 Content = notification.Alert, 282 CustomizedValue = notification.CustomizedValues, 283 Title = notification.Title 284 }, 285 Notification = new Notification 286 { 287 AndroidNotification = new AndroidNotificationParameters 288 { 289 Title = notification.Title, 290 Alert = notification.Alert, 291 CustomizedValues = notification.CustomizedValues 292 }, 293 iOSNotification = new iOSNotificationParameters 294 { 295 Badge = 1, 296 Alert = notification.Alert, 297 //Sound = "YourSound",//default 298 CustomizedValues = notification.CustomizedValues 299 } 300 } 301 }); 302 var res = response.ResponseCode.ToString(); 303 if (res == "Succeed") 304 { 305 //发送成功 306 List<string> idToCheck = new List<string>(); 307 308 idToCheck.Add(response.MessageId); 309 310 var statusList = new JPushHelper().QueryPushMessageStatus(idToCheck); 311 if (statusList != null) 312 { 313 //foreach (var one in statusList) 314 //{ 315 // Console.WriteLine(string.Format("Id: {0}, Android: {1}, iOS: {2}", one.MessageId, one.AndroidDeliveredCount, one.ApplePushNotificationDeliveredCount)); 316 //} 317 return new OperationResult(OperationResultType.Success, "推送成功", statusList); 318 } 319 return new OperationResult(OperationResultType.Success, "推送成功", null); 320 } 321 return new OperationResult(OperationResultType.Success, "推送失败", null); 322 } 323 324 325 /// <summary> 326 /// 推送给多个标签 327 /// (需要同时在多个标签范围内):在深圳并且是“女” 328 /// "tag_and" : [ "深圳", "女" ] 329 /// </summary> 330 /// <param name="tags">and标签数组</param> 331 /// <param name="notification"></param> 332 /// <param name="customizedValues"></param> 333 /// <returns></returns> 334 public static OperationResult DoPushByTagAnd( List<string> tags, NotificationInfo notification) 335 { 336 if (jpushClient == null) 337 Init(); 338 339 Audience audience = new Audience(); 340 audience.Add(PushTypeV3.ByTagWithinAnd, tags); 341 342 var response = jpushClient.SendPushMessage(new PushMessageRequestV3 343 { 344 Audience = audience, 345 Platform = PushPlatform.AndroidAndiOS, 346 IsTestEnvironment = true, 347 AppMessage = new AppMessage 348 { 349 Content = notification.Alert, 350 CustomizedValue = notification.CustomizedValues, 351 Title = notification.Title 352 }, 353 Notification = new Notification 354 { 355 AndroidNotification = new AndroidNotificationParameters 356 { 357 Title = notification.Title, 358 Alert = notification.Alert, 359 CustomizedValues = notification.CustomizedValues 360 }, 361 iOSNotification = new iOSNotificationParameters 362 { 363 Badge = 1, 364 Alert = notification.Alert, 365 //Sound = "YourSound",//default 366 CustomizedValues = notification.CustomizedValues 367 } 368 } 369 }); 370 var res = response.ResponseCode.ToString(); 371 if (res == "Succeed") 372 { 373 //发送成功 374 List<string> idToCheck = new List<string>(); 375 376 idToCheck.Add(response.MessageId); 377 378 var statusList = new JPushHelper().QueryPushMessageStatus(idToCheck); 379 if (statusList != null) 380 { 381 return new OperationResult(OperationResultType.Success, "推送成功", statusList); 382 } 383 return new OperationResult(OperationResultType.Success, "推送成功", null); 384 } 385 return new OperationResult(OperationResultType.Success, "推送失败", null); 386 } 387 388 389 390 public List<PushMessageStatus> QueryPushMessageStatus(List<string> messageIdCollection) 391 { 392 // JPush has limitation officially. One query support no more than 100 IDs. 393 const int limitation = 100; 394 395 List<PushMessageStatus> result = new List<PushMessageStatus>(); 396 397 string idCollection = string.Empty; 398 399 if (messageIdCollection.HasItem()) 400 { 401 if (messageIdCollection.Count > limitation) 402 { 403 messageIdCollection.RemoveRange(limitation, messageIdCollection.Count - limitation); 404 } 405 406 idCollection = string.Join(",", messageIdCollection); 407 } 408 409 if (!string.IsNullOrWhiteSpace(idCollection)) 410 { 411 try 412 { 413 var httpRequest = CreatePushQueryRequest(idCollection); 414 var responseBody = httpRequest.ReadResponseAsText(Encoding.UTF8); 415 result = JsonConvert.DeserializeObject<List<PushMessageStatus>>(responseBody); 416 } 417 catch (Exception ex) 418 { 419 throw ex.Handle(messageIdCollection); 420 } 421 } 422 423 return result; 424 } 425 426 427 /// <summary> 428 /// Creates the push query request. 429 /// </summary> 430 /// <param name="idCollectionString">The unique identifier collection string.</param> 431 /// <returns>HttpWebRequest.</returns> 432 private HttpWebRequest CreatePushQueryRequest(string idCollectionString) 433 { 434 var httpRequest = (reportBaseUrlFormat + "received?msg_ids=" + idCollectionString.SafeToString()).CreateHttpWebRequest(HttpConstants.HttpMethod.Get); 435 FillAuthentication(httpRequest); 436 437 return httpRequest; 438 } 439 440 /// <summary> 441 /// Fills the authentication. 442 /// </summary> 443 /// <param name="httpRequest">The HTTP request.</param> 444 private void FillAuthentication(HttpWebRequest httpRequest) 445 { 446 if (httpRequest != null) 447 { 448 httpRequest.Headers[HttpRequestHeader.Authorization] = GenerateQueryToken(jpushInfo.AppKey.SafeToString(), jpushInfo.MasterSecret.SafeToString()); 449 FillNetworkCredential(httpRequest); 450 } 451 } 452 protected static string GenerateQueryToken(string appKey, string masterSecret) 453 { 454 return string.Format("{0}:{1}", appKey, masterSecret).EncodeBase64(); 455 } 456 457 458 459 protected void FillNetworkCredential(HttpWebRequest httpRequest) 460 { 461 if (httpRequest != null) 462 { 463 httpRequest.Credentials = new NetworkCredential(jpushInfo.AppKey.SafeToString(), jpushInfo.MasterSecret.SafeToString()); 464 } 465 } 466 #endregion 467 468 } 469 470 471 472 473 474 475 public class OperationResult 476 { 477 private OperationResultType enumResult; 478 private string message; 479 private List<PushMessageStatus> pushMessageStatus; 480 481 public OperationResult(OperationResultType enumResult, string message, List<PushMessageStatus> pushMessageStatus) 482 { 483 this.enumResult = enumResult; 484 this.message = message; 485 this.pushMessageStatus = pushMessageStatus; 486 } 487 } 488 489 490 public enum OperationResultType 491 { 492 Success = 1, 493 Fail = 2, 494 Exception = 3 495 } 496 497 498 /// <summary> 499 /// 提示信息 500 /// </summary> 501 public class NotificationInfo 502 { 503 public string Title { get; set; } 504 public string Alert { get; set; } 505 public Dictionary<string, object> CustomizedValues { get; set; } 506 //customizedValues.Add("CK1", "CV1"); 507 // customizedValues.Add("CK2", "CV2"); 508 509 510 } 511 512 /// <summary> 513 /// 极光appKey和secret 514 /// </summary> 515 public class JPushInfo 516 { 517 public string AppKey { get; set; } 518 public string MasterSecret { get; set; } 519 } 520 521 522 523 // 524 // 摘要: 525 // Class PushMessageStatus. 526 public class PushMessageStatus 527 { 528 529 530 // 531 // 摘要: 532 // Gets or sets the message unique identifier. This value is decided by JPush Service. 533 [JsonProperty(PropertyName = "msg_id")] 534 public string MessageId { get; set; } 535 // 536 // 摘要: 537 // Gets or sets the android delivered count. 538 [JsonProperty(PropertyName = "android_received")] 539 public int? AndroidDeliveredCount { get; set; } 540 // 541 // 摘要: 542 // Gets or sets the apple push notification delivered count. 543 [JsonProperty(PropertyName = "ios_apns_sent")] 544 public int? ApplePushNotificationDeliveredCount { get; set; } 545 } 546 547 548 549 }
已经经过测试 可以直接运行
调用示例
var dictionary = new Dictionary<string, object>();
dictionary.Add("id","123");
dictionary.Add("content","this is content");
JPushHelper.DoPushByRegistrationId(new List<string> { "registrationid1" ,"registrationid2"},new NotificationInfo { Alert = "alerttest", Title = "titletest", CustomizedValues= dictionary });

浙公网安备 33010602011771号