asp.net core 腾讯验证码的接入示例代码
Intro
之前使用的验证码服务是用的极验验证,而且是比较旧的,好久之前接入的,而且验证码服务依赖Session,有点不太灵活,后来发现腾讯也有验证码服务,而且支持小程序,并且是唯一支持小程序的验证码。。(垄断么。。)
而且相比之下,腾讯验证码不需要依赖Session,集成起来也比较方便,于是就用了腾讯验证码,详细参考:https://007.qq.com/product.html?ADTAG=index.block
验证流程
服务器端接入
usingSystem.ComponentModel.DataAnnotations;
usingSystem.Net.Http;
usingSystem.Threading.Tasks;
usingMicrosoft.Extensions.Logging;
usingMicrosoft.Extensions.Options;
usingNewtonsoft.Json;
usingWeihanLi.Extensions;
namespaceActivityReservation.Common
{
publicclassTencentCaptchaOptions
{
///
///客户端AppId
/// 
[Required]
publicstringAppId{get;set;}
///
///AppSecretKey
/// 
[Required]
publicstringAppSecret{get;set;}
}
publicclassTencentCaptchaRequest
{
///
///验证码客户端验证回调的票据
/// 
publicstringTicket{get;set;}
///
///验证码客户端验证回调的随机串
/// 
publicstringNonce{get;set;}
///
///提交验证的用户的IP地址(eg:10.127.10.2)
/// 
publicstringUserIP{get;set;}
}
publicclassTencentCaptchaHelper
{
privateclassTencentCaptchaResponse
{
///
///1:验证成功,0:验证失败,100:AppSecretKey参数校验错误
/// 
[JsonProperty("response")]
publicintCode{get;set;}
///
///恶意等级[0,100]
/// 
[JsonProperty("evil_level")]
publicstringEvilLevel{get;set;}
///
///错误信息
/// 
[JsonProperty("err_msg")]
publicstringErrorMsg{get;set;}
}
privateconststringTencentCaptchaVerifyUrl="https://ssl.captcha.qq.com/ticket/verify";
privatereadonlyTencentCaptchaOptions_captchaOptions;
privatereadonlyILogger_logger;
privatereadonlyHttpClient_httpClient;
publicTencentCaptchaHelper(
IOptionsoption,
ILoggerlogger,
HttpClienthttpClient)
{
_captchaOptions=option.Value;
_logger=logger;
_httpClient=httpClient;
}
publicasyncTaskIsValidRequestAsync(TencentCaptchaRequestrequest)
{
//参考文档:https://007.qq.com/captcha/#/gettingStart
varresponse=await_httpClient.GetAsync(
$"{TencentCaptchaVerifyUrl}?aid={_captchaOptions.AppId}&AppSecretKey={_captchaOptions.AppSecret}&Ticket={request.Ticket}&Randstr={request.Nonce}&UserIP={request.UserIP}");
varresponseText=awaitresponse.Content.ReadAsStringAsync();
if(responseText.IsNotNullOrEmpty())
{
_logger.Debug($"Tencentcaptchaverifyresponse:{responseText}");
varresult=responseText.JsonToType();
if(result.Code==1)
{
returntrue;
}
}
returnfalse;
}
}
}
    
Startup配置:
services.AddHttpClient(client=>client.Timeout=TimeSpan.FromSeconds(3)) .ConfigurePrimaryHttpMessageHandler(()=>newNoProxyHttpClientHandler()); services.AddTencentCaptchaHelper(options=> { options.AppId=Configuration["Tencent:Captcha:AppId"]; options.AppSecret=Configuration["Tencent:Captcha:AppSecret"]; }); 
前端接入
前端接入这里不作多介绍了,接入方式多种多样,具体可以参考官方文档:https://cloud.tencent.com/document/product/1110/36841
下面的代码是angularspa在前端接入的核心代码
privateloadCaptcha():void{
vartCaptcha=document.getElementById("tCaptcha");
if(tCaptcha){
this.InitCaptcha();
return;
}
letscript=document.createElement('script');
script.id="tCaptcha";
script.type='text/javascript';
script.src="https://ssl.captcha.qq.com/TCaptcha.js"
if(script.readyState){//IE
script.onreadystatechange=()=>{
if(script.readyState==="loaded"||script.readyState==="complete"){
this.InitCaptcha();
}
};
}else{//Others
script.onload=()=>{
this.InitCaptcha();
};
}
document.getElementsByTagName('body')[0].appendChild(script);
}
privateInitCaptcha():void{
letcaptchaDom=document.getElementById('TencentCaptcha1');
if(!captchaDom){
return;
}
this.tencentRecaptcha=newTencentCaptcha(
captchaDom,appId,(res)=>{
this.captchaValid=false;
console.log(res);
//res(用户主动关闭验证码)={ret:2,ticket:null}
//res(验证成功)={ret:0,ticket:"String",randstr:"String"}
if(res.ret===0){
this.captchaInfo.nonce=res.randstr;
this.captchaInfo.ticket=res.ticket;
this.captchaValid=true;
this.tencentRecaptcha.destroy();
letbutton=document.getElementById("btnSubmit");
button.click();
}
}
);
console.log(`captchainited`);
this.tencentRecaptcha.show();
}
  
使用效果:
老版网站接入效果:
Reference
https://github.com/WeihanLi/ActivityReservation
https://reservation.weihanli.xyz/Home/Reservate
https://reservation-client.weihanli.xyz/reservation/new
https://cloud.tencent.com/document/product/1110/36841
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。