Google Recaptcha V3 Complete Code

grecaptcha
Requirements:
  1. jQuery (if not it will automated added into pages) 
  2.       if (typeof jQuery == 'undefined' || !window.jQuery) {
            var hs = document.createElement('script');
            hs.type = 'text/javascript';
            hs.async = true;
            hs.src = 'https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js';
            document.getElementsByTagName('head')[0].appendChild(hs);
            document.getElementsByTagName('body')[0].appendChild(hs);
            document.head.appendChild(hs);
            document.body.appendChild(hs);
          }
        
  3. Recaptcha Site Key And Secret (backend): Get Here
  4.     //Set site key as global variable
        const g_site_key = 'YOUR_SITE_KEY';
        
  5. Main Code:
  6.         //loader
            (function () {
              submitDisable();
              download_script('https://www.google.com/recaptcha/api.js?render='+g_site_key+'&render=explicit', function () {
                grecaptcha.ready(function () {
                  gexec();
                });
              });
            })();
          //function callback
          function gexec(){ //also refresh function
            grecaptcha.execute(g_site_key, { action: 'homepage' }).then(function (token) {
              recaptcha_insert_token(token); //insert element token into form
            });
          }
          //function add recaptcha elements
          function recaptcha_insert_token(token) {
            if (typeof jQuery == 'undefined'){
              console.log('JQuery Not Loaded');
            } else {
              var f = $('form'), fg = f.find('[name="g-recaptcha-response"]');
            if (fg.length === 0){
              $('<input type="hidden" readonly value="' + token + '" name="g-recaptcha-response">').appendTo(f);
            } else {
              fg.val(token);
            }
            }
          }
        

Complete Code

HTML
      <!--button refresh token (example)-->
      <button class="btn-block btn" onclick="gexec()">Refresh</button>
  
Javascript
    //load jQuery if not exists (automated)
    if (typeof jQuery == 'undefined' || !window.jQuery) {
      var hs = document.createElement('script');
      hs.type = 'text/javascript';
      hs.async = true;
      hs.src = 'https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js';
      document.getElementsByTagName('head')[0].appendChild(hs);
      document.getElementsByTagName('body')[0].appendChild(hs);
      document.head.appendChild(hs);
      document.body.appendChild(hs);
    }
    //set site key
    const g_site_key = 'YOUR_SITE_KEY';
    //loader
    (function () {
      submitDisable();
      download_script('https://www.google.com/recaptcha/api.js?render='+g_site_key+'&render=explicit', function () {
        grecaptcha.ready(function () {
          gexec();
        });
      });
    })();
    //function callback
    function gexec(){ //also refresh function
      grecaptcha.execute(g_site_key, { action: 'homepage' }).then(function (token) {
        recaptcha_insert_token(token); //insert element token into form
      });
    }
    //function add recaptcha elements
    function recaptcha_insert_token(token) {
      if (typeof jQuery == 'undefined'){
        console.log('JQuery Not Loaded');
      } else {
        var f = $('form'), fg = f.find('[name="g-recaptcha-response"]');
      if (fg.length === 0){
        $('<input type="hidden" readonly value="' + token + '" name="g-recaptcha-response">').appendTo(f);
      } else {
        fg.val(token);
      }
      }
    }
  
PHP (backend)
      <?php
      function recaptcha_verify($secret)
      {
      	if (isset($_POST['g-recaptcha-response'])) {
      		$response = $_POST['g-recaptcha-response'];
      		$remoteip = $this->getUIP();
      		$secret = $this->recaptcha_s;
      		$g_response = json_decode(file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret=' . $secret . '&response=' . $response . '&remoteip=' . $remoteip), true);
      		if (isset($g_response['success']) && true === $g_response['success']) {
      			return true;
      		} else {
      			return false;
      		}
      	}
      }

      if (isset($_POST['login'])){ //example if you have post named login
      	if (recaptcha_verify('YOUR_SECRET_KEY_HERE') !== false){
      		/* Recaptcha Success */
      	} else {
      		/* Recaptcha Failed */
      	}
      }
  

Full Example at Codepen

See the Pen Complete Google recaptcha v3 by dimas lanjaka (@dimaslanjaka) on CodePen.

Post a Comment

0 Comments