Getting started with Yandex SmartCaptcha
To get started with the service:
Getting started
- Go to the management console
. Log in to Yandex Cloud or register if you do not have an account yet. - On the Billing
page, make sure you have a billing account linked and it has theACTIVE
orTRIAL_ACTIVE
status. If you do not have a billing account, create one.
Create a CAPTCHA
-
In the management console
, select the appropriate folder. -
Select SmartCaptcha.
-
Click Create captcha.
-
Enter a CAPTCHA name. The naming requirements are as follows:
- It must be 2 to 63 characters long.
- It may contain lowercase Latin letters, numbers, and hyphens.
- The first character must be a letter, the last one cannot be a hyphen.
-
Select the type of the main challenge to complete by the user.
-
Select the type of the additional challenge to complete by the user.
-
Select the complexity:
Medium
. -
(Optional) Disable domain name validation.
-
Specify a list of sites where the CAPTCHA will be placed.
-
Leave the Style as is.
-
Click Create.
Retrieve the CAPTCHA keys
- In the management console
, select the appropriate folder. - Select SmartCaptcha.
- Click the name of the CAPTCHA or create a new one.
- In the Overview tab, copy the Client key and Server key field values.
With the client key, you can add a SmartCaptcha widget to your page. You will need a server key to check the user response.
Add the widget to the page
Add the widget automatically:
-
Add the JS script to the user page. To do this, place the following code anywhere on the page (for example, inside the
<head>
tag):<script src="https://smartcaptcha.yandexcloud.net/captcha.js" defer></script>
The
captcha.js
script will automatically find alldiv
elements with thesmart-captcha
class and install the widget in them. -
Add an empty container (
div
element) to the page so that thecaptcha.js
script loads the widget to it:<div id="captcha-container" class="smart-captcha" data-sitekey="<client_key>" ></div>
Note
During the upload, the widget changes the height of its host container to
100px
. This might result in an undesirable layout shift on the page due to the height change. To avoid this shift, set the100px
container height before the widget is loaded.<div ... style="height: 100px"></div>
The I’m not a robot button will appear on the page. The service will check the user request after the user clicks the button. If the request seems suspicious, the service will ask the user to perform an action.
Check the user response
After the check, the user is given a unique token. The token is loaded to the <input type="hidden" name="smart-token" value="<token>"
element inside the widget container. For example:
<div id="captcha-container" class="smart-captcha" ...>
<input type="hidden" name="smart-token" value="<token>">
...
</div>
To validate the token, send a GET request to https://smartcaptcha.yandexcloud.net/validate
with the following parameters:
secret
: Server key.token
: One-time token received after passing the check.ip
: IP address of the user that originated the request to validate the token. This is an optional parameter, but we ask you to provide the user IP when making requests. This helps improve SmartCaptcha performance.
Example of the token validation function:
const https = require('https'),
querystring = require('querystring');
const SMARTCAPTCHA_SERVER_KEY = "<server_key>";
function check_captcha(token, callback) {
const options = {
hostname: 'smartcaptcha.yandexcloud.net',
port: 443,
path: '/validate?' + querystring.stringify({
secret: SMARTCAPTCHA_SERVER_KEY,
token: token,
ip: '<user IP>', // Method for retrieving the user IP depends on your framework and proxy.
}),
method: 'GET',
};
const req = https.request(options, (res) => {
res.on('data', (content) => {
if (res.statusCode !== 200) {
console.error(`Allow access due to an error: code=${res.statusCode}; message=${content}`);
callback(true);
return;
}
callback(JSON.parse(content).status === 'ok');
});
});
req.on('error', (error) => {
console.error(error);
callback(true);
});
req.end();
}
let token = "<token>";
check_captcha(token, (passed) => {
if (passed) {
console.log("Passed");
} else {
console.log("Robot");
}
});
define('SMARTCAPTCHA_SERVER_KEY', '<server_key>');
function check_captcha($token) {
$ch = curl_init();
$args = http_build_query([
"secret" => SMARTCAPTCHA_SERVER_KEY,
"token" => $token,
"ip" => $_SERVER['REMOTE_ADDR'], // You need to provide the user IP.
// Method for retrieving the user IP depends on your proxy.
]);
curl_setopt($ch, CURLOPT_URL, "https://smartcaptcha.yandexcloud.net/validate?$args");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 1);
$server_output = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpcode !== 200) {
echo "Allow access due to an error: code=$httpcode; message=$server_output\n";
return true;
}
$resp = json_decode($server_output);
return $resp->status === "ok";
}
$token = $_POST['smart-token'];
if (check_captcha($token)) {
echo "Passed\n";
} else {
echo "Robot\n";
}
import requests
import sys
import json
SMARTCAPTCHA_SERVER_KEY = "<server_key>"
def check_captcha(token):
resp = requests.get(
"https://smartcaptcha.yandexcloud.net/validate",
{
"secret": SMARTCAPTCHA_SERVER_KEY,
"token": token,
"ip": "<user IP>" # Method for retrieving the IP depends on your framework and proxy.
# For example, in Flask, this can be request.remote_addr
},
timeout=1
)
server_output = resp.content.decode()
if resp.status_code != 200:
print(f"Allow access due to an error: code={resp.status_code}; message={server_output}", file=sys.stderr)
return True
return json.loads(server_output)["status"] == "ok"
token = "<token>" # For example, request.form["smart-token"]
if check_captcha(token):
print("Passed")
else:
print("Robot")
What's next
- Read more about connection methods for the SmartCaptcha widget.