1. 介绍

reCAPTCHA是google旗下的验证码服务(免费的),当然要保证网络能打开google才行,所以常用于国外的网站。如果需要在国内使用,只需将所有的www.google.com替换成www.recaptcha.net即可。
官网:https://developers.google.com/recaptcha/

2. 接入

(1) site key

To start using reCAPTCHA, you need to sign up for an API key pair for your site. The key pair consists of a site key and secret key. The site key is used to invoke reCAPTCHA service on your site or mobile application. The secret key authorizes communication between your application backend and the reCAPTCHA server to verify the user’s response. The secret key needs to be kept safe for security purposes.

申请Site Key: http://www.google.com/recaptcha/admin
Verifying the user’s response:
https://developers.google.com/recaptcha/docs/verify

本地开发时,可以使用此site key进行测试:
6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI
这里写图片描述

(2) 方式一:DOM中加入

<html>
  <head>
    <title>reCAPTCHA demo</title>
     <script src="https://www.google.com/recaptcha/api.js" async defer></script>
  </head>
  <body>
    <form action="?" method="POST">
      <div class="g-recaptcha" data-callback="robotVerified" data-sitekey="6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI"></div>
    </form>
  </body>
  <script>
    function robotVerified(){
      console.log('Verified: not robot');
    }
  </script>
</html>

(3) 方式二:Js 渲染

<html>
  <head>
    <title>reCAPTCHA demo</title>
    <script src="https://www.google.com/recaptcha/api.js?onloadCallback&render=explicit" async defer></script>
  </head>
  <body>
    <div id="robot"></div>
    <script type="text/javascript">
      var onloadCallback = function() {
        console.log("grecaptcha is ready!");
        //render grecaptcha
        grecaptcha.render('robot', {
          'sitekey': '6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI',
          'callback': function () {
            console.log('Verified: not robot');
          }
        });
      };
    </script>
  </body>
</html>

3. 配置

(1) 引用api.js的url参数

<script src="https://www.google.com/recaptcha/api.js?onloadCallback&render=explicit" async defer></script>

在引用recaptcha的api时,url上可以配置一些参数,如下:

参数名称是否可选描述
onload函数名称定义加载完成的回调函数名称
renderexplicit 或 onload(默认)当api加载好之后是否直接在类名为g-recaptcha的标签上渲染recaptcha。默认的onload是要渲染,explicit是不渲染
hl点击查询不同语言对应的值recaptcha显示语言,如果未指定,自动检测用户的语言。

[1] onload

<html>
  <head>
    <title>reCAPTCHA demo</title>
     <script src="https://www.google.com/recaptcha/api.js?onloadCallback" async defer></script>
  </head>
  <body>
    <form action="?" method="POST">
      <div class="g-recaptcha"data-sitekey="6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI"></div>
    </form>
  </body>
  <script>
    function onloadCallback(){
      console.log("grecaptcha is ready!");
    }
  </script>
</html>

[2] render

设置为explicit后,api加载完成以后也不会自动渲染rechaptcha框,页面会显示空白。

<html>
  <head>
    <title>reCAPTCHA demo</title>
     <script src="https://www.google.com/recaptcha/api.js?render=explicit" async defer></script>
  </head>
  <body>
    <form action="?" method="POST">
      <div class="g-recaptcha"data-sitekey="6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI"></div>
    </form>
  </body>
</html>

[3] hl

将hl配置为zh-CN后,显示简体中文界面。
这里写图片描述

<html>
  <head>
    <title>reCAPTCHA demo</title>
     <script src="https://www.google.com/recaptcha/api.js?hl=zh-CN" async defer></script>
  </head>
  <body>
    <form action="?" method="POST">
      <div class="g-recaptcha"data-sitekey="6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI"></div>
    </form>
  </body>
</html>

(2) reCAPTCHA自定义参数

在上文的接入章节中提到了,有两种接入的方式,两种方式都可以进行自定义配置。

类名为g-recaptcha的标签上的属性grecaptcha.render参数必填描述
data-sitekeysitekey网站sitekey
data-themethemedark或light(默认)主题颜色
data-sizesizecompact或normal(默认)框大小
data-tabindextabindex默认为0The tabindex of the widget and challenge. If other elements in your page use tabindex, it should be set to make user navigation easier.
data-callbackcallback验证成功回调函数g-recaptcha-response token会作为参数传递到回调函数中
data-expired-callbackexpired-callback验证失效回调函数用户需要重新验证
data-error-callbackerror-callback错误回调函数因为网络等问题无法验证,通过回调函数提醒用户重试

[1] theme

dark和light如下
这里写图片描述

[2] size

compact和normal如下:
这里写图片描述

[3] data-callback

