AI CAPTCHA quick start

更新时间:
复制 MD 格式

This guide shows you how to integrate AI CAPTCHA in two steps by adding Click-and-pass verification to a login page at test.example.com/login.

Step 1: Configure verification rule

Configure basic information, such as the URI to protect and the verification type.

  1. Log on to the ESA console and go to the AI CAPTCHA configuration page.

  2. On the Configuration page, click Add Rule.

    image

  3. On the Add Rule page, configure the following parameters:

    • Rule Name: Enter a custom name, such as login.

    • API to Be Verified: Enter the URI that you want to protect. In this example, enter test.example.com/login.

    • Methods to Verify: Select the request methods that require verification. In this example, select GET and POST.

    • Type: Select the verification type. In this example, select Click-and-Pass.

      For information about other types, see Types and Selection Suggestions.

    image

Step 2: Integrate front-end code

After you add the verification rule in the ESA console, integrate the CAPTCHA initialization code into your web or H5 page to enable client-side verification.

Obtain credentials

ESA uses an Identity and a Scenario ID for authentication. Before integrating the front-end code, obtain the following credentials:

  1. Identity: You can find your identity token in the upper-right corner of the Configuration page.image

  2. Scenario ID: You can find the ID in the Scenario ID column for the corresponding rule on the Configuration page.image

Add script

In your front-end code, such as login.html, add the following three script snippets:

  1. Define the global variable AliyunCaptchaConfig: Before loading the CAPTCHA JavaScript file, add a script to define the AliyunCaptchaConfig object. This object must contain the region and prefix parameters. Place this script in the section of your HTML, before the main CAPTCHA script.

    <script>
      window.AliyunCaptchaConfig = {
        region: "cn",  // Required. The region where your AI CAPTCHA instance is deployed. Valid values: cn (Chinese mainland) and sgp (Singapore).
        prefix: "IDENTITY",   // Required. Your identity token. Replace IDENTITY with the token you obtained in the previous step, such as: esa-q2*****cqb.
      };
    </script>
  2. Dynamically load the CAPTCHA script: After you define the AliyunCaptchaConfig object, add the following script tag to load the main CAPTCHA script.

    Note

    You must dynamically load the AI CAPTCHA script. Bypassing dynamic loading, for example by hosting the script locally, prevents the CAPTCHA service from being updated. This compromises security and can cause incorrect blocking or compatibility issues.

    <script
      type="text/javascript"
      src="https://o.alicdn.com/captcha-frontend/aliyunCaptcha/AliyunCaptcha.js"
    ></script>
  3. Add the initialization method: Call the initAliyunCaptcha function to initialize the CAPTCHA. For more information, see initAliyunCaptcha parameter reference.

    Note

    Do not call the initAliyunCaptcha function more than once unless necessary, for example, when initialization parameters change. If initialization fails, see Client-side initialization errors for troubleshooting.

    <script type="text/javascript">
      var captcha;
      window.initAliyunCaptcha({...});
    </script>

Sample code

Refer to the following sample code to add AI CAPTCHA to your front-end code.

Note
  • Load the CAPTCHA script as early as possible in your page lifecycle. This allows the script to collect more comprehensive environment and device data. Ensure at least a 2-second interval between loading the script and making a verification request.

  • To ensure faster resource loading, initialize the CAPTCHA as early as possible. Allowing at least 2 seconds between initialization and the verification request ensures that related resources, such as images, can load.

  • In your client's source code, reserve placeholder elements for the CAPTCHA. The element and button parameters will target these elements. For example: <div id="captcha-element"></div>.

