Google reCaptcha

.env

RECAPTCHA_SITE_KEY=xxxxx
RECAPTCHA_SECRET=xxxxxx

Front

<input type="hidden" id="grecaptcha" name="grecaptcha" value="">

<script src="https://www.google.com/recaptcha/api.js?render={{ env('RECAPTCHA_SITE_KEY') }}"></script>

<script>
$(document).ready(function(){
    $('#submit').on('click', function(){
        grecaptcha.ready(function() {
          grecaptcha.execute('{{ env('RECAPTCHA_SITE_KEY') }}', {action: 'submit'}).then(function(token) {
              $('#grecaptcha').val(token);
              $('#iform').submit();
			});
        });
    });
});
</script>

Backend

    public function login_save(Request $req){
        $captcha_token = $req->input('grecaptcha');
        if($captcha_token == false){
            return $this->fail_response('reCaptcha Error');
        }else{
            $result = $this->verify_recaptcha($captcha_token);
            if($result == false){
                return $this->fail_response($this->err);
            }
        }
        //logg('ok');

    }

    private function verify_recaptcha($response){
        $recaptcha_url = 'https://www.google.com/recaptcha/api/siteverify';
        $recaptcha_secret = env('RECAPTCHA_SECRET');
        $recaptcha_response = $response;

        // Make and decode POST request:
        $recaptcha = file_get_contents($recaptcha_url . '?secret=' . $recaptcha_secret . '&response=' . $recaptcha_response);
        $recaptcha = json_decode($recaptcha);
        //logg($recaptcha);

        // Take action based on the score returned:
        if($recaptcha->success == false){
            $errors = $recaptcha->{'error-codes'};
            //logg($errors);
            $this->err = implode(', ', $errors);
            return false;
        }else{
            if ($recaptcha->score >= 0.5) {
                // Verified - send email
                return true;
            } else {
                // Not verified - show form error
                $this->err = 'Score is too low';
                return false;
            }
        }
    }

Google Verify API response examples

Type: object<br/><pre>stdClass Object
(
    [success] => 1
    [challenge_ts] => 2020-04-20T15:48:54Z
    [hostname] => localhost
    [score] => 0.9
    [action] => signup
)
</pre>


Type: object<br/><pre>stdClass Object
(
    [success] => 
    [error-codes] => Array
        (
            [0] => timeout-or-duplicate
        )

)
</pre>

Reference:

  1. reCAPTCHA v3 Example for PHP
    https://stevencotterill.com/articles/adding-google-recaptcha-v3-to-a-php-form
  2. Official
    https://developers.google.com/recaptcha/docs/v3
  3. Admin Console
    https://www.google.com/recaptcha/admin