Connecting to a web application
-
Download the VK Капча SDK:
npmyarnpnpmJS scriptnpm install @vkid/captcha -
Add the retrieval of the
captchaWidgetclass to the frontend:npm, yarn, pnpmJS scriptimport { CaptchaWidget } from "@vkid/captcha"; -
Make sure that standard ports
80for HTTP and443for HTTPS are used during local development. -
Get the link for launching the captcha widget from the backend.
-
Display the captcha to the user. Use the SDK method
captchaWidget.show().The method will return a promise object with the captcha verification result: a successful captcha token if the user passed the captcha, or an error if the user closed the captcha.
-
Process the captcha verification result:
- If the promise object contains a successful captcha token, send it to the backend for validation.
- If the user closed the captcha, nothing is sent to the backend. Determine what should happen in the frontend in this case.
TypeScript code example:
const API_ERROR_CODE_CAPTCHA = <ERROR_CODE>; // Error code that the service backend sends when a captcha is required for the user's actioninterface ApiCaptchaError {error_code: number;error_msg: string;captcha_sid: string; // Captcha session identifierredirect_uri: string; // Link for launching the captcha widget, received from the backend, contains a session token}const handleCaptchaError = async (captchaUrl: string) => { // Captcha handlertry {const captchaWidget = new CaptchaWidget();const success_token = await captchaWidget.show({ // The show() method returns a promise object with the success_token when the captcha is successfully passedcontainer: document.body, // HTML element in which the captcha widget will be displayediframeSrc: captchaUrl, // Link for launching the captcha widget from the redirect_uri parametercaptchaType: 'type_1', // Captcha type: 'type_1'view: 'popup', // Captcha view: 'popup' or 'block'});fetch('url'); // Repeat request for user action + received success_token} catch (error) {if (error === 'close') {// Handling captcha closure by the user}}};fetch('url') // User performs an action.then((response) => response.json()).then((data) => { // Error code checkconst error = data.error;if (error?.error_code === API_ERROR_CODE_CAPTCHA) { // If the API_ERROR_CODE_CAPTCHA error code is returned, the captcha handler is called with redirect_urihandleCaptchaError(error.redirect_uri);}});