【问题标题】:Implementing Google Recaptcha V3 - Methods to implement实施 Google Recaptcha V3 - 实施方法
【发布时间】:2022-07-16 21:03:44
【问题描述】:

我计划在我的应用程序中使用 Google 隐形 Recaptcha V3。我想要建议我可以采用哪种方法。在开发者文档中,我可以看到两种方式,

  1. 自动将挑战绑定到按钮 (https://developers.google.com/recaptcha/docs/v3)
  2. 以编程方式调用挑战

对于第二个选项,我知道我们正在执行服务器端验证以检查来自我的站点的令牌并且我们正在获取分数。

我想知道我是否要使用第一个选项,以及如何从 ReCaptcha 服务器验证它。

【问题讨论】:

    标签: recaptcha-v3 invisible-recaptcha grecaptcha


    【解决方案1】:

    如果您想使用第一个选项,您只需在表单中包含一个提交按钮,您将在 POST 字段的“g-recaptcha-response”键中收到 reCaptcha 令牌(例如:$_POST[' g-recaptcha-response'],如果您使用的是 php)。

    <script src="https://www.google.com/recaptcha/api.js"></script>
    <form method="post" action="login" id="loginForm">
      <label for="password">Password:</label>
      <input type="password" name="password" value="">
      <!--Recaptcha button-->
      <button class="g-recaptcha" 
            data-sitekey="#your_site_key" 
            data-callback='onSubmit' 
            data-action='submit'>Submit</button>
    </form>
    <script>
      function onSubmit(token)
      {
        document.getElementById("loginForm").submit();
      }
    </script>

    然后,像使用第二个选项一样验证将其提交到“https://www.google.com/recaptcha/api/siteverify”的令牌。

    如果你在 php 上,从表单的 action 属性登录页面,应该是这样的:

    <?php
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify");
      curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
      curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, 1);
      curl_setopt($ch,CURLOPT_POSTFIELDS, http_build_query([
        "secret"=>"#yourSecretKey"
      , "response"=>$_POST['g-recaptcha-response']
      , "remoteip"=>$_SERVER['REMOTE_ADDR']
    ]));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $recaptcha = json_decode(curl_exec($ch), true);
    /** $recaptcha:
    Array
    (
        [success] => 1 // or 0
        [challenge_ts] => 2022-07-16T12:34:38Z
        [hostname] => host // hostname
        [score] => 0.9 // 0.0 to 1.0
        [action] => submit // data-action attribute from reCaptcha button
    )
    */
    if ($recaptcha["score"] >= 0.5 && $recaptcha["action"] === 'submit')
    {
      // action on success
    } else {
      // action on false
    }
    ?>
    

    关于使用哪一个,我不知道如何回答……但我想这两个选项的工作方式相似,所以选择一个更容易实现的选项。

    【讨论】:

      猜你喜欢
      • 2020-02-08
      • 1970-01-01
      • 2015-02-25
      • 2012-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多