3

我想在 Recaptcha 的新版本 (V3) 中插入一个联系人。

我寻找了不同的解决方案,但它们只显示了部分代码,它们不完整或我收到错误,并且找到的大多数解决方案对于如此简单的事情来说都非常复杂而且我不理解代码。

4

3 回答 3

20

我已经搜索了这个论坛和其他论坛,以在我的表单中实施新版本的 ReCaptcha (V3)。我需要知道如何:

  • 用JS插入
  • 如何使用 PHP 进行验证
  • 我的表单中需要哪些新字段。

我没有找到任何简单的解决方案,可以向我展示所有这些要点,或者对于只想在他们的网站上插入联系表格的人来说太复杂了。

最后,取多个解决方案的一些代码部分,我使用了一个简单且可重用的代码,您只需在其中插入相应的键。

这里是。

基本的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 = json_decode(file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secret."&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']));
        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 文档中看到一些使用示例。

您只需添加您的密钥,无需更多更改:

    src="https://www.google.com/recaptcha/api.js?render=your reCAPTCHA site key here"    
    grecaptcha.execute('your reCAPTCHA site key here'

    $secret = 'Your secret key here';

显然,您还必须更改表单的操作,在此示例中:

    action = "your_action.php"
于 2019-01-14T15:04:28.633 回答
0

自第一个答案以来,谷歌似乎改进了他们的文档。这是我的做法。

客户端集成形式:

这方面的文档在这里:https ://developers.google.com/recaptcha/docs/v3

根据 Google 的说法,您应该在每个页面上包含 Recaptcha API,以便它可以观察用户的行为。因此,我将此行添加到页脚的末尾,该页脚包含在每个页面中(不需要参数):

<script src="https://www.google.com/recaptcha/api.js"></script>

在表单上,​​您使用这样的提交按钮:

<button class="g-recaptcha" data-sitekey="PASTE-YOUR-RECAPTCHA-SITE-KEY-HERE" data-callback="onSubmit" data-action="submit">Submit Form</button>

并添加以下提交表单的 JavaScript 函数:

function onSubmit() {
    var form = document.forms[0]; // change this if you have multiple forms

    if (/* possible client-side form validation code here */) {
        form.submit();
    }
}

服务器端验证代码:

这方面的文档在这里:https ://developers.google.com/recaptcha/docs/verify

为此,我创建了一个辅助函数:

/**
 * Checks if the current script has a valid Google Captcha response token.
 * @returns True, if the script has a valid repsonse token, otherwise false.
 */
function isCaptchaValid()
{
    $captcha = isset($_POST['g-recaptcha-response']) ? $_POST['g-recaptcha-response'] : false;

    if (!$captcha) {
        return false;
    }

    $postdata = http_build_query(
        array(
            "secret" => "PASTE-YOUR-RECAPTCHA-SECRET-KEY-HERE",
            "response" => $captcha,
            "remoteip" => $_SERVER["REMOTE_ADDR"]
        )
    );
    $opts = array(
        'http' =>
        array(
            "method"  => "POST",
            "header"  => "Content-Type: application/x-www-form-urlencoded",
            "content" => $postdata
        )
    );
    $context  = stream_context_create($opts);
    $googleApiResponse = file_get_contents("https://www.google.com/recaptcha/api/siteverify", false, $context);

    if ($googleApiResponse === false) {
        return false;
    }

    $googleApiResponseObject = json_decode($googleApiResponse);

    return $googleApiResponseObject->success;
}

无需像在其他答案中那样检查任何得分值。根据文档,响应对象中甚至没有 score 属性。我检查了它,有一个,但我不使用它。

您应该在处理表单提交的 PHP 脚本的开头调用它,如下所示:

if (!isCaptchaValid()) {
    die("STOP! You are a bot."); // or do something else
}
于 2022-01-04T18:24:12.057 回答
0

在上面的答案中,需要更新这些行才能读取 PHP 中的响应值:

    $response = json_decode(file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secret."&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']));

    $response->{'success'}

    $response->{'score'}
于 2021-02-15T20:33:11.137 回答