<!doctype html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta name="data-spm" />
    <!-- 1. Before including the AI CAPTCHA script, define the global AliyunCaptchaConfig object. Place this in the <head> tag of your HTML. -->
    <script>
      window.AliyunCaptchaConfig = {
        region: "cn",
        prefix: "{{IDENTITY}}",
      };
    </script>
    <!-- 2. Load the main CAPTCHA script. -->
    <script
      type="text/javascript"
      src="https://o.alicdn.com/captcha-frontend/aliyunCaptcha/AliyunCaptcha.js"
    ></script>
  </head>
  <body>
    <!-- Placeholder element for the CAPTCHA. This is the target for the 'element' parameter in the initialization function. -->
    <div id="captcha-element"></div>
    <!-- In pop-up mode, this element triggers the CAPTCHA dialog. -->
    <button id="button" class="btn">Login</button>
    <!-- 3. Add a <script> tag to call the initAliyunCaptcha function. -->
    <script type="text/javascript">
      var captcha;
      window.initAliyunCaptcha({
        // The Scene ID. You can find this ID in the rule list on the Configuration page after you create a rule.
        SceneId: "{{SCENE_ID}}",
        // The CAPTCHA mode. 'popup' displays the CAPTCHA in a dialog. 'embed' renders it directly on the page. Do not change this unless required.
        mode: "popup",
        // The placeholder element where the CAPTCHA will be rendered. This must match the element reserved in your HTML.
        element: "#captcha-element", 
        // The ID of the element that triggers the pop-up or no-CAPTCHA verification.
        button: "#button",
        // Callback function for successful verification.
        success: function (captchaVerifyParam) {
          // The captchaVerifyParam is passed as an argument.
          // 1. Send this parameter to your backend server, which then sends it to the ESA server for signature verification.
          // 2. Handle the business logic based on the verification result from your server.
          // 3. To run the verification again, call captcha.refresh().
          console.log('SUCCESS'); // Print SUCCESS to the console for debugging.
        },
        // Callback function for failed verification.
        fail: function (result) {
          // The argument contains failure information.
          // No action is needed if the verification fails within its validity period. The CAPTCHA automatically refreshes for a new attempt.
          console.error(result);
        },
        // Callback function to get the CAPTCHA instance. This is called after successful initialization.
        getInstance: function (instance) {
          captcha = instance;
        },
        // Specifies the ESA service endpoint. Do not change this value.
        server: ['captcha-esa-open.aliyuncs.com', 'captcha-esa-open-b.aliyuncs.com'],
        // Style for the trigger box in slider verification and Click-and-pass modes. You can customize the width and height in pixels (px).
        slideStyle: {
          width: 360,
          height: 40,
        },
        // For other parameters, see the initAliyunCaptcha parameter reference.
      });
    </script>
  </body>
</html>

When the success: function (captchaVerifyParam) function is called, the client sends a request to ESA. The request must include the signature verification parameter captchaVerifyParam. captchaVerifyParam can be placed in the request parameters or in the header. Refer to the following two examples:

URI parameter

async function captchaVerifyCallback(captchaVerifyParam) {
    // 1. Send a request to your application's backend endpoint to verify the token.
    const result = await fetch('${YOUR_BACKEND_VERIFICATION_ENDPOINT}?captcha_verify_param=' + captchaVerifyParam, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json'},
        body: JSON.stringify({
            // Your custom business parameters
            // BizParam:
        }),
        credentials: 'include'
    });
    // Your backend must proxy the 'X-Captcha-Verify-Code' header from the ESA server's response.
    const verify_code = result.headers.get('X-Captcha-Verify-Code');
    if (verify_code === 'T001') {
        alert('Verification successful!');
    } else {
        alert('Verification failed: ' + verify_code);
    }
    // Refresh the CAPTCHA for the next verification.
    captcha.refresh();
    const data = await result.json();
    return data;
}

Header value

async function captchaVerifyCallback(captchaVerifyParam) {
    // 1. Send a request to your application's backend endpoint to verify the token.
    const result = await fetch('${YOUR_BACKEND_VERIFICATION_ENDPOINT}', {
        method: 'POST',
        headers: { 
            'Content-Type': 'application/json',
            'captcha-verify-param': captchaVerifyParam 
        },
        body: JSON.stringify({
            BizParam: document.getElementById('biz_result').value
        }),
        credentials: 'include'
    });
    // Your backend must proxy the 'X-Captcha-Verify-Code' header from the ESA server's response.
    const verify_code = result.headers.get('X-Captcha-Verify-Code');
    if (verify_code === 'T001') {
        alert('Verification successful!');
    } else {
        alert('Verification failed: ' + verify_code);
    }
    // Refresh the CAPTCHA for the next verification.
    captcha.refresh();
    const data = await result.json();
    return data;
}

Result:

Dec-29-2025 16-07-05

The ESA server-side verification response includes the x-captcha-verify-code header. Your backend must pass this header to the client. The client can then handle the result based on the following reason codes:

