Google Recaptcha v3示例演示

问题描述:

直到现在,我仍在使用Google Recaptcha v2,但现在我想使用最新版本(v3)更新我的WebApp.

Until now, I was working with Google Recaptcha v2, but now I want to update my WebApp using the lastest version (v3).

是否有人可以为基本表单添加一个可以正常运行的Google Recaptcha v3示例,因为我找不到它的任何演示示例?

Is it possible to anyone add a fully working Google Recaptcha v3 example for a basic form as I can't find any working demos of it?

我真的很感激.

非常感谢您.

PS:我在服务器端使用Java Servlet,但是无论您解释使用PHP还是其他方法都没关系.

PS: I'm using Java Servlets on the server side, but it doesn't matter if you explain using PHP or whatever.

用于实现ReCaptcha v3的简单代码

Simple code to implement ReCaptcha v3

基本JS代码

<script src="https://www.google.com/recaptcha/api.js?render=your reCAPTCHA site key here"></script>
<script>
    grecaptcha.ready(function() {
    // do request for recaptcha token
    // response is promise with passed token
        grecaptcha.execute('your reCAPTCHA site key here', {action:'validate_captcha'})
                  .then(function(token) {
            // add token value to form
            document.getElementById('g-recaptcha-response').value = token;
        });
    });
</script>

基本HTML代码

<form id="form_id" method="post" action="your_action.php">
    <input type="hidden" id="g-recaptcha-response" name="g-recaptcha-response">
    <input type="hidden" name="action" value="validate_captcha">
    .... your fields
</form>

基本的PHP代码

if (isset($_POST['g-recaptcha-response'])) {
    $captcha = $_POST['g-recaptcha-response'];
} else {
    $captcha = false;
}

if (!$captcha) {
    //Do something with error
} else {
    $secret   = 'Your secret key here';
    $response = file_get_contents(
        "https://www.google.com/recaptcha/api/siteverify?secret=" . $secret . "&response=" . $captcha . "&remoteip=" . $_SERVER['REMOTE_ADDR']
    );
    // use json_decode to extract json response
    $response = json_decode($response);

    if ($response->success === false) {
        //Do something with error
    }
}

//... The Captcha is valid you can continue with the rest of your code
//... Add code to filter access using $response . score
if ($response->success==true && $response->score <= 0.5) {
    //Do something to denied access
}

您必须使用$ response.score的值来过滤访问.它的取值范围为0.0到1.0,其中1.0表示与您的网站的最佳用户交互,而0.0表示最差的用户交互(如漫游器).您可以在 ReCaptcha文档中看到一些使用示例.

You have to filter access using the value of $response.score. It can takes values from 0.0 to 1.0, where 1.0 means the best user interaction with your site and 0.0 the worst interaction (like a bot). You can see some examples of use in ReCaptcha documentation.