All Products
Search
Document Center

Captcha:Integrate the WeChat mini program plugin (V3 architecture)

Last Updated:Oct 14, 2025

After you add a verification scenario in the console, you must integrate the Captcha initialization code into the WeChat mini program page that uses the verification feature. This topic describes how to integrate this code.

Prerequisites

WeChat mini program plugin integration

Integrate with a native WeChat mini program

Before you can use the plugin, you must add it in the mini program admin console. To do this, log on to the console, go to Settings > Third-party Services > Plugin Management, search for the plugin by its AppID (wxbe275ff84246f1a4), and add it.

Step 1: Integrate the plugin

  1. Import the Captcha mini program plugin.

    Before you use the plugin on a page, declare the Alibaba Cloud Captcha mini program plugin in the project's app.json file. The following code provides an example:

    Note

    Ensure that you use the latest plugin version. You can find the latest version in WeChat Developer Tools > Details > Basic Information > Plugin Information.

    V3 architecture

    {
      "plugins": {
        "AliyunCaptcha": {
          "version": "3.0.0", // Select the latest version of the mini program plugin.
          "provider": "wxbe275ff84246f1a4"
        }
      }
    }

    V2 architecture

    {
      "plugins": {
        "AliyunCaptcha": {
          "version": "2.3.0", // Select the latest version of the mini program plugin.
          "provider": "wxbe275ff84246f1a4"
        }
      }
    }
  2. Import the Captcha mini program component.

    To use the custom component provided by the plugin, specify the plugin's reference name and the custom component's name using the plugin:// protocol in the .json file of the page or component. The following code provides an example:

    {
      "usingComponents": {
        "aliyun-captcha": "plugin://AliyunCaptcha/captcha"
      }
    }

Step 2: Insert the template

Insert the aliyun-captcha template into the .wxml file. The parameters in this example are required.

The following example shows a logon scenario:

<view class="captchapage-container">
  <view class="input-group">
    <view class="label">Username:</view>
    <input class="input" type="text" placeholder="Enter your username" bindinput="inputUsername" />
  </view>
  <view class="input-group">
    <view class="label">Password:</view>
    <input class="input" type="password" placeholder="Enter your password" bindinput="inputPassword" />
  </view>
  <aliyun-captcha id="captcha-element" wx:if="{{loadCaptcha}}" props="{{pluginProps}}" />
  <!-- Bind the login method to the logon button. When the button is clicked, call the plugin instance method in the login method to display the Captcha. -->
  <button class="login-btn" bindtap="login">Log On</button>
</view>

Step 3: Initialize the plugin

When you need to use the plugin, call setData to pass the required initialization parameters.

The following example shows a logon scenario:

V3 architecture

// Get the Captcha plugin instance.
var AliyunCaptchaPluginInterface = requirePlugin('AliyunCaptcha');

// Callback function for successful verification.
/**
 * @name success
 * @function
 * Request parameter: The verification parameter returned by the Captcha script. Pass it directly to the server for secondary verification without any processing.
 * @params {string} captchaVerifyParam 
 */
var success = async function (captchaVerifyParam) {
  // After successful verification, uninstall the Captcha.
  this.setData({
    loadCaptcha: false,
  });
  console.log(this.data);
  // Business request code...
  const result = await customFetch('https://xxxx/demo/bizquery', {
      method: 'POST',
      data: {
        captchaVerifyParam, // Include the verification parameter.
        userName: this.data.username, // Get business data through this.data.
        password: this.data.password,
      },
    });
  console.log(captchaVerifyParam);
};

// Callback function for failed verification.
var fail = function (error) {
  console.error(error);
};

async function customFetch(url, option) {
  option.url = url;
  return new Promise((resolve, reject) => {
    wx.request({
      ...option,
      success(res) {
        resolve(res.data);
      },
      fail(res) {
        reject(new Error(res.toString()));
      },
    });
  });
}

