All Products
Search
Document Center

Captcha:Integrate the WeChat Mini Program plug-in with V3 architecture

Last Updated:Jul 14, 2026

After adding a verification scenario in the console, integrate the initialization code into the WeChat mini program page that requires the verification feature.

Prerequisites

WeChat Mini Program plug-in integration

Native

Before using the plug-in, add it in the WeChat mini program admin console. Log on to the admin console and go to Settings > Third-Party Service > Plug-in Management. Search for the plug-in by using the app ID (wxbe275ff84246f1a4) and add it.

Step 1: Integrate the plug-in

  1. Declare the Captcha 2.0 plug-in.

    Before using the plug-in on a page, declare it in the app.json file of your project.

    Note

    We recommend that you use the latest version of the plug-in. To view the latest version, go to WeChat DevTools > Details > Basic Information > Plug-in Information.

    V3 architecture

    {
      "plugins": {
        "AliyunCaptcha": {
          "version": "3.0.0", // Use the latest version of the mini program plug-in.
          "provider": "wxbe275ff84246f1a4"
        }
      }
    }

    V2 architecture

    {
      "plugins": {
        "AliyunCaptcha": {
          "version": "2.3.0", // Use the latest version of the mini program plug-in.
          "provider": "wxbe275ff84246f1a4"
        }
      }
    }
  2. Declare the custom component.

    To use the plug-in's custom component, declare it in the .json file of the relevant page or component. Use the plugin:// protocol to specify the plug-in's reference name and the custom component's name.

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

Step 2: Insert the template

Insert the aliyun-captcha template, including the required parameters shown in the sample code, into your .wxml file.

This 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 a username" bindinput="inputUsername" />
  </view>
  <view class="input-group">
    <view class="label">Password:</view>
    <input class="input" type="password" placeholder="Enter a 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, the login method calls the plug-in instance method to display the CAPTCHA. -->
  <button class="login-btn" bindtap="login">Log On</button>
</view>

Step 3: Initialize the plug-in

To initialize the plug-in, call the setData method with the required parameters.

This example shows a logon scenario.

V3 architecture

// Get the plug-in instance.
var AliyunCaptchaPluginInterface = requirePlugin('AliyunCaptcha');

// Success callback function.
/**
 * @name success
 * @function
 * Request parameter: The verification parameter returned by the CAPTCHA script. Pass this parameter directly to your server for server-side verification without any modification.
 * @params {string} captchaVerifyParam 
 */
var success = async function (captchaVerifyParam) {
  // After verification succeeds, unload the CAPTCHA.
  this.setData({
    loadCaptcha: false,
  });
  console.log(this.data);
  // Your 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 by using this.data.
        password: this.data.password,
      },
    });
  console.log(captchaVerifyParam);
};

// Fail callback function.
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 plug-in parameters.
    var pluginProps = {
      SceneId: 'xxxxx',
      mode: 'popup',
      // This must be bound to ensure that 'this' in the callback function refers to the current page context, allowing you to access business parameters by using this.data.
      success: success.bind(this), 
      // This must be bound to ensure that 'this' in the callback function refers to the current page context, allowing you to access business parameters by using this.data.
      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, // Controls whether to load or reload 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 add custom business validation.
    if (username && password) {
      // For pop-up mode, call the instance method to display the CAPTCHA. For frictionless mode, call the same method to trigger verification.
      AliyunCaptchaPluginInterface.show();
    } else {
      wx.showToast({
        title: 'Please enter a username and password.',
        icon: 'none'
      });
    }
  },
  // If you need to verify again, call this method to reload the CAPTCHA.
  reloadCaptcha: function () {
    this.setData({
      loadCaptcha: true,
    });
  },
})

After verification passes, call the reloadCaptcha method to reload the CAPTCHA if another verification is needed.

V2 architecture

// Get the plug-in instance.
var AliyunCaptchaPluginInterface = requirePlugin('AliyunCaptcha');

