PushNotification.php 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. <?php
  2. namespace App\Components;
  3. use Cache;
  4. use Http;
  5. use Log;
  6. class PushNotification
  7. {
  8. public static function send(string $title, string $content)
  9. {
  10. switch (sysConfig('is_notification')) {
  11. case 'serverChan':
  12. return self::ServerChan($title, $content);
  13. case 'bark':
  14. return self::Bark($title, $content);
  15. default:
  16. return false;
  17. }
  18. }
  19. /**
  20. * ServerChan推送消息.
  21. *
  22. * @param string $title 消息标题
  23. * @param string $content 消息内容
  24. *
  25. * @return mixed
  26. */
  27. private static function ServerChan(string $title, string $content)
  28. {
  29. $cacheKey = 'serverChanCount'.date('d');
  30. if (Cache::has($cacheKey)) {
  31. Cache::increment($cacheKey);
  32. } else {
  33. Cache::put($cacheKey, 1, Day); // 24小时
  34. }
  35. // 一天仅可发送不超过500条
  36. if (Cache::get($cacheKey) < 500) {
  37. $response = Http::timeout(15)->get('https://sc.ftqq.com/'.sysConfig('server_chan_key').'.send?text='.$title.'&desp='.urlencode($content));
  38. } else {
  39. Log::error('ServerChan消息推送异常:今日500条限额已耗尽!');
  40. return false;
  41. }
  42. // 发送成功
  43. if ($response->ok()) {
  44. $message = $response->json();
  45. if (! $message['errno']) {
  46. Helpers::addNotificationLog($title, $content, 2);
  47. return $message;
  48. }
  49. // 发送失败
  50. Helpers::addNotificationLog($title, $content, 2, 'admin', -1, $message ? $message['errmsg'] : '未知');
  51. return false;
  52. }
  53. // 发送错误
  54. Log::error('ServerChan消息推送异常:'.var_export($response, true));
  55. return false;
  56. }
  57. /**
  58. * Bark推送消息.
  59. *
  60. * @param string $title 消息标题
  61. * @param string $content 消息内容
  62. *
  63. * @return mixed
  64. */
  65. private static function Bark(string $title, string $content)
  66. {
  67. $response = Http::timeout(15)->get('https://api.day.app/'.sysConfig('bark_key').'/'.$title.'/'.$content);
  68. if ($response->ok()) {
  69. $message = $response->json();
  70. // 发送成功
  71. if ($message['code'] === 200) {
  72. Helpers::addNotificationLog($title, $content, 3);
  73. return $message;
  74. }
  75. // 发送失败
  76. Helpers::addNotificationLog($title, $content, 3, 'admin', -1, $message);
  77. return false;
  78. }
  79. // 发送错误
  80. Log::error('Bark消息推送异常:'.var_export($response, true));
  81. return false;
  82. }
  83. }