SmsVerification.Class.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <?php
  2. namespace Jindouyun\Cache;
  3. use http\Exception;
  4. use Mall\Framework\Factory;
  5. use Mall\Framework\Core\ResultWrapper;
  6. use Mall\Framework\Core\ErrorCode;
  7. class SmsVerification
  8. {
  9. private $cache;
  10. protected $registerSmsCountKey = 'registerSmsCount_'; //当天每个手机号发送验证码次数
  11. protected $key = '';
  12. protected $userRegisterSmsCodeExpire = 300;//短信验证码过期时间
  13. protected $registerSms = 'registerSms'; //当前手机号发送的验证码
  14. public function __construct()
  15. {
  16. $this->key = $this->registerSmsCountKey . date('Y-m-d', time());
  17. $this->cache = Factory::cache('default');
  18. }
  19. /**
  20. * 缓存用户注册时发送的短信验证码
  21. * @param $mobile
  22. * @param $mobileCode
  23. * @return ResultWrapper
  24. */
  25. public function userMobileCodeCache($mobile, $mobileCode)
  26. {
  27. if (empty($mobileCode)) {
  28. return ResultWrapper::fail('要缓存的数据为空', ErrorCode::$paramError);
  29. }
  30. $result = $this->cache->set($this->registerSms . '::' . $mobile, $mobileCode, $this->userRegisterSmsCodeExpire);
  31. if ($result) {
  32. //增加当天用户发送短信次数
  33. $returnData = $this->cache->zincrby($this->key, 1, $mobile);
  34. if ($returnData) {
  35. $this->cache->expire($this->key, 86400);
  36. }
  37. return ResultWrapper::success('用户注册手机验证码写入缓存成功');
  38. } else {
  39. return ResultWrapper::fail('用户注册手机验证码写入缓存失败', ErrorCode::$redisWriteError);
  40. }
  41. }
  42. /**
  43. * 获取指定手机号的短信验证码
  44. * @param $mobile
  45. * @return string
  46. * @throws \Exception
  47. */
  48. public function getMobileCode($mobile)
  49. {
  50. if (!$mobile) {
  51. return '';
  52. }
  53. $result = Factory::cache('default')->get($this->registerSms . '::' . $mobile);
  54. if (!$result) {
  55. return '';
  56. }
  57. return $result;
  58. }
  59. /**
  60. * 查询当天用户发送短信次数
  61. * @param $mobile
  62. * @return mixed
  63. */
  64. public function getRegisterSmsCount($mobile)
  65. {
  66. return $this->cache->zscore($this->key, $mobile);
  67. }
  68. }