Google reCAPTCHA使用教程

reCAPTCHA使用先进的风险分析引擎和自适应挑战来防止恶意软件在您的网站上进行滥用活动。与此同时,合法用户将能够登录、购买、查看页面或创建帐户,而虚假用户将被屏蔽。

官方网站

基于得分 (v3)

示例

正在自动验证中…

以编程方式调用验证方式

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

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

// 如无法连接 Google 服务器,请使用以下地址。

“`
– 针对您要保护的每项操作调用 grecaptcha.execute。

js
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 令牌。

js
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)

示例

代码

<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: "reCAPTCHA_site_key",
          callback: async function (response) {
            await fetch("https://api.zhangsifan.com/google/getReCAPTCHA", {
              method: "POST",
              body: JSON.stringify({
                token: response,
                id: "reCAPTCHA_site_key",
              }),
              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>

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注