All Products
Search
Document Center

:Integrate Captcha 2.0 into a WeChat mini program

Last Updated:Dec 09, 2024

After you create a verification scenario in the Captcha 2.0 console, you must integrate the initialization code of Captcha 2.0 into 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 into a WeChat mini program.

Prerequisites

Integrate Captcha 2.0 into a WeChat mini program that is developed by using the native language

Before you can use the Captcha 2.0 plug-in in a WeChat mini program, you must add the plug-in to the WeChat mini program. To add the plug-in, perform the following operations: Log on to the Mini Program Admin Console. In the left-side navigation pane, click Settings > Third-Party Service > Plug-in Management You can search for the Captcha 2.0 plug-in by using the app ID wxbe275ff84246f1a4.

Step 1: Integrate the plug-in

  1. 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 the plug-in in the app.json project file. The following code provides an example on how to declare the plug-in.

    Note

    We 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 WeChat developer tool > Details > Basic Information > Plug-in Information

    {
      "plugins": {
        "AliyunCaptcha": {
          "version": "2.0.0", // Specify the latest version of the Captcha 2.0 plug-in.
          "provider": "wxbe275ff84246f1a4"
        }
      }
    }
  2. Declare the components of the Captcha 2.0 plug-in.

    To use a custom component of the Captcha 2.0 plug-in, you must specify the reference name and custom component name of the plug-in by using the plugin:// protocol in the json file of the component or the page on which the component is used. The following code provides an example on how to declare the components of the plug-in:

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

Step 2: Insert a template

Insert the aliyun-captcha template in WXML. You must pass the parameters in the following sample code.

In the sample code, a logon scenario is used.

<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}}" />
  <!-- Associate the login method with the logon button. When you click the logon button, the login method is called and the plug-in method is then called to display a CAPTCHA. -->
  <button class="login-btn" bindtap="login">Logon</button>
</view>

Step 3: Initialize the plug-in

Call the setData method to pass the required parameters to initialize the plug-in.

In the sample code, a logon scenario is used.

// Obtain the Captcha 2.0 plug-in.
var AliyunCaptchaPluginInterface = requirePlugin('AliyunCaptcha');

