ServerChan.php 2.2 KB

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