All Products
Search
Document Center

Captcha:Web and H5 client V3 integration

Last Updated:Mar 31, 2026

Captcha 2.0 uses two configuration entries that must be set in the correct order. Before the page loads, define the AliyunCaptchaConfig global variable to identify your instance. After the page loads, call initAliyunCaptcha to render the CAPTCHA widget and handle verification results. This topic describes how to complete both steps.

Note

V3 architecture is not supported for WeChat mini programs. If your service uses the V2 architecture, see Integrate with Web and H5 clients using the V2 architecture.

Prerequisites

Before you begin, make sure you have:

How it works

Integration follows three steps, always in this order:

  1. Define AliyunCaptchaConfig in the HTML <head> before the Captcha JS file loads.

  2. Dynamically load the Captcha JS file from Alibaba Cloud's CDN.

  3. Call initAliyunCaptcha to render the CAPTCHA widget and register callbacks.

The full verification lifecycle works as follows:

  1. Page load: The Captcha JS file loads and begins collecting environment and device data.

  2. Widget rendering: initAliyunCaptcha renders the widget and preloads image resources.

  3. User interaction: The user triggers the widget. Captcha 2.0 analyzes behavioral and device signals.

  4. Token generation: On success, Captcha 2.0 returns captchaVerifyParam to the success callback.

  5. Server validation: Your backend sends captchaVerifyParam to the Captcha 2.0 server-side API to validate it. Act on the result in your business logic.

Important

The interval between loading the Captcha JS file and sending a verification request must be greater than 2 seconds. The interval between initialization and sending a verification request must also be greater than 2 seconds. Load the JS file and call initAliyunCaptcha as early as possible to give Captcha enough time to collect environment data and preload image resources.

Choose a mode

initAliyunCaptcha supports two rendering modes. Choose one before you begin integration.

Popup modeEmbedded mode
TriggerA button click opens the CAPTCHA dialog boxWidget is always visible on the page
DOM element neededYes — a container element and a button elementYes — a container element
No-captcha supportYesNo — no-captcha verification requires popup mode
Recommended forMost use cases, including login and registration formsPages where the CAPTCHA widget is a permanent UI element

Integrate Captcha 2.0

Step 1: Add the AliyunCaptchaConfig global variable

In the HTML <head>, add a <script> block that defines window.AliyunCaptchaConfig before any reference to the Captcha JS file.

<script>
  window.AliyunCaptchaConfig = {
    // Required. Valid values: cn (Chinese mainland), sgp (Singapore).
    region: "cn",
    // Required. Get this value from Overview > Cumulative Activation Time > Identity Prefix in the console.
    prefix: "xxxxxx",
  };
</script>
Important

Get the identity prefix from Overview > Cumulative Activation Time > Identity Prefix in the console, as shown below: image

The region value controls which control plane Captcha 2.0 uses to process behavioral and device data. The server-side endpoint must match: use the Chinese mainland endpoint when region is cn, and the Singapore endpoint when region is sgp. For endpoint details, see Server-side access.

Step 2: Dynamically load the Captcha JS file

Add the following <script> tag to load the Captcha JS file from Alibaba Cloud's CDN:

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

Always load the Captcha JS file dynamically from the CDN. Downloading and hosting it locally prevents the Captcha service from receiving updates, which can compromise security and cause blocking or compatibility issues.

Step 3: Initialize Captcha

After the page loads, call initAliyunCaptcha once to render the widget and bind verification callbacks.

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

Call initAliyunCaptcha only once per page load. Re-initialize only in specific scenarios, such as when initialization parameters change. If initialization fails, see Client-side initialization errors for troubleshooting.

Code example

The following complete example shows popup mode integration. The page reserves two DOM elements: one for the CAPTCHA widget container and one for the trigger button.

<!doctype html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta name="data-spm" />

    <!-- Step 1: Define AliyunCaptchaConfig before the Captcha JS file loads. -->
    <script>
      window.AliyunCaptchaConfig = {
        // Valid values: cn (Chinese mainland), sgp (Singapore).
        region: "cn",
        // Get from Overview > Cumulative Activation Time > Identity Prefix.
        prefix: "xxxxxx",
      };
    </script>

    <!-- Step 2: Dynamically load the Captcha JS file. -->
    <script
      type="text/javascript"
      src="https://o.alicdn.com/captcha-frontend/aliyunCaptcha/AliyunCaptcha.js"
    ></script>
  </head>

  <body>
    <!-- Reserved container for the CAPTCHA widget. Must match the element parameter below. -->
    <div id="captcha-element"></div>

    <!-- Trigger button. In popup mode, clicking this opens the CAPTCHA dialog box. -->
    <button id="button" class="btn">Log on</button>

    <!-- Step 3: Initialize Captcha after the page body is ready. -->
    <script type="text/javascript">
      var captcha;
      window.initAliyunCaptcha({
        // Get from the verification scenario list after creating a scenario.
        SceneId: "xxxxxx",
        // popup: dialog box triggered by button click.
        // embed: widget always visible on page.
        mode: "popup",
        // Must match the reserved container element in the HTML.
        element: "#captcha-element",
        // The element that triggers the CAPTCHA dialog box or no-captcha verification.
        button: "#button",
        // Called when verification succeeds. captchaVerifyParam is required for server-side validation.
        success: function (captchaVerifyParam) {
          // Send captchaVerifyParam to your backend.
          // Your backend calls the Captcha 2.0 server-side API to validate it.
          // Handle your business logic based on the validation result.
          // If re-verification is needed, call the initAliyunCaptcha initializer method to re-initialize Captcha.
        },
        // Called when verification fails. Captcha automatically retries within the validity period.
        fail: function (result) {
          // result contains the failure details.
          // No action required for transient failures — Captcha refreshes automatically.
          console.error(result);
        },
        // Called after Captcha initializes successfully. Stores the instance for later use.
        getInstance: function (instance) {
          captcha = instance;
        },
        // Width and height (px) of the trigger box for slider and point-and-click verification.
        // Minimum width: 320 px. Values below 320 are ignored and 320 is used instead.
        // Does not apply to puzzle CAPTCHA or image restoration verification.
        slideStyle: {
          width: 360,
          height: 40,
        },
        // For other parameters, see the parameter reference below.
      });
    </script>
  </body>
