After you create a verification scenario in the CAPTCHA 2.0 console, you must integrate the initialization code of CAPTCHA 2.0 with the WeChat mini program in which you want to call CAPTCHA 2.0. This topic describes how to integrate the initialization code of CAPTCHA 2.0 with a WeChat mini program.
Prerequisites
CAPTCHA 2.0 is activated. For more information, see Activate CAPTCHA 2.0.
A verification scenario whose Client Type is set to WeChat Mini Programs is created. For more information, see the "Step 2: Create a verification scenario" section of the Integration guide topic.
Integrate CAPTCHA 2.0 by using the WeChat mini program native language
You must add the CAPTCHA 2.0 plug-in to the WeChat mini program before you can use the plug-in. To add the plug-in, perform the following operations: Log on to the Mini Program Admin Console. In the left-side navigation pane, click
. On the page that appears, click the Third-Party Service tab. In the Plug-in Management section, add the CAPTCHA 2.0 plug-in. You can search for the CAPTCHA 2.0 plug-in by using the app ID wxbe275ff84246f1a4. After Alibaba Cloud approves your application to add the CAPTCHA 2.0 plug-in, you can use it in your WeChat mini program.You must register the WeChat mini program as an enterprise. The registration review takes one to three days.
Step 1: Integrate the plug-in
Declare the CAPTCHA 2.0 plug-in.
Before you can use the CAPTCHA 2.0 plug-in in your WeChat mini program, you must declare it in the
app.json
project file. Sample code:NoteWe recommend that you use the latest version of the CAPTCHA 2.0 plug-in. To query the latest version of the CAPTCHA 2.0 plug-in, perform the following operations: Log on to the
console. In the upper-right corner, click the Details icon. In the panel that appears, click the Basic Information tab. You can view the latest version of the CAPTCHA 2.0 plug-in in the Plug-in Information parameter.{ "plugins": { "AliyunCaptcha": { "version": "2.0.0", // Specify the latest version of the CAPTCHA 2.0 plug-in. "provider": "wxbe275ff84246f1a4" } } }
Declare the components of the CAPTCHA 2.0 plug-in.
To use a custom component provided by the CAPTCHA 2.0 plug-in, you must specify the plug-in reference name and custom component name by using the
plugin://
protocol in thejson
file of the component or that of the page on which the component is used. Sample code:{ "usingComponents": { "aliyun-captcha": "plugin://AliyunCaptcha/captcha" } }
Step 2: Insert the template
Insert the aliyun-captcha
template in WXML
. The parameters in the following sample code are required.
In this example, the logon scenario is used.
<view class="captchapage-container">
<view class="input-group">
<view class="label">Username:</view>
<input class="input" type="text" placeholder="Enter the username" bindinput="inputUsername" />
</view>
<view class="input-group">
<view class="label">Password:</view>
<input class="input" type="password" placeholder="Enter the password" bindinput="inputPassword" />
</view>
<aliyun-captcha id="captcha-element" wx:if="{{loadCaptcha}}" props="{{pluginProps}}" />
<! -- Bind the login method to the logon button. When a user clicks the logon button, the login method is triggered and the instance method provided by the plug-in is used to display a CAPTCHA. -->
<button class="login-btn" bindtap="login">Log on</button>
</view>
Step 3: Initialize the plug-in
Use the setData
method to pass the required parameters to initialize the plug-in.
In this example, the logon scenario is used.
// Obtain the CAPTCHA 2.0 instance.
var AliyunCaptchaPluginInterface = requirePlugin('AliyunCaptcha');
// The callback function for the business request with CAPTCHA verification.
/**
* @name captchaVerifyCallback
* @function
* Request parameters: The following parameter is a verification parameter that is called back by the CAPTCHA script. Directly pass this parameter to the business server instead of modifying it.
* @params {string} captchaVerifyParam
* Response parameters: The parameter names are fixed and the captchaResult parameter is required. If no business verification scenario is involved, the bizResult parameter is optional.
* @returns {{captchaResult: boolean, bizResult?: boolean|undefined}}
*/
var captchaVerifyCallback = async function (captchaVerifyParam) {
console.log(this.data);
// The business request code.
const result = await customFetch('https://xxxx/demo/bizquery', {
method: 'POST',
data: {
captchaVerifyParam, // Specify the verification parameter.
userName: this.data.username, // Use this.data to obtain business data.
password: this.data.password,
},
});
console.log(captchaVerifyParam);
return {
captchaResult: result.captchaVerifyResult, // Required. Indicates whether the CAPTCHA verification is passed. The value is of the BOOLEAN type.
bizResult: returns the business verification result, // Optional. Indicates whether the business verification is passed. The value is of the BOOLEAN type. If no business verification scenario is involved, the bizResult parameter can be left empty.
};
};
// The callback function for the business request verification result.
var onBizResultCallback = function (bizResult) {
if (bizResult === true) {
// The processing logic if the business verification is passed. In this example, the following message appears:
wx.showToast({
title: 'Business verification passed! ',
duration: 2000,
icon: 'success',
});
} else {
// The processing logic if the business verification fails. In this example, the following message appears:
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()));
},
});
});
}
// The page logic.
Page({
data: {
username: '',
password: '',
loadCaptcha: false, // Specify whether to load a CAPTCHA.
},
onLoad: function(options) {
// Construct plug-in parameters.
var pluginProps = {
SceneId: 'xxxxx',
mode: 'popup',
// The parameter value is fixed. Bind the callback function to this. Make sure that this indicates the same context of the current page. This way, you can use this.data to obtain business parameters by invoking the callback function.
captchaVerifyCallback: captchaVerifyCallback.bind(this),
// The parameter value is fixed. Bind the callback function to this. Make sure that this indicates the same context of the current page. This way, you can use this.data to obtain business parameters by invoking the callback function.
onBizResultCallback: onBizResultCallback.bind(this),
slideStyle: {
width: 540, // The default width of the slider CAPTCHA is 540 pixels.
height: 60, // The default height of the slider CAPTCHA is 60 pixels.
},
language: 'cn',
region: 'cn',
};
this.setData({
loadCaptcha: true, // Control the loading and reloading of a 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;
// Implement business verification based on your business requirements.
if (username && password) {
// Display a pop-up CAPTCHA by using the instance method.
AliyunCaptchaPluginInterface.show();
} else {
wx.showToast({
title: 'Enter the username and password',
icon: 'none'
});
}
},
})
Integrate the CAPTCHA 2.0 plug-in by using the Taro framework
Only React is supported to integrate the CAPTCHA 2.0 plug-in with the Taro framework.
Step 1: Integrate the plug-in
Declare the CAPTCHA 2.0 plug-in.
Before you can use the CAPTCHA 2.0 plug-in, you must declare it in the
app.config.js
file of the Taro project. Sample code:NoteWe recommend that you use the latest version of the CAPTCHA 2.0 plug-in. To query the latest version of the CAPTCHA 2.0 plug-in, perform the following operations: Log on to the
console. In the upper-right corner, click the Details icon. In the panel that appears, click the Basic Information tab. You can view the latest version of the CAPTCHA 2.0 plug-in in the Plug-in Information parameter.{ "plugins": { "AliyunCaptcha": { "version": "2.0.0", // Specify the latest version of the CAPTCHA 2.0 plug-in. "provider": "wxbe275ff84246f1a4" } } }
Declare the components of the CAPTCHA 2.0 plug-in.
To use a custom component provided by the CAPTCHA 2.0 plug-in, you must specify the plug-in reference name and custom component name by using the
plugin://
protocol in theindex.config.js
file of the component or that of the page on which the component is used. Sample code:export default { usingComponents: { 'aliyun-captcha': 'plugin://AliyunCaptcha/captcha', }, };
Step 2: Integrate the initialization code
In this example, the logon scenario is used.
import Taro from '@tarojs/taro';
import { useEffect, useState, useRef } from 'react';
import { View, Text, Input, Button, Form } from '@tarojs/components';
import './index.scss';
// Obtain the CAPTCHA 2.0 instance.
const AliyunCaptchaPluginInterface = Taro.requirePlugin('AliyunCaptcha');
// You must maintain the global variables to ensure that business parameters are available when the captchaVerifyCallback function is invoked. The state cannot be used to store business parameters.
// let userName = '';
// let passWord = '';
function Index() {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [loadCaptcha, setLoadCaptcha] = useState(false);
// We recommend that you maintain your business parameters by using references.
const bizParams = useRef({
username: '',
password: '',
});
useEffect(() => {
setLoadCaptcha(true); // Control the loading and reloading of a CAPTCHA.
}, []);
const handleUsernameChange = (e) => {
setUsername(e.tar get.value); // Update the state.
bizParams.current.username = e.tar get.value; // Update references at the same time.
// userName = e.tar get.value; // Alternatively, update global variables.
};
const handlePasswordChange = (e) => {
setPassword(e.tar get.value); // Update the state.
bizParams.current.password = e.tar get.value; // Update references at the same time.
// passWord = e.tar get.value; // Alternatively, update global variables.
};
const login = () => {
// Implement business verification based on your business requirements.
if (username && password) {
// Display a pop-up CAPTCHA by using the instance method.
AliyunCaptchaPluginInterface.show();
} else {
Taro.showToast({
title: 'Enter the username and password',
icon: 'none'
});
}
}
// The callback function for the business request with CAPTCHA verification.
/**
* @name captchaVerifyCallback
* @function
* Request parameters: The following parameter is a verification parameter that is called back by the CAPTCHA script. Directly pass this parameter to the business server instead of modifying it.
* @params {string} captchaVerifyParam
* Response parameters: The parameter names are fixed and the captchaResult parameter is required. If no business verification scenario is involved, the bizResult parameter is optional.
* @returns {{captchaResult: boolean, bizResult?: boolean|undefined}}
*/
async function captchaVerifyCallback(captchaVerifyParam) {
console.log(bizParams.current); // The references of business parameters.
// console.log(userName, passWord); // Alternatively, use business parameters stored in global variables.
// The business request code.
const result = await customFetch('https://xxxx/demo/bizquery', {
method: 'POST',
mode: 'cors',
enableHttp2: true,
enableQuic: true,
data: {
captchaVerifyParam, // Specify the verification parameter.
userName: bizParams.current.username, // Use references to obtain business data.
password: bizParams.current.password, // Use references to obtain business data.
// Alternatively, use global variables to obtain business data.
// username: userName, // Use global variables to obtain business data.
// password: passWord, // Use global variables to obtain business data.
},
});
return {
captchaResult: result.captchaVerifyResult, // Required. Indicates whether the CAPTCHA verification is passed. The value is of the BOOLEAN type.
bizResult: returns the business verification result, // Optional. Indicates whether the business verification is passed. The value is of the BOOLEAN type. If no business verification scenario is involved, the bizResult parameter can be left empty.
};
}
// The callback function for the business request verification result.
function onBizResultCallback(bizResult) {
if (bizResult === true) {
// The processing logic if the business verification is passed. In this example, the following message appears:
Taro.showToast({
title: 'Business verification passed! ',
duration: 2000,
icon: 'success',
});
} else {
// The processing logic if the business verification fails. In this example, the following message appears:
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 plug-in parameters.
const pluginProps = {
SceneId: 'xxxxx',
mode: 'popup',
captchaVerifyCallback,
onBizResultCallback,
slideStyle: {
width: 540, // The default width of the slider CAPTCHA is 540 pixels.
height: 60, // The default height of the slider CAPTCHA is 60 pixels.
},
language: 'cn',
region: 'cn',
};
return (
<View className="captcha-page">
<Form>
<View className="input-group">
<Text> Username:</Text>
<Input
type="text"
placeholder="Enter the username"
value={username}
onInput={handleUsernameChange}
/>
</View>
<View className="input-group">
<Text> Password:</Text>
<Input
type="password"
placeholder="Enter the password"
value={password}
onInput={handlePasswordChange}
/>
</View>
{/* Bind the login method to the logon button. When a user clicks the logon button, the login method is triggered and the instance method provided by the plug-in is used to display a 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;
Integrate CAPTCHA 2.0 by using uni-app
You can use only the Vue 3 framework to integrate CAPTCHA 2.0 by using uni-app.
Step 1: Integrate the plug-in
Declare the CAPTCHA 2.0 plug-in.
Before you can use the CAPTCHA 2.0 plug-in, you must declare it in the
manifest.json
file of your project. Sample code:NoteWe recommend that you use the latest version of the CAPTCHA 2.0 plug-in. To query the latest version of the CAPTCHA 2.0 plug-in, perform the following operations: Log on to the
console. In the upper-right corner, click the Details icon. In the panel that appears, click the Basic Information tab. You can view the latest version of the CAPTCHA 2.0 plug-in in the Plug-in Information parameter."mp-weixin": { "plugins": { "AliyunCaptcha": { "version": "2.0.0", "provider": "wxbe275ff84246f1a4", } } }
Declare the components of the CAPTCHA 2.0 plug-in.
You can use custom components provided by the plug-in in a similar way as you use general custom components. For more information, see Custom Component. When you declare the custom component to be used for the style node of the corresponding page in the
page.json
file, use theplugin://
protocol to specify the reference name of the plug-in 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 initialization code
Insert the aliyun-captcha
component into the <template>
section in the .vue
file. To use the plug-in, initialize the plug-in in the <script>
section.
In this example, the logon scenario is used.
<template>
<view class="captchapage-container">
<view class="input-group">
<view class="label">Username:</view>
<input
class="input"
type="text"
placeholder="Enter the username"
@input="inputUsername"
/>
</view>
<view class="input-group">
<view class="label">Password:</view>
<input
class="input"
type="password"
placeholder="Enter the password"
@input="inputPassword"
/>
</view>
<aliyun-captcha
id="captcha-element"
v-if="this.data.loadCaptcha"
:props="this.data.pluginProps"
/>
<button class="login-btn" @click="login">Log on</button>
</view>
</template>
<script>
// Obtain the CAPTCHA 2.0 instance.
const AliyunCaptchaPluginInterface = requirePlugin("AliyunCaptcha");
// The callback function for the business request with CAPTCHA verification.
/**
* @name captchaVerifyCallback
* @function
* Request parameters: The following parameter is a verification parameter that is called back by the CAPTCHA script. Directly pass this parameter to the business server instead of modifying it.
* @params {string} captchaVerifyParam
* Response parameters: The parameter names are fixed and the captchaResult parameter is required. If no business verification scenario is involved, the bizResult parameter is optional.
* @returns {{captchaResult: boolean, bizResult?: boolean|undefined}}
*/
var captchaVerifyCallback = async function (captchaVerifyParam) {
console.log(this.data);
// The business request code.
const result = await customFetch("https://xxxx/demo/bizquery", {
method: "POST",
data: {
captchaVerifyParam, // Specify the verification parameter.
userName: this.data.username, // Use this.data to obtain business data.
password: this.data.password,
},
});
console.log(captchaVerifyParam);
return {
captchaResult: result.captchaVerifyResult, // Required. Indicates whether the CAPTCHA verification is passed. The value is of the BOOLEAN type.
bizResult: returns the business verification result, // Optional. Indicates whether the business verification is passed. The value is of the BOOLEAN type. If no business verification scenario is involved, the bizResult parameter can be left empty.
};
};
// The callback function for the business request verification result.
var onBizResultCallback = function (bizResult) {
if (bizResult === true) {
// The processing logic if the business verification is passed. In this example, the following message appears:
uni.showToast({
title: "Business verification passed!",
duration: 2000,
icon: "success",
});
} else {
// The processing logic if the business verification fails. In this example, the following message appears:
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), // The parameter value is fixed. Bind the callback function to this.
onBizResultCallback: onBizResultCallback.bind(this), // The parameter value is fixed. Bind the callback function to this.
slideStyle: {
width: 540, // The default width of the slider CAPTCHA is 540 pixels.
height: 60, // The default height of the slider CAPTCHA is 60 pixels.
},
language: "cn",
region: "cn",
};
// Initialize the CAPTCHA 2.0 plug-in.
this.data.loadCaptcha = true; // Control the loading and reloading of a CAPTCHA.
this.data.pluginProps = pluginProps;
},
methods: {
// The method that processes the username input.
inputUsername(e) {
this.data.username = e.detail.value;
},
// The method that processes the password input.
inputPassword(e) {
this.data.password = e.detail.value;
},
// The method that processes clicks on the logon button.
login() {
const { username, password } = this.data;
// This example is for reference only. In actual development scenarios, the logon information needs to be sent to the server for verification.
if (username && password) {
AliyunCaptchaPluginInterface.show();
} else {
uni.showToast({
title: "Enter the username and password",
icon: "none",
});
}
},
},
};
</script>
<style></style>
Parameter description
Parameter | Type | Required | Default value | Description |
SceneId | String | Yes | N/A | The verification scenario ID. You can obtain the ID after you create a verification scenario. For more information, see the "Step 2: Create a verification scenario" section of the Integration guide topic. |
mode | String | Yes | N/A | The CAPTCHA mode. To improve protection and user experience, only the pop-up CAPTCHA mode is supported. Valid value:
|
captchaVerifyCallback | Function | Yes | captchaVerifyCallback | The callback function for the business request with CAPTCHA verification. For more information, see the comments in the preceding sample code. |
onBizResultCallback | Function | Yes | onBizResultCallback | The callback function for the business request verification result. The callback function is used to specify the verification result processing logic. |
slideStyle | Object | No | { width: 540, height: 60 } | The style of the slider CAPTCHA. You can specify the width and height. Unit: pixel. Note
|
language | String | No | cn | The language of the verification code. For more information about supported languages, see Configure custom text and multi-language settings. |
region | String | No | cn | The region in which the CAPTCHA 2.0 instance resides. Valid values:
Note
|