使用 Ajax 将 reCaptcha 令牌发送到 PHP

Sending reCaptcha token to PHP using Ajax

我想将 reCaptcha V3 添加到表单中。

表格如下:

<form action="mail.php" method="POST">
    <!-- This hidden input will contain the token -->
    <input type="hidden" name="token" id="token" />
    <input type="text" name="name" />
    <input type="text" name="email" />
    <textarea name="message"></textarea>
    <input type="submit" name="submit" value="Send" />
</form>

现在我试图将 token 值发送到 mail.php,所以有一个名为 jquery.form 的插件我用它来发送 Ajax 请求。

这里是 Javascript/Jquery 代码:

$('form').ajaxForm({

    beforeSubmit: function() {

        //Captcha part
        grecaptcha.ready(function() {

                grecaptcha.execute('My_website_key', {action: 'form'}).then(function(token) {

                    //Set token value to the hidden element
                    $('#token').val(token);

                });

        });//reCaptcha ready    

    },//Before submit function
    success: function(msg) {

        if(msg == 'Message has been sent.'){
            console.log('success!');
        }else{
            console.log(msg);
        }

    },//success function
    complete: function(xhr) {

        console.log(xhr.responseText);  

    }//complete function

});//End Ajax

当我提交表单时,然后我查看控制台,我看到 token 是空的并且似乎执行了 success 函数,在 token 之前隐藏元素获取令牌。

我无法在页面加载或任何其他操作时添加令牌,因为它会在 2 分钟后过期,所以我需要获取一个令牌并将其发送到 PHP 文件。

您需要在 recaptcha 处理程序中移动您的 ajax 请求,因为 beforeAjax 不会等待其内容被解析,更改您的代码如下:

// Fake grecaptcha method !!! you should delete this
// Form URL was changed as well to satisfy the example
let grecaptcha = {
  ready: function(cb) {
    cb();
  },
  execute: function(key, options) {
    return Promise.resolve('recaptchatoken');
  }
};

let formElem = $('form');

formElem.submit(function(e) {
  e.preventDefault();

  let thisForm = $(this);

  grecaptcha.ready(function() {
    grecaptcha.execute('My_website_key', {
      action: 'form'
    }).then(function(token) {

      $('#token').val(token);

      thisForm.ajaxSubmit({
        success: function(msg) {

          if (msg == 'Message has been sent.') {
            console.log('success!');
          } else {
            console.log(msg);
          }

        },
        complete: function(xhr) {

          console.log(xhr.responseText);

        }

      });


    });

  });

  return false; // false = prevent submit 
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="http://malsup.github.io/min/jquery.form.min.js"></script>
<form action="//reqres.in/api/users" method="POST">
  <!-- This hidden input will contain the token -->
  <input type="hidden" name="token" id="token" />
  <input type="text" name="name" />
  <input type="text" name="email" />
  <textarea name="message"></textarea>
  <input type="submit" name="submit" value="Send" />
</form>