The translation was generated automatically and may contain mistakes

Install and connect VK ID Captcha SDK for the web

The instructions describe how to install and connect the VK ID Captcha SDK for the web platform, as well as automatically configure the captcha display and the processing of results using the handler. More about the error — in the article Error with Captcha .

Before starting work, get acquainted with interaction scenario with VK ID Captcha SDK Web and software requirements .

Then integrate the VK ID Captcha SDK Web in one of two ways: the package manager (recommended) or loader script .

Supported versions of browsers

Browser
Version
Google Chrome
63 or newer
iOS Google Chrome
12 or later
Mozilla Firefox
55 or later
Microsoft Edge
79 or later
Opera
50 or more
Safari
12 or later
Samsung Internet
8.2 or later

Using the Package Manager

Step 1. Installation

  1. 1.

    To install an npm package, you need to configure the npm package registry for @vkid :

    “The command line
    npm install @vkid/captcha

  2. 2.

    To connect VK ID Captcha SDK Web, install npm package @vkid/captcha through one of the package managers:

    • •
      npm

    “The command line
    npm i @vkid/captcha

    * yarn ```Командная строка yarn add @vkid/captcha
    • •
      pnpm

    “The command line
    pnpm add @vkid/captcha

Step 2. Processor integration for package manager

Once the Captcha SDK Web VK ID is connected, integrate the captcha error handler into the Web API response handler.

Below are examples of integration with automatic and manual creation of a captcha widget.

Handler integration with captcha widget auto-creation

JavaScript
import { checkCaptchaError, CheckCaptchaType } from "@vkid/captcha"; function api(url: string, bodyParams: { [key: string]: any }) { fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(bodyParams), }).then(async (response) => { const responseResult = await response.json(); // ?1?’ызов обработчика ошибки капчи const { captchaType, captchaWidget } = checkCaptchaError({ responseHeaders: response.headers, url: response.url, responseError: responseResult.error, withWidget: true, }); // Известная ошибка капчи if (captchaType && captchaType !== CheckCaptchaType.UNKNOWN) { try { const successToken = await captchaWidget.show({ container: document.body, view: 'popup', }); // Повторный POST-запрос к API ?1?’Контакте, в который надо добавить success_token: <Полученное значение токена> api(url, { ...bodyParams, success_token: successToken, }); } catch (error) { if (error === 'close') { // Обработка закрытия капчи в случае неуспешного прохождения или закрытия капчи пользователем } else { // Обработка внутренней ошибки капчи } } } // Неизвестная ошибка капчи if (captchaType === CheckCaptchaType.UNKNOWN) { // ?1?’аша реализация обработки неизвестной ошибки (VK ID Captcha SDK не обрабатывает такие ошибки) } }); }

Integrating the handler with manually creating a captcha widget

JavaScript
import { CaptchaWidget, checkCaptchaError, CheckCaptchaType } from "@vkid/captcha"; function api(url: string, bodyParams: { [key: string]: any }) { fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(bodyParams), }).then(async (response) => { const responseResult = await response.json(); // ?1?’ызов обработчика ошибки капчи const { captchaType } = checkCaptchaError({ responseHeaders: response.headers, url: response.url, responseError: responseResult.error, withWidget: false, }); // Известная ошибка капчи if (captchaType && captchaType !== CheckCaptchaType.UNKNOWN) { try { const captchaWidget = new CaptchaWidget(); const successToken = await captchaWidget.show({ container: document.body, captchaType: captchaType, view: 'popup', }); // Повторный POST-запрос к API ?1?’Контакте, в который надо добавить success_token: <Полученное значение токена> api(url, { ...bodyParams, success_token: successToken, }); } catch (error) { if (error === 'close') { // Обработка закрытия капчи в случае неуспешного прохождения или закрытия капчи пользователем } else { // Обработка внутренней ошибки капчи } } } // Неизвестная ошибка капчи if (captchaType === CheckCaptchaType.UNKNOWN) { // ?1?’аша реализация обработки неизвестной ошибки (VK ID Captcha SDK не обрабатывает такие ошибки) } }); }

Using a script loader

Step 1. Installation and initialization

  1. 1.

    To install the Captcha SDK Web VK ID, add a script loader to your application code:

    JavaScript
    <script src="https://static.vk.ru/captchaSDK/loader/1/umd/index.js"></script>

    1 version of the script.

    After installing the VK ID Captcha, the SDK Web will be available in the object window.vkidCaptcha where vkidCaptcha Promise.

  2. 2.

    Initialize the VK ID Captcha SDK Web:

    JavaScript
    const { CaptchaWidget } = await window.vkidCaptcha;

Step 2. Integrating the handler for the boot script

Once the Captcha SDK Web VK ID is connected, integrate the captcha error handler into the Web API response handler.

Below are examples of integration with automatic and manual creation of a captcha widget.

Handler integration with captcha widget auto-creation

JavaScript
function api(url: string, bodyParams: { [key: string]: any }) { fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(bodyParams), }).then(async (response) => { const responseResult = await response.json(); const { checkCaptchaError } = await window.vkidCaptcha; // ?1?’ызов обработчика ошибки капчи const { captchaType, captchaWidget } = checkCaptchaError({ responseHeaders: response.headers, url: response.url, responseError: responseResult.error, withWidget: true, }); // Известная ошибка капчи if (captchaType && captchaType !== 'unknown') { try { const successToken = await captchaWidget.show({ container: document.body, view: 'popup', }); // Повторный POST-запрос к API ?1?’Контакте, в который надо добавить success_token: <Полученное значение токена> api(url, { ...bodyParams, success_token: successToken, }); } catch (error) { if (error === 'close') { // Обработка закрытия капчи в случае неуспешного прохождения или закрытия капчи пользователем } else { // Обработка внутренней ошибки капчи } } } // Неизвестная ошибка капчи if (captchaType === 'unknown') { // ?1?’аша реализация обработки неизвестной ошибки (VK ID Captcha SDK не обрабатывает такие ошибки) } }); }

Integrating the handler with manually creating a captcha widget

JavaScript
function api(url: string, bodyParams: { [key: string]: any }) { fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(bodyParams), }).then(async (response) => { const responseResult = await response.json(); const { CaptchaWidget, checkCaptchaError } = await window.vkidCaptcha; // ?1?’ызов обработчика ошибки капчи const { captchaType } = checkCaptchaError({ responseHeaders: response.headers, url: response.url, responseError: responseResult.error, withWidget: false, }); // Известная ошибка капчи if (captchaType && captchaType !== 'unknown') { try { const captchaWidget = new CaptchaWidget(); const successToken = await captchaWidget.show({ container: document.body, captchaType: captchaType, view: 'popup', }); // Повторный POST-запрос к API ?1?’Контакте, в который надо добавить success_token: <Полученное значение токена> api(url, { ...bodyParams, success_token: successToken, }); } catch (error) { if (error === 'close') { // Обработка закрытия капчи в случае неуспешного прохождения или закрытия капчи пользователем } else { // Обработка внутренней ошибки капчи } } } // Неизвестная ошибка капчи if (captchaType === 'unknown') { // ?1?’аша реализация обработки неизвестной ошибки (VK ID Captcha SDK не обрабатывает такие ошибки) } }); }

VK ID Captcha SDK methods for auto-processing

checkCaptchaError()

A function to check the API response for a captcha error. Returns the result of the check:

  • •
    Type of captcha captchaType if the check revealed a captcha error.
  • •
    Captcha widget captchaWidget if the captcha type is known by the VK ID Captcha SDK Web.

If the user has successfully passed the CAPTCHA, the VK ID Captcha SDK will send a callback notification onClose() and depending on the type of captcha display view will perform one of the actions:

  • •
    It will close the captcha if it is displayed as a pop-up window ( view = popup ).
  • •
    Leave the captcha on the page if it is displayed as a block ( view = block ).

If you want to close the captcha window manually, use the method captchaWidget.close() .

Query parameters

Parameter
Type of data
Description
responseHeaders Mandatory
Headers
API request headers.
url Mandatory
string
API request URL.
responseError Mandatory
object
These are the errors you received in response to the API VKontakte request.. More specifically, in responseError .
withWidget Non-binding
boolean
Captcha widget creation flag. Values available: • true Create and return a captcha widget instance. • false You don’t need to create a captcha instance.

Parameter responseError

In the parameter, you need to pass the error data that you received in response to a request to the VKontakte API..

Parameter data type

JSON
{ error_code: number | null; redirect_uri?: string; }

If the error you received in the response to the API request does not match the type you received, then you need to determine for yourself what the error is.

If the answer you get is a captcha error, you need to make it look like this:

JSON
{ error_code: responseData.errorType === 'captcha' ? 14 : null, redirect_uri: responseData.redirect_uri, }

Response parameters

Parameter
Type of data
Description
captchaType
CheckCaptchaType or null
Type of captcha. Possible meanings CheckCaptchaType : • type_1 , type_2 known types of captchas. • unknown Unknown type of captcha. You need to display the captcha yourself. For this type captchaWidget doesn't come back.
captchaUrl
string or undefined
URL captcha. Returns only for types captchaType : type_1 ' and type_2 .
captchaWidget
CaptchaWidget
Captcha widget.

captchaWidget.show()

A method for displaying captchas. Returns a promise with a captcha result:

  • •
    Token success_token if the user has successfully passed the captcha.
  • •
    A mistake error = close if the user has closed the captcha window.

If the user has successfully passed the CAPTCHA, the VK ID Captcha SDK will send a callback notification onClose() and depending on the type of captcha display view will perform one of the actions:

  • •
    It will close the captcha if it is displayed as a pop-up window ( view = popup ).
  • •
    Leave the captcha on the page if it is displayed as a block ( view = block ).

If you want to close the captcha window manually, use the method captchaWidget.close() .

Request schema

JSON
{ container: HTMLElement; // HTML-элемент, в который будет вставлен виджет view: 'popup' | 'block'; // Режим отображения autofocus: true | false; // Флаг автофокуса капчи при её отображении. Используется, только если view: `block` scheme?: 'light' | 'dark'; // Цветовая схема виджета lang?: string; // Локализация onClose?: () => {} // Callback-уведомление, срабатывает при автоматическом закрытии виджета }

Query parameters

Parameter
Type of data
Description
container Mandatory
HTMLElement
The HTML element that the widget will be inserted into.
view Mandatory
string
Appearance of CAPTCHA: • popup A pop-up window. • block Block (available only for captchaType = type_1 ).
autofocus Non-binding
boolean
The flag that is responsible for captcha autofocus. It is used only if view assigned value block . If the flag is enabled, the page focus will be moved to a web element with a captcha. If the flag is turned off, the focus on the page will remain in the same place as it was before the captcha appeared. Values available: • true Autofocus is enabled (by default). • false Autofocus is off.
scheme Non-binding
string
Widget color scheme: • light - Light. • dark - dark. By default, it corresponds to the layout of the page or application where the captcha is integrated.
lang Non-binding
string
Language of localization. If the value is not passed, it will be defined on the server. Values available: • ru - Russian. • uk - Ukrainian. • en - English. • es - Spanish. • de - German. • pl Polish. • fr - French. • uz - Uzbek. • tr - Turkish. • kk - Kazakh. • be - Belarusian. Example: ru
onClose Non-binding
() => void
Callback-notification of captcha closure, called after captcha closure.

Response schema

JavaScript
promise resolve <token> promise reject <error>

Response parameters

Parameter
Type of data
Description
token
string
Captcha Success Token success_token .
error
string
Mistake сlose if the user has closed the captcha.

captchaWidget.close()

A method for manually closing the captcha. Nothing is returned in response.

Example method call

JavaScript
captchaWidget.close();