DEV Community

moogoo
moogoo

Posted on • Updated on

Rough notes about Google reCAPTCHA (v2 checkbox type)

According to official docs:

There are 2 versions and four types of reCAPTCHA:

  • reCAPTCHA v3
    • returning a score, giving you the ability to take action in the context of your site: for instance requiring additional factors of authentication, sending a post to moderation, or throttling bots that may be scraping content.
  • reCAPTCHA v2
    • "I'm not a robot" Checkbox
    • Invisible reCAPTCHA badge
    • Android

I choose reCAPTCHA v2 Checkbox, seems most site use that type.

  1. render the widget Two ways can do that:

1) Automatically render

<html>
  <head>
    <title>reCAPTCHA demo: Simple page</title>
    <script src="https://www.google.com/recaptcha/api.js" async defer></script>
  </head>
  <body>
    <form action="?" method="POST">
      <div class="g-recaptcha" data-sitekey="your_site_key"></div>
      <br/>
      <input type="submit" value="Submit">
    </form>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

2) Explicitly render

<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit"
    async defer>
</script>
Enter fullscreen mode Exit fullscreen mode

more attributes

  1. Server side verifying

3 way to get user's response token
1) g-recaptcha-response POST parameter when the user submits the form on your site
2) grecaptcha.getResponse(opt_widget_id) after the user completes the reCAPTCHA challenge
3) As a string argument to your callback function if data-callback is specified in either the g-recaptcha tag attribute or the callback parameter in the grecaptcha.render method

API Request
URL: https://www.google.com/recaptcha/api/siteverify METHOD: POST

payload: {
  secret: 'MY_SECRET_KEY', // Required. The shared key between your site and reCAPTCHA.
  response: 'token', // Required. The user response token provided by the reCAPTCHA client-side integration on your site.
  remoteip: 'MY_IP', llOptional. The user's IP address.
}
Enter fullscreen mode Exit fullscreen mode

JSON Response

{
  "success": true|false,
  "challenge_ts": timestamp,  // timestamp of the challenge load (ISO format yyyy-MM-dd'T'HH:mm:ssZZ)
  "hostname": string,         // the hostname of the site where the reCAPTCHA was solved
  "error-codes": [...]        // optional
}
Enter fullscreen mode Exit fullscreen mode

Discussion (0)