Google Recaptcha v3示例演示

问题描述 投票:26回答:4

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

有人可能为基本表单添加一个完全正常工作的Google Recaptcha v3示例,因为我找不到它的任何有效演示吗?

我非常感谢。

非常感谢。

PS:我在服务器端使用Java Servlet,但是如果您解释使用php或其他方法都没关系。

servlets recaptcha recaptcha-v3
4个回答
11
投票

这里是链接:

https://recaptcha-demo.appspot.com/

只需请求v3的分数,它将以JSON形式返回响应


29
投票

实现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 documentation中看到一些使用示例。


5
投票

我假设您已经拥有站点密钥和机密。请执行此步骤。

在您的HTML文件中,添加脚本。

 <script src="https://www.google.com/recaptcha/api.js?render=put your site key here"></script>

此外,请使用jQuery简化事件处理。

这是简单的形式。

 <form id="comment_form" action="form.php" method="post" >
      <input type="email" name="email" placeholder="Type your email" size="40"><br><br>
      <textarea name="comment" rows="8" cols="39"></textarea><br><br>
      <input type="submit" name="submit" value="Post comment"><br><br>
    </form>

您需要初始化Google Recaptcha并监听ready事件。这是操作方法。

     <script>
       // when form is submit
    $('#comment_form').submit(function() {
        // we stoped it
        event.preventDefault();
        var email = $('#email').val();
        var comment = $("#comment").val();
        // needs for recaptacha ready
        grecaptcha.ready(function() {
            // do request for recaptcha token
            // response is promise with passed token
            grecaptcha.execute('put your site key here', {action: 'create_comment'}).then(function(token) {
                // add token to form
                $('#comment_form').prepend('<input type="hidden" name="g-recaptcha-response" value="' + token + '">');
                    $.post("form.php",{email: email, comment: comment, token: token}, function(result) {
                            console.log(result);
                            if(result.success) {
                                    alert('Thanks for posting comment.')
                            } else {
                                    alert('You are spammer ! Get the @$%K out.')
                            }
                    });
            });;
        });
  });
  </script>

这里是示例PHP文件。您可以使用Servlet或Node或任何后端语言来代替它。

<?php

        $email;$comment;$captcha;
        if(isset($_POST['email'])){
          $email=$_POST['email'];
        }if(isset($_POST['comment'])){
          $comment=$_POST['comment'];
        }if(isset($_POST['token'])){
          $captcha=$_POST['token'];
          }
        if(!$captcha){
          echo '<h2>Please check the the captcha form.</h2>';
          exit;
        }
        $secretKey = "put your secret key here";
        $ip = $_SERVER['REMOTE_ADDR'];

        // post request to server

        $url =  'https://www.google.com/recaptcha/api/siteverify?secret=' . urlencode($secretKey) .  '&response=' . urlencode($captcha);
        $response = file_get_contents($url);
        $responseKeys = json_decode($response,true);
        header('Content-type: application/json');
        if($responseKeys["success"]) {
                echo json_encode(array('success' => 'true'));
        } else {
                echo json_encode(array('success' => 'false'));
        }
?>

这里是教程链接:https://codeforgeek.com/2019/02/google-recaptcha-v3-tutorial/

希望有帮助。


1
投票

我们仅使用recaptcha-V3来查看网站流量质量,并将其用作非阻塞。由于recaptcha-V3不需要在网站上显示,可以用作隐藏内容,但您必须显示recaptcha隐私等链接(根据建议)

头部脚本标签

<script src="https://www.google.com/recaptcha/api.js?onload=ReCaptchaCallbackV3&render='SITE KEY' async defer></script>

注意:“异步延迟”确保其非阻塞性是我们的特定要求

JS代码:

<script>
    ReCaptchaCallbackV3 = function() {
        grecaptcha.ready(function() {
            grecaptcha.execute("SITE KEY").then(function(token) {
                $.ajax({
                    type: "POST",
                    url: `https://api.${window.appInfo.siteDomain}/v1/recaptcha/score`,
                    data: {
                        "token" : token,
                    },
                    success: function(data) {
                        if(data.response.success) {
                            window.recaptchaScore = data.response.score;
                            console.log('user score ' + data.response.score)
                        }
                    },
                    error: function() {
                        console.log('error while getting google recaptcha score!')
                    }
                });

            });
        });
    };
</script> 

HTML / Css代码:

there is no html code since our requirement is just to get score and don't want to show recaptcha badge.

后端-Laravel代码:

Route:

Route::post('/recaptcha/score', 'Api\\ReCaptcha\\RecaptchaScore@index');


Class:

class RecaptchaScore extends Controller
{
    public function index(Request $request)
    {
        $score = null;

        $response = (new Client())->request('post', 'https://www.google.com/recaptcha/api/siteverify', [
            'form_params' => [
                'response' => $request->get('token'),
                'secret' => 'SECRET HERE',
            ],
        ]);

        $score = json_decode($response->getBody()->getContents(), true);

        if (!$score['success']) {
            Log::warning('Google ReCaptcha Score', [
                'class' => __CLASS__,
                'message' => json_encode($score['error-codes']),
            ]);
        }

        return [
            'response' => $score,
        ];
    }
} 

我们获得分数并保存在稍后提交表单时使用的变量中。

参考:https://developers.google.com/recaptcha/docs/v3https://developers.google.com/recaptcha/

© www.soinside.com 2019 - 2024. All rights reserved.