Let’s Talk

How to add Google reCAPTCHA v3 to a Form (PHP/HTML)

Google’s reCAPTCHA v2 made the user interact with a box (see our integration guide); having to click “I’m not a robot” was annoying and hindered conversion rates. v3 removes that, working behind the scenes to calculate whether a bot or human is completing the form.

Step 1

Sign up and get your keys here: https://www.google.com/recaptcha/admin; make sure to select “v3”. You will get a SITE key and a SECRET key.

Step 2

Include this on your page:

<script src="https://www.google.com/recaptcha/api.js?render=SITE_KEY"></script>
<script>
    grecaptcha.ready(function() {
        grecaptcha.execute('SITE_KEY', {action: 'contact_us'}).then(function(token) {
            // Send the token to your server
            document.getElementById('recaptcha-token').value = token;
        });
    });
</script>

Where “action” is whatever descriptive term you want to give the page/type of form you’re working with and SITE_KEY is the site key that was generated in Step 1.

Step 3

Add the following into your form:

<input type="hidden" name="recaptcha_token" id="recaptcha-token"/>

Step 4

On form submission do this:

$response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=SECRET_KEY&response=".$_POST['recaptcha_token']);
$responseData = json_decode($response);

if($responseData->success && $responseData->score >= 0.5){
    // User is likely human; process form submission
}else{
    // Possible bot or suspicious activity; abort form submission
}

Where SECRET_KEY is the secret key generated in Step 1. You can tweak the score to suit; 0 means it’s definitely a bot and 1 means it’s definitely a human.

Enjoy!

This code is free to use at your own discretion. It comes without warranty. Please feel free to feedback any edits.