// Page logic.
Page({
  data: {
    username: '',
    password: '',
    loadCaptcha: false, // Specifies whether to load the Captcha.
  },
  onLoad: function(options) {
    // Construct the plugin parameters.
    var pluginProps = {
      SceneId: 'xxxxx',
      mode: 'popup',
      // This is a fixed syntax. You must bind this to ensure that 'this' in the callback function points to the current page. This lets you get business parameters through this.data in the callback function.
      success: success.bind(this), 
      // This is a fixed syntax. You must bind this to ensure that 'this' in the callback function points to the current page. This lets you get business parameters through this.data in the callback function.
      fail: fail.bind(this), 
      slideStyle: {
        width: 540, // The default width is 540 rpx.
        height: 60, // The default height is 60 rpx.
      },
      language: 'cn',
      region: 'cn',
    };
    this.setData({
      loadCaptcha: true, // You can use this to control loading or reloading the Captcha.
      pluginProps,
    });
  },
  inputUsername: function(e) {
    this.setData({
      username: e.detail.value
    });
  },
  inputPassword: function(e) {
    this.setData({
      password: e.detail.value
    });
  },
  login: function() {
    const { username, password } = this.data;
    // You can perform custom business validation.
    if (username && password) {
      // For pop-up mode, call the instance method to display the Captcha. For no-captcha mode, also call this method to trigger verification.
      AliyunCaptchaPluginInterface.show();
    } else {
      wx.showToast({
        title: 'Enter your username and password.',
        icon: 'none'
      });
    }
  },
  // To verify again, call this method to reload the Captcha.
  reloadCaptcha: function () {
    this.setData({
      loadCaptcha: true,
    });
  },
})

To perform another verification after a successful one, call `reloadCaptcha` to reload the Captcha.

V2 architecture

// Get the Captcha plugin instance.
var AliyunCaptchaPluginInterface = requirePlugin('AliyunCaptcha');

// Business request (with Captcha verification) callback function.
/**
 * @name captchaVerifyCallback
 * @function
 * Request parameter: The verification parameter returned by the Captcha script. Pass it directly to the server without any processing.
 * @params {string} captchaVerifyParam
 * Return parameter: The field name is fixed. captchaResult is required. bizResult is optional if there is no business verification scenario.
 * @returns {{captchaResult: boolean, bizResult?: boolean|undefined}} 
 */
var captchaVerifyCallback = async function (captchaVerifyParam) {
  console.log(this.data);
  // Business request code...
  const result = await customFetch('https://xxxx/demo/bizquery', {
      method: 'POST',
      data: {
        captchaVerifyParam, // Include the verification parameter.
        userName: this.data.username, // Get business data through this.data.
        password: this.data.password,
      },
    });
  console.log(captchaVerifyParam);
  return {
    captchaResult: result.captchaVerifyResult, // Specifies whether the Captcha verification is successful. This is a boolean and is required.
    bizResult: Get your business verification result from the result. // Specifies whether the business verification is successful. This is a boolean and is optional. If there is no business verification result, bizResult can be empty.
  };
};

// Business request verification result callback function.
var onBizResultCallback = function (bizResult) {
  if (bizResult === true) {
    // Logic for successful business verification, such as displaying a success message.
    wx.showToast({
      title: 'Business verification successful!',
      duration: 2000,
      icon: 'success',
    });
  } else {
  // Logic for failed business verification, such as displaying a failure message.
    wx.showToast({
      title: 'Business verification failed!',
      duration: 2000,
      icon: 'error',
    });
  }
};

async function customFetch(url, option) {
  option.url = url;
  return new Promise((resolve, reject) => {
    wx.request({
      ...option,
      success(res) {
        resolve(res.data);
      },
      fail(res) {
        reject(new Error(res.toString()));
      },
    });
  });
}

// Page logic.
Page({
  data: {
    username: '',
    password: '',
    loadCaptcha: false, // Specifies whether to load the Captcha.
  },
  onLoad: function(options) {
    // Construct the plugin parameters.
    var pluginProps = {
      SceneId: 'xxxxx',
      mode: 'popup',
      // This is a fixed syntax. You must bind this to ensure that 'this' in the callback function points to the current page. This lets you get business parameters through this.data in the callback function.
      captchaVerifyCallback: captchaVerifyCallback.bind(this), 
      // This is a fixed syntax. You must bind this to ensure that 'this' in the callback function points to the current page. This lets you get business parameters through this.data in the callback function.
      onBizResultCallback: onBizResultCallback.bind(this), 
      slideStyle: {
        width: 540, // The default width is 540 rpx.
        height: 60, // The default height is 60 rpx.
      },
      language: 'cn',
      region: 'cn',
    };
    this.setData({
      loadCaptcha: true, // You can use this to control loading or reloading the Captcha.
      pluginProps,
    });
  },
  inputUsername: function(e) {
    this.setData({
      username: e.detail.value
    });
  },
  inputPassword: function(e) {
    this.setData({
      password: e.detail.value
    });
  },
  login: function() {
    const { username, password } = this.data;
    // You can perform custom business validation.
    if (username && password) {
      // For pop-up mode, call the instance method to display the Captcha. For no-captcha mode, also call this method to trigger verification.
      AliyunCaptchaPluginInterface.show();
    } else {
      wx.showToast({
        title: 'Enter your username and password.',
        icon: 'none'
      });
    }
  },
})

