PushNotification.php 1.8 KB

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