Vue3+Vue-cli4 使用腾讯滑块验证码的方法

滑块验证码相比于传统的图片验证码具有以下优点:

  • 验证码的具体验证不需要服务端去验证,服务端只需要核验验证结果即可。
  • 验证码的实现不需要我们去了解,也不需要我们去具体实现。
  • 滑块验证码的安全程度相比于传统验证码高不少。
  • ...

由于网络上和腾讯api文档中缺少关于vue3中组合式api怎么应用腾讯的滑块验证码,所以出此教程。本人也非vue大佬,对vue的理解也不过停留在初级使用的程度上,有错误之处,敬请指出。

 

开始:

首先,我们需要去腾讯云申请一个图形验证的api,使用场景中选择自己的使用场景。完成步骤后我们会获得CaptchaAppId和AppSecretKey。这两个东西就是后面我们服务端核验验证结果的参数之二。

在Vue3中使用,首先需要在public文件夹的index.html中,引入腾讯验证码的js。

<script src="https://ssl.captcha.qq.com/TCaptcha.js"></script>

在需要用到滑块验证码的组件中,为登陆的按钮绑定方法。并且在表单对象中添加以下两个字段ticket,randstr。

我这里示例是这样写的

export default {
  name: "Login",
  setup() {
      const loginForm = reactive({
          accountName: '',
          accountPassword: '',
          ticket: '',
          randstr: ''
      })
      return {
          loginForm
      }
  }
}

登陆按钮绑定方法

export default {
  name: "Login",
  setup() {
      const loginForm = reactive({
          accountName: '',
          accountPassword: '',
          ticket: '',
          randstr: ''
      })

      const loginPost = () => {

          let captcha = new window.TencentCaptcha(config.app_id, res => {
              loginForm.randstr = res.randstr;
              loginForm.ticket = res.ticket;

              userLogin(loginForm).then(resp => {

                  if (resp.code === 200) {
                      //登陆成功后的逻辑
                  } else {
                      //登陆失败后的逻辑
                  }
              }).catch(() => {
                  ElMessage.error({
                      message: '系统发生错误!请稍后重试!'
                  })
              })
          })
          captcha.show();
      }

      return {
          loginPost,
          loginForm
      }
  }
}

以上是在vue中写的代码,但是这里只实现了用户完成验证码的操作,具体的最终判断逻辑必须要在我们后端实现。我们后端就用Springboot来实现核验操作。

首先要引入腾讯sdk的maven依赖

<!--        腾讯SDK-滑块验证码依赖-->
<dependency>
<groupId>com.tencentcloudapi</groupId>
<artifactId>tencentcloud-sdk-java</artifactId>
<version>4.0.11</version>
</dependency>

我们在utils包中新建一个类。

public class DescribeCaptchaResult {
  @Value("${Tencent.SecretId}")
  private String secretId;

  @Value("${Tencent.SecretKey}")
  private String secretKey;

  @Value("${Tencent.CaptchaAppId}")
  private int captchaAppId;

  @Value("${Tencent.AppSecretKey}")
  private String appSecretKey;

  public JSONObject getTencentCaptchaResult(String ticket, String randstr, String userIp) {
      try {
          // 实例化一个认证对象,入参需要传入腾讯云账户secretId,secretKey,此处还需注意密钥对的保密
          // 密钥可前往https://console.cloud.tencent.com/cam/capi网站进行获取
          Credential cred = new Credential(secretId, secretKey);
          // 实例化一个http选项,可选的,没有特殊需求可以跳过
          HttpProfile httpProfile = new HttpProfile();
          httpProfile.setEndpoint("captcha.tencentcloudapi.com");
          // 实例化一个client选项,可选的,没有特殊需求可以跳过
          ClientProfile clientProfile = new ClientProfile();
          clientProfile.setHttpProfile(httpProfile);
          // 实例化要请求产品的client对象,clientProfile是可选的
          CaptchaClient client = new CaptchaClient(cred, "", clientProfile);
          // 实例化一个请求对象,每个接口都会对应一个request对象
          DescribeCaptchaResultRequest req = new DescribeCaptchaResultRequest();
          req.setCaptchaType(9L);
          req.setTicket(ticket);
          req.setRandstr(randstr);
          req.setUserIp(userIp);
          req.setCaptchaAppId((long) captchaAppId);
          req.setAppSecretKey(appSecretKey);
          // 返回的resp是一个DescribeCaptchaResultResponse的实例,与请求对象对应
          DescribeCaptchaResultResponse resp = client.DescribeCaptchaResult(req);
          // 输出json格式的字符串回包
          return JSONObject.parseObject(DescribeCaptchaResultResponse.toJsonString(resp));
      } catch (TencentCloudSDKException e) {
          throw new ServiceException(e.getMessage());
      }
  }
}

下面解析一下该类需要的参数。

 

 

参数 解析
secretId SecretId为你腾讯云账号的Api密钥ID(推荐使用子账号,授权)
secretKey SecretKey为你腾讯云账号的Api密钥Key(推荐使用子账号,授权)
captchaAppId captchaAppId为你申请的腾讯验证码api密钥
appSecretKey appSecretKey为你申请的腾讯验证码api密钥
ticket ticket为你前端滑块验证码验证后返回的参数
randstr randstr你前端滑块验证码验证后返回的参数
userIp userIp为你业务层获取的Ip

提供参数发送之后,会返回一个DescribeCaptchaResultResponse类型的数据,我们将他转为FastJson的JSONObject类型进行解析。返回数据结构如下:

{
"Response": {
"RequestId": "3b61a17b-cb38-470e-802c-b6242faf81ac",
"CaptchaCode": 1,
"CaptchaMsg": "OK",
"EvilLevel": 0,
"GetCaptchaTime": 1583749870
},
"retcode": 0,
"retmsg": "success"
}

具体其他参数可以参考腾讯api文档:https://cloud.tencent.com/document/product/1110/36926

我这里读取CaptchaCode的值,如果值为1则是验证码验证成功,不为1则是验证失败。

//核验验证码
JSONObject tencentCaptchaResult = captchaResult.getTencentCaptchaResult(ticket, randstr, clientIp);

int captchaCode = Integer.parseInt(tencentCaptchaResult.getString("CaptchaCode"));


if (captchaCode != 1) {
  throw new ServiceException("验证码错误!");
}
//...后续业务逻辑

 

后续

在腾讯云中还能为验证码设置更多的东西,如验证码的主题,验证码的场景配置,验证码恶意拦截的等级等等。。

在后台也能看到验证码的请求量

我感觉后端和前端还可以再封装一下,让代码更加简洁。阿里云还有其他的新型验证码还没有尝试,我个人是感觉腾讯验证码使用起来是挺好的,但是api文档什么的有点差了,资料也很少。

关于Vue3+Vue-cli4项目中使用腾讯滑块验证码的方法的文章就介绍至此,更多相关vue腾讯滑块验证码内容请搜索编程宝库以前的文章,希望以后支持编程宝库

element更新了版本兼容vue3,我们简单介绍一下如何使用element-plus。 1、安装npm install element-plus --save 2、在main. ...