• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

Ani's Webdev Blog

A learning diary of website development

  • Home
  • Demo
    • Ajax Contact Form
  • WordPress
  • Front-end
  • Backend

reCaptcha v3: How to implement on WordPress custom forms to stop bot signups

Modified on: February 17, 2021

Including reCaptcha as a security layer is one way to fight against bots. In this article, let’s discuss how to implement reCaptcha v3 on a custom forms. Also, we will take a look what are the differences among the reCaptcha versions.

Table of contents

  1. 1. Task description
    1. 2. reCaptcha v2 and v3: What are the differences?
      1. 3. Implementing reCaptcha v3 on WordPress
        1. 3.1. Using plugin: Invisible reCaptcha for WordPress
          1. 3.2. Without plugin: reCaptcha v3 with PHP and Javascript
          2. 4. References

            1. Task description

            • Install reCaptcha v3 in the page only where there is a registration form. The form includes fields such as name, website url, email, text areas, a selection field, phone number field which have some basic jQuery validation.
            • Test if the reCaptcha is installed correctly.

            By installing the reCaptcha only when there is the form that needs to be checked, we save time and http request for a better performance.

            I think this is a good habit for WordPress users to remove unnecessary things because as you might notice, whenever installing a new plugin, more or less there will be custom js and css files to load with your page not care about does the page needs it or not, which increases the http requests and makes the website slowlier.

            We will need a Site Key and a Secret Key to use the reCaptcha. This is free to setup and retrieve so you can go to the dashboard and register your website here. After that you can have 1 Site Key and 1 Secret Key.

            recaptcha site keys and secret keys

            2. reCaptcha v2 and v3: What are the differences?

            Which types of reCaptcha to choose from? What are their differences?

            So when registering a new domain name, you will be asked to choose the type of reCaptcha to be implemented. Most of the time I was confusing with reCaptcha v3, and reCaptcha v2: I’m not a robot and Invisible reCaptcha badge. Let’s have a quick look how they are different.

            recaptcha types

            Some images of reCaptcha.

            google early captcha
            The early captcha which brings about bad user experiences.
            I'm not a robot
            The common “I’m not a robot” reCaptcha which can be seen in many websites nowadays.
            recaptcha challenges
            reCaptcha v2 I’m not a robot extra challenges.

            So basically:

            • reCaptcha v3 does not require users to do anything themselves, but instead give a score based on their behavior with the web page. The lower the score, the higher the possibility it is a bot.
            • reCaptcha v2 sometimes let user pass without doing anything, or with checking the box “I’m not a robot”, sometimes ask for extra puzzle solving.
            • With reCaptcha v2, if the system suspects that you are a bot, you still can prove that you are human with extra challenges e.g image selection.
            • With reCaptcha v3, if you are not a bot and google thinks you are a bot, you can’t do anything. But, this strictness level can be customized with a lower threshold score.
            v3 - Invisible reCaptchav2- I'm not a robotv2- Invisible Badge
            How it worksObserves user behaviors and interactions with the page and then return a score reflecting how likely this user is a bot or human.Requires user to click a checkbox to verify that he / she is not bot. It will give extra puzzle to solve in case of suspection.Invokes when user clicks on an existing button or via Javascript API call. It will give extra puzzle to solve in case of suspection.
            Extra challenges in case of suspectionNot naturally, but developers can suggest an action for the user based on the score returns.YesYes
            Requires user to click on checkboxNoYesNo
            Returns valuea json object including scores and success (true | false)NoNo
            Further actions can be implemented based on the validationYesNoYes
            Shows a reCaptcha badge on your websiteYesNo, only display the checkbox.Yes
            Requires a JavaScript callbackNoNoYes

            3. Implementing reCaptcha v3 on WordPress

            There are two ways that the reCaptcha can be implemented on WordPress: using a plugin or code it yourself.

            3.1. Using plugin: Invisible reCaptcha for WordPress

            Notice: Some form plugins for WordPress already have the reCaptcha integration, so if you only want for e.g Contact Form 7 you don’t need to download any extra plugin because the form itself will let you paste in the Site Key and Secret Key for spam prevention.

            For Gravity Forms, Contact Form 7, WooCommerce or common WordPress forms like login or register, you can have a look at Invisible reCaptcha for WordPress by Mihai Chelaru. The plugin has quite straightforward instructions on how to implement the invisible reCaptcha on WordPress.

            So if you have many forms and want a quick way to do this, then just go ahead and download the plugin, then go to the Settings and input your Site Key and Secret Key and you’re ready to go.

            It is easy if you want to integrate it with Contact Form 7, or Gravity Forms as you only need to tick the buttons in the plugin’s settings page. But if you would like to have it on a custom form which is custom coded, there are some hooks that you can use, as reference from the plugin developer. For basic setup, we can use the google_invre_render_widget_action action and google_invre_is_valid_request_filter.

            So to the theme’s functions.php:

            PHP

            On the HTML page template of the form, add this before the </form> closing tag:

            PHP

            Alternatively, you also can add the code straight to the page template before the form closing tag. This is a faster way to do and also ensures that you only have the code on the form page.

            PHP

            If doing it correctly we can see the reCaptcha badge on the form page, bottom right. Then, in the PHP processing file, validate the form with recaptcha before processing it.

            PHP

            Depending on your structure it might look different, but in a nutshell what we have to do:

            • Call do_action(‘google_invre_render_widget_action’); to add the recaptcha possibility to the form.
            • Write a function with google_invre_is_valid_request_filter to check if the form return is not submitted by a bot.

            So hope it helps. I did not process far with this setup because it has conflicts with jQuery validation, where the form submitted with only reCaptcha validation and ignore other validation. So I switch to the code solution.

            3.2. Without plugin: reCaptcha v3 with PHP and Javascript

            The steps are quite similar as to use the plugin. Basically what we need to do is:

            • Add a reCaptcha token to the form
            • Check with Google if the form submission looks legit, based on the token
            • Refuse or pass based on the result that Google returns

            Add reCaptcha token to the form

            Let’s add a hidden field before the form closing tag:

            HTML

            Next, add the value of the form to be equal to the token that is provided by the reCaptcha. We will do it with this piece of javascript, as instructions on the reCaptcha docs:

            JS

            Or if you prefer jQuery:

            JS

            If doing it correctly we can see the reCaptcha badge on the form page, bottom right.

            recaptcha badge
            The reCaptcha badge.

            Now if you inspect the hidden field with the browser console, you can see a string of token attached to it. This string will change everytime the form loads.

            recaptcha token string
            A string of token.

            Check with Google if the form submission looks legit, based on the token

            Depending on your file structure, you can write this as a private function in a class or if you do not have any structure, you can paste this to your functions.php.

            Google will return with a json object.

            JSON

            Because we only need to check is it legit or not, let’s just take the “success”. So it will return true or false, and we based on that to continue processing the form or to stop.

            Plain Text

            Validate before processing the form:

            PHP

            4. References

            • reCaptcha docs
            • Create reCaptcha keys for your website
            • Invisible reCaptcha plugin for WordPress
            • What is the differences among reCaptcha different versions

            Filed Under: Backend, Featured, Wordpress, Wordpress Plugins, WordPress Themes Tagged With: javascript, php, security

            Recent posts

            [WordPress] Let’s Make Plugin E01: A Simple View Count Plugin

            [WordPress] Create custom post type programmatically

            [WordPress] Open Images in Posts into Lightboxes On Clicks (Without Plugins)

            Reader Interactions

            You are here: Home / Backend / reCaptcha v3: How to implement on WordPress custom forms to stop bot signups

            Comments

            1. Ovinz says

              October 18, 2020 at 1:14 pm

              Thanks for your post!

              Just a mistake in your last snippet
              It should be inverted as :

              if(!recaptcha_validate($_POST[‘token’])) {
              // …
              }

              Reply
              • Anh Karppinen says

                October 20, 2020 at 5:51 am

                Yes, thank you for your correction! I’ll fix it to the post.

                Reply
            2. Stef Serafin says

              February 17, 2021 at 6:43 pm

              Hey Anh, great post. I’m looking at adding your input only. I have V3 keys enabled thru Contact Form 7. Do I still need to do all this HTML and JS if the keys are inside CF7 too?

              I was hoping to just lay this down before the review comment portion to trick bots.

              Thanks
              Stef

              Reply
              • Anh Karppinen says

                February 17, 2021 at 9:27 pm

                Hello Stef,

                Thank you for commenting.
                Do you mean you are customizing the WordPress’s built in comment section?
                As I understand, Contact Form 7 does not handle the this section in WordPress, so if you are adding new input with your own code, you would need to implement both HTML and JS, so that the reCaptcha is triggered correctly.

                I think your keys that were registered via Contact Form 7 will be available to be reused for the comment section. You could login to the reCaptcha dashboard (https://www.google.com/recaptcha/admin) to ensure that the keys are available and / or make a key dedicated to comment section so you can see statistics separately.

                Anh

                Reply

            Leave a Reply Cancel reply

            Your email address will not be published. Required fields are marked *

            Primary Sidebar

            Hi! I am a Vietnamese coder living in Oulu, Finland. Currently I am working with PHP, MySQL, HTML, CSS, and JavaScript. This blog is my learning diary, in which I share knowledge from my own experience or research. Hopefully you can find something useful here and don’t hesitate to open a discussion or leave a feedback!

            FOLLOW MY BLOG

            Thank you for visiting this website! I hope you find something useful here :). Contact me by email: anh@anhkarppinen.com.