Php 如何验证Google Recaptcha V3响应?

Php 如何验证Google Recaptcha V3响应?,php,recaptcha,invisible-recaptcha,Php,Recaptcha,Invisible Recaptcha,如何在客户端和服务器端(php)中集成GoogleReCAPTCHA版本3。下面的代码用于显示recaptcha,但效果不佳。如何进行这种集成 grecaptcha.ready(函数(){ grecaptcha.execute('XXXX-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'{ 动作:“动作名称” }); }); 在代码的这一点上,您将需要执行一个post请求来重新捕获TCHA以验证令牌,如下所述:。响应将是一个json对象,字段为“suc

如何在客户端和服务器端(php)中集成GoogleReCAPTCHA版本3。下面的代码用于显示recaptcha,但效果不佳。如何进行这种集成


grecaptcha.ready(函数(){
grecaptcha.execute('XXXX-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'{
动作:“动作名称”
});
});
在代码的这一点上,您将需要执行一个post请求来重新捕获TCHA以验证令牌,如下所述:。响应将是一个json对象,字段为“success”(真/假)和“action” 用于比较(=)和分数(从0.0到1.0的数字)

您还可以为每个请求指定操作名称(创建帖子、更新帖子、创建评论…)

试试这个

<script>
  grecaptcha.ready(function() {
   grecaptcha.execute('YOUR_SITE_KEY', {action: 'MyForm'})
   .then(function(token) {
    console.log(token)
    document.getElementById('g-recaptcha-response').value =    token;
   }); 
  }); 
 </script> 

<form action="verify.php" method="post">
  <input type="hidden" id="g-recaptcha-response" name="g-recaptcha-response">
  <input type="text" name="name" placeholder="Your name" required >
  <input type="email" name="email" placeholder="Your email address" required>
  <input type="submit" name="submit" value="SUBMIT" >
</form>

grecaptcha.ready(函数(){
execute('YOUR_SITE_KEY',{action:'MyForm'})
.then(功能(令牌){
console.log(令牌)
document.getElementById('g-recaptcha-response')。value=token;
}); 
}); 

下面是一个示例工作代码和演示

html端码

<html>
  <head>
    <title>Google recapcha v3 demo - Codeforgeek</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <script src="https://www.google.com/recaptcha/api.js?render=put your site key here"></script>
  </head>
  <body>
    <h1>Google reCAPTHA Demo</h1>
    <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>
      <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>
  </body>
</html>

Google recapcha v3演示版-CodeForgek
谷歌重演演示






//提交表格时 $(“#注释表单”)。提交(函数(){ //我们阻止了它 event.preventDefault(); var email=$('#email').val(); var comment=$(“#comment”).val(); //准备好了吗 grecaptcha.ready(函数(){ //对recaptcha令牌的do请求 //响应是带有传递令牌的承诺 执行('put your site key here',{action:'create_comment'})。然后(函数(令牌){ //将令牌添加到表单 $('comment_form')。前缀(''; $.post(“form.php”,{email:email,comment:comment,token:token},函数(结果){ 控制台日志(结果); 如果(结果、成功){ 提醒('谢谢发表评论') }否则{ 警报('您是垃圾邮件发送者!请将@$%K取出。')) } }); });; }); });
PHP代码

<?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'));
        }
?>

工作正常

演示:


教程:

我想为您提供一个完整的工作流程,将recaptchav3集成到ASP.NET核心MVC解决方案中

在appsettings.json文件中:

  "RecaptchaSettings": {
    "Uri": "https://www.google.com/recaptcha/api/siteverify",
    "SecretKey": "your private key"
    "SiteKey": "your public key",
    "Version": "v3"
  }
在您的视图中(@razor语法):