<html>
  <head>
    <title>reCAPTCHA demo</title>
     <script src="https://www.google.com/recaptcha/api.js" async defer></script>
  </head>
  <body>
    <form action="?" method="POST">
      <div class="g-recaptcha" data-callback="robotVerified" data-sitekey="6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI"></div>
    </form>
  </body>
  <script>
    function robotVerified(data){
      console.log(data);
    }
  </script>
</html>

在回调函数robotVerified中接受到的这个参数就是g-recaptcha-response token(注意:每次都不一样)。如下:

03AHqfIOks78_xzIktpZlVUGhCIiRruEDFaP9aAir-ChZpGbSdQ3JcUpCuEQ9KwuynC5M-TR8wQfppmIJqIXBGl1xvusZqj444QqI2dhyTXx6LmL9y00knaFIRn5KC9ILWX-H3Hgv66mamhakmo3x1EIEoiA03EixOtPgbW_Q68dDl48B0_8qHl6o9KOfLiolqdwIApi61FZCqUXhvPKZc55i2FVA2qvsh0oauN0YdHWG_ReyXlW2vdS-A0U0E28NWafM1-IfDnxOBchxSE-uYIiXB4QeruyeNaA

(3) JavaScript API

方法参数返回描述
grecaptcha.render(container,parameters)【container】id名称(字符串) or document.getElementById(‘example1’)
【parameters】参照上节内容,如{"sitekey": "your_site_key", "theme": "light"}
widget id在container指定的标签内渲染reCAPTCHA模块
grecaptcha.reset(opt_widget_id)widget id(可选,省略时默认为第一个创建的模块)重置reCAPTCHA
grecaptcha.getResponse(opt_widget_id)widget id(可选,省略时默认为第一个创建的模块)【未通过】””
【已通过】g-recaptcha-response token
获得reCAPTCHA的结果响应

[1] render

<html>
  <head>
    <title>reCAPTCHA demo</title>
    <script src="https://www.google.com/recaptcha/api.js?onloadCallback&render=explicit" async defer></script>
  </head>
  <body>
    <div id="robot1"></div>
    <div id="robot2"></div>
    <script type="text/javascript">
      var onloadCallback = function() {

        var widge1 = grecaptcha.render('robot1', {
          'sitekey': '6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI',
          theme: 'dark'
        });
        console.log(widge1); //0
        var widget2 = grecaptcha.render(document.getElementById('robot2'), {
          'sitekey': '6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI',
          tabindex:'2'
        });
        console.log(widget2); //1
      };
    </script>
  </body>
</html>

[2] reset

<html>
  <head>
    <title>reCAPTCHA demo</title>
    <script src="https://www.google.com/recaptcha/api.js?onloadCallback&render=explicit" async defer></script>
  </head>
  <body>
    <div id="robot"></div>
    <button onclick="resetRecaptcha()">重置</button>
    <script type="text/javascript">
      var widgeId;
      var onloadCallback = function() {

        widgeId = grecaptcha.render('robot', {
          'sitekey': '6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI',
        });

      };
      function resetRecaptcha(){
        grecaptcha.reset(widgeId); // <---看这里
      }
    </script>
  </body>
</html>

[3] getResponse

<html>
  <head>
    <title>reCAPTCHA demo</title>
    <script src="https://www.google.com/recaptcha/api.js?onloadCallback&render=explicit" async defer></script>
  </head>
  <body>
    <div id="robot"></div>
    <button onclick="getResponseFromRecaptcha()">看看验证通过了没?</button>
    <script type="text/javascript">
      var widgetId;
      var onloadCallback = function() {

        widgetId = grecaptcha.render('robot', {
          'sitekey': '6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI',
        });

      };
      function getResponseFromRecaptcha(){
        var response = grecaptcha.getResponse(widgetId); // <---看这里
        if (response.length == 0) { //返回""或 token(如:03AHqfIOmtBMGg686uP3YPAN7hJyaqUi69SSrEnC3Km7Hcnr5y1u-A-yp8z28yBvgVxqWiRndLrXrk_TyJrdob3tVh4BGnI4YNsoKocqZmbilGnJRX6Mxxj6jQ0AkhoRangAVFmRFZyy7RH5u5ruM5t_H7-P4GNnaFUaMELgOYyJ5ZgUtEMwBS1iNrGg6B6MZmgd4kcJXhWYR4vU_RwqFOuzxd9NMF7OCLl8FzOhN4baI5S2krnORqMBkiWenKNUtCuKfB1HzGdiVog7mzBKJvseSBlAPXrTN-Gg)
          console.log('reCaptcha not verified'); 
          return false;
        } else {
          console.log('reCaptcha verified');
          return true;
        }
      }
    </script>
  </body>
</html>

https://blog.csdn.net/joyce_lcy/article/details/81980683