Integrate with a Taro framework mini program

Note

Taro integration is currently supported only for the React framework.

Step 1: Integrate the plugin

  1. Import the Captcha mini program plugin.

    Before you use the plugin on a page, declare the Alibaba Cloud Captcha mini program plugin in the project's app.config.js file. The following code provides an example:

    Note

    Ensure that you use the latest plugin version. You can find the latest version in WeChat Developer Tools > Details > Basic Information > Plugin Information.

    V3 architecture

    {
      "plugins": {
        "AliyunCaptcha": {
          "version": "3.0.0", // Select the latest version of the mini program plugin.
          "provider": "wxbe275ff84246f1a4"
        }
      }
    }

    V2 architecture

    {
      "plugins": {
        "AliyunCaptcha": {
          "version": "2.3.0", // Select the latest version of the mini program plugin.
          "provider": "wxbe275ff84246f1a4"
        }
      }
    }
  2. Import the Captcha mini program component.

    To use the custom component provided by the plugin, specify the plugin's reference name and the custom component's name using the plugin:// protocol in the index.config.js file of the page or component. The following code provides an example:

    export default {
      usingComponents: {
        'aliyun-captcha': 'plugin://AliyunCaptcha/captcha',
      },
    };

Step 2: Integrate the code

The following example shows a logon scenario:

V3 architecture

import Taro from '@tarojs/taro';
import { useEffect, useState, useRef } from 'react';
import { View, Text, Input, Button, Form } from '@tarojs/components';
import './index.scss';

// Get the Captcha plugin instance.
const AliyunCaptchaPluginInterface = Taro.requirePlugin('AliyunCaptcha');

// Business parameters must be maintained as global variables to be used in 'success'. Using 'state' will not work.
// let userName = '';
// let passWord = '';

function Index() {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [loadCaptcha, setLoadCaptcha] = useState(false);
  // You can also use 'ref' to maintain business parameters. This is recommended.
  const bizParams = useRef({
    username: '',
    password: '',
  });

  useEffect(() => {
    setLoadCaptcha(true); // You can use this to control loading or reloading the Captcha.
  }, []);

  const handleUsernameChange = (e) => {
    setUsername(e.target.value); // Update state.
    bizParams.current.username = e.target.value; // Also update ref.
    // userName = e.target.value; // Or update the global variable.
  };

  const handlePasswordChange = (e) => {
    setPassword(e.target.value); // Update state.
    bizParams.current.password = e.target.value; // Also update ref.
    // passWord = e.target.value; // Or update the global variable.
  };

  const login = () => {
    // You can perform custom business validation.
    if (username && password) {
      // For pop-up mode, call the instance method to display the Captcha. For no-captcha mode, also call this method to trigger verification.
      AliyunCaptchaPluginInterface.show();
    } else {
      Taro.showToast({
        title: 'Enter your username and password.',
        icon: 'none'
      });
    } 
  }

  // Callback function for successful verification.
  /**
   * @name success
   * @function
   * Request parameter: The verification parameter returned by the Captcha script. Pass it directly to the server for secondary verification without any processing.
   * @params {string} captchaVerifyParam
  */
  async function success(captchaVerifyParam) {
    // After successful verification, uninstall the Captcha.
    setLoadCaptcha(false);
    console.log(bizParams.current); // Business parameter ref.
    // console.log(userName, passWord); // Or use global business parameters.
    // Business request code...
    const result = await customFetch('https://xxxx/demo/bizquery', {
      method: 'POST',
      mode: 'cors',
      enableHttp2: true,
      enableQuic: true,
      data: {
        captchaVerifyParam, // Include the verification parameter.
        userName: bizParams.current.username, // Get business data through ref.
        password: bizParams.current.password, // Get business data through ref.
        // Or get business data through a global variable.
        // username: userName, // Get business data through a global variable.
        // password: passWord, // Get business data through a global variable.
      },
    });
  }

  // Business request verification result callback function.
  function fail(error) {
    console.error(error)
  }

  // To verify again, call this method to reload the Captcha.
  function reloadCaptcha() {
    setLoadCaptcha(true);
  }

  async function customFetch(url, option) {
    option.url = url;
    return new Promise((resolve, reject) => {
      Taro.request({
        ...option,
        success(res) {
          resolve(res.data);
        },
        fail(res) {
          reject(new Error(res.toString()));
        },
      });
    });
  }

  // Construct the plugin parameters.
  const pluginProps = {
    SceneId: 'xxxxx',
    mode: 'popup',
    success,
    fail,
    slideStyle: {
      width: 540, // The default width is 540 rpx.
      height: 60, // The default height is 60 rpx.
    },
    language: 'cn',
    region: 'cn',
  };

  return (
    <View className="captcha-page">
    <Form>
    <View className="input-group">
    <Text>Account:</Text>
    <Input
  type="text"
  placeholder="Enter your account"
  value={username}
  onInput={handleUsernameChange}
    />
    </View>
    <View className="input-group">
    <Text>Password:</Text>
    <Input
  type="password"
  placeholder="Enter your password"
  value={password}
  onInput={handlePasswordChange}
    />
    </View>
  {/* Bind the login method to the logon button. When the button is clicked, call the plugin instance method in the login method to display the Captcha. */}
  <Button style={{ margin: '20px' }} id="captcha-button" onClick={login}>Log On</Button>
  </Form>
{loadCaptcha && <aliyun-captcha id="captcha-element" props={pluginProps} />}
  </View>
 );
}

