Google has announced a new reCAPTCHA with more security to protect your website from spam and other types of automated systems.
Google is providing this service freely. Here we will discus on how to implement this captcha in your website using JavaScript
Signing Up for reCAPTCHA
To use this service you need to signup for it.
Google recatcha signup
You need to provide a label for the site to identify it later and a list of domains, with each domain in a new line for which the captcha must be displayed.
Once you finish the signup process, you will be provided with a 2 key pair.
- site key – used to display the widget in site(s) you registered.
- secret – used to authorize communication between your backend application and the reCAPTCHA server to verify the users response.
Keep the secret key safe for security reasons
Google reCAPTCHA working Overview
Displaying the reCAPTCHA
The reCAPTCHA can be displayed either Automatically(HTML) or Explicitly(JS). Here the explicit method is used using JavaScript.
reCAPTCHA JavaScript API
grecaptcha.render(container, parameters)
- container – Either the ID(string) or DOM element of HTML where the widget should be rendered.
- parameters – A object containing the reCAPTCHA config key value pairs.ParamValuesDefaultDescriptionOptionalsitekeyYour site key got after signup.Nothemedark, lightlightColor theme of widgetYestypeaudio, imageimageThe CAPTCHA type to be shown.YescallbackYour callback function that’s executed when the user submits a successful CAPTCHA response. The user’s response, g-recaptcha-response, will be the input for your callback function.Yes
This method renders the container as a reCAPTCHA widget and returns the ID of the newly created widget element.
Example
var captchaContainer = null;
var loadCaptcha = function() {
captchaContainer = grecaptcha.render('captcha_container', {
'sitekey' : '',
'callback' : function(response) {
console.log(response);
}
});
};
grecaptcha.reset(widget_id)
- widget_id (Optional) – Widget id to reset. If not provided, defaults to the first widget that was created.
Resets the widget.grecaptcha.getResponse(widget_id)
- widget_id (Optional) – Widget id to get the response from. If not provided, defaults to the first widget that was created.
Gets the reCAPTCHA widget response.
Loading reCAPTCHA JS API
The JS reCAPTCHA API must be loaded to render the widget. Two of the request params must be passed in the request while loading the API.
- onload – The method to invoke after the API has loaded successfully.
- render – Either Automatically(onload) or Explicit(explicit).
<script src="https://www.google.com/recaptcha/api.js?onload=loadCaptcha&render;=explicit" async defer></script>
Example
<html>
<head>
<title>Loading captcha with JavaScript</title>
<script type='text/javascript'>
var captchaContainer = null;
var loadCaptcha = function() {
captchaContainer = grecaptcha.render('captcha_container', {
'sitekey' : 'Your sitekey',
'callback' : function(response) {
console.log(response);
}
});
};
</script>
</head>
<body>
<form action="http://www.codedodle.comxa.com/demos/recaptcha/submit.php" method="POST">
<label>Username: <input type="text" name="username" /></label>
<small>Are you a robot?</small>
<div id="captcha_container"></div>
<input type="submit" value="Submit">
</form>
<script src="https://www.google.com/recaptcha/api.js?onload=loadCaptcha&render;=explicit" async defer></script>
</body>
</html>
The response from the user’s captcha challenge can be got three ways. It can be as,
- g-recaptcha-response – a POST parameter in the submitted form
- grecaptcha.getResponse(widget_id) – will provide the response after the user completes the captcha.
- A string argument to the callback function specified in the config object passed to the render method.
In the demo provided, the callback will alert the response string and the form input “g-recaptcha-response” will be used to verify the response.
Verifying – Human or Robot?
After we have got the user’s challenge response, we need to make a request to the google recaptcha API with the user’s response with the backend to get the result.
The URL to request the result is,
URL: https://www.google.com/recaptcha/api/siteverify?secret=your_secret&response=response_string&remoteip=user_ip_address
Once the user submit’s the form, a GET request is sent to the above link with the secret, response_string.
Response Format
{
"success": true|false,
"error-codes": [...] // optional
}
For a full list of error-codes available, please visit – Google Documentation
Backend Verification
At the server side, the response from the form and the secret must be used to request to the link provided for verifying the response of the user’s captcha challenge. Here PHP is used to verify the response. You can use any language, but the process is same.
Backend Code in PHP
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Construct the Google verification API request link.
$params = array();
$params['secret'] = 'Your secret key here.'; // Secret key
if (!empty($_POST) && isset($_POST['g-recaptcha-response'])) {
$params['response'] = urlencode($_POST['g-recaptcha-response']);
}
$params['remoteip'] = $_SERVER['REMOTE_ADDR'];
$params_string = http_build_query($params);
$requestURL = 'https://www.google.com/recaptcha/api/siteverify?' . $params_string;
// Get cURL resource
$curl = curl_init();
// Set some options
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $requestURL,
));
// Send the request
$response = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);
$response = @json_decode($response, true);
if ($response["success"] == true) {
echo '<h3 class="alert alert-success">Login Successful</h3>';
} else {
echo '<h3 class="alert alert-danger">Login failed</h3>';
}
}