// Callback function for a business request that includes CAPTCHA verification.
/**
 * @name captchaVerifyCallback
 * @function
 * Request parameter: The verification parameter returned by the CAPTCHA script. Pass this parameter directly to your server without any modification.
 * @params {string} captchaVerifyParam
 * Return value: The field names are fixed. captchaResult is required. bizResult is optional if no business logic is verified.
 * @returns {{captchaResult: boolean, bizResult?: boolean|undefined}} 
 */
var captchaVerifyCallback = async function (captchaVerifyParam) {
  console.log(this.data);
  // Your 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 by using this.data.
        password: this.data.password,
      },
    });
  console.log(captchaVerifyParam);
  return {
    captchaResult: result.captchaVerifyResult, // Required. A boolean value that indicates whether the CAPTCHA is passed.
    bizResult: result.yourBizResult, // Optional. The business verification result. This can be left empty if no business logic is verified.
  };
};

// Callback function for the business logic verification result.
var onBizResultCallback = function (bizResult) {
  if (bizResult === true) {
    // Logic to execute if business logic verification passes, such as displaying a success message.
    wx.showToast({
      title: 'Business verification passed!',
      duration: 2000,
      icon: 'success',
    });
  } else {
    // Logic to execute if business logic verification fails, such as displaying an error 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 plug-in parameters.
    var pluginProps = {
      SceneId: 'xxxxx',
      mode: 'popup',
      // This must be bound to ensure that 'this' in the callback function refers to the current page context, allowing you to access business parameters by using this.data.
      captchaVerifyCallback: captchaVerifyCallback.bind(this), 
      // This must be bound to ensure that 'this' in the callback function refers to the current page context, allowing you to access business parameters by using this.data.
      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, // Controls whether to load or reload 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 add custom business validation.
    if (username && password) {
      // For pop-up mode, call the instance method to display the CAPTCHA. For frictionless mode, call the same method to trigger verification.
      AliyunCaptchaPluginInterface.show();
    } else {
      wx.showToast({
        title: 'Please enter a username and password.',
        icon: 'none'
      });
    }
  },
})

Taro framework

Note

Taro integration currently supports only React.

Step 1: Integrate the plug-in

  1. Declare the Captcha 2.0 plug-in.

    Before using the plug-in on a page, declare it in the app.config.js file of your project.

    Note

    We recommend that you use the latest plug-in version. To check the latest version, go to WeChat DevTools > Details > Basic Information > Plug-in Information.

    V3 architecture

    {
      "plugins": {
        "AliyunCaptcha": {
          "version": "3.0.0", // Use the latest version of the mini program plug-in.
          "provider": "wxbe275ff84246f1a4"
        }
      }
    }

    V2 architecture

    {
      "plugins": {
        "AliyunCaptcha": {
          "version": "2.3.0", // Use the latest version of the mini program plug-in.
          "provider": "wxbe275ff84246f1a4"
        }
      }
    }
  2. Declare the custom component.

    To use the plug-in's custom component, specify the plug-in's reference name and the custom component name by using the plugin:// protocol in the index.config.js file of the page or component.

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

Step 2: Integrate the code

This 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 plug-in instance.
const AliyunCaptchaPluginInterface = Taro.requirePlugin('AliyunCaptcha');

// Global variables must be used to maintain business parameters for use in the `success` callback, as state changes may not be reflected.
// let userName = '';
// let passWord = '';

