ServerChan.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. namespace App\Components;
  3. use App\Http\Models\EmailLog;
  4. use Log;
  5. class ServerChan
  6. {
  7. /**
  8. * 推送消息
  9. *
  10. * @param string $title 消息标题
  11. * @param string $content 消息内容
  12. *
  13. * @return mixed
  14. */
  15. public static function send($title, $content)
  16. {
  17. if (Helpers::systemConfig()['is_server_chan'] && Helpers::systemConfig()['server_chan_key']) {
  18. try {
  19. // TODO:一天仅可发送不超过500条
  20. $url = 'https://sc.ftqq.com/' . Helpers::systemConfig()['server_chan_key'] . '.send?text=' . $title . '&desp=' . urlencode($content);
  21. $response = Curl::send($url);
  22. $result = json_decode($response);
  23. if (!$result->errno) {
  24. self::addLog($title, $content);
  25. } else {
  26. self::addLog($title, $content, 0, $result->errmsg);
  27. }
  28. } catch (\Exception $e) {
  29. Log::error('ServerChan消息推送异常:' . $e);
  30. }
  31. } else {
  32. Log::error('消息推送失败:未启用或未正确配置ServerChan');
  33. }
  34. }
  35. /**
  36. * 添加serverChan推送日志
  37. *
  38. * @param string $title 标题
  39. * @param string $content 内容
  40. * @param int $status 投递状态
  41. * @param string $error 投递失败时记录的异常信息
  42. *
  43. * @return int
  44. */
  45. private static function addLog($title, $content, $status = 1, $error = '')
  46. {
  47. $log = new EmailLog();
  48. $log->type = 2;
  49. $log->address = 'admin';
  50. $log->title = $title;
  51. $log->content = $content;
  52. $log->status = $status;
  53. $log->error = $error;
  54. return $log->save();
  55. }
  56. }