webman框架后台代码如下:
post('ticket', '');
$randstr = $request->post('randstr', '');
$userIp = $request->getRealIp(); // 直接获取真实IP,无需重复赋值
// 2. 配置腾讯云密钥(区分API密钥和验证码应用密钥!)
$secretId = "AAAAAAAAAAAAAAAAAAAAAAAAAAA"; // API密钥的SecretId(访问管理控制台获取)
$secretKey = "BBBBBBBBBBBBBBBBBBBBBBBBBBB"; // API密钥的SecretKey(访问管理控制台获取)
// 3. 初始化认证信息
$cred = new Credential($secretId, $secretKey);
// 4. 配置HTTP选项
$httpProfile = new HttpProfile();
$httpProfile->setEndpoint("captcha.tencentcloudapi.com");
$httpProfile->setReqTimeout(30); // 增加超时时间,避免网络问题
// 5. 配置客户端选项
$clientProfile = new ClientProfile();
$clientProfile->setHttpProfile($httpProfile);
// 6. 初始化验证码客户端(关键:地域必须与控制台应用地域一致)
$client = new CaptchaClient($cred, "ap-beijing", $clientProfile);
// 7. 构造请求参数(核心修复:核对AppId和AppSecretKey)
$req = new DescribeCaptchaResultRequest();
$params = [
"CaptchaType" => 9, // 9=滑块验证码(与前端type:slide对应)
"Ticket" => $ticket, // 前端传入的票据(不能为空)
"UserIp" => $userIp, // 用户真实IP(不能为空)
"Randstr" => $randstr, // 前端传入的随机串(不能为空)
"CaptchaAppId" => 111111111111111111111111111, // 验证码应用ID(控制台获取,必须正确)
"AppSecretKey" => "CCCCCCCCCCCCCCCCCCCCCCCCCCC" // 验证码应用密钥(控制台该AppId对应的密钥,不是API的SecretKey!)
];
// 校验必填参数(新增:避免空参数导致验证失败)
if (empty($ticket) || empty($randstr) || empty($userIp)) {
throw new Exception("ticket/randstr/userIp 不能为空");
}
$req->fromJsonString(json_encode($params));
// 8. 发送请求并获取结果
$resp = $client->DescribeCaptchaResult($req);
// 9. 解析返回结果(新增:判断CaptchaCode是否为1,1=验证成功)
$result = json_decode($resp->toJsonString(), true);
$captchaCode = $result['CaptchaCode'] ?? -1;
if ($captchaCode === 1) {
return json(['code' => 200, 'msg' => '验证成功', 'data' => $result]);
} else {
return json(['code' => 500, 'msg' => $result, 'captchaCode' => $captchaCode]);
}
} catch (TencentCloudSDKException $e) {
// 捕获SDK异常,输出具体错误信息
return json(['code' => 5003, 'msg' => '腾讯云SDK调用失败:' . $e->getMessage()]);
} catch (Exception $e) {
// 捕获其他业务异常
return json(['code' => 5004, 'msg' => '业务处理失败:' . $e->getMessage()]);
}
}
public function index($request){
$this->common($request);
$ip = $request->getRealIp();
View::assign(['ip'=>$ip]);
$template = $request->template.'index';
return view($template);
}
}jquery前端代码:
腾讯滑动验证码 点击验证
上一篇: webman开发学习步骤(二)
下一篇: 暂无数据