function Index() {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [loadCaptcha, setLoadCaptcha] = useState(false);
  // We recommend using a ref to maintain business parameters.
  const bizParams = useRef({
    username: '',
    password: '',
  });

  useEffect(() => {
    setLoadCaptcha(true); // Controls whether to load or reload the CAPTCHA.
  }, []);

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

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

  const login = () => {
    // You can add custom business validation.
    if (username && password) {
      // For pop-up mode, call the instance method to display the CAPTCHA. For frictionless mode, call the same method to trigger verification.
      AliyunCaptchaPluginInterface.show();
    } else {
      Taro.showToast({
        title: 'Please enter a username and password.',
        icon: 'none'
      });
    } 
  }

  // Success callback function.
  /**
   * @name success
   * @function
   * Request parameter: The verification parameter returned by the CAPTCHA script. Pass this parameter directly to your server for server-side verification without any modification.
   * @params {string} captchaVerifyParam
  */
  async function success(captchaVerifyParam) {
    // After verification succeeds, unload the CAPTCHA.
    setLoadCaptcha(false);
    console.log(bizParams.current); // Business parameters from ref.
    // console.log(userName, passWord); // Or use global business parameters.
    // Your 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 from the ref.
        password: bizParams.current.password, // Get business data from the ref.
        // Or get business data from global variables.
        // username: userName, 
        // password: passWord, 
      },
    });
  }

  // Fail callback function.
  function fail(error) {
    console.error(error)
  }

  // If you need 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 plug-in 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 an account"
  value={username}
  onInput={handleUsernameChange}
    />
    </View>
    <View className="input-group">
    <Text>Password:</Text>
    <Input
  type="password"
  placeholder="Enter a password"
  value={password}
  onInput={handlePasswordChange}
    />
    </View>
  {/* Bind the login method to the Logon button. When the button is clicked, the login method calls the plug-in instance 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;

After verification passes, call the reloadCaptcha method to reload the CAPTCHA if another verification is needed.

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 plug-in instance.
const AliyunCaptchaPluginInterface = Taro.requirePlugin('AliyunCaptcha');

// Global variables must be used to maintain business parameters for use in the `captchaVerifyCallback` callback, as state changes may not be reflected.
// let userName = '';
// let passWord = '';

function Index() {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [loadCaptcha, setLoadCaptcha] = useState(false);
  // We recommend using a ref to maintain business parameters.
  const bizParams = useRef({
    username: '',
    password: '',
  });

  useEffect(() => {
    setLoadCaptcha(true); // Controls whether to load or reload the CAPTCHA.
  }, []);

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

  const login = () => {
    // You can add custom business validation.
    if (username && password) {
      // For pop-up mode, call the instance method to display the CAPTCHA. For frictionless mode, call the same method to trigger verification.
      AliyunCaptchaPluginInterface.show();
    } else {
      Taro.showToast({
        title: 'Please enter a username and password.',
        icon: 'none'
      });
    } 
  }

  // Callback function for a business request that includes CAPTCHA verification.
  /**
   * @name captchaVerifyCallback
   * @function
   * Request parameter: The verification parameter returned by the CAPTCHA script. Pass this parameter directly to your server without any modification.
   * @params {string} captchaVerifyParam
   * Return value: The field names are fixed. captchaResult is required. bizResult is optional if no business logic is verified.
   * @returns {{captchaResult: boolean, bizResult?: boolean|undefined}} 
   */
  async function captchaVerifyCallback(captchaVerifyParam) {
    console.log(bizParams.current); // Business parameters from ref.
    // console.log(userName, passWord); // Or use global business parameters.
    // Your 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 from the ref.
        password: bizParams.current.password, // Get business data from the ref.
        // Or get business data from global variables.
        // username: userName,
        // password: passWord, 
      },
    });
    return {
      captchaResult: result.captchaVerifyResult, // Required. A boolean value that indicates whether the CAPTCHA is passed.
      bizResult: result.yourBizResult, // Optional. The business verification result. This can be left empty if no business logic is verified.
    };
  }

  // Callback function for the business logic verification result.
  function onBizResultCallback(bizResult) {
    if (bizResult === true) {
      // Logic to execute if business logic verification passes, such as displaying a success message.
      Taro.showToast({
        title: 'Business verification passed!',
        duration: 2000,
        icon: 'success',
      });
    } else {
      // Logic to execute if business logic verification fails, such as displaying an error 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 plug-in 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 an account"
            value={username}
            onInput={handleUsernameChange}
          />
        </View>
        <View className="input-group">
          <Text>Password:</Text>
          <Input
            type="password"
            placeholder="Enter a password"
            value={password}
            onInput={handlePasswordChange}
          />
        </View>
        {/* Bind the login method to the Logon button. When the button is clicked, the login method calls the plug-in instance 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 only Webpack for packaging. For new projects that use Vite, we recommend switching to Webpack to ensure optimal compatibility. For existing projects where switching to Webpack is not feasible, the workaround is to manually add the captcha's WXML element to the dist directory.

  1. When you use Vite for packaging, the WeChat Mini Program displays the following WXML Runtime warning, indicating that the template is not found:

    WXMLRT_$6c6f67696e2f:./base.wxml:template:20:18: Template `tmpl_0_aliyun-captcha` not found.
    WXMLRT_$6c6f67696e2f:./base.wxml:template:20:18: Template `tmpl_0_aliyun-captcha` not found.
    
    [WXML Runtime warning] ./base.wxml
    Template `tmpl_0_aliyun-captcha` not found.
      18 | <template name="tmpl_0_3">
      19 |   <view style="{{i.st}}" class="{{i.cl}}"   id="{{i.uid||i.sid}}" data-sid="{{i.sid}}">
    > 20 |     <template is="{{xs.a(c, item.nn, l)}}" data="{{i:item,c:c+1,l:xs.f(l,item.nn)}}" wx:for="{{i.cn}}" wx:key="sid" />
         |              ^
      21 |   </view>
      22 | </template>
      23 |
    
  2. In the packaged dist/base.wxml file, add the following code.

    <template name="tmpl_0_alibaba-cloud-captcha">
      <alibaba-cloud-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>
      </alibaba-cloud-captcha>
    </template>

uni-app

uni-app integration supports both Vue 2 and Vue 3. This section uses Vue 3 as an example.

Step 1: Integrate the plug-in

  1. Declare the Captcha 2.0 plug-in.

    Before using the plug-in on a page, declare it in the manifest.json file of your project.

    Note

    We recommend that you use the latest version of the plug-in. To check the latest version, go to WeChat DevTools > Details > Basic Information > Plug-in Information.

    V3 architecture

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

    V2 architecture

    {
      "plugins": {
        "AliyunCaptcha": {
          "version": "2.3.0", // Use the latest version of the mini program plug-in.
          "provider": "wxbe275ff84246f1a4"
        }
      }
    }
  2. Declare the custom component.

    Using a plug-in's custom component is similar to using a standard custom component. In the page.json file, under the style node for the corresponding page, use the plugin:// protocol to specify the plug-in's reference name and the custom component name.

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

Step 2: Integrate the code

In your .vue file, insert the aliyun-captcha component into the <template> section. Initialize the plug-in in the <script> section.

This 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 a username"
        @input="inputUsername"
      />
    </view>
    <view class="input-group">
      <view class="label">Password:</view>
      <input
        class="input"
        type="password"
        placeholder="Enter a 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 plug-in instance.
  const AliyunCaptchaPluginInterface = requirePlugin("AliyunCaptcha");

  // Success callback function.
  /**
   * @name success
   * @function
   * Request parameter: The verification parameter returned by the CAPTCHA script. Pass this parameter directly to your server for server-side verification without any modification.
   * @params {string} captchaVerifyParam
   */
  var success = async function (captchaVerifyParam) {
    // After verification succeeds, unload the CAPTCHA.
    this.data.loadCaptcha = false;
    console.log(this.data);
    // Your 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 by using this.data.
        password: this.data.password,
      },
    });
  };

  // Fail callback function.
  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 must be bound.
        fail: fail.bind(this), // This must be bound.
        slideStyle: {
          width: 540, // The default width is 540 rpx.
          height: 60, // The default height is 60 rpx.
        },
        language: "cn",
        region: "cn",
      };
      // Initialize the plug-in.
      this.data.loadCaptcha = true; // Controls whether to load or reload the CAPTCHA.
      this.data.pluginProps = pluginProps;
    },
    methods: {
      // Handler for username input.
      inputUsername(e) {
        this.data.username = e.detail.value;
      },
      // Handler for password input.
      inputPassword(e) {
        this.data.password = e.detail.value;
      },
      // Handler for logon button click.
      login() {
        const { username, password } = this.data;
        // This is an example. In a real application, you must send logon information to the server for verification.
        // For pop-up mode, call the instance method to display the CAPTCHA. For frictionless mode, call the same method to trigger verification.
        if (username && password) {
          AliyunCaptchaPluginInterface.show();
        } else {
          uni.showToast({
            title: "Please enter a username and password.",
            icon: "none",
          });
        }
      },
      // If you need to verify again, call this method to reload the CAPTCHA.
      reloadCaptcha() {
        this.data.loadCaptcha = true;
      }
    },
  };
