ServerChan.php 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. }
  36. /**
  37. * 添加serverChan推送日志
  38. *
  39. * @param string $title 标题
  40. * @param string $content 内容
  41. * @param int $status 投递状态
  42. * @param string $error 投递失败时记录的异常信息
  43. *
  44. * @return int
  45. */
  46. private static function addLog($title, $content, $status = 1, $error = '')
  47. {
  48. $log = new EmailLog();
  49. $log->type = 2;
  50. $log->address = 'admin';
  51. $log->title = $title;
  52. $log->content = $content;
  53. $log->status = $status;
  54. $log->error = $error;
  55. return $log->save();
  56. }
  57. }