All Products
Search
Document Center

Captcha:Web and H5 client integration (V3 architecture)

Last Updated:Jul 13, 2026

After you add a verification scenario in the console, integrate the Captcha initialization code into your web or H5 pages. This topic describes the integration process.

Prerequisites

Method overview

You can integrate your business client with Captcha 2.0 in just 3 steps:

  1. Add the global variable AliyunCaptchaConfig.

  2. Dynamically load the Captcha JS script.

  3. Call the initialization method.

Note

Procedure

Step 1: Add the AliyunCaptchaConfig global variable

Before you include the Alibaba Cloud CAPTCHA JS script, or at the beginning of the HTML head tag, add a script to define a global variable named AliyunCaptchaConfig that contains the region and prefix parameters.

<script>
  window.AliyunCaptchaConfig = {
    // Required. The region where the Captcha instance is located. Supported values: cn (Chinese mainland) and sgp (Singapore).
    region: "cn",
    // Required. The prefix of your Captcha instance. After you activate Alibaba Cloud Captcha 2.0, you can obtain the prefix from the Instance Information card on the Overview page in the console.
    prefix: "******",
  };
</script>
Important

You can find the prefix in the Overview > Cumulative Activation Time > Identity Prefix section, as shown in the following figure:

image

Step 2: Dynamically load Captcha JS

Dynamically load the Captcha JS script into your web page. This allows you to call the Captcha for verification when needed.

Note

You must dynamically load the Captcha JS script. Bypassing dynamic loading, for example by downloading the JS for local deployment, prevents the service from updating correctly. This can lead to security vulnerabilities, incorrect blocking, or compatibility issues. Do not load the script multiple times, as this can cause verification to fail.

<script
  type="text/javascript"
  src="https://o.alicdn.com/captcha-frontend/aliyunCaptcha/AliyunCaptcha.js"
></script>

Step 3: Call the initialization method

If the initAliyunCaptcha method fails during initialization, refer to Client initialization errors for troubleshooting.

<script type="text/javascript">
  var captcha;
  // Parameters other than region and prefix
  window.initAliyunCaptcha({...});
</script>

Code example

Note
  • Load the Captcha JS script as early as possible to collect more complete environment and device information. Ensure a delay of at least 2 seconds between loading the script and initiating a verification request.

  • To ensure faster loading of image resources, initialize the Captcha as early as possible. This pre-loads related resources and accelerates image loading. Ensure an interval of at least 2 seconds between initialization and the verification request.

  • In your client's source code, create a placeholder element for the Captcha. This DOM element will be referenced by the element and button parameters, such as <div id="captcha-element"></div> in the following example.

<!doctype html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta name="data-spm" />
    <!-- 1. Before loading the Alibaba Cloud Captcha JS script, or at the beginning of the HTML head tag, add a script to save a global variable AliyunCaptchaConfig that contains the region and prefix parameters. -->
    <script>
      window.AliyunCaptchaConfig = {
        // Required. The region where the Captcha instance is located. Supported values: cn (Chinese mainland) and sgp (Singapore).
        region: "cn",
        // Required. The prefix of your Captcha instance. After you activate Alibaba Cloud Captcha 2.0, you can obtain the prefix from the Instance Information card on the Overview page in the console.
        prefix: "xxxxxx",
      };
    </script>
    <!-- 2. Integrate the main JS script. -->
    <script
      type="text/javascript"
      src="https://o.alicdn.com/captcha-frontend/aliyunCaptcha/AliyunCaptcha.js"
    ></script>
  </head>

  <body>
    <div id="captcha-element"></div>
    <!-- A placeholder element for the Captcha, used for the element parameter in the initialization function. -->
    <button id="button" class="btn">Log On</button>
    <!-- In popup mode, this element triggers the Captcha dialog. -->
    <!-- 3. Create a <script> tag to call the Captcha initialization function initAliyunCaptcha. -->
    <script type="text/javascript">
      var captcha;
      // In popup mode, these are the parameters excluding region and prefix.
      window.initAliyunCaptcha({
        // The scene ID. After you create a verification scenario, you can find the scene ID in the verification scenario list.
        SceneId: "******",
        // The Captcha mode. 'popup' for popup mode, 'embed' for embedded mode. Do not change this value.
        mode: "popup",
        // The placeholder element on the page for rendering the Captcha. This must match the placeholder element in your code.
        element: "#captcha-element",
        // The element that triggers the Captcha dialog or traceless verification.
        button: "#button",
        // The callback function for successful verification.
        success: function (captchaVerifyParam) {
          // The input parameter is captchaVerifyParam.
          // 1. Send a request to your backend to validate the captchaVerifyParam.
          // 2. Handle the business logic based on the validation result.
          // 3. If your business requires re-verification, call the initAliyunCaptcha method to re-initialize Captcha.
        },
        // The callback function for failed verification.
        fail: function (result) {
          // The input parameter contains the failure information.
          // No action is needed within the normal verification validity period. The Captcha refreshes automatically for a new attempt.
          console.error(result);
        },
        // The callback function for binding the Captcha instance. This callback is invoked after Captcha is successfully initialized.
        getInstance: function (instance) {
          captcha = instance;
        },
        // The style for the slider and click-to-verify challenge trigger boxes. You can customize the width and height in pixels (px).
        slideStyle: {
          width: 360,
          height: 40,
        },
        // ...Other parameters. See the initAliyunCaptcha parameter description.
      });
    </script>
  </body>