export default Index;

To perform another verification after a successful one, call `reloadCaptcha` to reload the Captcha.

V2 architecture

import Taro from '@tarojs/taro';
import { useEffect, useState, useRef } from 'react';
import { View, Text, Input, Button, Form } from '@tarojs/components';
import './index.scss';

// Get the Captcha plugin instance.
const AliyunCaptchaPluginInterface = Taro.requirePlugin('AliyunCaptcha');

// Business parameters must be maintained as global variables to be used in 'captchaVerifyCallback'. Using 'state' will not work.
// let userName = '';
// let passWord = '';
function Index() {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [loadCaptcha, setLoadCaptcha] = useState(false);
  // You can also use 'ref' to maintain business parameters. This is recommended.
  const bizParams = useRef({
    username: '',
    password: '',
  });

  useEffect(() => {
    setLoadCaptcha(true); // You can use this to control loading or reloading the Captcha.
  }, []);

  const handleUsernameChange = (e) => {
    setUsername(e.target.value); // Update state.
    bizParams.current.username = e.target.value; // Also update ref.
    // userName = e.target.value; // Or update the global variable.
  };
  
  const handlePasswordChange = (e) => {
    setPassword(e.target.value); // Update state.
    bizParams.current.password = e.target.value; // Also update ref.
    // passWord = e.target.value; // Or update the global variable.
  };

  const login = () => {
    // You can perform custom business validation.
    if (username && password) {
      // For pop-up mode, call the instance method to display the Captcha. For no-captcha mode, also call this method to trigger verification.
      AliyunCaptchaPluginInterface.show();
    } else {
      Taro.showToast({
        title: 'Enter your username and password.',
        icon: 'none'
      });
    } 
  }


  // Business request (with Captcha verification) callback function.
  /**
   * @name captchaVerifyCallback
   * @function
   * Request parameter: The verification parameter returned by the Captcha script. Pass it directly to the server without any processing.
   * @params {string} captchaVerifyParam
   * Return parameter: The field name is fixed. captchaResult is required. bizResult is optional if there is no business verification scenario.
   * @returns {{captchaResult: boolean, bizResult?: boolean|undefined}} 
   */
  async function captchaVerifyCallback(captchaVerifyParam) {
    console.log(bizParams.current); // Business parameter ref.
    // console.log(userName, passWord); // Or use global business parameters.
    // Business request code...
    const result = await customFetch('https://xxxx/demo/bizquery', {
      method: 'POST',
      mode: 'cors',
      enableHttp2: true,
      enableQuic: true,
      data: {
        captchaVerifyParam, // Include the verification parameter.
        userName: bizParams.current.username, // Get business data through ref.
        password: bizParams.current.password, // Get business data through ref.
        // Or get business data through a global variable.
        // username: userName, // Get business data through a global variable.
        // password: passWord, // Get business data through a global variable.
      },
    });
    return {
      captchaResult: result.captchaVerifyResult, // Specifies whether the Captcha verification is successful. This is a boolean and is required.
      bizResult: Get your business verification result from the result. // Specifies whether the business verification is successful. This is a boolean and is optional. If there is no business verification result, bizResult can be empty.
    };
  }

  // Business request verification result callback function.
  function onBizResultCallback(bizResult) {
    if (bizResult === true) {
      // Logic for successful business verification, such as displaying a success message.
      Taro.showToast({
        title: 'Business verification successful!',
        duration: 2000,
        icon: 'success',
      });
    } else {
    // Logic for failed business verification, such as displaying a failure message.
    Taro.showToast({
        title: 'Business verification failed!',
        duration: 2000,
        icon: 'error',
      });
    }
  }

  async function customFetch(url, option) {
    option.url = url;
    return new Promise((resolve, reject) => {
      Taro.request({
        ...option,
        success(res) {
          resolve(res.data);
        },
        fail(res) {
          reject(new Error(res.toString()));
        },
      });
    });
  }
  
  // Construct the plugin parameters.
  const pluginProps = {
    SceneId: 'xxxxx',
    mode: 'popup',
    captchaVerifyCallback,
    onBizResultCallback,
    slideStyle: {
      width: 540, // The default width is 540 rpx.
      height: 60, // The default height is 60 rpx.
    },
    language: 'cn',
    region: 'cn',
  };

  return (
    <View className="captcha-page">
      <Form>
        <View className="input-group">
          <Text>Account:</Text>
          <Input
            type="text"
            placeholder="Enter your account"
            value={username}
            onInput={handleUsernameChange}
          />
        </View>
        <View className="input-group">
          <Text>Password:</Text>
          <Input
            type="password"
            placeholder="Enter your password"
            value={password}
            onInput={handlePasswordChange}
          />
        </View>
        {/* Bind the login method to the logon button. When the button is clicked, call the plugin instance method in the login method to display the Captcha. */}
        <Button style={{ margin: '20px' }} id="captcha-button" onClick={login}>Log On</Button>
      </Form>
      {loadCaptcha && <aliyun-captcha id="captcha-element" props={pluginProps} />}
    </View>
  );
}

