本页介绍了如何从应用的后端验证用户对 reCAPTCHA 质询的响应。
对于 Web 用户,您可以通过以下三种方式之一获取用户的响应令牌:
- g-recaptcha-responsePOST 参数(当用户在您的网站上提交表单时)
- 用户完成 reCAPTCHA 验证后的 grecaptcha.getResponse(opt_widget_id)
- 作为回调函数的字符串参数(如果在 g-recaptcha标记属性中或在grecaptcha.render方法中的回调参数中指定了data-callback)
对于 Android 库用户,您可以调用 SafetyNetApi.RecaptchaTokenResult.getTokenResult() 方法在状态返回成功时获取响应令牌。
令牌限制
每个 reCAPTCHA 用户响应令牌的有效期为两分钟,只能验证一次, 从而防止重放攻击如果您需要新令牌,可以重新运行 reCAPTCHA 验证。
获得响应令牌后,您需要在两分钟内通过 reCAPTCHA 使用 以下 API 来确保令牌有效。
API 请求
URL:https://www.google.com/recaptcha/api/siteverify
方法:POST
| POST 参数 | 说明 | 
|---|---|
| secret | 必需。您的网站与 reCAPTCHA 之间的共享密钥。 | 
| response | 必需。您网站上的 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
}
对于 reCAPTCHA Android:
{
  "success": true|false,
  "challenge_ts": timestamp,  // timestamp of the challenge load (ISO format yyyy-MM-dd'T'HH:mm:ssZZ)
  "apk_package_name": string, // the package name of the app where the reCAPTCHA was solved
  "error-codes": [...]        // optional
}
错误代码参考
| 错误代码 | 说明 | 
|---|---|
| missing-input-secret | 缺少 Secret 参数。 | 
| invalid-input-secret | Secret 参数无效或格式错误。 | 
| missing-input-response | 缺少响应参数。 | 
| invalid-input-response | 响应参数无效或格式错误。 | 
| bad-request | 请求无效或格式错误。 | 
| timeout-or-duplicate | 响应不再有效:过旧或以前使用过。 | 
