After you add a verification scenario in the console, you must integrate the Captcha initialization code into the web or H5 pages that require verification. This topic describes how to perform this client-side integration.
Prerequisites
You have enabled Alibaba Cloud Captcha 2.0.
You have created a verification scenario for which Client Type is set to Web or H5.
V2 verification architecture sequence diagram
Slider CAPTCHA, Puzzle Verification, One-click CAPTCHA, and Image Restoration
Description of the sequence diagram:
The client initializes Captcha and then sends a request to the Captcha server to obtain resources, such as images and questions.
If the request fails, you can check the error message received by the client to identify the cause and resolve the issue.
A user completes the Captcha interaction (such as a slider, puzzle, click, or image restore) and the business interaction (such as logon or registration) on the webpage.
After the interactions are complete, the client sends the Captcha parameters and business parameters to the business server.
The business server calls the VerifyIntelligentCaptcha API and sends a verification request to the Captcha server for threat analysis.
The Captcha server determines the threat level and returns the verification result to the business server.
The business server processes the request based on its business logic. After processing is complete, it returns the verification result and the business processing result to the client.
The client page displays a prompt and processes the business request.
If verification fails, the Captcha is refreshed, and the process returns to Step 1.
Invisible CAPTCHA
Description of the sequence diagram:
The client initializes Captcha and then sends a request to the Captcha server to obtain resources, such as images and questions.
If the request fails, you can check the error message received by the client to identify the cause and resolve the issue.
A user completes the business interaction, such as logon or registration, on the client.
After the interaction is complete, the client sends the no-interaction verification parameters and business parameters to the business server.
The business server calls the VerifyIntelligentCaptcha API and sends a verification request to the Alibaba Cloud server for threat analysis.
The Alibaba Cloud server determines the threat level and returns the verification result to the business server.
The business server processes the request based on its business logic.
If the user is not at risk, the verification process ends.
If the user is at risk, secondary authentication is triggered.
The user completes the Captcha interaction (such as a slider, puzzle, click, or image restore) and the business interaction (such as logon or registration) on the webpage.
After the interactions are complete, the client sends the Captcha parameters and business parameters to the business server.
The business server calls the VerifyIntelligentCaptcha API and sends a verification request to the Alibaba Cloud server for threat analysis.
The Alibaba Cloud server determines the threat level and returns the verification result to the business server.
The business server processes the request based on its business logic. After processing is complete, it returns the verification result and the business processing result to the client.
The client page displays a prompt and processes the business request.
If verification fails, the client page re-initiates Captcha, and the process returns to Step i.
Integrate the Captcha initialization code
Web and H5 pages support pop-up and embedded modes. This section uses a logon scenario as an example to describe how to integrate the Captcha code into the client's source code.
In the client's source code, reserve a page element for Captcha. This element is the DOM element referenced by the element and button parameters, such as <div id="captcha-element"></div> in the following example. We recommend that you set the height of the business module container to be adaptive. This prevents the Captcha element from exceeding the container height if the Captcha height changes when you switch the Captcha type.
ImportantAfter integration, if you modify the scenario configuration in the console, such as the Captcha mode, you do not need to adjust the initialization parameters or page structure. The program loads the new configuration on demand.
// Example of original client code const button = document.getElementById('button'); button.onclick = function () { // Request the backend API... const result = await getWithParams('xx', { yourBizParam... // Business parameters }); const { bizResult } = result; if (bizResult) { // Redirect to the corresponding page. In this example, the page is https://www.aliyun.com/. window.location.href = 'https://www.aliyun.com/'; } } // Code in the client body <div id="space-semantic"> <div id="embed-wrapper"> <h2>Pop-up</h2> <div class="embed-wrapper"> <div> <label>Username:</label> <input id="username-embed" class="biz-input"> </div> <div> <label>Password:</label> <input id="password-embed" type="password" class="biz-input"> </div> <div id="captcha-element"></div> // Reserved page element for the Captcha, used to configure the element parameter in the initializer function <button id="button" class="login-btn">Log on</button> </div> </div> </div>Integrate the Captcha initialization code, which includes the global variable and the Captcha JS script. Before you import the Alibaba Cloud Captcha JS script, or at the beginning of the head tag in the HTML file, add a script that defines a global variable named
AliyunCaptchaConfig. This variable contains the region and prefix parameters.ImportantYou must dynamically import the Captcha JS. If you use other methods to avoid dynamic loading, such as pulling the JS code for local deployment, Captcha cannot be updated as expected. This may compromise security, cause false blocks, or lead to compatibility issues.
Load the Captcha JS as early as possible to collect more complete environment and device information. The interval between loading the Captcha JS and sending a verification request must be greater than 2 s.
To ensure faster loading of image resources, initialize Captcha as early as possible. The interval between initialization and sending a verification request must be greater than 2 s. This loads Captcha-related resources and speeds up image loading.
Do not call the
initAliyunCaptchamethod repeatedly, except in necessary scenarios, such as when initialization parameters change.
Pop-up
<!doctype html> <html> <head> <meta charset="utf-8" /> <meta name="data-spm" /> <!--1. Before you import the Alibaba Cloud Captcha JS script or at the beginning of the head tag in the HTML file, add a script that saves a global variable named AliyunCaptchaConfig that contains the region and prefix parameters.--> <script> window.AliyunCaptchaConfig = { // Required. The region where the Captcha instance resides. Valid values: cn (the Chinese mainland) and sgp (Singapore). region: "cn", // Required. The identity credential. After you activate Alibaba Cloud Captcha 2.0, you can obtain the identity credential in the Instance Basic Information card on the Overview page of the console. prefix: "xxxxxx", }; </script> <!--2. Integrate the main JS.--> <script type="text/javascript" src="https://o.alicdn.com/captcha-frontend/aliyunCaptcha/AliyunCaptcha.js"> </script> </head> <body> <!--3. Create a <script> tag to call the Captcha initializer function initAliyunCaptcha.--> <script type="text/javascript"> var captcha; // Parameters for the pop-up mode, excluding region and prefix window.initAliyunCaptcha({ // The scenario ID. After you create a verification scenario in Step 2, you can obtain the scenario ID from the verification scenario list. SceneId: 'c9h3****', // The Captcha mode. popup indicates that the Captcha is in pop-up mode. You do not need to modify this parameter. mode: 'popup', // The element reserved on the page for rendering the Captcha. This must be the same as the page element reserved in the original code. element: '#captcha-element', // The element that triggers the Captcha pop-up window. button indicates that the captchaVerifyCallback function is triggered after you click the logon button. You can modify the value of element based on the element you use. button: '#button', // The callback function for business requests with Captcha verification. You do not need to modify this parameter. captchaVerifyCallback: captchaVerifyCallback, // The callback function for business request results. You do not need to modify this parameter. onBizResultCallback: onBizResultCallback, // The function to bind the Captcha instance. You do not need to modify this parameter. getInstance: getInstance, // The style of the slider Captcha. You can customize the width and height in pixels (px). The minimum width is 320 px. slideStyle: { width: 360, height: 40, }, // The language of the Captcha. Valid values: cn (Simplified Chinese), tw (Traditional Chinese), and en (English). language: 'cn', }); function getInstance(instance) { captcha = instance } async function captchaVerifyCallback(captchaVerifyParam) { // 1. Send a business request to the backend to obtain the Captcha verification result and the business result. const result = await xxxx('http://Your business request address', { // Captcha parameters captchaVerifyParam: captchaVerifyParam, // Business parameters yourBizParam... }); // 2. Construct standard return parameters. const verifyResult = { // Specifies whether the Captcha verification is passed. This parameter is of the boolean type and is required. captchaResult: result.captchaVerifyResult, // Specifies whether the business verification is passed. This parameter is of the boolean type and is optional. If no business verification result is available, you can leave bizResult empty. bizResult: Obtain your business verification result from the result, }; return verifyResult; } // The callback function for business request verification results function onBizResultCallback(bizResult) { if (bizResult === true) { // If the business verification is passed, you are redirected to the corresponding page. In this example, the page is https://www.aliyun.com/. window.location.href = 'https://www.aliyun.com/'; } else { // If the business verification fails, a failure message is returned. In this example, the message is "Business verification failed!". alert('Business verification failed!'); } } </script> </body> </html>Embedded
<!doctype html> <html> <head> <meta charset="utf-8" /> <meta name="data-spm" /> <!-- 1. Before you import the Alibaba Cloud Captcha JS script or at the beginning of the head tag in the HTML file, add a script that saves a global variable named AliyunCaptchaConfig that contains the region and prefix parameters. --> <script> window.AliyunCaptchaConfig = { // Required. The region where the Captcha instance resides. Valid values: cn (the Chinese mainland) and sgp (Singapore). region: "cn", // Required. The identity credential. After you activate Alibaba Cloud Captcha 2.0, you can obtain the identity credential in the Instance Basic Information card on the Overview page of the console. prefix: "xxxxxx", }; </script> <!-- 2. Integrate the main JS. --> <script type="text/javascript" src="https://o.alicdn.com/captcha-frontend/aliyunCaptcha/AliyunCaptcha.js"> </script> </head> <body> <!-- 3. Create a <script> tag to call the Captcha initializer function initAliyunCaptcha. --> <script type="text/javascript"> var captcha; // Parameters for the embedded mode, excluding region and prefix window.initAliyunCaptcha({ // The scenario ID. After you create a verification scenario in Step 1, you can obtain the scenario ID from the verification scenario list. SceneId: 'c9h3****', // The Captcha mode. embed indicates that the Captcha is in embedded mode. You do not need to modify this parameter. mode: 'embed', // The element reserved on the page for rendering the Captcha. This must be the same as the page element reserved in the original code. element: '#captcha-element', // The element that triggers the business request. button indicates that the captchaVerifyCallback function is triggered after you click the logon button. You can modify the value of element based on the element you use. button: '#button', // The callback function for business requests with Captcha verification. You do not need to modify this parameter. captchaVerifyCallback: captchaVerifyCallback, // The callback function for business request results. You do not need to modify this parameter. onBizResultCallback: onBizResultCallback, // The function to bind the Captcha instance. You do not need to modify this parameter. getInstance: getInstance, // The style of the slider Captcha. You can customize the width and height in pixels (px). The minimum width is 320 px. slideStyle: { width: 360, height: 40, }, // The language of the Captcha. Valid values: cn (Simplified Chinese), tw (Traditional Chinese), and en (English). language: 'cn', // Specifies whether to immediately send a verification request (call the captchaVerifyCallback function) after the verification is complete. immediate: false, }); // The function to bind the Captcha instance. This is a fixed expression and does not need to be modified. function getInstance(instance) { captcha = instance; } // The callback function for business requests with Captcha verification /** * @name captchaVerifyCallback * @function * Request parameter: The verification parameter returned by the Captcha script. You do not need to process this parameter. You can directly pass it to the server. * @params {string} captchaVerifyParam * Return parameter: The field name is fixed. captchaResult is required. If no business verification scenario is available, bizResult is optional. * @returns {{captchaResult: boolean, bizResult?: boolean|undefined}} */ async function captchaVerifyCallback(captchaVerifyParam) { // 1. Send a business request to the backend to obtain the Captcha verification result and the business result. const result = await xxxx('http://Your business request address', { // Captcha parameters captchaVerifyParam: captchaVerifyParam, // Business parameters yourBizParam... }); // 2. Construct standard return parameters. const verifyResult = { // Specifies whether the Captcha verification is passed. This parameter is of the boolean type and is required. captchaResult: result.captchaVerifyResult, // Specifies whether the business verification is passed. This parameter is of the boolean type and is optional. If no business verification result is available, you can leave bizResult empty. bizResult: Obtain your business verification result from the result, }; return verifyResult; } // The callback function for business request verification results function onBizResultCallback(bizResult) { if (bizResult === true) { // If the business verification is passed, you are redirected to the corresponding page. In this example, the page is https://www.aliyun.com/. window.location.href = 'https://www.aliyun.com/'; } else { // If the business verification fails, a failure message is returned. In this example, the message is "Business verification failed!". alert('Business verification failed!'); } } </script> </body> </html>The captchaVerifyCallback function uses ES6 syntax. To use ES5 syntax, refer to the following example. Call the second parameter of captchaVerifyCallback, which is a callback function, and pass the verification result to it:
/** * @name captchaVerifyCallback * @function * @param {String} captchaVerifyParam - The verification parameter returned by the Captcha script. You do not need to process this parameter. You can directly pass it to the server. * @param {Function} callback - The callback function used to process the verification result. It is compatible with the ES5 syntax. */ function captchaVerifyCallback(captchaVerifyParam, callback) { // 1. Send a business request to the backend to obtain the Captcha verification result and the business result. requestVerifyResult('http://Your business request address', { captchaVerifyParam: captchaVerifyParam, // Captcha parameters yourBizParam... // Business parameters }, function(result) { // 2. Construct standard return parameters. var verifyResult = { captchaResult: result.captchaVerifyResult, bizResult: result.bizResult, }; // Call the callback function and pass the verification result. callback(verifyResult); }); }
If you have any questions during the integration, submit a ticket.
Parameters
AliyunCaptchaConfig parameters
Parameter | Type | Required | Default value | Description |
region | String | Yes | cn | The region where the Captcha instance resides. Valid values:
Important
|
prefix | String | Yes | None | The identity credential of the Captcha. You can obtain this value after you activate Captcha 2.0. |
initAliyunCaptcha parameters
Parameter | Type | Required | Default value | Description |
SceneId | String | Yes | None | The scenario ID of the Captcha. You can obtain this value after you create a verification scenario. |
mode | String | Yes | None | The Captcha mode. Options:
|
element | String | Yes | captcha-element | The element reserved on the page for rendering the Captcha. This must be the same as the page element reserved in the source code. |
button | String | Yes | None | The element that triggers the Captcha pop-up window. The value must be the same as the value of the button parameter in the client body. |
captchaVerifyCallback | Function | Yes | captchaVerifyCallback | The callback function for business requests with Captcha verification. For more information, see captchaVerifyCallback. |
onBizResultCallback | Function | Yes | onBizResultCallback | The callback function for business request results, which is used to set the logic for processing verification results. |
getInstance | Function | Yes | getInstance | The function to bind the Captcha instance. The fixed expression is: |
slideStyle | Object | No | { width: 360, height: 40 } | The style of the slider Captcha. You can customize the width and height in pixels (px). Important
|
language | String | No | cn | The language types supported by Captcha 2.0. |
immediate | Boolean | No | false | In embedded mode, specifies whether to immediately send a verification request (call the captchaVerifyCallback function) after the verification is complete. |
timeout | Number | No | 5000 | The timeout period for a single Captcha initialization request. Unit: milliseconds (ms). |
rem | Number | No | 1 | Scales the entire Captcha UI. Enter a positive number. For example, 0.5 means to reduce the size by half, and 2 means to double the size. Note The rem parameter is mainly used for mobile browsers. |
autoRefresh | Boolean | No | true | Specifies whether to automatically refresh the Captcha after the verification is passed. Note If this parameter is set to false, you must manually call the instance method to refresh the Captcha. For more information, see Q4 in the FAQ. |
onError | Function | No | None | The error callback function for failed or timed-out Captcha initialization API requests. |
captchaLogoImg | String | No | None | The parameter for replacing the company logo on the right of the click verification button. The value can be an image URL or data in Base64 format. |
captchaVerifyCallback parameters
Request parameters
Parameter
Type
Required
Default value
Description
captchaVerifyParam
String
Yes
captchaVerifyParam
Captcha parameters. The verification parameter returned by the Captcha script. You do not need to process this parameter. You can directly pass it to the server.
Return parameters
Parameter
Type
Default value
Description
captchaResult
Boolean
None
Specifies whether the Captcha verification is passed.
bizResult
Boolean
None
Specifies whether the business verification is passed. If no business verification result is available, the value of bizResult can be empty.