// The callback function that is used to initiate a CAPTCHA verification request for the business request.
/**
 * @name captchaVerifyCallback
 * @function
 * The request parameter: The verification parameter that is called back by the CAPTCHA script. You can directly pass this parameter to the business server without modifying it.
 * @params {string} captchaVerifyParam
 * The response parameters: The parameter names are fixed. The captchaResult parameter is required. If no business verification 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 is involved, the bizResult parameter is left empty.
  };
};

// The callback function that is used to process the result of the business request.
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 is 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. The callback function must be bound to this to ensure that this indicates the same context of the current page. This way, the callback function can use this.data to obtain business parameters. 
      captchaVerifyCallback: captchaVerifyCallback.bind(this), 
      // The parameter value is fixed. The callback function must be bound to this to ensure that this indicates the same context of the current page. This way, the callback function can use this.data to obtain business parameters. 
      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, // Specify whether to load or reload 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 plug-in method.
      AliyunCaptchaPluginInterface.show();
    } else {
      wx.showToast({
        title: 'Enter a username and a password',
        icon: 'none'
      });
    }
  },
})

Integrate the Captcha 2.0 plug-in into a WeChat mini program that is developed by using the Taro framework

Note

When you integrate the Captcha 2.0 plug-in into a WeChat mini program that is developed by using the Taro framework, you can use only React to write code.

Step 1: Integrate the plug-in

  1. Declare the Captcha 2.0 plug-in.

    Before you can use the Captcha 2.0 plug-in in a WeChat mini program, you must declare the plug-in in the app.config.js file of your Taro project. The following code provides an example on how to declare the plug-in.

    Note

    We 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 WeChat developer tool > Details > Basic Information > Plug-in Information

    {
      "plugins": {
        "AliyunCaptcha": {
          "version": "2.0.0", // Specify the latest version of the Captcha 2.0 plug-in.
          "provider": "wxbe275ff84246f1a4"
        }
      }
    }
  2. Declare the components of the Captcha 2.0 plug-in.

    To use a custom component of the Captcha 2.0 plug-in, you must specify the reference name and custom component name of the plug-in by using the plugin:// protocol in the index.config.js file of the component or the page on which the component is used. The following code provides an example on how to declare the components of the plug-in:

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

Step 2: Integrate the initialization code

In the sample code, a 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 plug-in.
const AliyunCaptchaPluginInterface = Taro.requirePlugin('AliyunCaptcha');

// You must use global variables to maintain business parameters to ensure that the business parameters are available when the captchaVerifyCallback function is invoked. You cannot use only the state variable to maintain 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 use the ref variable to maintain business parameters.
  const bizParams = useRef({
    username: '',
    password: '',
  });

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

  const handleUsernameChange = (e) => {
    setUsername(e.target.value); // Modify the state variable.
    bizParams.current.username = e.target.value; // Modify the ref variable together with the state variable.
    // userName = e.target.value; // Alternatively, modify global variables.
  };
  
  const handlePasswordChange = (e) => {
    setPassword(e.target.value); // Modify the state variable.
    bizParams.current.password = e.target.value; // Modify the ref variable together with the state variable.
    // passWord = e.target.value; // Alternatively, modify global variables.
  };

  const login = () => {
    // Implement business verification based on your business requirements.
    if (username && password) {
      // Display a pop-up CAPTCHA by using the plug-in method.
      AliyunCaptchaPluginInterface.show();
    } else {
      Taro.showToast({
        title: 'Enter a username and a password',
        icon: 'none'
      });
    } 
  }


  // The callback function that is used to initiate a CAPTCHA verification request for the business request.
  /**
   * @name captchaVerifyCallback
   * @function
   * The request parameter: The verification parameter that is called back by the CAPTCHA script. You can directly pass this parameter to the business server without modifying it.
   * @params {string} captchaVerifyParam
   * The response parameters: The parameter names are fixed. The captchaResult parameter is required. If no business verification is involved, the bizResult parameter is optional.
   * @returns {{captchaResult: boolean, bizResult?: boolean|undefined}} 
   */
  async function captchaVerifyCallback(captchaVerifyParam) {
    console.log(bizParams.current); // Use business parameters stored in the ref variable.
    // 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 the ref variable to obtain business data.
        password: bizParams.current.password, // Use the ref variable 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 is involved, the bizResult parameter is left empty.
    };
  }

  // The callback function that is used to process the result of the business request.
  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 is 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 a username"
            value={username}
            onInput={handleUsernameChange}
          />
        </View>
        <View className="input-group">
          <Text>Password:</Text>
          <Input
            type="password"
            placeholder="Enter a password"
            value={password}
            onInput={handlePasswordChange}
          />
        </View>
        {/* Associate the login method with the logon button. When you click the logon button, the login method is called and the plug-in method is then called to display a CAPTCHA. */}
        <Button style={{ margin: '20px' }} id="captcha-button" onClick={login}>Logon</Button>
      </Form>
      {loadCaptcha && <aliyun-captcha id="captcha-element" props={pluginProps} />}
    </View>
  );
}

export default Index;

Integrate Captcha 2.0 into a WeChat mini program that is developed by using the uni-app framework

Note

Only vue3 is supported in uni-app.

Step 1: Integrate the plug-in

  1. Declare the Captcha 2.0 plug-in.

    Before you can use the Captcha 2.0 plug-in in a WeChat mini program, you must declare the plug-in in the manifest.json file of your uni-app project. The following code provides an example on how to declare the plug-in.

    Note

    We 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 WeChat developer tool > Details > Basic Information > Plug-in Information

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

  2. Declare the components of the Captcha 2.0 plug-in.

    You can use custom components of the Captcha 2.0 plug-in in a similar manner as you use general custom components. For more information, see Custom components. To use a custom component of the Captcha 2.0 plug-in, you must specify the reference name and custom component name of the plug-in by using the plugin:// protocol in the style node of the page.json file of the related page. The following code provides an example on how to declare the components of the plug-in:

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

