V2 integration for web and H5 clients
After adding a verification scenario on the console, integrate the Captcha initialization code into the web or H5 pages where verification is required. This topic explains this client-side integration.
Prerequisites
Before you begin, make sure you have:
Activated Alibaba Cloud Captcha 2.0
Created a verification scenario with Integration Method set to Web/H5
V2 verification architecture sequence diagram
Slider CAPTCHA, Puzzle Verification, One-click CAPTCHA, and Image Restoration
Description of the sequence diagram:
-
A customer initializes the CAPTCHA on the business client. The business client sends a request to the captcha server to obtain CAPTCHA resources, such as images and challenges.
If the request fails, the returned error message helps identify the cause and resolve the issue.
-
A user completes the CAPTCHA interaction (such as slider CAPTCHA, puzzle verification, one-click CAPTCHA, and image restoration) and the business interaction (such as logon or registration) on the web page.
After the interactions are complete, the business 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 assesses the verification risk and returns the verification result to the business server.
-
The business server processes the request and returns the verification and business results to the business client.
-
The client page displays a message and handles the business operation.
If the verification fails, the CAPTCHA refreshes and the process returns to Step 1.
Invisible CAPTCHA
Description of the sequence diagram:
-
A customer initializes the CAPTCHA on the business client. The business client sends a request to the captcha server to obtain CAPTCHA resources, such as images and challenges.
If the request fails, the returned error message helps identify the cause and resolve the issue.
-
A user completes the business interaction (such as logon or registration) on the business client.
After the interaction is complete, the business client sends the invisible 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 assesses the verification risk and returns the verification result to the business server.
-
The business server processes the request.
-
If the user is not considered risky, the verification process ends.
-
If the user is considered risky, secondary authentication is triggered.
-
The user completes the CAPTCHA interaction (such as slider CAPTCHA, puzzle verification, one-click CAPTCHA, or image restoration) and the business interaction (such as logon or registration) on the web page.
After the interactions are complete, the business 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 assesses the verification risk and returns the verification result to the business server.
-
The business server processes the request and returns the verification and business results to the business client.
-
The client page displays a message and handles the business operation.
If the verification fails, the CAPTCHA refreshes, and the process returns to the beginning of the secondary authentication.
-
-
Integrate Captcha initialization code
Web and H5 pages support pop-up and embedded modes. This section uses a logon scenario to show how to integrate Captcha into client source code.
-
In your client source code, reserve a page element to render the Captcha. The
elementandbuttonparameters will reference this DOM element, such as <div id="captcha-element"></div> in the example below. It is recommended to set the height of the business module's container to be adaptive. This prevents the Captcha element from exceeding the container height if the Captcha's height changes when you switch Captcha types.ImportantAfter the 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. Captcha 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 a global variable and the Captcha JS script. Before you import the Alibaba Cloud Captcha JS script, or at the top of the <head> tag in your HTML file, add a script that defines a global variable named
AliyunCaptchaConfig. This variable contains theregionandprefixparameters.Important-
You must dynamically import the Captcha JS. If you use other methods to bypass dynamic loading, such as fetching the JS code for local deployment, Captcha will not update correctly. This can 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 seconds.
-
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 seconds. This loads Captcha-related resources and speeds up image loading.
-
Do not call the
initAliyunCaptchamethod repeatedly, except when necessary, for example, 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 top of the <head> tag in your 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 activating Alibaba Cloud Captcha 2.0, obtain it from the Instance Basic Information card on the console's Overview page. 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, you can obtain its ID from the verification scenario list in the console. SceneId: 'c9h3****', // The Captcha mode. 'popup' indicates the pop-up mode. Do not modify this parameter. mode: 'popup', // The DOM element where the Captcha will be rendered. This must match the element you reserved. element: '#captcha-element', // The element that triggers the Captcha pop-up. '#button' indicates that the captchaVerifyCallback function is triggered when the logon button is clicked. Modify the 'button' value to match your element. button: '#button', // The callback function for business requests with Captcha verification. Do not modify. captchaVerifyCallback: captchaVerifyCallback, // The callback function for business request results. Do not modify. onBizResultCallback: onBizResultCallback, // The function to bind the Captcha instance. Do not modify. 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 your backend to get the Captcha and business verification results. const result = await xxxx('http://Your business request address', { // Captcha parameters captchaVerifyParam: captchaVerifyParam, // Business parameters yourBizParam... }); // 2. Construct the standard return object. const verifyResult = { // captchaResult: Required. A boolean that indicates whether the Captcha verification passed. captchaResult: result.captchaVerifyResult, // bizResult: Optional. A boolean that indicates whether the business verification passed. Omit this if not applicable. bizResult: getYourBusinessResult(result), }; return verifyResult; } // The callback function for business request verification results. function onBizResultCallback(bizResult) { if (bizResult === true) { // If the business verification passes, 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 displayed. 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 top of the <head> tag in your 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 activating Alibaba Cloud Captcha 2.0, obtain it from the Instance Basic Information card on the console's Overview page. 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, you can obtain its ID from the verification scenario list in the console. SceneId: 'c9h3****', // The Captcha mode. 'embed' indicates the embedded mode. Do not modify this parameter. mode: 'embed', // The DOM element where the Captcha will be rendered. This must match the element you reserved. element: '#captcha-element', // The element that triggers the business request. '#button' indicates that the captchaVerifyCallback function is triggered when the logon button is clicked. Modify the 'button' value to match your element. button: '#button', // The callback function for business requests with Captcha verification. Do not modify. captchaVerifyCallback: captchaVerifyCallback, // The callback function for business request results. Do not modify. onBizResultCallback: onBizResultCallback, // The function to bind the Captcha instance. Do not modify. 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 (by calling captchaVerifyCallback) after the user passes the challenge. immediate: false, }); // Binds the Captcha instance. This is a standard function and does not need to be modified. function getInstance(instance) { captcha = instance; } // The callback function for business requests with Captcha verification. /** * @name captchaVerifyCallback * @function * @param {string} captchaVerifyParam - The verification parameter that is returned by the Captcha script. Pass this parameter directly to your server without processing it. * @returns {{captchaResult: boolean, bizResult?: boolean|undefined}} - The return object. The field names are fixed. captchaResult is required. bizResult is optional and can be omitted if you do not have a business verification scenario. */ async function captchaVerifyCallback(captchaVerifyParam) { // 1. Send a business request to your backend to get the Captcha and business verification results. const result = await xxxx('http://Your business request address', { // Captcha parameters captchaVerifyParam: captchaVerifyParam, // Business parameters yourBizParam... }); // 2. Construct the standard return object. const verifyResult = { // captchaResult: Required. A boolean that indicates whether the Captcha verification passed. captchaResult: result.captchaVerifyResult, // bizResult: Optional. A boolean that indicates whether the business verification passed. Omit this if not applicable. bizResult: getYourBusinessResult(result), }; return verifyResult; } // The callback function for business request verification results. function onBizResultCallback(bizResult) { if (bizResult === true) { // If the business verification passes, 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 displayed. In this example, the message is "Business verification failed!". alert('Business verification failed!'); } } </script> </body> </html>For ES5 syntax, refer to the following example, which uses a callback function as the second parameter of
captchaVerifyCallbackto receive the verification result:/** * @name captchaVerifyCallback * @function * @param {String} captchaVerifyParam - The verification parameter that is returned by the Captcha script. Pass this parameter directly to your server without processing it. * @param {Function} callback - The callback function used to process the verification result, for ES5 compatibility. */ function captchaVerifyCallback(captchaVerifyParam, callback) { // 1. Send a business request to your backend to get the Captcha and business verification results. requestVerifyResult('http://Your business request address', { captchaVerifyParam: captchaVerifyParam, // Captcha parameters yourBizParam... // Business parameters }, function(result) { // 2. Construct the standard return object. 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 integration, submit a ticket.
Parameters
AliyunCaptchaConfig parameters
|
Parameter |
Type |
Required |
Default |
Description |
|
region |
String |
Yes |
cn |
The region of the Captcha instance. Valid values:
Important
|
|
prefix |
String |
Yes |
None |
The identity credential for Captcha 2.0. To obtain it, activate Captcha 2.0, log on to the Captcha 2.0 console, and find the Identity Credential at the bottom of the Overview page. This ID is used for parameter configuration. |
initAliyunCaptcha parameters
|
Parameter |
Type |
Required |
Default |
Description |
|
SceneId |
String |
Yes |
None |
The scenario ID for Captcha. After creating a verification scenario, log on to the Captcha 2.0 console, go to the Scenario Management page, and find the |
|
mode |
String |
Yes |
None |
The Captcha mode. Valid values:
|
|
element |
String |
Yes |
captcha-element |
The page element where the Captcha will be rendered. This must match the corresponding element in your source code. |
|
button |
String |
Yes |
None |
The selector for the element that, when clicked, triggers the Captcha pop-up. |
|
captchaVerifyCallback |
Function |
Yes |
captchaVerifyCallback |
The callback function to handle business logic after a successful Captcha verification. For more information, see captchaVerifyCallback. |
|
onBizResultCallback |
Function |
Yes |
onBizResultCallback |
The callback function for business request results. Use this function to define the logic for handling the verification result. |
|
getInstance |
Function |
Yes |
getInstance |
A callback that receives the Captcha instance. The syntax is fixed as follows:
|
|
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 |
Specifies the display language of the Captcha UI. For supported languages, see language types. |
|
immediate |
Boolean |
No |
false |
In embedded mode, specifies whether to call the captchaVerifyCallback function immediately after the user passes verification. |
|
timeout |
Number |
No |
5000 |
The timeout period for a single Captcha initialization request, in milliseconds (ms). |
|
rem |
Number |
No |
1 |
Scales the entire Captcha UI. Enter a positive number. For example, Note
The rem parameter is primarily used for mobile browsers. |
|
autoRefresh |
Boolean |
No |
true |
Specifies whether to automatically refresh the Captcha after a user passes the verification. Note
If this parameter is set to |
|
onError |
Function |
No |
None |
The error callback function for failed or timed-out Captcha initialization API requests. |
|
captchaLogoImg |
String |
No |
None |
Replaces the default logo to the right of the click verification button. The value can be an image URL or a Base64-encoded string. |
captchaVerifyCallback parameters
-
Request parameters
Parameter
Type
Required
Default
Description
captchaVerifyParam
String
Yes
captchaVerifyParam
The verification parameter returned by the Captcha script. Pass this parameter directly to your server without modification.
-
Return parameters
Parameter
Type
Default
Description
captchaResult
Boolean
None
Indicates whether the Captcha verification passed.
bizResult
Boolean
None
Indicates whether the business verification passed. This value can be omitted if no business verification result is available.