ServerChan.php 1.5 KB

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