PushNotification.php 2.3 KB

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