ServerChanChannel.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. <?php
  2. namespace App\Channels;
  3. use Cache;
  4. use Helpers;
  5. use Http;
  6. use Illuminate\Notifications\Notification;
  7. use Log;
  8. class ServerChanChannel
  9. {
  10. public function send($notifiable, Notification $notification)
  11. {
  12. $message = $notification->toCustom($notifiable);
  13. $cacheDayKey = 'serverChanCountDays';
  14. $cacheMinuteKey = 'serverChanCountMinutes';
  15. if (Cache::has($cacheDayKey)) {
  16. Cache::increment($cacheDayKey);
  17. } else {
  18. Cache::put($cacheDayKey, 1, Day); // 天限制
  19. }
  20. if (Cache::has($cacheMinuteKey)) {
  21. Cache::increment($cacheMinuteKey);
  22. } else {
  23. Cache::put($cacheMinuteKey, 1, Minute); // 分钟限制
  24. }
  25. if (Cache::get($cacheDayKey) < 1000) { // 订阅会员 一天仅可发送不超过1000条
  26. if (Cache::get($cacheMinuteKey) < 5) {
  27. $response = Http::timeout(15)
  28. ->post('https://sctapi.ftqq.com/'.sysConfig('server_chan_key').'.send?title='.urlencode($message['title']).'&desp='.urlencode($message['content']));
  29. } else {
  30. Log::critical('[ServerChan] 消息推送异常:分钟频率过高,请优化通知场景!');
  31. return false;
  32. }
  33. } else {
  34. Log::critical('[ServerChan] 消息推送异常:今日限额已耗尽!');
  35. return false;
  36. }
  37. // 发送成功
  38. if ($response->ok()) {
  39. $ret = $response->json();
  40. if (! $ret['errno']) {
  41. Helpers::addNotificationLog($message['title'], $message['content'], 2);
  42. return $ret;
  43. }
  44. // 发送失败
  45. Helpers::addNotificationLog($message['title'], $message['content'], 2, -1, $ret ? $ret['errmsg'] : '未知');
  46. return false;
  47. }
  48. // 发送错误
  49. Log::critical('[ServerChan] 消息推送异常:'.var_export($response, true));
  50. return false;
  51. }
  52. }