PushNotification.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. <?php
  2. namespace App\Components;
  3. use Exception;
  4. use Log;
  5. use stdClass;
  6. class PushNotification
  7. {
  8. public static function send($title, $content)
  9. {
  10. switch(Helpers::systemConfig()['is_notification']){
  11. case 'serverChan':
  12. return self::ServerChan($title, $content);
  13. break;
  14. case 'bark':
  15. return self::Bark($title, $content);
  16. break;
  17. default:
  18. }
  19. return FALSE;
  20. }
  21. /**
  22. * ServerChan推送消息
  23. *
  24. * @param string $title 消息标题
  25. * @param string $content 消息内容
  26. *
  27. * @return mixed
  28. */
  29. private static function ServerChan($title, $content)
  30. {
  31. $result = FALSE;
  32. try{
  33. // TODO:一天仅可发送不超过500条
  34. $url = 'https://sc.ftqq.com/'.Helpers::systemConfig()['server_chan_key'].'.send?text='.$title.'&desp='.urlencode($content);
  35. $result = json_decode(Curl::send($url));
  36. if(empty(Helpers::systemConfig()['server_chan_key'])){
  37. $result = new stdClass();
  38. $result->errno = TRUE;
  39. $result->errmsg = "未正确配置ServerChan";
  40. }
  41. if($result != NULL && !$result->errno){
  42. Helpers::addNotificationLog($title, $content, 2);
  43. }else{
  44. Helpers::addNotificationLog($title, $content, 2, 'admin', 1, $result? $result->errmsg : '未知');
  45. }
  46. } catch(Exception $e){
  47. Log::error('ServerChan消息推送异常:'.$e);
  48. }
  49. return $result;
  50. }
  51. /**
  52. * Bark推送消息
  53. *
  54. * @param string $title 消息标题
  55. * @param string $content 消息内容
  56. *
  57. * @return mixed
  58. */
  59. private static function Bark($title, $content)
  60. {
  61. $result = FALSE;
  62. try{
  63. $url = 'https://api.day.app/'.Helpers::systemConfig()['bark_key'].'/'.$title.'/'.$content;
  64. $result = json_decode(Curl::send($url));
  65. if($result){
  66. if($result->code == 200){
  67. Helpers::addNotificationLog($title, $content, 3);
  68. }else{
  69. Helpers::addNotificationLog($title, $content, 3, 'admin', $result->message);
  70. }
  71. }
  72. } catch(Exception $e){
  73. Log::error('Bark消息推送异常:'.$e);
  74. }
  75. return $result;
  76. }
  77. }