Registration
First we need to get credentials for our website. Lets go to https://www.google.com/recaptcha/intro/v3.html and click on “Admin console” button.

You’ll get to “Register a new site” form where you should provide the following parameters:
- Label — just a name of the configuration
- reCAPTCHA type — you should select v3
- Domains — yourdomain.com, www.yourdomain.com and localhost

After submitting the form you will get your Site and Secret keys:

Site key will be put on your web page and will be visible to everyone.
Secret key should be passed as an environment variable to your backend server.
Integration
Lets create a simple web application using Node.js and Express.
mkdir recaptcha_v3 && cd recaptcha_v3
touch server.js
touch .envmkdir public
touch public/index.html
npm init -y
npm install express body-parser dotenv isomorphic-fetch
Lets create a start script in package.json so that we will be able to run our server with npm start.
"scripts": {
"start": "node server.js"
},
Lets configure Express in server.js so that we can serve index.html from public.
const express = require('express');
const app = express();
const port = 3000;
app.use(express.static('public'));
app.listen(port, () => console.log(`Listening on port ${port}!`));
First thing is to add reCAPTCHA to your index.html page. Replace <SITE_KEY> with your value.
<script src="https://www.google.com/recaptcha/api.js?render=<SITE_KEY>"></script>
Then you need to get the token:
grecaptcha.ready(function() {
grecaptcha.execute('<SITE_KEY>', {action: 'demo'})
.then(function(token) {
// this token will be passed together with your data
});
});
In our example we will be sending JSON data to POST /send endpoint:
var data = {
hello: hello,
token: token
};fetch('/send', {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
method: 'post',
body: JSON.stringify(data)
})
.then(...)
So, lets create a simple index.html with the following content:
<h1>reCAPTCHA v3 Demo</h1>
<input type="text" id="hello" value="Hello World" />
<button type="button" id="send_button">Send</button>
<hr>
<div id="result"></div>
<script src="https://www.google.com/recaptcha/api.js?render=6Lc7abAUAAAAAJt28TbC0dciNKqcHq4S_uMYBJgG"></script>
<script>
function showResult(text) {
document.querySelector('#result').innerHTML = text;
}
function handleClick(token) {
return function() {
var hello = document.querySelector('#hello').value;
var data = {
hello: hello,
token: token
};
fetch('/send', {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
method: 'post',
body: JSON.stringify(data)
})
.then(response => response.text())
.then(text => showResult(text))
.catch(error => showResult(error));
}
}
grecaptcha.ready(function() {
grecaptcha.execute('6Lc7abAUAAAAAJt28TbC0dciNKqcHq4S_uMYBJgG', {action: 'demo'})
.then(function(token) {
document.querySelector('#send_button').addEventListener('click', handleClick(token));
});
});
</script>
If you run npm start and open http://localhost:3000/ you’ll see the following page:

Verification
On server side you need to verify the token using reCAPTCHA API.
Send POST request to the following URL with secret_key and token received from the client:
const url = `https://www.google.com/recaptcha/api/siteverify?secret=${secret_key}&response=${token}`;
You need to add SECRET_KEY to .env file so that it can be read by Node.js process.
SECRET_KEY=6Lc7abAUAAAAAOQHz...
Below is the complete code for our Express endpoint:
require('dotenv').config();
const express = require('express');
const bodyParser = require('body-parser');
const fetch = require('isomorphic-fetch');
const app = express();
const port = 3000;
app.use(express.static('public'));
app.use(bodyParser.json());
const handleSend = (req, res) => {
const secret_key = process.env.SECRET_KEY;
const token = req.body.token;
const url = `https://www.google.com/recaptcha/api/siteverify?secret=${secret_key}&response=${token}`;
fetch(url, {
method: 'post'
})
.then(response => response.json())
.then(google_response => res.json({ google_response }))
.catch(error => res.json({ error }));
};
app.post('/send', handleSend);
app.listen(port, () => console.log(`Listening on port ${port}!`));
Result
If everything went well, you’ll see the following validation response:

The following attributes are available in the response:
{
"success": true|false, // whether this request was a valid reCAPTCHA token for your site
"score": number // the score for this request (0.0 - 1.0)
"action": string // the action name for this request (important to verify)
"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
}
You need to check that request was successful, the score is in the acceptable range, the action is valid, etc.
For more information about the validation process and scores interpretation see https://developers.google.com/recaptcha/docs/v3#score
Comments
Post a Comment