ServerChan.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. namespace App\Components;
  3. use App\Http\Models\EmailLog;
  4. use GuzzleHttp\Client;
  5. use GuzzleHttp\Psr7;
  6. use GuzzleHttp\Exception\RequestException;
  7. use Log;
  8. class ServerChan
  9. {
  10. protected static $systemConfig;
  11. function __construct()
  12. {
  13. self::$systemConfig = Helpers::systemConfig();
  14. }
  15. /**
  16. * 推送消息
  17. *
  18. * @param string $title 消息标题
  19. * @param string $content 消息内容
  20. *
  21. * @return mixed
  22. * @throws \GuzzleHttp\Exception\GuzzleException
  23. */
  24. public static function send($title, $content)
  25. {
  26. $client = new Client();
  27. try {
  28. $response = $client->request('GET', 'https://sc.ftqq.com/' . self::$systemConfig['server_chan_key'] . '.send', [
  29. 'query' => [
  30. 'text' => $title,
  31. 'desp' => $content
  32. ]
  33. ]);
  34. $result = json_decode($response->getBody());
  35. if (!$result->errno) {
  36. self::addlog($title, $content);
  37. } else {
  38. self::addlog($title, $content, 0, $result->errmsg);
  39. }
  40. } catch (RequestException $e) {
  41. Log::error(Psr7\str($e->getRequest()));
  42. if ($e->hasResponse()) {
  43. Log::error(Psr7\str($e->getResponse()));
  44. }
  45. }
  46. }
  47. /**
  48. * 添加serverChan投递日志
  49. *
  50. * @param string $title 标题
  51. * @param string $content 内容
  52. * @param int $status 投递状态
  53. * @param string $error 投递失败时记录的异常信息
  54. *
  55. * @return int
  56. */
  57. private static function addlog($title, $content, $status = 1, $error = '')
  58. {
  59. $log = new EmailLog();
  60. $log->type = 2;
  61. $log->address = 'admin';
  62. $log->title = $title;
  63. $log->content = $content;
  64. $log->status = $status;
  65. $log->error = $error;
  66. $log->created_at = date('Y-m-d H:i:s');
  67. return $log->save();
  68. }
  69. }