PushNotification.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. return FALSE;
  19. }
  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. $ret = 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. $ret = TRUE;
  44. }else{
  45. Helpers::addNotificationLog($title, $content, 2, 'admin', 1, $result? $result->errmsg : '未知');
  46. }
  47. }catch(Exception $e){
  48. Log::error('ServerChan消息推送异常:'.$e);
  49. }
  50. return $ret;
  51. }
  52. /**
  53. * Bark推送消息
  54. *
  55. * @param string $title 消息标题
  56. * @param string $content 消息内容
  57. *
  58. * @return mixed
  59. */
  60. private static function Bark($title, $content)
  61. {
  62. $ret = FALSE;
  63. try{
  64. $url = 'https://api.day.app/'.Helpers::systemConfig()['bark_key'].'/'.$title.'/'.$content;
  65. $result = json_decode(Curl::send($url));
  66. if($result){
  67. if($result->code == 200){
  68. Helpers::addNotificationLog($title, $content, 3);
  69. $ret = TRUE;
  70. }else{
  71. Helpers::addNotificationLog($title, $content, 3, 'admin', $result->message);
  72. }
  73. }
  74. }catch(Exception $e){
  75. Log::error('Bark消息推送异常:'.$e);
  76. }
  77. return $ret;
  78. }
  79. }