export default Index;

Taro build tool recommendations

Taro supports packaging only with Webpack. If you are creating a new project that uses Vite for packaging, we recommend switching to Webpack to ensure optimal compatibility. If switching to Webpack significantly impacts an existing project, you can use the compatibility solution and manually add the Captcha WXML element to the `dist` directory.

  1. If you use Vite for packaging, the following error message may appear in WeChat Developer Tools because of a compatibility issue:image

  2. To resolve this issue, add the following code to the `dist/base.wxml` file in the packaged project:

    <template name="tmpl_0_aliyun-captcha">
      <aliyun-captcha
        props="{{i.props}}"
        id="{{i.uid||i.sid}}"
        data-sid="{{i.sid}}"
      >
        <block wx:for="{{i.cn}}" wx:key="sid">
          <template
            is="{{xs.a(c, item.nn, l)}}"
            data="{{i:item,c:c+1,l:xs.f(l,item.nn)}}"
          />
        </block>
      </aliyun-captcha>
    </template>

Integrate with a uni-app mini program

uni-app supports integration with mini programs using Vue2 and Vue3. This section uses Vue3 as an example.

Step 1: Integrate the plugin

  1. Import the Captcha mini program plugin.

    Before you use the plugin on a page, declare the Alibaba Cloud Captcha mini program plugin in the project's manifest.json file. The following code provides an example:

    Note

    Ensure that you use the latest plugin version. You can find the latest version in WeChat Developer Tools > Details > Basic Information > Plugin Information.

    V3 architecture

    "mp-weixin": {
      "plugins": {
        "AliyunCaptcha": {
          "version": "3.0.0",
          "provider": "wxbe275ff84246f1a4",
        }
      }
    }

    V2 architecture

    {
      "plugins": {
        "AliyunCaptcha": {
          "version": "2.3.0", // Select the latest version of the mini program plugin.
          "provider": "wxbe275ff84246f1a4"
        }
      }
    }
  2. Import the Captcha mini program component.

    Using the custom component provided by the plugin is similar to using a regular custom component. In the page.json file of the corresponding page, configure the custom component under the `style` node. Use the plugin:// protocol to specify the plugin's reference name and the name of the custom component. The following code provides an example:

    {
      "path": "pages/CaptchaPage",
      "style": {
        "mp-weixin": {
            "usingComponents": {
                "aliyun-captcha": "plugin://AliyunCaptcha/captcha"
            }
        }
      }
    }

