文档

微信小程序接入

更新时间:
一键部署

在控制台添加验证场景后,您需要在使用验证功能的微信小程序页面中,集成验证码初始化代码,实现微信小程序接入。本文介绍如何集成验证码初始化代码。

前提条件

微信小程序原生语言接入

在使用插件前,首先要在小程序管理后台设置 > 第三方服务 > 插件管理中添加插件。开发者可登录小程序管理后台,通过 appid (wxbe275ff84246f1a4)查找插件并添加。申请添加后,需要等待阿里云验证码后台通过后,方可在小程序中使用。

说明

申请微信小程序账号主体为企业认证主体,审核周期为1~3天。

微信小程序1

步骤一:集成插件

  1. 引入验证码小程序插件。

    页面中使用插件前,需要先在项目app.json中声明阿里云验证码小程序插件。代码示例如下:

    说明

    插件版本建议使用最新版本,查看最新版本方法:微信开发者工具 > 详情 > 基本信息 > 插件信息

    {
      "plugins": {
        "AliyunCaptcha": {
          "version": "2.0.0", //请选择小程序插件最新版本
          "provider": "wxbe275ff84246f1a4"
        }
      }
    }
  2. 引入验证码小程序组件。

    使用插件提供的自定义组件,需要在页面或组件的json 文件中使用plugin://协议指明插件的引用名和自定义组件名。代码示例如下:

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

步骤二:模板插入

wxml中插入aliyun-captcha模板,示例中的参数为必传参数。

以登录场景为例:

<view class="captchapage-container">
  <view class="input-group">
    <view class="label">用户名:</view>
    <input class="input" type="text" placeholder="请输入用户名" bindinput="inputUsername" />
  </view>
  <view class="input-group">
    <view class="label">密码:</view>
    <input class="input" type="password" placeholder="请输入密码" bindinput="inputPassword" />
  </view>
  <aliyun-captcha id="captcha-element" wx:if="{{loadCaptcha}}" props="{{pluginProps}}" />
  <!-- 在登录按钮上绑定login方法,点击时在login方法内调用插件实例方法展示验证码 -->
  <button class="login-btn" bindtap="login">登录</button>
</view>

步骤三:插件初始化

在需要使用插件的时候,使用setData传入必传参数进行初始化。

以登录场景为例:

// 获取验证码插件实例
var AliyunCaptchaPluginInterface = requirePlugin('AliyunCaptcha');

// 业务请求(带验证码校验)回调函数
/**
 * @name captchaVerifyCallback
 * @function
 * 请求参数:由验证码脚本回调的验证参数,不需要做任何处理,直接传给服务端即可
 * @params {string} captchaVerifyParam
 * 返回参数:字段名固定,captchaResult为必选;如无业务验证场景时,bizResult为可选
 * @returns {{captchaResult: boolean, bizResult?: boolean|undefined}} 
 */
var captchaVerifyCallback = async function (captchaVerifyParam) {
  console.log(this.data);
  // 业务请求代码...
  const result = await customFetch('https://xxxx/demo/bizquery', {
      method: 'POST',
      data: {
        captchaVerifyParam, // 携带上验证参数
        userName: this.data.username, // 通过this.data获取业务数据
        password: this.data.password,
      },
    });
  console.log(captchaVerifyParam);
  return {
    captchaResult: result.captchaVerifyResult, // 验证码验证是否通过,boolean类型,必选
    bizResult: 从result获取您的业务验证结果, // 业务验证是否通过,boolean类型,可选;若为无业务验证结果的场景,bizResult可以为空
  };
};

