网上几乎找不到ALTCHA使用教程,公司要用,记录一下遇到的问题和解决方法。官网:https://altcha.org/docs/website-integration/
技术栈:vue2+js+webpack
需求:点击获取验证码,先通过ALTCHA小组件得到一份处理过的字符串,将字符串携带在原发验证码接口中传给后端,在用户 层面来说ALTCHA处理要是无感知的。
-
安装
npm install altcha
-
引入
在main.js中引入import 'altcha';
-
运行
运行项目后报错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'],
-
使用
在页面中加入如下代码:
<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') {
// 校验失败或出错,容错处理
}
}
}
- 测试
点击发送验证码,开始冷却倒计时60s,成功收到验证码,再次点击发送验证码,依然能正常进入倒计时,再次成功收到验证码,比改造之前多调用了一个ALTCHA小组件的接口,但用户无感知。