WeChat Mini Program integration

更新时间:
复制 MD 格式

This topic describes how to integrate Captcha into a WeChat Mini Program and provides details about the related interfaces.

Preparations

Environment requirements

Developer tool

WeChat DevTools

Debugging base library

2.10.4 or later

Download the SDK

Log on to the Phone Number Verification Service console. On the Overview page, find the API&SDK area on the right and click Download Now. On the API&SDK page, download and decompress the SDK as instructed.

Sample demo

A sample demo is also available for integrating the Captcha feature into a WeChat Mini Program. You can use the sample code to quickly understand the integration steps. For more information about how to download the demo, see WeChat Mini Program Integration Demo.

Create a verification plan

  1. Log on to the Phone Number Verification Service console.

  2. In the left navigation pane, choose Integrated Verification (Based on Atomic Capabilities) > Captcha Service > Captcha Plan Management.

  3. On the Captcha Plan Management page, click Add Captcha Plan.

    Enter a Plan Name, set Client Type to H5, and create the Captcha plan. This provides the key parameters, such as appId and appKey.

    Note

    The Client Type setting is for tagging purposes only and does not affect the use of the plan ID.

Integration steps

Import the component

  1. Add the domain name https://captcha.alicaptcha.com to the request domain whitelist in the WeChat Mini Program backend.

  2. In the xxxx.json file for the page that requires verification, import the component. The following code provides an example. For more information, see the index.json file in the demo:

    {  
       "usingComponents": {
        "captcha4": "/component/captcha4/captcha4"
      }
    }

Initialization

In the xxxx.wxml file for the page that requires verification, import the component. The following parameters are required.

<captcha4  id="captcha" wx:if="{{loadCaptcha}}"  captchaId="{{captchaId}}" />

Component parameters:

Parameter

Required

Type

Description

captchaId

Yes

string

The Captcha ID. This is the appId obtained after you create a verification plan in the console.

language

No

string

The specified language. Default value: zh.

useNativeButton

No

boolean

Specifies whether to use a button to trigger the Captcha. Valid values:

  • true (default): Button mode.

  • false: Buttonless mode. In this mode, you must call the showCaptcha method to display the verification interface.

riskType

No

string

If risk control integration is configured on the server, this parameter can specify the verification method.

Important

This parameter is not yet effective because the risk control integration mode is not available.

hideBar

No

array

Hides the Close and Refresh buttons on the verification interface. Optional values: close, refresh.

scale

No

number

The scaling ratio. Default value: 1.

mask

No

object

Configures whether to close the verification pop-up when a user clicks outside the Captcha area, and sets the background color of the pop-up. Default value: {outside:true,bgColor:'#0000004d'}

hideSuccess

No

boolean

Specifies whether to hide the success pop-up in bind mode. Default value: false.

The following code provides an example of how to bind an event listener. For more information about event descriptions and code examples, see Event description.

<captcha4
    id="captcha"
    wx:if="{{loadCaptcha}}"
    captchaId="{{captchaId}}"
    bindSuccess="captchaSuccess"
    bindReady="captchaReady"
    bindClose="captchaClose"
    bindError="captchaError"
    bindFail="captchaFail"
/>

In buttonless mode, you must manually call the showCaptcha method to display the Captcha. The following code provides an example. For more information, see the index.js file in the demo.

const captcha = this.selectComponent('#captcha');
captcha.showCaptcha();

Obtain the success credential

After the user completes the Captcha, the user-defined captchaSuccess function is triggered. The verification result is stored in `result`. You can customize how the result is saved. The result is then retrieved and sent for secondary authentication. In buttonless mode, you can perform secondary authentication directly in this function.

captchaSuccess: function(result) {
    console.log("captcha-Success!");
    this.setData({
        result: result.detail
    })
}

Submit for secondary validation

When a user clicks the submit button, the secondary authentication process is triggered.

captchaValidate: function() {
    var self = this;
    var data = self.data.result; // Get the verification result stored when the Captcha was completed.
    
    if (typeof data !== 'object') {
        console.log("Please complete the verification first!");
        return;
    }
    
    // Submit the result to your server for secondary authentication.
    wx.request({
        url: "your_business_interface", // Replace with your actual URL.
        method: 'POST',
        dataType: 'json',
        data: Object.assign({}, data, {
            captcha_id: self.data.captchaId
        }),
        success: function(res) {
            wx.showToast({
                title: res.data.result
            });
        },
        fail: function() {
            console.log('error');
        }
    });
}

Event description

In WeChat Mini Program event communication, an `event` object is always passed. The value returned by the component is in the `detail` property of this object. The following callback parameters represent the values in the `detail` property.

bindReady

Listens for the event that indicates the Document Object Model (DOM) for the verification button has been generated.

// wxml
<captcha4 bindReady="captchaReady"/>
// js
captchaReady: function () {
    console.log('captcha-Ready!')
}

bindError

Listens for verification error events. The error callback is triggered for errors that the Captcha component can handle, such as too many refreshes, failed static resource loading, or poor network connectivity. The error callback returns an `e` object. The `e.detail` property contains two attributes: `code` (the error code) and `tips` (the error message).

// wxml
<captcha4 bindError="captchaError"/>
// js
captchaError: function (e) {
    console.log('captcha-Error!', e.detail)
}

bindSuccess

Listens for the successful verification event. This event returns a `result` object. The `detail` property of the `result` object contains four attributes: `lot_number`, `pass_token`, `captcha_output`, and `gen_time`. These parameters are the credentials for the successful verification and must be sent for secondary authentication.

// wxml
<captcha4 bindSuccess="captchaSuccess"/>
// js
captchaSuccess: function (result) {
    console.log('captcha-Success!')
    // Store the parameters in result here. They will be passed for secondary authentication.
    this.setData({
         result: result.detail
    })
}

bindClose

This callback is triggered when the user closes the verification pop-up window.

// wxml
<captcha4 bindClose="captchaClose"/>
// js
captchaClose: function () {
    console.log('captcha-Close!')
}

bindFail

Listens for the verification failure event.

// wxml
<captcha4 bindFail="captchaFail"/>
// js
captchaFail: function () {
    console.log('captcha-Fail!')
}

Methods

Method Name

Description

showCaptcha

Call this method only when `useNativeButton` is `false`. It displays the Captcha pop-up.

reset

Resets the Captcha.

Abnormal situations (downtime)

If the client cannot access the server during Captcha initialization because of network issues or other problems, a downtime process is triggered. During downtime, the Captcha verification passes immediately, and the success event is triggered instantly. For example, in the bindSuccess event, the `e.detail` object contains lot_number, pass_token, captcha_output, gen_time, and is_offline. In this case, the value of is_offline is always true.