// 业务请求验证结果回调函数
var onBizResultCallback = function (bizResult) {
  if (bizResult === true) {
    // 业务验证通过后的逻辑,如提示通过
    wx.showToast({
      title: '业务验证通过!',
      duration: 2000,
      icon: 'success',
    });
  } else {
  // 业务验证不通过后的逻辑,如提示不通过
    wx.showToast({
      title: '业务验证不通过!',
      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({
  data: {
    username: '',
    password: '',
    loadCaptcha: false, // 是否加载验证码
  },
  onLoad: function(options) {
    // 构造插件参数
    var pluginProps = {
      SceneId: 'xxxxx',
      mode: 'popup',
      // 固定写法,需要绑定this,保证回调函数中的this是当前页面指向的this,以此在回调函数中通过this.data获取业务参数。
      captchaVerifyCallback: captchaVerifyCallback.bind(this), 
      // 固定写法,需要绑定this,保证回调函数中的this是当前页面指向的this,以此在回调函数中通过this.data获取业务参数。
      onBizResultCallback: onBizResultCallback.bind(this), 
      slideStyle: {
        width: 540, // 宽度默认为540rpx
        height: 60, // 高度默认为60rpx
      },
      language: 'cn',
      region: 'cn',
    };
    this.setData({
      loadCaptcha: true, // 可以用来控制加载/重载验证码
      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;
    // 可以做自定义业务校验
    if (username && password) {
      // 弹出式下调用实例方法展示验证码
      AliyunCaptchaPluginInterface.show();
    } else {
      wx.showToast({
        title: '请填写用户名和密码',
        icon: 'none'
      });
    }
  },
})

Taro框架小程序插件接入

说明

Taro接入时,暂时只支持React接入。

步骤一:集成插件

  1. 引入验证码小程序插件。

    页面中使用插件前,需要先在项目app.config.js中声明阿里云验证码小程序插件。代码示例如下:

    说明

    插件版本建议使用最新版本,查看最新版本方法:微信开发者工具 > 详情 > 基本信息 > 插件信息

    {
      "plugins": {
        "AliyunCaptcha": {
          "version": "2.0.0", //请选择小程序插件最新版本
          "provider": "wxbe275ff84246f1a4"
        }
      }
    }
  2. 引入验证码小程序组件。

    使用插件提供的自定义组件,需要在页面或组件的index.config.js文件中使用plugin://协议指明插件的引用名和自定义组件名。代码示例如下:

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

步骤二:代码集成

以登录场景为例:

import Taro from '@tarojs/taro';
import { useEffect, useState, useRef } from 'react';
import { View, Text, Input, Button, Form } from '@tarojs/components';
import './index.scss';

// 获取验证码插件实例
const AliyunCaptchaPluginInterface = Taro.requirePlugin('AliyunCaptcha');

// 业务参数需要维护全局变量来在captchaVerifyCallback中使用,使用state无法生效
// let userName = '';
// let passWord = '';

function Index() {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [loadCaptcha, setLoadCaptcha] = useState(false);
  // 业务参数也可以使用ref来维护,推荐
  const bizParams = useRef({
    username: '',
    password: '',
  });

  useEffect(() => {
    setLoadCaptcha(true); // 可以用来控制加载/重载验证码
  }, []);

  const handleUsernameChange = (e) => {
    setUsername(e.target.value); // 更新state
    bizParams.current.username = e.target.value; // 同时更新ref
    // userName = e.target.value; // 或者更新全局变量
  };
  
  const handlePasswordChange = (e) => {
    setPassword(e.target.value); // 更新state
    bizParams.current.password = e.target.value; // 同时更新ref
    // passWord = e.target.value; // 或者更新全局变量
  };

  const login = () => {
    // 可以做自定义业务校验
    if (username && password) {
      // 弹出式下调用实例方法展示验证码
      AliyunCaptchaPluginInterface.show();
    } else {
      Taro.showToast({
        title: '请填写用户名和密码',
        icon: 'none'
      });
    } 
  }


  // 业务请求(带验证码校验)回调函数
  /**
   * @name captchaVerifyCallback
   * @function
   * 请求参数:由验证码脚本回调的验证参数,不需要做任何处理,直接传给服务端即可
   * @params {string} captchaVerifyParam
   * 返回参数:字段名固定,captchaResult为必选;如无业务验证场景时,bizResult为可选
   * @returns {{captchaResult: boolean, bizResult?: boolean|undefined}} 
   */
  async function captchaVerifyCallback(captchaVerifyParam) {
    console.log(bizParams.current); // 业务参数ref
    // console.log(userName, passWord); // 或者使用全局业务参数
    // 业务请求代码...
    const result = await customFetch('https://xxxx/demo/bizquery', {
      method: 'POST',
      mode: 'cors',
      enableHttp2: true,
      enableQuic: true,
      data: {
        captchaVerifyParam, // 携带上验证参数
        userName: bizParams.current.username, // 通过ref获取业务数据
        password: bizParams.current.password, // 通过ref获取业务数据
        // 或者通过全局变量获取业务数据
        // username: userName, // 通过全局变量获取业务数据
        // password: passWord, // 通过全局变量获取业务数据
      },
    });
    return {
      captchaResult: result.captchaVerifyResult, // 验证码验证是否通过,boolean类型,必选
      bizResult: 从result获取您的业务验证结果, // 业务验证是否通过,boolean类型,可选;若为无业务验证结果的场景,bizResult可以为空
    };
  }

  // 业务请求验证结果回调函数
  function onBizResultCallback(bizResult) {
    if (bizResult === true) {
      // 业务验证通过后对逻辑,如提示通过
      Taro.showToast({
        title: '业务验证通过!',
        duration: 2000,
        icon: 'success',
      });
    } else {
    // 业务验证不通过后的逻辑,如提示不通过
      Taro.showToast({
        title: '业务验证不通过!',
        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()));
        },
      });
    });
  }
  
  // 构造插件参数
  const pluginProps = {
    SceneId: 'xxxxx',
    mode: 'popup',
    captchaVerifyCallback,
    onBizResultCallback,
    slideStyle: {
      width: 540, // 宽度默认为540rpx
      height: 60, // 高度默认为60rpx
    },
    language: 'cn',
    region: 'cn',
  };

  return (
    <View className="captcha-page">
      <Form>
        <View className="input-group">
          <Text>账号:</Text>
          <Input
            type="text"
            placeholder="请输入账号"
            value={username}
            onInput={handleUsernameChange}
          />
        </View>
        <View className="input-group">
          <Text>密码:</Text>
          <Input
            type="password"
            placeholder="请输入密码"
            value={password}
            onInput={handlePasswordChange}
          />
        </View>
        {/* 在登录按钮上绑定login方法,点击时在login方法内调用插件实例方法展示验证码 */}
        <Button style={{ margin: '20px' }} id="captcha-button" onClick={login}>登录</Button>
      </Form>
      {loadCaptcha && <aliyun-captcha id="captcha-element" props={pluginProps} />}
    </View>
  );
}

export default Index;

参数说明

参数

类型

是否必填

默认值

描述

SceneId

String

验证码场景ID,新建验证场景后可获取该值。具体操作,请参见步骤二:新建验证场景

mode

String

验证码模式,考虑到防护效果和接入体验,目前只支持弹出式。可选项:

  • popup:表示弹出式。

captchaVerifyCallback

Function

captchaVerifyCallback

业务请求(带验证码校验)回调函数。更多信息,请参考上文示例代码注释部分。

onBizResultCallback

Function

onBizResultCallback

业务请求结果回调函数,用于设置验证结果处理逻辑。

slideStyle

Object

{ width: 540, height: 60 }

滑块验证码样式,支持自定义宽度和高度,单位为rpx。

说明
  • 由于验证码需要通过滑动采集足够多的信息用于策略模型判断,所以,建议您将滑块的宽度(width值)最小设置为540 rpx。如果width值小于540 rpx,系统会按照540 rpx进行配置。

  • 该参数仅对滑块模式有效,并不适用于拼图验证码。如果您使用的是拼图验证码,由于拼图验证码的图像尺寸和验证答案是预设固定的,请不要复写 CSS 强行修改样式,否则会导致验证异常。

language

String

cn

验证码语言类型,请参见验证码2.0支持的语言

region

String

cn

验证码实例所属地域。取值:

  • cn:表示中国内地。

  • sgp:新加坡。

说明
  • 客户端接入region参数和服务端接入地址endpoint不一致,会导致验证请求返回错误

  • 产品在中国内地(华东2(上海))和新加坡分别设置了管控中心平台,根据客户自行配置的调用参数,客户端采集的行为数据、设备数据等将回传到对应中心处理,主要实现安全验证功能。