reCAPTCHA是Google公司推出的一项验证服务,使用十分方便快捷,在国外许多网站上均有使用。它与许多其他的人机验证方式不同,它极少需要用户进行各种识图验证。
它的使用方式如下如所示,只需勾选复选框即可通过人机验证。
虽然简单但效果很好,因为Google会收集一些浏览器信息,网络信息,鼠标轨迹等信息,最后通过神经网络判断是否为机器人。而且reCAPTCHA还可以记录并分析使用该人机验证的请求次数,并对可以的请求进行统计和监管。
一些准备工作:
需要一个谷歌账号没有的先去注册一个
reCAPTCHA官网:https://developers.google.com/recaptcha/ (需要科学上网)
使用reCAPTCHA需要创建密匙对,创建密匙:https://www.google.com/recaptcha/admin
首先先创建密匙
进入 https://www.google.com/recaptcha/admin
创建成功后会产生一对密匙
前端部署
在你需要添加reCAPTCHA的界面添加script标签
<script src="https://www.recaptcha.net/recaptcha/api.js"></script>
然后再你需要显示reCAPTCHA验证框的地方添加
<div class="g-recaptcha" data-sitekey="你的网站密匙"></div>
可以设置验证框的主题默认主题为light,可以添加属性:data-theme="dark" 变为暗色主题
后端部署
在每次验证完成后会生成一个g-recaptcha-response验证码,需要将这个验证码和你的密匙一起发送至:https://www.recaptcha.net/recaptcha/api/siteverify (使用GET方式传参)
传参的格式:secret=xxxxxx&response=xxxxxxx
下图为需要传递的参数及其含义
secret (必须) | 你的secret密匙(第二个密匙) |
response (必须) | 客户端获取到的 g-recaptcha-response验证码 |
remoteip (可选) | 客户端的ip |
接口返回的数据是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
}
验证通过后success返回的值为“true”,如果验证失败则会返回error-code,下面为error-code及其对应原因
Error code | Description |
---|---|
missing-input-secret | The secret parameter is missing. |
invalid-input-secret | The secret parameter is invalid or malformed. |
missing-input-response | The response parameter is missing. |
invalid-input-response | The response parameter is invalid or malformed. |
bad-request | The request is invalid or malformed. |
timeout-or-duplicate | The response is no longer valid |
请求统计
访问:https://www.google.com/recaptcha/admin 可以查看请求的统计