webman框架后台代码如下:
<?php
namespace app\cn\controller;
use support\Request;
use support\View;
use support\Response;
use GuzzleHttp\Client;
use TencentCloud\Common\Credential;
use TencentCloud\Common\Profile\HttpProfile;
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Exception\TencentCloudSDKException;
use TencentCloud\Captcha\V20190722\CaptchaClient;
use TencentCloud\Captcha\V20190722\Models\DescribeCaptchaResultRequest;
class Test extends Base{
// 腾讯验证码校验接口
public function verify(Request $request){
try {
// 1. 获取前端参数(修复:优先用getRealIp,避免重复赋值)
$ticket = $request->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前端代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>腾讯滑动验证码</title>
<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
<script src="https://turing.captcha.qcloud.com/TCaptcha.js"></script>
<style>
#captchaContainer { width: 300px; margin: 50px auto; }
#result { text-align: center; margin-top: 20px; color: red; }
</style>
</head>
<body>
<button id="captchaBtn">点击验证</button>
<div id="result"></div>
<script>
$(document).ready(function() {
if (typeof TencentCaptcha === 'undefined') {
console.error('腾讯验证码SDK加载失败!');
$('#result').text('验证码SDK加载失败,请刷新页面重试');
return;
}
// 必须与后端CaptchaAppId一致
var appId = '1111111111111111111111111111111';
$('#captchaBtn').click(function() {
var captcha = new TencentCaptcha(appId, function(res) {
console.log('前端验证结果:', res);
if (res.ret === 0) {
// 验证成功,调用后端
$.post('/test/verify', {
ticket: res.ticket,
randstr: res.randstr
// 移除user_ip参数,后端自行获取真实IP(更安全,避免前端伪造)
}, function(data) {
if (data.code === 200) {
$('#result').text('验证通过!').css('color', 'green');
console.log('后端验证成功:', data);
} else {
$('#result').text('验证失败:' + data.msg);
console.log('后端验证失败:', data);
}
}).fail(function(xhr, status, error) {
$('#result').text('请求后端失败:' + error);
console.error('后端请求失败:', status, error);
});
} else {
var errorMsg = res.msg || '验证取消或失败';
$('#result').text('验证失败:' + errorMsg);
console.log('前端验证失败:', errorMsg);
}
}, {
type: 'slide', // 与后端CaptchaType=9对应
enableDarkMode: false,
timeout: 60000,
needFeedBack: false // 该参数设为false即可隐藏帮助图标
});
captcha.show();
});
});
</script>
</body>
</html>上一篇: webman开发学习步骤(二)
下一篇: 暂无数据