ServerChan.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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 $systemConfig;
  12. function __construct()
  13. {
  14. self::$systemConfig = Helpers::systemConfig();
  15. }
  16. /**
  17. * @param string $title 消息标题
  18. * @param string $content 消息内容
  19. *
  20. * @return string
  21. */
  22. public function send($title, $content)
  23. {
  24. $client = new Client();
  25. try {
  26. $response = $client->request('GET', 'https://sc.ftqq.com/' . self::$systemConfig['server_chan_key'] . '.send', [
  27. 'query' => [
  28. 'text' => $title,
  29. 'desp' => $content
  30. ]
  31. ]);
  32. $result = json_decode($response->getBody());
  33. if (!$result->errno) {
  34. $this->addEmailLog(1, '[ServerChan]' . $title, $content);
  35. } else {
  36. $this->addEmailLog(1, '[ServerChan]' . $title, $content, 0, $result->errmsg);
  37. }
  38. } catch (RequestException $e) {
  39. Log::error(Psr7\str($e->getRequest()));
  40. if ($e->hasResponse()) {
  41. Log::error(Psr7\str($e->getResponse()));
  42. }
  43. }
  44. }
  45. /**
  46. * 写入邮件发送日志
  47. *
  48. * @param int $user_id 用户ID
  49. * @param string $title 标题
  50. * @param string $content 内容
  51. * @param int $status 投递状态
  52. * @param string $error 投递失败时记录的异常信息
  53. */
  54. private function addEmailLog($user_id, $title, $content, $status = 1, $error = '')
  55. {
  56. $emailLogObj = new EmailLog();
  57. $emailLogObj->user_id = $user_id;
  58. $emailLogObj->title = $title;
  59. $emailLogObj->content = $content;
  60. $emailLogObj->status = $status;
  61. $emailLogObj->error = $error;
  62. $emailLogObj->created_at = date('Y-m-d H:i:s');
  63. $emailLogObj->save();
  64. }
  65. }