Step 2: Integrate the code

In the .vue file, insert the aliyun-captcha component into the <template> tag. Then, initialize the plugin within the <script> tag when it is needed.

The following example shows a logon scenario:

V3 architecture

<template>
  <view class="captchapage-container">
    <view class="input-group">
      <view class="label">Username:</view>
      <input
        class="input"
        type="text"
        placeholder="Enter your username"
        @input="inputUsername"
      />
    </view>
    <view class="input-group">
      <view class="label">Password:</view>
      <input
        class="input"
        type="password"
        placeholder="Enter your password"
        @input="inputPassword"
      />
    </view>
    <aliyun-captcha
      id="captcha-element"
      v-if="data.loadCaptcha"
      :props="data.pluginProps"
    />
    <button class="login-btn" @click="login">Log On</button>
  </view>
</template>

<script>
  // Get the Captcha plugin instance.
  const AliyunCaptchaPluginInterface = requirePlugin("AliyunCaptcha");

  // Callback function for successful verification.
  /**
   * @name success
   * @function
   * Request parameter: The verification parameter returned by the Captcha script. Pass it directly to the server for secondary verification without any processing.
   * @params {string} captchaVerifyParam
   * Return parameter: The field name is fixed. captchaResult is required. error is optional if there is no business verification scenario.
   * @returns {{captchaResult: boolean, error?: boolean|undefined}}
   */
  var success = async function (captchaVerifyParam) {
    // After successful verification, uninstall the Captcha.
    this.data.loadCaptcha = false;
    console.log(this.data);
    // Business request code...
    const result = await customFetch("https://xxxx/demo/bizquery", {
      method: "POST",
      data: {
        captchaVerifyParam, // Include the verification parameter.
        userName: this.data.username, // Get business data through this.data.
        password: this.data.password,
      },
    });
  };

  // Callback function for failed verification.
  var fail = function (error) {
    console.error(error);
  };

  async function customFetch(url, option) {
    option.url = url;
    return new Promise((resolve, reject) => {
      uni.request({
        ...option,
        success(res) {
          resolve(res.data);
        },
        fail(res) {
          reject(new Error(res.toString()));
        },
      });
    });
  }

  export default {
    data() {
      return {
        data: {
          username: "",
          password: "",
          loadCaptcha: false,
        },
      };
    },
    onLoad(options) {
      console.log(AliyunCaptchaPluginInterface);
      var pluginProps = {
        SceneId: "xxxxx",
        mode: "popup",
        success: success.bind(this), // This is a fixed syntax. You must bind this.
        fail: fail.bind(this), // This is a fixed syntax. You must bind this.
        slideStyle: {
          width: 540, // The default width is 540 rpx.
          height: 60, // The default height is 60 rpx.
        },
        language: "cn",
        region: "cn",
      };
      // Initialize the Captcha plugin.
      this.data.loadCaptcha = true; // You can use this to control loading or reloading the Captcha.
      this.data.pluginProps = pluginProps;
    },
    methods: {
      // Handler function for username input.
      inputUsername(e) {
        this.data.username = e.detail.value;
      },
      // Handler function for password input.
      inputPassword(e) {
        this.data.password = e.detail.value;
      },
      // Handler function for logon button click.
      login() {
        const { username, password } = this.data;
        // This is just an example. In actual development, you need to send the logon information to the server for verification.
        // For pop-up mode, call the instance method to display the Captcha. For no-captcha mode, also call this method to trigger verification.
        if (username && password) {
          AliyunCaptchaPluginInterface.show();
        } else {
          uni.showToast({
            title: "Enter your username and password.",
            icon: "none",
          });
        }
      },
      // To verify again, call this method to reload the Captcha.
      reloadCaptcha = function () {
        this.data.loadCaptcha = true;
      }
    },
  };