</script>

After verification passes, call the reloadCaptcha method to reload the CAPTCHA if another verification is needed.

V2 architecture

<template>
  <view class="captchapage-container">
    <view class="input-group">
      <view class="label">Username:</view>
      <input
        class="input"
        type="text"
        placeholder="Enter a username"
        @input="inputUsername"
      />
    </view>
    <view class="input-group">
      <view class="label">Password:</view>
      <input
        class="input"
        type="password"
        placeholder="Enter a 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 plug-in instance.
  const AliyunCaptchaPluginInterface = requirePlugin("AliyunCaptcha");

  // Callback function for a business request that includes CAPTCHA verification.
  /**
   * @name captchaVerifyCallback
   * @function
   * Request parameter: The verification parameter returned by the CAPTCHA script. Pass this parameter directly to your server without any modification.
   * @params {string} captchaVerifyParam
   * Return value: The field names are fixed. captchaResult is required. bizResult is optional if no business logic is verified.
   * @returns {{captchaResult: boolean, bizResult?: boolean|undefined}}
   */
  var captchaVerifyCallback = async function (captchaVerifyParam) {
    console.log(this.data);
    // Your 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 by using this.data.
        password: this.data.password,
      },
    });
    console.log(captchaVerifyParam);
    return {
      captchaResult: result.captchaVerifyResult, // Required. A boolean value that indicates whether the CAPTCHA is passed.
      bizResult: result.yourBizResult, // Optional. The business verification result. This can be left empty if no business logic is verified.
    };
  };

  // Callback function for the business logic verification result.
  var onBizResultCallback = function (bizResult) {
    if (bizResult === true) {
      // Logic to execute if business logic verification passes, such as displaying a success message.
      uni.showToast({
        title: "Business verification passed!",
        duration: 2000,
        icon: "success",
      });
    } else {
      // Logic to execute if business logic verification fails, such as displaying an error 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 must be bound.
        onBizResultCallback: onBizResultCallback.bind(this), // This must be bound.
        slideStyle: {
          width: 540, // The default width is 540 rpx.
          height: 60, // The default height is 60 rpx.
        },
        language: "cn",
        region: "cn",
      };
      // Initialize the plug-in.
      this.data.loadCaptcha = true; // Controls whether to load or reload the CAPTCHA.
      this.data.pluginProps = pluginProps;
    },
    methods: {
      // Handler for username input.
      inputUsername(e) {
        this.data.username = e.detail.value;
      },
      // Handler for password input.
      inputPassword(e) {
        this.data.password = e.detail.value;
      },
      // Handler for logon button click.
      login() {
        const { username, password } = this.data;
        // This is an example. In a real application, you must send logon information to the server for verification.
        // For pop-up mode, call the instance method to display the CAPTCHA. For frictionless mode, call the same method to trigger verification.
        if (username && password) {
          AliyunCaptchaPluginInterface.show();
        } else {
          uni.showToast({
            title: "Please enter a username and password.",
            icon: "none",
          });
        }
      },
    },
  };
