Google new reCAPTCHA using JavaScript
Reading Time:
Reading Time:
Google is providing this service freely. Here we will discus on how to implement this captcha in your website using JavaScript
To use this service you need to signup for it.
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.
Keep the secret key safe for security reasons
The reCAPTCHA can be displayed either Automatically(HTML) or Explicitly(JS). Here the explicit method is used using JavaScript.
grecaptcha.render(container, parameters)
Param | Values | Default | Description | Optional |
---|---|---|---|---|
sitekey | Your site key got after signup. | No | ||
theme | dark, light | light | Color theme of widget | Yes |
type | audio, image | image | The CAPTCHA type to be shown. | Yes |
callback | Your 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.
var captchaContainer = null;
var loadCaptcha = function() {
captchaContainer = grecaptcha.render('captcha_container', {
'sitekey' : '',
'callback' : function(response) {
console.log(response);
}
});
};
grecaptcha.reset(widget_id)
Resets the widget.
grecaptcha.getResponse(widget_id)
Gets the reCAPTCHA widget response.
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.
<script src="https://www.google.com/recaptcha/api.js?onload=loadCaptcha&render=explicit" async defer></script>
<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,
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.
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.
{
"success": true|false,
"error-codes": [...] // optional
}
For a full list of error-codes available, please visit – Google Documentation
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.
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>';
}
}
The above API reference is from Google recaptcha Documentation.