cmbYouku_Api/app/service/util/SmsUtil.php

46 lines
1.2 KiB
PHP
Raw Normal View History

2024-07-01 15:57:07 +08:00
<?php
declare (strict_types=1);
namespace app\service\util;
use app\config\BusinessCacheKey;
use app\exception\BusinessException;
use think\helper\Str;
/**
* @author canny
* @date 2023/11/20 15:03
**/
class SmsUtil
{
public static function requestLimit($key, $expire, $limitSecond = 60)
{
$ttl = RedisService::getRedisInstance()->ttl($key);
if (!empty($ttl) && $expire - $ttl < $limitSecond) {
throw new BusinessException("请求过于频繁");
}
}
public static function getSmsCode(string $key, int $ttl): string
{
$redis = RedisService::getRedisInstance();
$redis->del($key);
$code = Str::random(6, 1);
$redis->set($key, $code, 'ex', $ttl);
return $code;
}
public static function compareSmsCode(string $codeCacheKey, $code)
{
$redis = RedisService::getRedisInstance();
$cacheCode = $redis->get($codeCacheKey);
if (empty($cacheCode) || $code != $cacheCode) {
throw new BusinessException("验证码错误");
}
$redis->del($codeCacheKey);
}
public static function getSmsKey($mobile): string
{
return BusinessCacheKey::SITE_SMS_CODE['key'] . ":" . $mobile;
}
}