</html>

Parameter reference

AliyunCaptchaConfig parameters

Define these parameters before the Captcha JS file loads.

ParameterTypeRequiredDefaultDescription
regionStringYescnThe region of your Captcha instance. Valid values: cn (Chinese mainland), sgp (Singapore). The client sends behavioral and device data to the corresponding control plane. The server-side endpoint must match.
prefixStringYesNoneThe identity prefix for your Captcha instance. Get this value from Overview > Cumulative Activation Time > Identity Prefix in the console after activating Captcha 2.0. image

initAliyunCaptcha parameters

Call initAliyunCaptcha after the page loads. The following table lists the most commonly used parameters.

Commonly used parameters

ParameterTypeRequiredDefaultDescription
SceneIdStringYesNoneThe scenario ID. Get this value after creating a verification scenario. image
modeStringYesNoneThe rendering mode. popup: a dialog box appears when triggered. embed: the widget is always visible. No-captcha verification requires popup.
elementStringYesNoneCSS selector for the reserved container element where Captcha renders. Must match the DOM element in your HTML.
buttonStringYesNoneCSS selector for the element that triggers the CAPTCHA dialog box or no-captcha verification.
successFunctionYesNoneCallback for successful verification. Receives captchaVerifyParam, which your backend uses to call the server-side validation API.
failFunctionNoNoneCallback for failed verification. Exposes the error code for the failure. Captcha retries automatically within the validity period.
getInstanceFunctionYesgetInstanceCallback invoked after successful initialization. Use it to store a reference to the Captcha instance. The syntax is fixed: function getInstance(instance) { captcha = instance; }
slideStyleObjectNo{ width: 360, height: 40 }Width and height (px) of the trigger box for slider and point-and-click verification. Minimum width: 320 px — values below 320 are treated as 320. Does not apply to puzzle CAPTCHA or image restoration verification. Do not override CSS for puzzle CAPTCHA; its image size and answer are preset and cannot be modified.

Additional parameters

ParameterTypeRequiredDefaultDescription
languageStringNocnThe display language. For supported values, see Custom copy and multi-language settings.
timeoutNumberNo5000Timeout (ms) for a single initialization request.
remNumberNo1Scales the entire CAPTCHA UI. Enter a positive number: 0.5 halves the size, 2 doubles it. Mainly useful for mobile browsers.
onErrorFunctionNoNoneError callback for initialization API failures or resource loading timeouts.
onCloseFunctionNoNoneCallback triggered when the CAPTCHA dialog box is closed.
captchaLogoImgStringNoNoneReplaces the company logo to the right of the trigger button in embedded mode (point-and-click, puzzle CAPTCHA, and image restoration verification). Accepts an image URL or base64-encoded data.
dualStackBooleanNofalseEnables dual-stack networking. false: IPv4 only. true: IPv4 and IPv6.
showErrorTipBooleanNotrueShows an error message when access fails due to poor network quality.
delayBeforeSuccessBooleanNotrueDelays the success callback by 1 second after successful verification.

Instance methods

After initialization, use the Captcha instance (stored via getInstance) to control widget visibility programmatically.

Note

The show and hide methods are not supported for the first verification in no-captcha mode.

MethodDescriptionExampleWhen to use
showDisplays the Captcha element and mask.captcha.show()Auto-open the CAPTCHA dialog box without a button click — for example, when a form is submitted programmatically.
hideHides or closes the Captcha element and mask.captcha.hide()Auto-close the CAPTCHA dialog box without user interaction — for example, after a timeout.

Returned data

After a user completes behavioral verification, Captcha 2.0 returns a CAPTCHA code and supporting parameters to the client. View the returned data in your browser's Network panel. For details on the response structure, see Data returned by the V3 client architecture.

lQLPJxFSi2GYDIHNBHTNCpawwjNH3sY_CI4IOehh6YNsAQ_2710_1140

rem parameter example

Use the rem parameter to scale the CAPTCHA UI on mobile browsers where the viewport is narrower than the default slider width.

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) {
  // Scale the UI proportionally so the slider fits the viewport.
  const rem = Math.floor((pageWidth / customWidth) * 100) / 100;
  initCaptcha(rem);
}

What's next