</script>

To perform another verification after a successful one, call `reloadCaptcha` to reload the Captcha.

V2 architecture

<template>
  <view class="captchapage-container">
    <view class="input-group">
      <view class="label">Username:</view>
      <input
        class="input"
        type="text"
        placeholder="Enter your username"
        @input="inputUsername"
      />
    </view>
    <view class="input-group">
      <view class="label">Password:</view>
      <input
        class="input"
        type="password"
        placeholder="Enter your password"
        @input="inputPassword"
      />
    </view>
    <aliyun-captcha
      id="captcha-element"
      v-if="data.loadCaptcha"
      :props="data.pluginProps"
    />
    <button class="login-btn" @click="login">Log On</button>
  </view>
</template>

<script>
  // Get the Captcha plugin instance.
  const AliyunCaptchaPluginInterface = requirePlugin("AliyunCaptcha");

  // Business request (with Captcha verification) callback function.
  /**
   * @name captchaVerifyCallback
   * @function
   * Request parameter: The verification parameter returned by the Captcha script. Pass it directly to the server without any processing.
   * @params {string} captchaVerifyParam
   * Return parameter: The field name is fixed. captchaResult is required. bizResult is optional if there is no business verification scenario.
   * @returns {{captchaResult: boolean, bizResult?: boolean|undefined}}
   */
  var captchaVerifyCallback = async function (captchaVerifyParam) {
    console.log(this.data);
    // Business request code...
    const result = await customFetch("https://xxxx/demo/bizquery", {
      method: "POST",
      data: {
        captchaVerifyParam, // Include the verification parameter.
        userName: this.data.username, // Get business data through this.data.
        password: this.data.password,
      },
    });
    console.log(captchaVerifyParam);
    return {
      captchaResult: result.captchaVerifyResult, // Specifies whether the Captcha verification is successful. This is a boolean and is required.
      bizResult: Get your business verification result from the result. // Specifies whether the business verification is successful. This is a boolean and is optional. If there is no business verification result, bizResult can be empty.
    };
  };

  // Business request verification result callback function.
  var onBizResultCallback = function (bizResult) {
    if (bizResult === true) {
      // Logic for successful business verification, such as displaying a success message.
      uni.showToast({
        title: "Business verification successful!",
        duration: 2000,
        icon: "success",
      });
    } else {
      // Logic for failed business verification, such as displaying a failure message.
      uni.showToast({
        title: "Business verification failed!",
        duration: 2000,
        icon: "error",
      });
    }
  };

  async function customFetch(url, option) {
    option.url = url;
    return new Promise((resolve, reject) => {
      uni.request({
        ...option,
        success(res) {
          resolve(res.data);
        },
        fail(res) {
          reject(new Error(res.toString()));
        },
      });
    });
  }

  export default {
    data() {
      return {
        data: {
          username: "",
          password: "",
          loadCaptcha: false,
        },
      };
    },
    onLoad(options) {
      console.log(AliyunCaptchaPluginInterface);
      var pluginProps = {
        SceneId: "xxxxx",
        mode: "popup",
        captchaVerifyCallback: captchaVerifyCallback.bind(this), // This is a fixed syntax. You must bind this.
        onBizResultCallback: onBizResultCallback.bind(this), // This is a fixed syntax. You must bind this.
        slideStyle: {
          width: 540, // The default width is 540 rpx.
          height: 60, // The default height is 60 rpx.
        },
        language: "cn",
        region: "cn",
      };
      // Initialize the Captcha plugin.
      this.data.loadCaptcha = true; // You can use this to control loading or reloading the Captcha.
      this.data.pluginProps = pluginProps;
    },
    methods: {
      // Handler function for username input.
      inputUsername(e) {
        this.data.username = e.detail.value;
      },
      // Handler function for password input.
      inputPassword(e) {
        this.data.password = e.detail.value;
      },
      // Handler function for logon button click.
      login() {
        const { username, password } = this.data;
        // This is just an example. In actual development, you need to send the logon information to the server for verification.
        // For pop-up mode, call the instance method to display the Captcha. For no-captcha mode, also call this method to trigger verification.
        if (username && password) {
          AliyunCaptchaPluginInterface.show();
        } else {
          uni.showToast({
            title: "Enter your username and password.",
            icon: "none",
          });
        }
      },
    },
  };
