RequestTokenService.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * Name: 芸众商城系统
  5. * Author: 广州市芸众信息科技有限公司
  6. * Profile: 广州市芸众信息科技有限公司位于国际商贸中心的广州,专注于移动电子商务生态系统打造,拥有芸众社交电商系统、区块链数字资产管理系统、供应链管理系统、电子合同等产品/服务。官网 :www.yunzmall.com www.yunzshop.com
  7. * Date: 2021/11/24
  8. * Time: 17:30
  9. */
  10. namespace app\common\services;
  11. use Illuminate\Support\Facades\Redis;
  12. class RequestTokenService
  13. {
  14. /**
  15. * 规定时间内不能再次请求,时间单位:s
  16. * @param $key
  17. * @param int $second
  18. * @return bool false 不可以 true 可以
  19. */
  20. public static function limitRepeat($key, $second = 10)
  21. {
  22. $code = \YunShop::app()->uniacid."_{$key}";
  23. $token = Redis::exists($code);
  24. if ($token) {
  25. return false;
  26. }
  27. Redis::setex($code, $second,$key);
  28. return true;
  29. }
  30. /**
  31. * @param $key
  32. * @param int $time
  33. * @return string
  34. */
  35. public static function getRequestToken($key,$time = 120)
  36. {
  37. $key .= \YunShop::app()->uniacid;
  38. $token = Redis::get($key);
  39. if ($token) {
  40. return false; //这个token还在,返回错误
  41. }
  42. $token = self::getRandomStr();
  43. Redis::setex($key , $time, $token);
  44. return $token;
  45. }
  46. public static function checkRequestToken($key,$token)
  47. {
  48. $key .= \YunShop::app()->uniacid;
  49. $hasToken = Redis::get($key);
  50. if (!$hasToken || $hasToken != $token) {
  51. return false;
  52. }
  53. return true;
  54. }
  55. public static function delRequestToken($key)
  56. {
  57. $key .= \YunShop::app()->uniacid;
  58. Redis::del($key);
  59. }
  60. /**
  61. * 获取$length长度的随机字符串
  62. * @param int $length
  63. * @return string
  64. */
  65. private static function getRandomStr($length = 32)
  66. {
  67. $str = '1234567890abcdefghijklmnopqrstuvwxyz';
  68. $result = '';
  69. for ($i=1;$i<=$length;$i++) {
  70. $result .= substr($str,rand(0,(strlen($str)-1)),1);
  71. }
  72. return $result.time();
  73. }
  74. }