</script>
Note

For Vue 2 integration, follow Step 1 and Step 2 for Vue 3. Additionally, import a patch file and replace the native __patch__ method on the Vue object for the page that uses the CAPTCHA.

  1. Import the patch.js file.

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

  3. Restore 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.
  // Initialize the CAPTCHA by following the Vue 3 example.
},
beforeDestroy() {
  Vue.prototype.__patch__ = this.originalPatch; // Restore the patch function.
}

Parameters

V3 architecture

Parameter

Type

Required

Default

Description

SceneId

String

Yes

None

The ID of the verification scenario, obtained after you create a verification scenario.

mode

String

Yes

None

The CAPTCHA mode. For security and user experience, only popup (pop-up mode) is supported.

success

Function

Yes

None

The callback function triggered after the CAPTCHA passes. This function returns the CaptchaVerifyParam, which you can send to your server for server-side verification.

fail

Function

Yes

None

The callback function that is triggered when the CAPTCHA fails. 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
  • For effective risk analysis, the recommended minimum slider width (width) is 540 rpx. The system defaults to 540 rpx if a smaller width is set.

  • This parameter applies only to slider CAPTCHA challenges, not puzzle CAPTCHA challenges, which have a predefined size. Overriding the CSS to modify the style may cause verification to fail.