Reason code

Description

T001

Verification passed.

F003

Failed to parse CaptchaVerifyParam.

F005

The Scene ID (SceneId) does not exist.

F017

The content of VerifyToken was modified.

F018

The signature verification data was reused.

F019

Signature verification timed out (valid for 90 seconds) or was performed before a verification was initiated.

F020

The verification ticket does not match the Scene ID or user.

F021

The SceneId used for verification does not match the SceneId used for signature verification.

References

AliyunCaptchaConfig parameters

Parameter

Type

Required

Default

Description

region

String

Yes

cn

The region where the CAPTCHA instance is deployed. Valid values:

  • cn: Chinese mainland

  • sgp: Singapore

The AI CAPTCHA service has control planes in the Chinese mainland (China (Shanghai)) and Singapore regions. Based on your configuration, client-side data such as user behavior and device information is sent to the corresponding regional center for security processing.

prefix

String

Yes

None

Your identity token.

initAliyunCaptcha parameters

Parameter

Type

Required

Default

Description

SceneId

String

Yes

None

The Scene ID for the verification scenario.

mode

String

Yes

None

The display mode for the CAPTCHA. Valid values:

  • popup: Displays the CAPTCHA in a pop-up dialog.

  • embed: Renders the CAPTCHA in embedded mode. This is not applicable to no-CAPTCHA verification.

element

String

Yes

None

A CSS selector for the HTML element where the embedded CAPTCHA will be rendered. This must match the placeholder element in your source code.

button

String

Yes

None

The element that is clicked to display the CAPTCHA pop-up or trigger no-CAPTCHA verification. The value must be the same as the value of the button parameter in the client body.

success

Function

Yes

None

When the CAPTCHA verification is successful, the callback function returns the verification parameter. In this function, you can obtain CaptchaVerifyParam and request your server to validate CaptchaVerifyParam.

fail

Function

No

None

The callback function that is executed upon a failed verification. It receives an error code.

getInstance

Function

Yes

getInstance

A callback function that receives the CAPTCHA instance object after initialization. Use the following syntax:

function getInstance(instance) {
  captcha = instance;
}

slideStyle

Object

No

{ width: 360, height: 40 }

An object to customize the style of the trigger box for slider verification and Click-and-pass types. You can set the width and height in pixels (px). Notes:

  • For slider verification, we recommend a minimum width of 320 px to ensure sufficient data collection for the policy model. If the width is less than 320 px, the system defaults to 320 px.

  • This parameter does not apply to puzzle or image restore verification types. For puzzle CAPTCHAs, the image dimensions and answers are preset. Do not override the CSS to change the style, as this will cause verification to fail.

language

String

No

cn

The language for the CAPTCHA UI. Valid values:

  • cn: Simplified Chinese

  • tw: Traditional Chinese

  • en: English

  • ar: Arabic

  • de: German

  • es: Spanish

  • fr: French

  • in: Indonesian

  • it: Italian

  • ja: Japanese

  • ko: Korean

  • pt: Portuguese

  • ru: Russian

  • ms: Malay

  • th: Thai

  • tr: Turkish

  • vi: Vietnamese

timeout

Number

No

5000

The timeout for a single initialization request, in milliseconds.

rem

Number

No

1

A number to scale the CAPTCHA UI. For example, 0.5 halves the size and 2 doubles it.

rem parameter is primarily for mobile browsers.

onError

Function

No

None

An error callback function for failures or timeouts during the initialization request or resource loading. Use the following syntax:

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

onClose

Function

No

None

A callback function that is triggered when the CAPTCHA pop-up dialog is closed.

showErrorTip

Boolean

No

true

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

delayBeforeSuccess

Boolean

No

true

Specifies whether to delay the success callback by 1 second after a successful verification.

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);
}

No-CAPTCHA mode methods

You can call methods on the CAPTCHA instance. In no-CAPTCHA mode, the initial verification is triggered automatically. Do not use the following methods to control the initial verification, but you can use them for custom flows:

Method name

Description

Example

Use case

show

Displays the CAPTCHA element and overlay.

captcha.show()

Use this method to programmatically trigger the CAPTCHA dialog without a user click.

hide

Hides or closes the CAPTCHA element and overlay.

captcha.hide()

Use this method to programmatically close the CAPTCHA dialog.