PHP中的Google Invisible Recaptch集成

时间:2017-05-04 14:16:15

标签: recaptcha

  1. 使用您的Google帐户登录
  2. 2.访问google recaptcha链接。

    3.然后按照代码集成的链接,按照客户端和服务器端验证的代码进行操作。 https://developers.google.com/recaptcha/docs/invisible

    4.创建recaptcha后,增加或降低安全级别一次,转到此处的高级设置,https://www.google.com/recaptcha/admin#list

        <!--
    i.stack.imgur.com slash NqyVT.png
    6aZNw.png
    n5gfN.png
    
    Button     HTML
        <div id='recaptcha' class="g-recaptcha"
          data-sitekey="put the key here"
          data-callback="onSubmit"
          data-size="invisible"
          data-callback="callback"></div>
        <button id='btnsubmit' class="c-button--primary">Submit</button>
    //Apply the exact script from document 
    
        //PHP Validation 
        if($_POST['g-recaptcha-response'] != ''){
                $post_data = http_build_query(['secret'=>'put the secret key here', 'response'=>$_POST['g-recaptcha-response'] ]);
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
                curl_setopt($ch, CURLOPT_URL, 'https://www.google.com/recaptcha/api/siteverify');
                curl_setopt($ch, CURLOPT_POST, 1);      
                curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);     
                // Send the request
                $result = json_decode(curl_exec($ch), true);
                // Free up the resources $curl is using
                curl_close($ch);
                //print_r($result);exit();
                $hostname = strtolower($result['hostname']);
                //echo $hostname.' - '.$result['success'];exit();
                if($result['success'] == 1 && ($hostname == 'www.yousiteurl.com')){
                    //Write here actual execution code for email or data submit
                }
        }
        -->
    

1 个答案:

答案 0 :(得分:0)

<script>
  function onSubmit(token) {
    alert('thanks ' + document.getElementById('field').value);
  }

  function validate(event) {
    event.preventDefault();
    if (!document.getElementById('field').value) {
      alert("You must add text to the required field");
    } else {
      grecaptcha.execute();
    }
  }

  function onload() {
    var element = document.getElementById('submit');
    element.onclick = validate;
  }
</script>
Before body tag close
<script>onload();</script>