fix(platform): 修复由于使用的Think-Captcha版本不同造成的验证码的问题

This commit is contained in:
2025-12-08 13:45:14 +08:00
parent ea322c9727
commit 0a9eadcdd0

View File

@@ -105,11 +105,7 @@ class Login extends Controller
$expire = 600; $expire = 600;
try { try {
// 尝试使用版本3.x的方式 // 直接使用门面生成验证码图片
$captchaInstance = new \think\captcha\Captcha(app()->make('config'), app()->make('session'));
$captchaInstance->configure();
$generator = $captchaInstance->generate();
$code = $generator['value'];
$captchaResponse = ThinkCaptcha::create(); $captchaResponse = ThinkCaptcha::create();
// 获取图片内容 // 获取图片内容
@@ -118,11 +114,31 @@ class Login extends Controller
$imgContent = ob_get_clean(); $imgContent = ob_get_clean();
// 生成base64图片 // 生成base64图片
$imgBase64 = 'data:image/png;base64,' . base64_encode($imgContent); $imgBase64 = 'data:image/png;base64,' . base64_encode($imgContent);
// 获取当前session中的验证码
$session = app()->make('session');
$captchaInfo = $session->get('captcha');
// 由于无法直接获取验证码文本,我们需要重新生成一个验证码实例
// 并使用相同的配置来生成验证码文本
$captchaInstance = new \think\captcha\Captcha(app()->make('config'), $session);
// 反射获取受保护的generate方法
$reflection = new \ReflectionClass($captchaInstance);
$generateMethod = $reflection->getMethod('generate');
$generateMethod->setAccessible(true);
$generator = $generateMethod->invoke($captchaInstance);
$code = $generator['value'];
} catch (\Exception $e) { } catch (\Exception $e) {
// 如果失败尝试使用版本2.x的方式 try {
$captchaData = ThinkCaptcha::create(null, true); // 如果失败尝试使用版本2.x的方式
$code = $captchaData['code']; $captchaData = ThinkCaptcha::create(null, true);
$imgBase64 = $captchaData['img']; $code = $captchaData['code'];
$imgBase64 = $captchaData['img'];
} catch (\Exception $e2) {
// 如果都失败,返回错误信息
return error(-1, '验证码生成失败: ' . $e2->getMessage());
}
} }
Cache::set($captcha_id, $code, $expire); Cache::set($captcha_id, $code, $expire);