阅读文档:
https://developers.google.com/recaptcha/docs/verify
验证用户的反应
本页说明如何验证用户对来自应用后端的 reCAPTCHA 质询的响应。当最终用户解决 reCAPTCHA 时,将在 HTML 中填充一个新字段 (g-recaptcha-response)。您可以通过以下三种方式之一获取用户的响应:
g-recaptcha-response 用户在您的网站上提交表单时的 POST 参数
用户完成验证码质询后的 grecaptcha.getResponse(opt_widget_id)
如果在 g-recaptcha 标记属性或 grecaptcha.render 方法中的回调参数中指定了数据回调,则作为回调函数的字符串参数
每个 reCAPTCHA 响应都是一个只能使用一次的令牌。如果使用特定令牌进行了验证尝试,则不能再次使用它。您需要调用 grecaptcha.reset() 要求最终用户再次使用 reCAPTCHA 进行验证。
获取响应令牌后,您需要使用以下 API 使用 reCAPTCHA 进行验证,以确保令牌有效。
API 请求
网址:https://www.google.com/recaptcha/api/siteverify
方法:发布
POST参数说明
秘密 必需。您的站点和 reCAPTCHA 之间的共享密钥。
回复 必填。 reCAPTCHA 提供的用户响应令牌,用于验证您网站上的用户。
remoteip 可选。用户的 IP 地址。
API 响应
响应是一个 JSON 对象:
{
"success": true|false,
"challenge_ts": timestamp, // timestamp of the challenge load (ISO format yyyy-MM-dd'T'HH:mm:ssZZ)
"hostname": string, // the hostname of the site where the reCAPTCHA was solved
"error-codes": [...] // optional
}
PHP 示例:
// set post fields
$post = [
'secret' => $secret,
'response' => $_POST['g-recaptcha-response'],
'remoteip' => $_SERVER['REMOTE_ADDR']
];
$ch = curl_init('https://www.google.com/recaptcha/api/siteverify');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
// execute!
$response = curl_exec($ch);
// close the connection, release resources used
curl_close($ch);
// do anything you want with your response
var_dump(json_decode($response));