You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
75 lines
1.5 KiB
75 lines
1.5 KiB
<?php
|
|
|
|
namespace app\util;
|
|
|
|
use fast\FuncException;
|
|
use think\facade\Cache;
|
|
|
|
class AuthCodeUtil
|
|
{
|
|
//redis连接
|
|
private $cache;
|
|
//验证码的保存秒数,600秒,即:10分钟
|
|
private $ttl = 600;
|
|
|
|
//构造
|
|
public function __construct($cache)
|
|
{
|
|
$this->cache = $cache;
|
|
}
|
|
|
|
//生成code保存到redis,并返回code
|
|
public function setCode($mobile)
|
|
{
|
|
$key = "Auth:" . $mobile;
|
|
$code = $this->newAuthCode();
|
|
$this->cache->set($key, $code, $this->ttl);
|
|
return $code;
|
|
}
|
|
|
|
/**
|
|
* 校对验证码
|
|
* @param $mobile
|
|
* @param $code
|
|
* @return bool
|
|
*/
|
|
public function verifyCode($mobile, $code): bool
|
|
{
|
|
$key = "Auth:" . $mobile;
|
|
$cacheCode = $this->cache->get($key);
|
|
if ($cacheCode == $code) {
|
|
return true;
|
|
} else {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
/**
|
|
*
|
|
* @return int
|
|
*/
|
|
public function newAuthCode(): int
|
|
{
|
|
return rand(100000, 999999);
|
|
}
|
|
|
|
/**
|
|
* @param $mobile
|
|
* @return bool
|
|
* @throws FuncException
|
|
*/
|
|
public function setRate($mobile): bool
|
|
{
|
|
$key = "Auth:" . $mobile;
|
|
$cacheCode = $this->cache->get($key);
|
|
|
|
if ($cacheCode) {
|
|
$ttl = Cache::store('redis')->ttl($key);
|
|
if (($this->ttl - $ttl) < 60) {
|
|
throw new FuncException('请超过60秒之后再发送短信');
|
|
}
|
|
}
|
|
|
|
return true;
|
|
}
|
|
}
|