顶象无感防刷验证的使用记录
记录一段坑
莫名的函数调用
代码说明
// token是否有效
isValidToken = () => {
const wmti = localStorage.getItem('workbench_mobile_token_isValid');
if (!wmti) return false;
const curr_time = new Date().getTime();
const send_time = Number(wmti);
const isRemove = (curr_time - send_time) / 1000 >= 120;
if (isRemove) {
localStorage.removeItem('workbench_mobile_token_isValid');
return false;
}
return true;
};
// 传手机号之前进行安全防刷
useCaptchaModel = (phone: string) => {
if (this.isValidToken()) {
this.sendSmsCode(phone);
} else {
const mainDiv = document.getElementById('captcha-brush-box');
if ((window as any)._dx) {
const myCaptcha = (window as any)._dx.Captcha(mainDiv, {
...this.getDxParams(),
style: 'popup',
isSaaS: false,
tpc: `${new Date().getTime()}_1_1`,
width:
this.prmContainerRef && this.prmContainerRef.current?.clientWidth,
success: async (token: string) => {
const curr_time = new Date().getTime();
// token两分钟时效性
localStorage.setItem(
'workbench_mobile_token_isValid',
curr_time.toString()
);
// 校验token时效性
const isCheck = await verifyBrushToken({ token });
if (isCheck) {
this.sendSmsCode(phone);
myCaptcha.hide();
}
setTimeout(() => {
myCaptcha.reload();
}, 1000);
},
fail: () => {
myCaptcha.reload();
},
});
myCaptcha.show();
}
}
};
注意事项
token有效期两分钟,需要注意
前端需要判断token是否在有效期,然后决定是否调起滑块。
当回调函数中,存在定时器操作
需要做异常处理,比如,回调函数中存在设置了60秒倒计时,那么需要在进入定时器之前判断当前倒计时的初始值,是否满足>=0, 不然会出现倒计时一直在重复定义和清除。(为什么这么说,因为当前函数在调用的时候,本身没问题,当嵌入到顶象的success回调的时候,就会一直调用,不使用防刷模块就不会有问题,此时可能会说,为什么不在调用之前设定传入的倒计时控制为正数,那是因为该函数只有一处引用,且传入的是常量正数)
代码如下:
// 设置验证码定时器
setTimerVerifyCode = (cdSeconds: number) => {
let temp = cdSeconds;
// 防止异常事件 这段代码建议加上
if (temp <= 0) {
return;
}
timer = setInterval(() => {
temp--;
this.setState({
codeText: `重新发送(${temp >= 10 ? temp : `0${temp}`}s)`,
});
// 保存当前读秒
localStorage.setItem(
'workbench_mobile_verifyCodeRegister',
temp.toString()
);
// 保存当前时间戳
localStorage.setItem(
'workbench_mobile_verifyCodeRegister_current_time',
new Date().getTime().toString()
);
if (temp <= 0) {
this.setState({
isVerifyCode: false,
codeText: '获取验证码',
});
localStorage.removeItem('workbench_mobile_verifyCodeRegister');
localStorage.removeItem(
'workbench_mobile_verifyCodeRegister_current_time'
);
clearInterval(timer);
timer = null;
}
}, 1000);
};