使用Microsoft.Extensions.Configuration @注入I配置配置 grecaptcha.ready(函数(){ grecaptcha.execute('@Configuration.GetSection(“RecaptchaSettings”)[“SiteKey”],{action:'homepage'}) .then(功能(令牌){ document.getElementById('g-recaptcha-response')。value=token; }); }); 在你的表格中写下:

<form action="/">
…
<input type="hidden" id="g-recaptcha-response" name="g-recaptcha-response">
…

</form>

…
…
我创建了一个简单的方法来管理它:

public async Task<bool> ChallengePassed(string uri, string gRecaptchaResponse, string secret)
        {

            var concUri = uri + "?secret=" + secret + "&response=" + gRecaptchaResponse;

            var request = new HttpRequestMessage(HttpMethod.Get, concUri);
            var res = await _Client.SendAsync(request);

            if (!res.IsSuccessStatusCode)
            {
                return false;
            }

            var data = await res.Content.ReadAsStringAsync();

            dynamic JSONdata = JObject.Parse(data);
            if (JSONdata.success != "true")
            {
                return false;
            }

            return true;
        }

        #endregion

        #region PRIVATE

        #endregion

        #endregion

        #endregion
    }
public async Task ChallengePassed(字符串uri、字符串gRecaptchaResponse、字符串secret)
{
var concUri=uri+“?secret=“+secret+”&response=“+gRecaptchaResponse;
var request=newhttprequestmessage(HttpMethod.Get,concUri);
var res=await\u Client.SendAsync(请求);
如果(!res.IsSuccessStatusCode)
{
返回false;
}
var data=await res.Content.ReadAsStringAsync();
动态JSONdata=JObject.Parse(数据);
if(JSONdata.success!=“true”)
{
返回false;
}
返回true;
}
#端区
#地区私人
#端区
#端区
#端区
}
我把它简单地称为控制器:

 //recaptcha validation

    bool isChallengeOk = await _CaptchaVerify.ChallengePassed(_Configuration.GetValue<string>("RecaptchaSettings:Uri"), Request.Form["g-recaptcha-response"], _Configuration.GetValue<string>("RecaptchaSettings:SecretKey"));
//recaptcha验证
bool isChallengeOk=wait _captchavify.ChallengePassed(_Configuration.GetValue(“RecaptchaSettings:Uri”)、Request.Form[“g-recaptcha-response”]、_Configuration.GetValue(“RecaptchaSettings:SecretKey”);
请注意,我正在从“_Configuration”对象设置输入参数,该对象表示Startup.cs中配置设置对象的实例。您可以手动将输入参数传递给该方法

享受它吧

这是一个简单的联系人表单示例,由Google reCAPTCHA v3使用纯JavaScript和PHP验证 tldr;跳到底部的代码

相关reCAPTCHA文件等:
  • 创建关键点:
  • 前端集成:
  • 后端验证:
(如果谷歌在听,我们很喜欢你的工作,如果能有一些更详细的例子链接到上面的页面,那就太好了。)

概述:
  • 从谷歌获取密钥
  • 在html的头部加载recaptcha/api.js
  • 用JavaScript劫持表单提交,然后从Google获取令牌
  • 将带有令牌的表单提交到服务器
  • 从您的网站后端向Google发出请求,以验证 提交表格
  • 解释响应并在必要时继续
  • 需要注意的重要事项:成功响应参数仅表示验证码评估是否成功,而不表示提交内容是否可能是垃圾邮件

    “score”参数是您需要了解的结果。分数越高(0到1之间的数字),提交的内容越有可能是真实的,接受的门槛(例如0.5)取决于您

    详细内容: 在HTML的开头添加以下行以加载recaptcha api.js代码:

    <script src="https://www.google.com/recaptcha/api.js?render=$reCAPTCHA_site_key"></script>
    
    (注意,“contact”是contact.php,但我已经用.htaccess“重写”了url)

    现在我们需要劫持默认表单提交来生成令牌。我们可以在第页生成令牌
    public async Task<bool> ChallengePassed(string uri, string gRecaptchaResponse, string secret)
            {
    
                var concUri = uri + "?secret=" + secret + "&response=" + gRecaptchaResponse;
    
                var request = new HttpRequestMessage(HttpMethod.Get, concUri);
                var res = await _Client.SendAsync(request);
    
                if (!res.IsSuccessStatusCode)
                {
                    return false;
                }
    
                var data = await res.Content.ReadAsStringAsync();
    
                dynamic JSONdata = JObject.Parse(data);
                if (JSONdata.success != "true")
                {
                    return false;
                }
    
                return true;
            }
    
            #endregion
    
            #region PRIVATE
    
            #endregion
    
            #endregion
    
            #endregion
        }
    
     //recaptcha validation
    
        bool isChallengeOk = await _CaptchaVerify.ChallengePassed(_Configuration.GetValue<string>("RecaptchaSettings:Uri"), Request.Form["g-recaptcha-response"], _Configuration.GetValue<string>("RecaptchaSettings:SecretKey"));
    
    <script src="https://www.google.com/recaptcha/api.js?render=$reCAPTCHA_site_key"></script>
    
    <form id="contactForm" method="post" action="contact">
        <!-- other form inputs -->
        <input type="hidden" id="gRecaptchaResponse" name="gRecaptchaResponse">
        <input type="submit" name="contact_submit" value="Send message">
    </form>
    
    <script>
        contactForm.addEventListener('submit', event => {
            event.preventDefault()
            validate(contactForm)
        });
    </script>
    
    function validate(form) {
        //perform optional error checking on form. If no errors then request a token and put it into the hidden field
        getRecaptchaToken(form)
    }
    
    //some other (optional) form validation functions
    
    function getRecaptchaToken(form) {
        grecaptcha.ready(function() {
            grecaptcha.execute($reCAPTCHA_site_key, {action: 'contactForm'}).then(function(token) {
                gRecaptchaResponse.value = token //set the value of the hidden field
                form.submit() //submit the form
            });
        });
    }
    
    //get the IP address of the origin of the submission
    $ip = $_SERVER['REMOTE_ADDR'];
    
    //construct the url to send your private Secret Key, token and (optionally) IP address of the form submitter to Google to get a spam rating for the submission (I've saved '$reCAPTCHA_secret_key' in config.php)
    $url =  'https://www.google.com/recaptcha/api/siteverify?secret=' . urlencode($reCAPTCHA_secret_key) . '&response=' . urlencode($g_recaptcha_response) . '&remoteip=' . urlencode($ip);
    
    //save the response, e.g. print_r($response) prints { "success": true, "challenge_ts": "2019-07-24T11:19:07Z", "hostname": "your-website-domain.co.uk", "score": 0.9, "action": "contactForm" }
    $response = file_get_contents($url);
    
    //decode the response, e.g. print_r($responseKeys) prints Array ( [success] => 1 [challenge_ts] => 2019-07-24T11:19:07Z [hostname] => your-website-domain.co.uk [score] => 0.9 [action] => contactForm )
    $responseKeys = json_decode($response, true);
    
    //check if the test was done OK, if the action name is correct and if the score is above your chosen threshold (again, I've saved '$g_recaptcha_allowable_score' in config.php)
    if ($responseKeys["success"] && $responseKeys["action"] == 'contactForm') {
        if ($responseKeys["score"] >= $g_recaptcha_allowable_score) {
            //send email with contact form submission data to site owner/ submit to database/ etc
            //redirect to confirmation page or whatever you need to do
        } elseif ($responseKeys["score"] < $g_recaptcha_allowable_score) {
            //failed spam test. Offer the visitor the option to try again or use an alternative method of contact.
        }
    } elseif($responseKeys["error-codes"]) { //optional
        //handle errors. See notes below for possible error codes
        //personally I'm probably going to handle errors in much the same way by sending myself a the error code for debugging and offering the visitor the option to try again or use an alternative method of contact
    } else {
        //unkown screw up. Again, offer the visitor the option to try again or use an alternative method of contact.
    }
    
    
       {
         "success": true|false,      // whether this request was a valid reCAPTCHA token for your site
         "score": number             // the score for this request (0.0 - 1.0)
         "action": string            // the action name for this request (important to verify)
         "challenge_ts": timestamp,  // timestamp of the challenge load (ISO format yyyy-MM-dd'T'HH:mm:ssZZ)
         "hostname": string,         // the hostname of the site where the reCAPTCHA was solved
         "error-codes": [...]        // optional
       }
    
    <?php  //contact.php
    
        require_once('config.php');
    
        //do server-side validation of other form fields
    
        if (/*form has been submitted and has passed server-side validation of the other form fields*/) {
            $ip = $_SERVER['REMOTE_ADDR'];
            $url =  'https://www.google.com/recaptcha/api/siteverify?secret=' . urlencode($reCAPTCHA_secret_key) . '&response=' . urlencode($g_recaptcha_response) . '&remoteip=' . urlencode($ip);
            $response = file_get_contents($url);
            $responseKeys = json_decode($response, true);
    
            if ($responseKeys["success"] && $responseKeys["action"] == 'contactForm') {
                if ($responseKeys["score"] >= $g_recaptcha_allowable_score) {
                    //send email with contact form submission data to site owner/ submit to database/ etc
                    //redirect to confirmation page or whatever you need to do
                } elseif ($responseKeys["score"] < $g_recaptcha_allowable_score) {
                    //failed spam test. Offer the visitor the option to try again or use an alternative method of contact.
                }
            } elseif($responseKeys["error-codes"]) { //optional
                //handle errors. See notes below for possible error codes
                //(I handle errors by sending myself an email with the error code for debugging and offering the visitor the option to try again or use an alternative method of contact)
            } else {
                //unkown screw up. Again, offer the visitor the option to try again or use an alternative method of contact.
            }
    
            exit;
    
        } else { //(re)display the page with the form
    
            echo <<<_END
    
                <!DOCTYPE html>
                <html lang="en">
                    <head>
                        <title>Contact | Your website</title>
                        <link rel="stylesheet" href="css/style.css">
                        <script src="https://www.google.com/recaptcha/api.js?render=$reCAPTCHA_site_key"></script>
                    </head>
                    <body>
    
                        <!-- header etc -->
    
                        <form id="contactForm" method="post" action="contact">
                            //other form inputs
                            <input type="hidden" id="gRecaptchaResponse" name="gRecaptchaResponse">
                            <input type="submit" name="contact_submit" value="Send message">
                        </form>
                        <script>
                            contactForm.addEventListener('submit', event => {
                                event.preventDefault()
                                validate(contactForm)
                            });
                        </script>
    
                        <!-- footer etc -->
    
                        <script>
                            function validate(form) {
                                //perform optional client-side error checking of the form. If no errors are found then request a token and put it into the hidden field. Finally submit the form.
                                getRecaptchaToken(form)
                            }
    
                            //some (optional) form field validation functions
    
                            function getRecaptchaToken(form) {
                                grecaptcha.ready(function() {
                                    grecaptcha.execute($reCAPTCHA_site_key, {action: 'contactForm'}).then(function(token) {
                                        gRecaptchaResponse.value = token
                                        form.submit()
                                    });
                                });
                            }
                        </script>
                    </body>
                </html>
    
    _END;
    
    <?php //config.php
    
    //other site settings
    
    // Google reCAPTCHA v3 keys
    // For reducing spam contact form submissions
    
    // Site key (public)
    $reCAPTCHA_site_key = 'N0t-a-real-0N3_JHbnbUJ-BLAHBLAH_Blahblah';
    
    // Secret key
    $reCAPTCHA_secret_key = 'N0t-a-real-0N3_i77tyYGH7Ty6UfG-blah';
    
    // Min score returned from reCAPTCHA to allow form submission
    $g_recaptcha_allowable_score = 0.5; //Number between 0 and 1. You choose this. Setting a number closer to 0 will let through more spam, closer to 1 and you may start to block valid submissions.