Step 2: Integrate the initialization code

Add the aliyun-captcha component to the <template> section in the .vue file. To use the Captcha 2.0 plug-in, initialize the plug-in in the <script> section.

In the sample code, a 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 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="this.data.loadCaptcha"
      :props="this.data.pluginProps"
    />
    <button class="login-btn" @click="login">Logon</button>
  </view>
</template>

<script>
  // Obtain the Captcha 2.0 plug-in.
  const AliyunCaptchaPluginInterface = requirePlugin("AliyunCaptcha");

  // The callback function that is used to initiate a CAPTCHA verification request for the business request.
  /**
   * @name captchaVerifyCallback
   * @function
   * The request parameter: The verification parameter that is called back by the CAPTCHA script. You can directly pass this parameter to the business server without modifying it.
   * @params {string} captchaVerifyParam
   * The response parameters: The parameter names are fixed. The captchaResult parameter is required. If no business verification 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 is involved, the bizResult parameter is left empty.
    };
  };

  // The callback function that is used to process the result of the business request.
  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 is 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. The callback function must be bound to this.
        onBizResultCallback: onBizResultCallback.bind(this), // The parameter value is fixed. The callback function must be bound 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; // Specify whether to load or reload a CAPTCHA.
      this.data.pluginProps = pluginProps;
    },
    methods: {
      // The function that is used to process the specified username.
      inputUsername(e) {
        this.data.username = e.detail.value;
      },
      // The function that is used to process the specified password.
      inputPassword(e) {
        this.data.password = e.detail.value;
      },
      // The function that is used to process clicks on the logon button.
      login() {
        const { username, password } = this.data;
        // The sample code is only for reference. In actual development scenarios, the logon information needs to be sent to the required server for verification.
        if (username && password) {
          AliyunCaptchaPluginInterface.show();
        } else {
          uni.showToast({
            title: "Enter a username and a password",
            icon: "none",
          });
        }
      },
    },
  };
</script>

<style></style>

Parameters

Parameter

Type

Required

Default value

Description

SceneId

String

Yes

None

The ID of the verification scenario. You can obtain the ID after you create a verification scenario. For more information, see Step 2: Create a verification scenario.

mode

String

Yes

None

The CAPTCHA mode. To improve protection and user experience, only the pop-up mode is supported. Valid value:

  • popup: pop-up mode

captchaVerifyCallback

Function

Yes

captchaVerifyCallback

The callback function that is used to initiate a CAPTCHA verification request for the business request. For more information, see the comments in the preceding sample code.

onBizResultCallback

Function

Yes

onBizResultCallback

The callback function that is used to process the result of the business request. You can specify custom processing logic in the function.

slideStyle

Object

No

{ width: 540, height: 60 }

The slider CAPTCHA. You can change the width and height. Unit: pixels.

Note
  • You must drag a slider CAPTCHA to collect enough information for policy model judgement. We recommend that you configure the width parameter to set the minimum width of a slider CAPTCHA to 540 pixels. If the value of the width parameter is less than 540 pixels, the system uses the default width of 540 pixels.

  • This parameter is valid only for slider CAPTCHAs and does not apply to puzzle CAPTCHAs. If you use a puzzle CAPTCHA, we recommend that you do not overwrite CSS code to modify the puzzle CAPTCHA because the image size of the puzzle CAPTCHA and the verification answer are predefined. If you forcefully modify the puzzle CAPTCHA, a verification error may occur.

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 to which the Captcha 2.0 instance belongs. Valid values:

  • cn: Chinese mainland

  • sgp: Singapore

Note
  • If the endpoint that is used to call Captcha 2.0 does not match the region that is specified by the region parameter, an error message is returned.

  • Control-plane platforms for Captcha 2.0 are built in the China (Shanghai) and Singapore regions. The behavior data and device data that are collected by clients based on the specified callback parameters are sent to the related platforms for processing. This achieves security verification.