H5 client integration

更新时间:
复制 MD 格式

This topic describes how to integrate the web SDK into an H5 page to implement CAPTCHA verification.

Procedure

  1. Download the SDK: Log on to the Phone Number Verification Service console. In the API & SDK section on the right side of the Overview page, click Download Now. On the API & SDK page, select CAPTCHA > Web > h5 to download and decompress the SDK package. The web SDK is the ct4.js file within the decompressed package.

  2. Include the resource: Upload the web SDK to your static resource server. Obtain the URL for the web SDK and include it using a script tag.

    <script type="text/javascript" charset="utf-8" src="${your-sdk-asset-path}/ct4.js"></script>
  3. Create a verification solution: When you use the SDK, you will need key parameters. In the CAPTCHA verification solution management console, add a new CAPTCHA verification solution to obtain the key parameters, such as appId and appKey.

Example

initAlicom4({
    captchaId: "<YOUR_APP_ID>", // Enter your appId.
    product: "bind",
  },
  function(captchaObj) {
    captchaObj
      .onNextReady(function() {
        // Call the showCaptcha method only after the CAPTCHA is ready.
      })
      .onSuccess(function() {
        // your code; reset the CAPTCHA based on your business logic.
        captchaObj.reset();
      })
      .onError(function() {
        // your code
      });
    // Button submit event
    $("#btn").click(function() {
      // some code
      // Check if the CAPTCHA is ready before displaying it.
      captchaObj.showCaptcha(); // Display the CAPTCHA.
      // some code
    });
  }
);

For a complete demo, see the downloaded SDK folder, which also includes demos for frameworks like Vue and React.

Additional demos are provided for Angular, Flutter Web, React Native, Uniapp, and a comprehensive (master) version.

Methods

Initialization

To initialize the SDK, call the initAlicom4 method with the configuration parameters and a callback function.

initAlicom4({
    captchaId: "<YOUR_APP_ID>", // Enter the appId generated after you create a solution in the console.
    product: "bind",
  },
  function(captchaObj) {
    // Configure callbacks.
  }
);

Configuration parameters

Parameter

Required

Type

Description

captchaId

Yes

string

The verification ID. This is the appId generated after you create a verification solution in the console.

product

Yes

string

The default value is bind. No modification is required.

language

No

string

Specifies the display language. By default, the SDK uses the browser's language setting. For supported languages and their codes, see Languages and codes.

rem

No

number

Controls the page scaling ratio. The default value is 1.

Callbacks

Required:

Optional:

onSuccess(callback)

Listens for a successful verification event. The callback parameter is a function.

initAlicom4({
  // Configuration parameters omitted.
  product: 'bind'
}, function(captchaObj) {
  // Other method calls omitted.
  document.getElementById('btn').addEventListener('click', function() {
    if (check()) { // Check if the submission can be made.
      captchaObj.showCaptcha();
    }
  });
  captchaObj.onSuccess(function() {
    // After the user passes verification, perform the actual submission.
    // todo
  });
});

getValidate

The result obtained from the onSuccess callback after a user is successfully verified. This result is used by the server-side SDK for secondary verification. The returned object contains the following fields:

Parameter

Type

Description

lot_number

string

The verification serial number.

captcha_output

string

The verification output information.

pass_token

string

The pass token.

gen_time

string

The timestamp of the successful verification.

In other cases, false is returned. You can use this return value to decide whether to proceed, for example, by submitting a form or using an AJAX request for secondary verification.

AJAX secondary verification

captchaObj.onSuccess(function () {
  var result = captchaObj.getValidate();
  // AJAX pseudo-code
  $.ajax({
    url: "server",
    data: result,
    dataType: "json",
    success: function (res) {
      console.log(res.result);
    },
  });
});

showCaptcha

Displays the CAPTCHA. Before calling this method, validate the user's input to ensure there are no issues.

  document.getElementById('btn').addEventListener('click', function() {
    if (check()) { // Check if the submission can be made.
      captchaObj.showCaptcha();
    }
  });

onReady(callback)

Registers a callback that fires when the verification button's DOM has been rendered. You can use this callback to hide UI elements such as a "Loading..." message.

captchaObj.onReady(function () {
  // After the DOM is ready, hide the #loading-tip element.
  // This is for demonstration purposes only. Use a method that suits your needs.
  document.getElementById("loading-tip").style.display = "none";
});

onNextReady(callback)

