cmbYouku_Api/app/service/util/CaptchaUtil.php

48 lines
1.2 KiB
PHP
Raw Permalink Normal View History

2024-07-01 15:57:07 +08:00
<?php
declare (strict_types=1);
namespace app\service\util;
use think\captcha\facade\Captcha;
/**
* @author canny
* @date 2024/1/3 16:06
**/
class CaptchaUtil
{
const CAPTCHA_CACHE_KEY = 'captcha:';
const CACHE_TTL = 1800;
public static function create($sceneConfig = ''): array
{
$res = Captcha::create($sceneConfig);
$base64Image = 'data:image/png;base64,' . base64_encode($res->getData());
$key = session('captcha.key');
$uuid = uniqid();
RedisService::getRedisInstance()->set(self::getKey($uuid), $key, 'ex', self::CACHE_TTL);
return ['uuid' => $uuid, 'img' => $base64Image];
}
public static function check($uuid, $code): bool
{
$redis = RedisService::getRedisInstance();
$key = $redis->get(self::getKey($uuid));
if (empty($key)) {
return false;
}
$code = mb_strtolower($code, 'UTF-8');
$res = password_verify($code, $key);
if ($res) {
$redis->del(self::getKey($uuid));
}
return $res;
}
private static function getKey($uuid): string
{
return self::CAPTCHA_CACHE_KEY . $uuid;
}
}