JAVA短信验证登录
短信验证登陆
1、点击触发,以电话号码为参数调用发送验证登录短信方法
2、默认模板为验证模板
生成6位验证码
3、将生成的验证码和手机号码放入缓存,(已经设置好缓存存放时间)
4、调用发送模板短信方法发送短信(设置好短信中验证码有效的时间)
5、点击触发登陆,调用对应验证登录函数 ,以电话号码和验证码为参数
6、校验缓存中对应保留的信息
如果一致,登陆成功;
登陆不成功是返回原因(1、超时 2、验证码输入错误)
/** *发送验证码短信 *参数:手机号码 */ public void sendVerifyLoginSMS(String to) { Jedis cache = sendSMSCache.getResource(); //生成六位验证码 String charValue = ""; for (int i = 0; i < 6; i++) { char c = (char) (randomInt(0, 9) + '0'); charValue += String.valueOf(c); } //将生成的六位验证码和传进来的手机号码存入缓存,时间90S try{ Pipeline pipeline = cache.pipelined(); pipeline.set("CACHE" + to, charValue); pipeline.expire("CACHE", 90); pipeline.sync(); } finally { if (cache != null) { cache.close(); } } //验证码和显示时间 String[] datas = {charValue,"1.5"}; //短信模板 String templateId = "1"; sMSClientBiz.sendSMS(to, templateId, datas); } /** * 生成随机数 * * */ public int randomInt(int from, int to) { Random r = new Random(); return from + r.nextInt(to - from); } /** * 验证短信验证码登陆 * * */ public boolean verifySMS(String to, String verifyCode) { Jedis cache = sendSMSCache.getResource(); // 缓存中验证码 String cacheVerifyCode; try{ cacheVerifyCode = cache.get("CACHE" + to); } finally { if (cache != null) { cache.close(); } } //如果输入的验证码和缓存中的验证码一致,则验证成功 if(verifyCode ==cacheVerifyCode ){ return true; }else return false; }