PHP集成reCAPTCHA提示incorrect-captcha-sol错误的解决求助
解决reCAPTCHA "incorrect-captcha-sol" 错误的排查方案
通用排查要点
- 响应参数传递校验:确认前端提交的reCAPTCHA响应值(v2的
g-recaptcha-response、v3的响应token)被完整传递到calc.php,参数名无拼写错误 - API请求格式合规性:
- v2版本需POST请求到
https://www.google.com/recaptcha/api/siteverify,必须携带secret、response、remoteip三个参数 - v3版本同样POST到该地址,需额外传递
action参数,且要与前端grecaptcha.execute中的action值完全一致
- v2版本需POST请求到
- 服务器网络连通性:检查服务器是否能访问reCAPTCHA的API域名,部分服务器可能因防火墙、代理限制导致请求失败,可在
calc.php中添加错误捕获,查看API返回的具体响应内容
前端代码常见问题修正
- 脚本加载正确性:
- v2需加载:
<script src="https://www.google.com/recaptcha/api.js"></script> - v3需加载:
<script src="https://www.google.com/recaptcha/api.js?render=你的Site Key"></script>
- v2需加载:
- v2组件位置:
<div class="g-recaptcha" data-sitekey="你的Site Key"></div>必须放在表单内部,确保提交时g-recaptcha-response字段被包含在表单数据中 - v3响应值提交:需在表单提交前主动获取token并作为隐藏字段提交,示例代码:
同时在表单内添加隐藏字段:document.getElementById('your-form-id').addEventListener('submit', function(e) { e.preventDefault(); grecaptcha.execute('你的Site Key', {action: 'submit'}).then(function(token) { document.getElementById('recaptcha-token').value = token; this.submit(); }.bind(this)); });<input type="hidden" id="recaptcha-token" name="g-recaptcha-response">
calc.php后端代码修正示例
v2版本验证代码
$secretKey = "你的Secret Key"; $responseKey = $_POST['g-recaptcha-response'] ?? ''; $userIP = $_SERVER['REMOTE_ADDR']; $url = "https://www.google.com/recaptcha/api/siteverify"; $data = [ 'secret' => $secretKey, 'response' => $responseKey, 'remoteip' => $userIP ]; $options = [ 'http' => [ 'header' => "Content-type: application/x-www-form-urlencoded\r\n", 'method' => 'POST', 'content' => http_build_query($data) ] ]; $context = stream_context_create($options); $result = file_get_contents($url, false, $context); $response = json_decode($result); if ($response->success) { // 验证通过,执行表单处理逻辑 } else { // 打印错误码定位问题 var_dump($response->{'error-codes'}); }
v3版本验证代码
$secretKey = "你的Secret Key"; $responseKey = $_POST['g-recaptcha-response'] ?? ''; $userIP = $_SERVER['REMOTE_ADDR']; $url = "https://www.google.com/recaptcha/api/siteverify"; $data = [ 'secret' => $secretKey, 'response' => $responseKey, 'remoteip' => $userIP, 'action' => 'submit' // 必须与前端action一致 ]; $options = [ 'http' => [ 'header' => "Content-type: application/x-www-form-urlencoded\r\n", 'method' => 'POST', 'content' => http_build_query($data) ] ]; $context = stream_context_create($options); $result = file_get_contents($url, false, $context); $response = json_decode($result); // v3需同时校验success和score(建议阈值≥0.5) if ($response->success && $response->score >= 0.5) { // 验证通过,执行表单处理逻辑 } else { var_dump($response->{'error-codes'}); }
额外排查项
- 清除浏览器缓存与Cookie,避免旧会话干扰
- 关闭广告拦截类浏览器插件,防止其阻止reCAPTCHA脚本加载或响应
- 尽量使用真实域名测试(localhost在部分场景下可能受限,可通过本地域名映射或线上测试环境验证)
内容的提问来源于stack exchange,提问作者Matúš Rebroš
相关产品推荐
相关产品推荐

