After adding a verification scenario in the console, integrate the initialization code into the WeChat mini program page that requires the verification feature.
Prerequisites
You have activated Captcha 2.0.
You have created a verification scenario for a WeChat mini program client.
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 . Search for the plug-in by using the app ID (wxbe275ff84246f1a4) and add it.
Step 1: Integrate the plug-in
Declare the Captcha 2.0 plug-in.
Before using the plug-in on a page, declare it in the
app.jsonfile of your project.NoteWe recommend that you use the latest version of the plug-in. To view the latest version, go to .
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" } } }Declare the custom component.
To use the plug-in's custom component, declare it in the
.jsonfile of the relevant page or component. Use theplugin://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
Taro integration currently supports only React.
Step 1: Integrate the plug-in
Declare the Captcha 2.0 plug-in.
Before using the plug-in on a page, declare it in the
app.config.jsfile of your project.NoteWe recommend that you use the latest plug-in version. To check the latest version, go to .
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" } } }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 theindex.config.jsfile 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.
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 |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
Declare the Captcha 2.0 plug-in.
Before using the plug-in on a page, declare it in the
manifest.jsonfile of your project.NoteWe recommend that you use the latest version of the plug-in. To check the latest version, go to .
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" } } }Declare the custom component.
Using a plug-in's custom component is similar to using a standard custom component. In the
page.jsonfile, under the style node for the corresponding page, use theplugin://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>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.
Import the patch.js file.
Replace the
__patch__function at the beginning of the beforeCreate hook.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 |
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
|
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:
Note
|
onClose | Function | No | None | The following callback function is triggered when the Captcha pop-up window closes: |
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.
|
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
|
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:
Note
|