WechatStateCache.php 899 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. <?php
  2. namespace App\Cache;
  3. use App\Libs\Utils;
  4. use Illuminate\Support\Facades\Redis;
  5. class WechatStateCache
  6. {
  7. /**
  8. * 写入扫码 state
  9. *
  10. * @param string $state
  11. * @param int $ttl 有效期(秒)
  12. * @return void
  13. */
  14. public static function set(string $state, int $ttl)
  15. {
  16. Redis::setex(Utils::getCacheKey('wechat.state', [$state]), $ttl, '1');
  17. }
  18. /**
  19. * 校验并消费 state(一次性)
  20. *
  21. * @param string $state
  22. * @return bool
  23. */
  24. public static function pull(string $state): bool
  25. {
  26. if ($state === '') {
  27. return false;
  28. }
  29. $cacheKey = Utils::getCacheKey('wechat.state', [$state]);
  30. $value = Redis::get($cacheKey);
  31. if ($value === null || $value === '') {
  32. return false;
  33. }
  34. Redis::del($cacheKey);
  35. return true;
  36. }
  37. }