验证码前置校验:ALTCHA使用记录

网上几乎找不到ALTCHA使用教程,公司要用,记录一下遇到的问题和解决方法。官网:https://altcha.org/docs/website-integration/
技术栈:vue2+js+webpack
需求:点击获取验证码,先通过ALTCHA小组件得到一份处理过的字符串,将字符串携带在原发验证码接口中传给后端,在用户 层面来说ALTCHA处理要是无感知的。
在这里插入图片描述

  1. 安装

    npm install altcha
    
  2. 引入
    在main.js中引入

    import 'altcha';
    
  3. 运行
    运行项目后报错You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file.
    解决:在vue.config.js的module.exports中加入

    transpileDependencies: ['altcha'],
    
  4. 使用
    在这里插入图片描述

    在页面中加入如下代码:

    <form class="altcha">
      <altcha-widget id="altcha" ref="altchaWidget" :challengeurl="challengeurl" maxnumber="50"
        delay="1"></altcha-widget>
      <button type="reset" id="reset">重置</button>
    </form>
    

    根据class写样式,隐藏此模块,防止影响自己的页面样式。

    .altcha {
      display: none;
    }
    

我此处是希望点击获取验证码按钮时触发防护,代码如下:

mounted() {
 if (this.$refs.altchaWidget) {
    this.$refs.altchaWidget.addEventListener('statechange', this.onStateChange) //监听验证的状态变化
  }
}
methods: {
	onStateChange(ev) {
	  // 安全防护 https://altcha.org/docs/website-integration/
	  // state: unverified, verifying, verified, error
	  if (ev.detail.state === 'verified') { //校验成功
	    this.payload = ev.detail.payload
	    // 此处继续写原来的发送短信功能
	    document.querySelector('#reset').click() //这里是为了重置校验,为下一次用户的点击做准备
	  } else if (ev.detail.state === 'unverified' || ev.detail.state === 'error') {
	    // 校验失败或出错,容错处理
	  }
	}
}
  1. 测试
    点击发送验证码,开始冷却倒计时60s,成功收到验证码,再次点击发送验证码,依然能正常进入倒计时,再次成功收到验证码,比改造之前多调用了一个ALTCHA小组件的接口,但用户无感知。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值