«

引入google recaptcha 谷歌人机身份验证

emer 发布于 2021-1-21 14:36   1814 次阅读     


官方文档
https://developers.google.com/recaptcha/intro 

管理后台

https://www.google.com/recaptcha/admin/site/350006937 

填写资料

https://www.google.com/recaptcha/admin/create 

前端

官方的demo

 
<script src="https://www.google.com/recaptcha/api.js?render=_reCAPTCHA_site_key"></script>
<script>
    grecaptcha.ready(function() {
        grecaptcha.execute('_reCAPTCHA_site_key_', {action: 'homepage'}).then(function(token) {

        });
    });
</script>

_reCAPTCHA_site_key_ 就是客户的的密钥

核心代码就是通过执行 grecaptcha.execute(...) 方法,在回调中获取到 token值。

action 参数 可以理解为 验证场景。可以自己定义名称。作用就是可以在后台,对于不同的场景进行特别的设置。例如专门为登录设计一个场景: login

国内的用户需要替换js文件的地址和服务端验证接口的地址(Fuck GFW)

替换客户端js地址

https://www.google.com/recaptcha/api.js 替换为

https://www.recaptcha.net/recaptcha/api.js 

替换服务端接口地址

https://www.google.com/recaptcha/api/siteverify 替换为 https://www.recaptcha.net/recaptcha/api/siteverify

完整的一个例子客户端

<!DOCTYPE html>
<html>
<head>
    <title>google验证码V2</title>
    <meta charset="UTF-8">
</head>
<body>
    <div id="google-reCaptcha"></div>
    <button>验证后提交</button>
</body>
<script src="https://www.recaptcha.net/recaptcha/api.js?onload=onloadCallback&render=explicit" async defer> </script>
<script type="text/javascript">
    var verifyCallback = function(token) {
        document.querySelector('button').addEventListener('click', () => {
            console.log('客户端token:' + token);
        fetch('/validate?token=' + token, {
            method: 'GET'
        }).then(response => {
            if (response.ok){
            response.json().then(message => {
                console.log('服务端验证');
            console.log(message);
            alert(message);
        });
        }
    });
    });

    };
    var onloadCallback = function() {
        grecaptcha.render('google-reCaptcha', {
            'sitekey' : '6LdctdwUAAAAAORpZqPoqPta7PUKjU4Wl24JIGRs',
            'callback' : verifyCallback,
            'theme' : 'light'
        });
    };
</script>
</html>

或者
<div id="robotLogin"></div>
    onloadCallback(
            "robotLogin",
            function(res) {
              if (res) {
                let params = {
                  email: _that.formInline.email,
                  password: _that.setSha(_that.formInline.password),
                  personType: "GOOGLE",
                  personCode: res,
                  domainCode: "APIFINY",
                  deviceType: "WEB",
                  language: "EN"
                };
                _that.loginFunc(params);
              }
            },
            function(err) {
              _that.robotModalflag = false;
              _that.loaded = true;
            },
            function(netError) {
              _that.robotModalflag = false;
              _that.loaded = true;
            }
          );
前后端集成:
https://www.cnblogs.com/echolun/p/12436226.html