一. MD5加密工具类 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 import java.security.MessageDigest;import java.security.NoSuchAlgorithmException;public class Md5Utils { public static String encrypByMd5 (String context) { try { MessageDigest md = MessageDigest.getInstance("MD5" ); md.update(context.getBytes()); byte [] encryContext = md.digest(); int i; StringBuffer buf = new StringBuffer ("" ); for (int offset = 0 ; offset < encryContext.length; offset++) { i = encryContext[offset]; if (i < 0 ) i += 256 ; if (i < 16 ) buf.append("0" ); buf.append(Integer.toHexString(i)); } return buf.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null ; } } }
二. 短信服务 短信验证,只有三大运营商具有短信发送的能力。要发送短信只有找三大运营,或者中间商。简单说就是要找第三方的短信平台。常见的有阿里云,京东智联云,乐讯通等等非常多。举例使用网建短信通:http://www.smschinese.cn/
操作流程
1 2 3 4 5 6 7 点击左上角首页 -> API接口 -> 网建SMS短信通API接口地址 -> UTF-8 编码发送短信接口: http: 本站用户名Uid:注册时用户名 接口安全密钥key:刚刚看到的密钥 手机号码smsMob:手机号码 短信内容smsText:随便写 api接口中有发送短信的各个对应状态:发送了一条,就只剩下4 条了
导入依赖
1 2 3 4 5 6 7 <dependency > <groupId > commons-httpclient</groupId > <artifactId > commons-httpclient</artifactId > <version > 3.1</version > </dependency >
发送短信工具类(官网也有相应代码可参考)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 package io.coderyeah.basic.util;import org.apache.commons.httpclient.HttpClient;import org.apache.commons.httpclient.NameValuePair;import org.apache.commons.httpclient.methods.PostMethod;public class SmsUtils { public static final String UID = "codermyth" ; public static final String KEY = "29766C0677741B5DA2CE2203260365DB" ; public static String sendSms (String phones, String content) { PostMethod post = null ; try { HttpClient client = new HttpClient (); post = new PostMethod ("http://utf8.api.smschinese.cn" ); post.addRequestHeader("Content-Type" , "application/x-www-form-urlencoded;charset=utf8" ); NameValuePair[] data = {new NameValuePair ("Uid" , SmsUtils.UID), new NameValuePair ("Key" , SmsUtils.KEY), new NameValuePair ("smsMob" , phones), new NameValuePair ("smsText" , content)}; post.setRequestBody(data); client.executeMethod(post); int statusCode = post.getStatusCode(); System.out.println("statusCode:" + statusCode); String result = new String (post.getResponseBodyAsString().getBytes("utf8" )); return result; } catch (Exception e) { e.printStackTrace(); } finally { if (post != null ) { post.releaseConnection(); } } return null ; } public static void main (String[] args) { System.out.println(SmsUtils.sendSms("18365403510" , "您的验证码为:【8848】,鉴于您优秀的能力表现,您被授予玛丽叶奥特曼称号,accept it, cutie!" )); } }
三. 前端获取验证码接口 1 2 3 4 5 <div class ="verification" > <label for ="code" > <i class ="am-icon-code-fork" > </i > </label > <input type ="tel" name ="" id ="code" v-model ="phoneUserForm.phoneCode" placeholder ="请输入验证码" > <button type ="button" id ="dyMobileButton" @click ="sendMobileCode" > 获取验证码</button > </div >
获取短信验证码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 sendMobileCode ( ) { if (!this .phoneUserForm .phone ) { alert ("手机号不能为空" ); return ; } if (!this .phoneUserForm .imageCode ) { alert ("图片验证码不能为空" ); return ; } let sendBtn = $(event.target ); sendBtn.attr ("disabled" , true ); let param = { phone : this .phoneUserForm .phone , imageCode : this .phoneUserForm .imageCode , imageCodeKey : localStorage .getItem ("verifyCodeKey" ) }; this .$http .post ("/verifyCode/smsCode" , param).then (res => { const ajaxResult = res.data ; if (ajaxResult.success ) { alert ("手机验证码已经发送到您的手机,请在3分钟内使用" ); let time = 60 ; let interval = window .setInterval (function ( ) { time = time - 1 ; sendBtn.html (time + 's' ); if (time <= 0 ) { sendBtn.html ("重新发送" ); sendBtn.attr ("disabled" , false ); window .clearInterval (interval); } }, 1000 ); } else { sendBtn.attr ("disabled" , false ); alert (ajaxResult.msg ); } }) }
发送请求
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 phoneRegister ( ) { if (!this .agree ) { alert ('请勾选服务协议' ) return ; } this .$http .post ('/user/register/phone' , this .phoneUserForm ).then (res => { if (res.data .success ) { location.href = "login.html" ; } else { alert (res.data .msg ); } }).catch (res => { alert ("系统错误!" ) }); },
四. 后端实现获取短信接口 1 2 3 4 5 6 7 8 9 10 11 12 @PostMapping("/smsCode") @ApiOperation("获取短信验证码") public Result getPhoneCode (@RequestBody PhoneCodeDTO phoneCodeDTO) { try { return verifyCodeService.getPhoneCode(phoneCodeDTO); } catch (BusinessException e) { e.printStackTrace(); return Result.fail(e.getMessage()); } catch (Exception e) { return Result.fail("系统异常,请稍后重试!" ); } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 @Override public Result getPhoneCode (PhoneCodeDTO phoneCodeDTO) { final String phone = phoneCodeDTO.getPhone(); final String InputImageCode = phoneCodeDTO.getImageCode(); final String imageCodeKey = phoneCodeDTO.getImageCodeKey(); if (StrUtil.isBlank(phone)) { throw new BusinessException ("电话号码不能为空" ); } if (StrUtil.isBlank(InputImageCode)) { throw new BusinessException ("图形验证码不能为空不能为空" ); } final String imageCode = stringRedisTemplate.opsForValue().get("cache:code:image:" + imageCodeKey); if (StrUtil.isBlank(imageCode)) { throw new BusinessException ("图形验证码已过期,请重新输入!" ); } if (!InputImageCode.equalsIgnoreCase(imageCode)) { throw new BusinessException ("图片验证码错误,请重新输入!" ); } final User user = userMapper.selectOne(new LambdaQueryWrapper <User>().eq(User::getPhone, phone)); if (user != null ) { throw new BusinessException ("该手机号码已被注册过,请您直接登录..." ); } String code = null ; final String value = stringRedisTemplate.opsForValue().get(Constants.USER_REGISTER_PHONE_PREFIX + phone); if (value != null ) { final long oldTime = Long.parseLong(value.split(":" )[1 ]); if ((System.currentTimeMillis() - oldTime) <= 1000 * 60 ) { throw new BusinessException ("操作频繁,请稍后再试!" ); } else { code = value.split(":" )[0 ]; } } else { code = String.valueOf(RandomUtil.randomNumbers(6 )); } stringRedisTemplate.opsForValue().set("user:register:" + phone, code + ":" + System.currentTimeMillis(), 3L , TimeUnit.MINUTES); log.info("=========您的验证码是:{}=========" , code); return Result.success("获取验证码成功【" + code + "】" ); }