22
33namespace App \Components ;
44
5+ use App \Http \Models \Config ;
6+ use App \Http \Models \EmailLog ;
57use GuzzleHttp \Client ;
68use GuzzleHttp \Psr7 ;
79use GuzzleHttp \Exception \RequestException ;
810use Log ;
911
1012class ServerChan
1113{
14+ protected static $ config ;
15+
16+ function __construct ()
17+ {
18+ self ::$ config = $ this ->systemConfig ();
19+ }
20+
1221 /**
1322 * @param string $title 消息标题
1423 * @param string $content 消息内容
15- * @param string $key ServerChan上申请的SCKEY
1624 * @return string
1725 */
18- public function send ($ title , $ content, $ key )
26+ public function send ($ title , $ content )
1927 {
2028 $ client = new Client ();
2129
2230 try {
23- $ response = $ client ->request ('GET ' , 'https://sc.ftqq.com/ ' . $ key . '.send ' , [
31+ $ response = $ client ->request ('GET ' , 'https://sc.ftqq.com/ ' . self :: $ config [ ' server_chan_key ' ] . '.send ' , [
2432 'query ' => [
2533 'text ' => $ title ,
2634 'desp ' => $ content
2735 ]
2836 ]);
2937
30- return json_decode ($ response ->getBody ());
38+ $ result = json_decode ($ response ->getBody ());
39+ if ($ result ->errno > 0 ) {
40+ $ this ->sendEmailLog (1 , '[ServerChan] ' . $ title , $ content );
41+ } else {
42+ $ this ->sendEmailLog (1 , '[ServerChan] ' . $ title , $ content , 0 , $ result ->errmsg );
43+ }
3144 } catch (RequestException $ e ) {
3245 Log ::error (Psr7 \str ($ e ->getRequest ()));
3346 if ($ e ->hasResponse ()) {
3447 Log ::error (Psr7 \str ($ e ->getResponse ()));
3548 }
3649 }
3750 }
51+
52+ /**
53+ * 写入邮件发送日志
54+ *
55+ * @param int $user_id 用户ID
56+ * @param string $title 标题
57+ * @param string $content 内容
58+ * @param int $status 投递状态
59+ * @param string $error 投递失败时记录的异常信息
60+ */
61+ private function sendEmailLog ($ user_id , $ title , $ content , $ status = 1 , $ error = '' )
62+ {
63+ $ emailLogObj = new EmailLog ();
64+ $ emailLogObj ->user_id = $ user_id ;
65+ $ emailLogObj ->title = $ title ;
66+ $ emailLogObj ->content = $ content ;
67+ $ emailLogObj ->status = $ status ;
68+ $ emailLogObj ->error = $ error ;
69+ $ emailLogObj ->created_at = date ('Y-m-d H:i:s ' );
70+ $ emailLogObj ->save ();
71+ }
72+
73+ // 系统配置
74+ private function systemConfig ()
75+ {
76+ $ config = Config ::query ()->get ();
77+ $ data = [];
78+ foreach ($ config as $ vo ) {
79+ $ data [$ vo ->name ] = $ vo ->value ;
80+ }
81+
82+ return $ data ;
83+ }
3884}
0 commit comments