Registers a callback that fires after the resources for the next verification step have loaded. This callback is useful for ensuring that showCaptcha can open the pop-up window successfully.

captchaObj.onNextReady(function() {});

onFail(callback)

Registers a callback that fires when the user fails the verification challenge. The callback receives a failObj object containing the following information:

  • captcha_id: The verification ID, which is the appId generated after you create a verification solution in the console.

  • captcha_type: The verification type. Types include icon selection (icon), text selection (word), sequence selection (phrase), slide puzzle (slide), and nine-square grid (nine).

  • lot_number: The verification serial number.

captchaObj.onFail(function (failObj) {
  // Collect statistics on the error information.
});

onError(callback)

Registers a callback for verification error events. This callback is triggered by errors such as static resource loading failures or poor network connectivity. The callback receives an error object containing the following fields:

  • code: The error code.

  • msg: The message prompt.

  • desc: This object contains the detail property, which describes the specific error information.

captchaObj.onError(function (error) {
  // An error occurred. You can prompt the user to try again later.
  // The error object includes code, msg, and desc.
  // {code: '60000', msg:"User configuration error", desc:{ detail: "User ID is missing"} }
});

onClose(callback)

This callback is triggered when the user closes the verification pop-up window.

captchaObj.onClose(function () {
  // The user has closed the verification window. You can prompt them that verification must be completed to proceed.
});

reset

Resets the verification to its initial state. Use this method when a user passes verification but other information is incorrect (such as username or password), or when a verification error occurs.

captchaObj.onSuccess(function() {
  var result = captchaObj.getValidate();
  // AJAX pseudo-code
  ajax(
    "/login", {
      lot_number: result.lot_number,
      captcha_output: result.captcha_output,
      pass_token: result.pass_token,
      gen_time: result.gen_time,
      username: "xxx",
      password: "xxx",
      // Other data required by the server, such as username and password for login.
    },
    function(data) {
      // Perform a redirect or other actions based on the server-side secondary verification result.
      if (data.status === "fail") {
        alert("Incorrect username or password. Please re-enter and complete the verification.");
        captchaObj.reset(); // Call this method to reset.
      }
    }
  );
});

destroy

Destroys the verification instance. This action removes the verification UI and its registered event listeners.

captchaObj.onSuccess(function() {
  var result = captchaObj.getValidate();
  // AJAX pseudo-code
  ajax('/login', {
    lot_number: result.lot_number,
    captcha_output: result.captcha_output,
    pass_token: result.pass_token,
    gen_time: result.gen_time,
    username: 'xxx',
    password: 'xxx'
    // Other data required by the server, such as username and password for login.
  }, function(data) {
    // Perform a redirect or other actions based on the server-side secondary verification result.
    if (data.status === 'fail') {
      alert('Incorrect username or password. Please re-enter and complete the verification.');
      captchaObj.reset(); // Call this method to reset.
    } else if (data.status === 'success') {
      // Decide whether to remove the verification based on your business logic.
      captchaObj.destroy();
      captchaObj = null;
    }
  });
});

Languages and codes

Language

Language

Language short code

Simplified Chinese

Chinese(Simplified)

zho

Traditional Chinese (Hong Kong)

Chinese(Hong Kong)

zho-hk

Traditional Chinese (Taiwan)

Chinese(Taiwan)

zho-tw

American English

English

eng

British English

English

eng-gb

Japanese

Japanese

jpn

Indonesia

Indonesian

ind

Korean

Korean

kor

Russian

Russian

rus

Arabic

Arabic

ara

Spanish

Spanish

spa

French

French

fra

German

German

deu

Uyghur

Uyghur

udm

Brazilian Portuguese

Portuguese(Brazil)

pon

European Portuguese

Portuguese(Europe)

por

Error codes

Error code

Description

60001

The captcha_id configuration parameter passed during initialization is invalid.

60100

An internal request error occurred. We recommend that you:

  • Ensure your network connection is stable.

  • Check the captchaId configuration parameter passed during initialization.

60101

An internal request error occurred. Ensure your network connection is stable.

60200

Failed to load the skin. Ensure your network connection is stable.

60201

Failed to load the language pack. Ensure your network connection is stable.

60202

Failed to load the verification image. Ensure your network connection is stable.

60204

Resource loading timed out. Ensure your network connection is stable.

60205

Loading the ct4.js resource timed out. Ensure your network connection is stable.

60500

Forbidden by the server.