language

String

No

cn

The languages supported by Captcha 2.0.

region

String

No

cn

The region where the Captcha 2.0 instance is deployed. Valid values:

  • cn: Chinese mainland

  • sgp: Singapore

Note
  • If the region specified on the client does not match the server endpoint, the verification request fails.

  • Based on your configured parameters, the client sends collected behavioral and device data to the corresponding center for security verification.

onClose

Function

No

None

The following callback function is triggered when the Captcha pop-up window closes:

function onClose(isVerify) { 
    if(isVerify) {
    // The window is closed after successful validation.
    } else {
    // The window is closed in other scenarios, such as being closed manually.
    }
}

timeout

Number

No

10000

The timeout for a single CAPTCHA initialization request, in milliseconds (ms).

disableMaskClick

Boolean

No

false

Specifies whether to disable clicks on the overlay.

  • false (default): Clicking the overlay closes the modal.

  • true: Clicking the overlay does not close the modal.

V2 architecture

Parameter

Type

Required

Default

Description

SceneId

String

Yes

None

The ID of the verification scenario, obtained after you create a verification scenario.

mode

String

Yes

None

The CAPTCHA mode. For security and user experience, only popup (pop-up mode) is supported.

captchaVerifyCallback

Function

Yes

captchaVerifyCallback

The callback function for business requests that include CAPTCHA verification. See the code comments for details.

onBizResultCallback

Function

Yes

onBizResultCallback

The callback function for the business logic verification result, where you can define custom logic to handle the outcome.

slideStyle

Object

No

{ width: 540, height: 60 }

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

Note
  • For effective risk analysis, the recommended minimum slider width (width) is 540 rpx. The system defaults to 540 rpx if a smaller width is set.

  • This parameter applies only to slider CAPTCHA challenges, not puzzle CAPTCHA challenges, which have a predefined size. Overriding the CSS to modify the style may cause verification to fail.

language

String

No

cn

The languages supported by Captcha 2.0.

region

String

No

cn

The region where the Captcha 2.0 instance is deployed. Valid values:

  • cn: Chinese mainland

  • sgp: Singapore

Note
  • If the region specified on the client does not match the server endpoint, the verification request fails.

  • Based on your configured parameters, the client sends collected behavioral and device data to the corresponding center for security verification.