86 lines
2.7 KiB
PHP
86 lines
2.7 KiB
PHP
<?php
|
||
namespace app\utils;
|
||
|
||
// 引入极验 SDK 的核心类
|
||
use geetest\GeetestLib;
|
||
use app\model\System\SystemSiteSettings;
|
||
|
||
class Geetest
|
||
{
|
||
/**
|
||
* 极验 3.0 的 ID 和 KEY
|
||
* 优先从系统配置表 SystemSiteSettings 中读取 geetest3ID / geetest3KEY
|
||
*/
|
||
private $captchaId;
|
||
private $privateKey;
|
||
|
||
public function __construct()
|
||
{
|
||
// 默认值可以为空,避免硬编码
|
||
$this->captchaId = null;
|
||
$this->privateKey = null;
|
||
|
||
try {
|
||
// 从系统设置表中读取极验3.0配置
|
||
$settings = SystemSiteSettings::where('delete_time', null)
|
||
->whereIn('label', ['geetest3ID', 'geetest3KEY'])
|
||
->column('value', 'label');
|
||
|
||
if (!empty($settings['geetest3ID']) && !empty($settings['geetest3KEY'])) {
|
||
$this->captchaId = $settings['geetest3ID'];
|
||
$this->privateKey = $settings['geetest3KEY'];
|
||
}
|
||
} catch (\Throwable $e) {
|
||
// 读取配置失败时,不抛出致命错误,留给上层决定是否启用极验
|
||
error_log('加载极验配置失败: ' . $e->getMessage());
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 初始化极验验证(前端获取验证参数)
|
||
* @return string JSON 字符串
|
||
*/
|
||
public function init()
|
||
{
|
||
$gtLib = new GeetestLib($this->captchaId, $this->privateKey);
|
||
// 用户唯一标识(可传用户ID、IP等,不能为空)
|
||
$userId = request()->ip();
|
||
// 预处理验证
|
||
$status = $gtLib->pre_process($userId);
|
||
// 保存状态到 session
|
||
session('gtserver', $status);
|
||
session('gt_user_id', $userId);
|
||
// 返回前端需要的验证参数
|
||
return $gtLib->get_response_str();
|
||
}
|
||
|
||
/**
|
||
* 验证前端提交的极验数据
|
||
* @param array $data 前端提交的 geetest_challenge/validate/seccode
|
||
* @return bool 验证结果
|
||
*/
|
||
public function verify(array $data)
|
||
{
|
||
$gtLib = new GeetestLib($this->captchaId, $this->privateKey);
|
||
$userId = session('gt_user_id');
|
||
$status = session('gtserver');
|
||
|
||
if ($status == 1) {
|
||
// 正常模式验证
|
||
$result = $gtLib->success_validate(
|
||
$data['geetest_challenge'],
|
||
$data['geetest_validate'],
|
||
$data['geetest_seccode'],
|
||
$userId
|
||
);
|
||
} else {
|
||
// 宕机模式验证
|
||
$result = $gtLib->fail_validate(
|
||
$data['geetest_challenge'],
|
||
$data['geetest_validate'],
|
||
$data['geetest_seccode']
|
||
);
|
||
}
|
||
return $result;
|
||
}
|
||
} |