</script>
Note

The integration process for Vue2 is similar to the process for Vue3. However, you must also import a patch file and replace the native __patch__ method of the Vue object on the page where Captcha is used.

  1. Import the patch.js file.

  2. Replace the __patch__ function at the beginning of the `beforeCreate` hook.

  3. Revert the __patch__ function in the `beforeDestroy` hook.

import { myPatch } from "@/xxx/patch.js"
import Vue from 'vue';

data() {
  return {
    data: {
      originalPatch: Vue.prototype.__patch__,
    },
  },
},
beforeCreate() {
  this.originalPatch = Vue.prototype.__patch__; // Save the original patch function.
  Vue.prototype.__patch__ = myPatch; // Replace the patch function.
  // Refer to the Vue3 code for Captcha initialization.
},
beforeDestroy() {
  Vue.prototype.__patch__ = this.originalPatch; // Revert the patch function.
}

Parameters

V3 architecture

Parameter

Type

Required

Default

Description

SceneId

String

Yes

None

The ID of the verification scenario. You can get this value after you create a verification scenario.

mode

String

Yes

None

The Captcha mode. For protection and user experience, only popup is supported.

success

Function

Yes

None

The callback function for successful Captcha verification. This function returns the verification parameter. You can get CaptchaVerifyParam in this callback function and request your server to verify CaptchaVerifyParam.

fail

Function

Yes

None

The callback function for failed Captcha verification. This function returns the error code for the failure.

slideStyle

Object

No

{ width: 540, height: 60 }

The style of the slider Captcha. You can customize the width and height in rpx.

Note
  • The Captcha needs to collect enough information through sliding for the policy model to make a judgment. Therefore, set the minimum width of the slider (width value) to 540 rpx. If the width value is less than 540 rpx, the system configures it as 540 rpx.

  • This parameter is valid only for the slider mode and does not apply to puzzle Captchas. If you use a puzzle Captcha, do not override the CSS to forcibly change the style. The image size and verification answer of a puzzle Captcha are preset and fixed. Changing the style will cause verification to fail.

language

String

No

cn

The language types supported by Captcha 2.0.

region

String

No

cn

The region where the Captcha instance belongs. Valid values:

  • cn: the Chinese mainland.

  • sgp: Singapore.

Note
  • If the region parameter for client integration is different from the endpoint for server integration, the verification request returns an error.

  • The product has management console platforms in the Chinese mainland (China (Shanghai)) and Singapore. Based on the call parameters you configure, behavioral data, device data, and other information collected by the client are sent back to the corresponding center for processing. This is mainly for security authentication.

V2 architecture

Parameter

Type

Required

Default

Description

SceneId

String

Yes

None

The ID of the verification scenario. You can get this value after you create a verification scenario.

mode

String

Yes

None

The Captcha mode. For protection and user experience, only popup is supported.

captchaVerifyCallback

Function

Yes

captchaVerifyCallback

The callback function for business requests (with Captcha verification). For more information, see the comments in the code examples.

onBizResultCallback

Function

Yes

onBizResultCallback

The callback function for business request results. Use this to set the logic for handling verification results.

slideStyle

Object

No

{ width: 540, height: 60 }

The style of the slider Captcha. You can customize the width and height in rpx.

Note
  • The Captcha needs to collect enough information through sliding for the policy model to make a judgment. Therefore, set the minimum width of the slider (width value) to 540 rpx. If the width value is less than 540 rpx, the system configures it as 540 rpx.

  • This parameter is valid only for the slider mode and does not apply to puzzle Captchas. If you use a puzzle Captcha, do not override the CSS to forcibly change the style. The image size and verification answer of a puzzle Captcha are preset and fixed. Changing the style will cause verification to fail.

language

String

No

cn

The language types supported by Captcha 2.0.

region

String

No

cn

The region where the Captcha instance belongs. Valid values:

  • cn: the Chinese mainland.

  • sgp: Singapore.

Note
  • If the region parameter for client integration is different from the endpoint for server integration, the verification request returns an error.

  • The product has management console platforms in the Chinese mainland (China (Shanghai)) and Singapore. Based on the call parameters you configure, behavioral data, device data, and other information collected by the client are sent back to the corresponding center for processing. This is mainly for security authentication.