官方网站

基于得分 (v3)

示例

正在自动验证中...

以编程方式调用验证方式

如果您希望更好地控制 reCAPTCHA 的运行时间,可以在 grecaptcha 对象中使用 execute 方法。为此,您需要在 reCAPTCHA 脚本加载中添加 render 参数。

  • 使用您的网站密钥加载 JavaScript API。

    1
    2
    3
    <script src="https://www.google.com/recaptcha/api.js?render=reCAPTCHA_site_key"></script>
    // 如无法连接 Google 服务器,请使用以下地址。
    <script src="https://recaptcha.net/recaptcha/api.js?render=reCAPTCHA_site_key"></script>
  • 针对您要保护的每项操作调用 grecaptcha.execute。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    function onClick(e) {
    e.preventDefault();
    grecaptcha.ready(function () {
    grecaptcha
    .execute("reCAPTCHA_site_key", { action: "submit" })
    .then(function (token) {
    // Add your logic to submit to your backend server here.
    });
    });
    }
  • 在您的后端验证 reCAPTCHA 令牌。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    const {
    "success": true|false, // whether this request was a valid reCAPTCHA token for your site
    "score": number // the score for this request (0.0 - 1.0)
    "action": string // the action name for this request (important to verify)
    "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
    } = await fetch("https://www.google.com/recaptcha/api/siteverify", {
    method: "POST",
    headers: {
    "Content-Type": "application/x-www-form-urlencoded; charset=utf-8",
    },
    body: `secret=your_secret&response=${token}`,
    })

基于验证方式 (v2)

示例

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<html>
<head>
<title>reCAPTCHA</title>
<script
src="https://www.recaptcha.net/recaptcha/api.js"
async
defer
></script>
</head>
<body>
<div id="html_element"></div>
<script>
function open() {
grecaptcha.render("html_element", {
sitekey: "6Lf2irwpAAAAAIfBI_Bjo7TAccpnUAPsiI01rF7x",
callback: async function (response) {
await fetch("https://api.zhangsifan.com/google/getReCAPTCHA", {
method: "POST",
body: JSON.stringify({
token: response,
id: "6Lf2irwpAAAAAIfBI_Bjo7TAccpnUAPsiI01rF7x",
}),
headers: {
"Content-Type": "application/json",
},
}).then(async (response) => {
const { result } = await response.json();
if (result.success) {
if (window.confirm("验证成功,是否重置验证器?")) {
grecaptcha.reset();
}
} else {
window.alert("验证失败,是否重置验证器?");
grecaptcha.reset();
}
});
},
});
}
setTimeout(() => open(), 3000);
</script>
</body>
</html>