</html>

Parameters

AliyunCaptchaConfig parameters

Parameter

Type

Required

Default

Description

region

String

Yes

cn

The region where the Captcha instance is located. Valid values:

  • cn: Chinese mainland.

  • sgp: Singapore.

Important
  • If the client region is cn, your server side must call the Chinese mainland endpoint. If the region is sgp, call the Singapore endpoint.

  • The service has control plane centers in the China (Shanghai) and Singapore regions. Based on the region parameter you specify, client-side data, such as behavioral and device information, is sent to the corresponding center to perform security verification.

prefix

String

Yes

None

The prefix of your Captcha instance. After you activate Alibaba Cloud Captcha 2.0, you can find this prefix in the upper-right corner of the Overview page in the console.image

initAliyunCaptcha parameters

Call the Captcha initialization method as early as possible after the page loads.

Parameter

Type

Required

Default

Description

SceneId

String

Yes

None

The scene ID of the Captcha. You can obtain this value after you create a verification scenario.image

mode

String

Yes

None

The Captcha mode. Valid values:

  • popup: The Captcha appears in a dialog box.

  • embed: The Captcha is embedded in the page.

    Important

    traceless verification does not support embedded mode. Use popup mode instead.

element

String

Yes

None

The selector for the HTML element where the Captcha will be rendered. The value must be a valid CSS selector, such as '#captcha-element'.

button

String

Yes

None

The selector for the HTML element that triggers the Captcha. Clicking this element displays the Captcha dialog or starts traceless verification. The value must be a valid CSS selector, such as '#my-button'.

success

Function

Yes

None

The callback function for successful CAPTCHA verification provides the verification parameter. In this callback function, you can obtain CaptchaVerifyParam and request your server to perform CaptchaVerifyParam validation.

fail

Function

No

None

The callback function executed if verification fails. It receives an object containing details about the failure.

getInstance

Function

Yes

getInstance

The callback function for obtaining the Captcha instance object after initialization. This callback is invoked after the Captcha is successfully initialized. Use this function to get a reference to the instance:

function getInstance(instance) {
  captcha = instance;
}

slideStyle

Object

No

{ width: 360, height: 40 }

The style for the trigger box of slider and click-to-verify challenges. You can customize the width and height in pixels (px). This parameter is compatible with legacy parameter names.

Important
  • To ensure accurate verification, the system needs to collect sufficient data from the slide action. We recommend a slider width of at least 320 px. If the width is less than 320 px, the system configures it as 320 px.

  • This parameter does not apply to jigsaw puzzle and image restoration challenges. If you are using a jigsaw puzzle Captcha, do not override the CSS to forcibly change the style. The image size and verification answers for jigsaw puzzle Captcha are fixed, and modifying the style will cause verification to fail.

language

String

No

cn

The languages supported by Alibaba Cloud Captcha 2.0.

timeout

Number

No

5000

The timeout duration for a single Captcha initialization request, in milliseconds (ms).

rem

Number

No

1

Scales the entire Captcha UI. The value acts as a multiplier. For example, 0.5 halves the size, and 2 doubles it. Must be a positive number.

Note

The rem parameter is intended primarily for mobile browsers.

onError

Function

No

None

The error callback function for failures or timeouts in the Captcha initialization API request and resource loading. Use the following fixed format:

function onError(errorInfo) { 
  const {code, msg} = errorInfo;
  console.log(code, msg);
}

onClose

Function

No

None

When the verification code pop-up is closed, the onClose callback is triggered. The parameter reason indicates the specific reason for closing, and its possible values are defined as follows:

  • userDismiss: The user manually closed the dialog.

  • verifyComplete: The verification process is complete and the SDK automatically closes the dialog. This includes automatic closure after successful verification and in disaster recovery scenarios.

Use the following fixed format:

function onClose(reason: string) {
  console.log('captcha closed:', reason);
}

captchaLogoImg

String

No

None

A parameter to replace the company logo displayed to the right of the trigger button for embedded click-to-verify, jigsaw puzzle, or image restoration challenges. The value can be an image URL or a Base64-encoded string.

dualStack

Boolean

No

false

Specifies whether to enable dual stack support for the initialization and verification request domain names. Valid values:

  • false: Supports only IPv4.

  • true: Supports both IPv4 and IPv6.

