1

我正在尝试将 Google reCaptcha V3 添加到表单中,我对其进行了搜索,并从另一个问题中找到了一些文章和一些代码片段。

它不是带有复选框的,它显示在右下角或页面上。

这是HTML代码:

<script src='https://www.google.com/recaptcha/api.js?render=My Website Key'></script>
</head>

JS代码:

<body>

    <script>

        //When page is loaded
        $(document).ready(function() { 

             //When recaptcha is ready
             grecaptcha.ready(function() {

                 grecaptcha.execute('The Website Key', {action: 'homepage'}).then(function(token) {

                    //Add token element at the end of the form
                    $('#mailForm').prepend('<input type="hidden" name="token" value="' + token + '">');

                    //Add action element at the end of the form
                    $('#mailForm').prepend('<input type="hidden" name="action" value="homepage">');

                });

            }); //Recaptcha ready

        }); //Page is loaded

    </script>

表格:

<form action='php/mail.php' method="post" id='mailForm' enctype='multipart/form-data'>

    //Some inputs 

</form>

PHP代码:

if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])) {

    $secret = 'My Secret Key';

    //get verify response data
    $verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response']);

    $responseData = json_decode($verifyResponse);

    if($responseData->success){
        //Send the mail
    }else{
        echo 'Please check reCaptcha';
    }
}else{
    echo 'Please check reCaptcha';
}

因此,当页面加载时令牌会更新,因此如果用户出于任何原因再次尝试,它将不起作用并且他会收到一条错误消息。

那么当用户提交表单时我应该更新令牌吗?或者这可能会导致垃圾邮件?或者在这种情况下我应该怎么做?

4

0 回答 0