使用的是腾讯云图形验证
腾讯图形验证文档
https://cloud.tencent.com/document/product/1110/36841
1.注册新建验证
2.找到新建好的验证配置 appid html需要用到
3.页面引用
在 Head 标签的最后加入以下代码,引入验证 JS 文件(建议直接在 HTML 中引入)。
<script type="text/javascript" src="js/hScroll.js"></script>
在您需要激活验证码的 DOM 元素(button、div、span)内加入以下 ID 及属性。
<!--点击此元素会自动激活验证码-->
<!--id : 元素的 ID(必须)-->
<!--data-appid : 验证码AppID(必须)-->
<!--data-cbfn : 回调函数名(必须)-->
<!--data-biz-state : 业务自定义透传参数(可选)-->
<button id="TencentCaptcha"
data-appid=""
data-cbfn="callback"
type="button"
>验证</button>
js代码
<script type="text/javascript">
window.callback = function(res){
console.log(res)
// res(用户主动关闭验证码)= {ret: 2, ticket: null}
// res(验证成功) = {ret: 0, ticket: "String", randstr: "String"}
if(res.ret === 0){
alert(res.ticket) // 票据
}
}
</script>
4.页面测试
后端需要在验证一次
导入Maven依赖
<!-- https://mvnrepository.com/artifact/com.tencentcloudapi/tencentcloud-sdk-java -->
<dependency>
<groupId>com.tencentcloudapi</groupId>
<artifactId>tencentcloud-sdk-java</artifactId>
<version>3.0.94</version>
</dependency>
控制层代码
/**
* 验证图形验证码是否正确
* @param request ticket 票据 randstr验证参数
* @param response
* @return
* @author zhuzq
* 2021-01-30 10:52:23
*/
@RequestMapping("/describeCaptchaResult")
@ResponseBody
public ResponseMap describeCaptchaResult(String ticket, String randstr,HttpServletRequest request, HttpServletResponse response){
ResponseMap responseMap = new ResponseMap();
try{
//cred 第一个参数 SecretId 第二个参数SecretKey 在腾讯云秘钥获取
Credential cred = new Credential("xxx", "xxx");
HttpProfile httpProfile = new HttpProfile();
httpProfile.setEndpoint("captcha.tencentcloudapi.com");
ClientProfile clientProfile = new ClientProfile();
clientProfile.setHttpProfile(httpProfile);
CaptchaClient client = new CaptchaClient(cred, "", clientProfile);
DescribeCaptchaResultRequest req = new DescribeCaptchaResultRequest();
req.setAppSecretKey("0bxShYXgIlwbQI5IVYYBYKA**"); //用于服务器端校验验证码票据的验证密钥,请妥善保密,请勿泄露给第三方
req.setCaptchaAppId(xxx); //验证码应用ID
req.setCaptchaType(9L); //固定填值:9。可在控制台配置不同验证码类型。
req.setUserIp(HttpUtil.getIpAddr(request)); //用户操作来源的外网 IP
req.setTicket(ticket); //前端回调函数返回的用户验证票据
req.setRandstr(randstr); //前端回调函数返回的随机字符串
DescribeCaptchaResultResponse resp = client.DescribeCaptchaResult(req);
logger.info("验证图形验证码是否正确返回" + DescribeCaptchaResultResponse.toJsonString(resp));
if(1 == resp.getCaptchaCode()){
//成功
responseMap.success();
return responseMap;
}else{
responseMap.failure();
return responseMap;
}
}catch (Exception e) {
responseMap.failure("验证图形验证码失败");
logger.error("验证图形验证码是否正确失败" + e.getMessage());
return responseMap;
}
window.callback = function(res){
// res(用户主动关闭验证码)= {ret: 2, ticket: null}
// res(验证成功) = {ret: 0, ticket: "String", randstr: "String"}
if(res.ret === 0){
$.ajax({
type:"post",
url:"http://188.188.3.27:8080/api/describeCaptchaResult",
data:"ticket="+res.ticket+"&randstr="+res.randstr,
dataType: "json",
success:function (message) {
if(message.code == 200){
settime(this);
}else{
}
}
});
}
}