UserCertifyId

String

No

None

A custom certifyId that you generate. This optional parameter is passed through and returned by the server side verification API, allowing you to validate it on your backend.

Important

Format: prefix_10-character random string. The random string can include uppercase letters, lowercase letters, and digits. Example: 1q5***_7G47iByes3. For a code example, see UserCertifyId parameter code example.

showErrorTip

Boolean

No

true

Specifies whether to display an error message for access anomalies due to poor network quality.

delayBeforeSuccess

Boolean

No

true

Specifies whether to delay triggering the success callback function by 1 second after successful verification. The default value is true.

EncryptedSceneId

String

No

None

The encrypted SceneId. After you create a verification scenario, you receive the original SceneId. Use the Encrypt Key (ekey) issued by the console to encrypt the SceneId according to the documented encryption process. The resulting encrypted string is the value for this parameter.

zIndex

Number

No

None

The layer level (z-index) of the Captcha element block. The current default is 1000000. You can use this parameter to reset it.

disableMaskClick

Boolean

No

false

Specifies whether clicking the mask layer (the area outside the dialog) closes the Captcha. If true, clicking the mask does nothing. If false (default), clicking the mask closes the dialog.

rem parameter code example

const customWidth = 360;
function initCaptcha(rem) {
  window.initAliyunCaptcha({
    SceneId: "xxxxxx",
    mode: "popup",
    element: "#captcha-element",
    button: "#captcha-button",
    success: success,
    fail: fail,
    getInstance: getInstance,
    slideStyle: {
      width: customWidth,
      height: 40,
    },
    language: "cn",
    rem: rem,
  });
}

const pageWidth = window.innerWidth;
if (pageWidth <= customWidth) {
  const rem = Math.floor(pageWidth / customWidth * 100) / 100;
  initCaptcha(rem);
}

UserCertifyId parameter code example

// Sample code
function generateRandomString(length) {
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  let result = '';
  const charactersLength = characters.length;
  for (let i = 0; i < length; i++) {
    result += characters.charAt(Math.floor(Math.random() * charactersLength));
  }
  return result;
}

const initCaptcha = async () => {
  const prefix = 'xxxxxx';
  const UserCertifyId = prefix + '_' + generateRandomString(10);

  // Alibaba Cloud Captcha initialization logic
  window.initAliyunCaptcha({
    // Generate a custom certifyId in the required format and pass it to the initialization method.
    UserCertifyId: UserCertifyId,
    // ...Other parameters. See the initAliyunCaptcha parameter description.
  });
};

Method calls

Call the corresponding methods of the Captcha instance.

Method name

Description

Example

Use case

show

Displays the Captcha element and mask layer.

captcha.show()

Programmatically displays the Captcha dialog without requiring a user to click a trigger element.

Note

Not supported in traceless verification mode.

hide

Hides or closes the Captcha element and mask layer.

captcha.hide()

Use this method to programmatically close the Captcha dialog.

Note

Not supported in traceless verification mode.

startTracelessVerification

Independently calls the traceless verification method.

captcha.startTracelessVerification()

This method is specific to traceless verification mode. It allows you to start verification programmatically, for example, after performing business logic checks, instead of waiting for a user to click the trigger element.

Code example of an independent call for traceless verification

<!doctype html>
<link rel="shortcut icon" href="//www.aliyun.com/favicon.ico" type="image/x-icon" />
<script>
  window.AliyunCaptchaConfig = {
    region: 'cn',
    prefix: 'prefix',
  };
</script>
<script type="text/javascript" src="AliyunCaptcha.js"></script>

<div>
  <button id="login-button" class="login-btn">Log On</button>
</div>

<script type="text/javascript">
  var captcha;

  function initCaptcha() {
      window.initAliyunCaptcha({
        // showErrorTip: false,
        delayBeforeSuccess: false,
        SceneId: 'SceneId',
        mode: 'popup',
        element: '#traceless-element',
        success: function(){
          
        },
        getInstance: function(instance){
          captcha = instance;
        },
        slideStyle: {
          width: 360,
          height: 40,
        },
        language: 'cn',
      });  
    }
  }

  initCaptcha();

  document.getElementById('login-button').onclick = function() {
    // Your business logic
    ...
    
    // Readjusts the display of the dialog.
    captcha.show();
    // Starts traceless verification.
    captcha.startTracelessVerification();

    // Your business logic
    ...
  }


</script>

Returned data

When you integrate the Alibaba Cloud Captcha 2.0 V3 client architecture, the Alibaba Cloud Captcha 2.0 server verifies the user's response to determine if the request is from a human. The server then returns verification data to your client. You can view the returned data on the Network tab of your browser. For more information, see Data returned by the V3 client architecture.

lQLPJxFSi2GYDIHNBHTNCpawwjNH3sY_CI4IOehh6YNsAQ_2710_1140

V3 client architecture demo downloads