前端控制按钮通过js实现60秒倒计时
$(function () {
$("#sendCode").click(function () {
//2、倒计时
if ($(this).hasClass("disabled")) {
//正在倒计时中
} else {
//1、给指定手机号发送验证码
$.get("/sms/sendCode?phone=" + $("#phoneNum").val(), function (data) {
if (data.code != 0) {
alert(data.msg);
}
});
timeoutChangeStyle();// 开始倒计时
}
});
});
var num = 60;
function timeoutChangeStyle() {
$("#sendCode").attr("class", "disabled");// 已经点击发送验证码后,当前按钮不可点击
if (num == 0) {
$("#sendCode").text("发送验证码");// 60秒后,文本更改为发送验证码
num = 60;
$("#sendCode").attr("class", "");// 60秒后,可以点击
} else {
var str = num + "s 后再次发送";
$("#sendCode").text(str);
setTimeout("timeoutChangeStyle()", 1000);// 一秒后执行timeoutChangeStyle()
num--;
}
}
第三方服务,发送短信包
1.1搜索短信接口,购买一个5条的短信
![](https://img-blog.csdnimg.cn/0fc94449048e41ac95fa627e3a5c1b4a.png)
1.2购买后进入云市场,查看相关3个参数(AppKey、AppSecret、AppCode)
云市场
![](https://img-blog.csdnimg.cn/e4782801d9814379a02c0b0b1a2ed5cb.png)
1.3代码实现(请求头使用Authorization作为key + 值使用AppCode的值来验证身份)
/**
* 短信配置类
* @Author: wanzenghui
* @Date: 2021/11/27 23:01
*/
@Configuration
public class SmsConfig {
@Bean
@ConfigurationProperties(prefix = "spring.cloud.alicloud.sms")
public SmsServiceImpl smsService() {
return new SmsServiceImpl();
}
}
/**
* 短信服务实现类
* @Author: wanzenghui
* @Date: 2021/11/27 22:58
*/
@Data
public class SmsServiceImpl implements SmsService {
private String host;
private String path;
private String appcode;
private String sign;
private String skin;
@Override
public Boolean sendCode(String phone, String code) {
String urlSend = host + path + "?code=" + code + "&phone=" + phone + "&sign=" + sign + "&skin=" + skin ; // 拼接请求链接
try {
URL url = new URL(urlSend);
HttpURLConnection httpURLCon = (HttpURLConnection) url.openConnection();
httpURLCon.setRequestProperty("Authorization", "APPCODE " + appcode);// 格式Authorization:APPCODE
// (中间是英文空格)
int httpCode = httpURLCon.getResponseCode();
if (httpCode == 200) {
String json = read(httpURLCon.getInputStream());
System.out.println("正常请求计费(其他均不计费)");
System.out.println("获取返回的json:");
System.out.print(json);
} else {
Map<String, List<String>> map = httpURLCon.getHeaderFields();
String error = map.get("X-Ca-Error-Message").get(0);
if (httpCode == 400 && error.equals("Invalid AppCode `not exists`")) {
System.out.println("AppCode错误 ");
} else if (httpCode == 400 && error.equals("Invalid Url")) {
System.out.println("请求的 Method、Path 或者环境错误");
} else if (httpCode == 400 && error.equals("Invalid Param Location")) {
System.out.println("参数错误");
} else if (httpCode == 403 && error.equals("Unauthorized")) {
System.out.println("服务未被授权(或URL和Path不正确)");
} else if (httpCode == 403 && error.equals("Quota Exhausted")) {
System.out.println("套餐包次数用完 ");
} else {
System.out.println("参数名错误 或 其他错误");
System.out.println(error);
}
}
} catch (MalformedURLException e) {
System.out.println("URL格式错误");
} catch (UnknownHostException e) {
System.out.println("URL地址错误");
} catch (Exception e) {
// 打开注释查看详细报错异常信息
// e.printStackTrace();
}
return true;
}
/*
* 读取返回结果
*/
private static String read(InputStream is) throws IOException {
StringBuffer sb = new StringBuffer();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
while ((line = br.readLine()) != null) {
line = new String(line.getBytes(), "utf-8");
sb.append(line);
}
br.close();
return sb.toString();
}
}
/**
* 短信服务
* @Author: wanzenghui
* @Date: 2021/11/27 23:20
*/
@RestController
@RequestMapping("/sms")
public class SmsController {
@Autowired
SmsServiceImpl smsService;
/**
* 发送短信验证码
* 提供其他模块调用
* @param phone 号码
* @param code 验证码
*/
@GetMapping("/test")
public R sendCode(@RequestParam("phone") String phone, @RequestParam("code") String code) {
smsService.sendCode(phone, code);
return R.ok();
}
}
1.4认证模块_调用发送短信验证码
@Controller
public class LoginController {
@Autowired
ThirdPartFeignService thirdPartFeignService;
/**
* 发送短信验证码
* @param phone 号码
* @param code 验证码
*/
@ResponseBody
@GetMapping("/sms/sendCode")
public R sendCode(@RequestParam("phone") String phone) {
String code = UUID.randomUUID().toString().substring(0, 5);
thirdPartFeignService.sendCode(phone, code);
return R.ok();
}
}
完善版本(添加Redis实现60秒内防刷)
/**
* 发送短信验证码
*
* @param phone 号码
* @param code 验证码
*/
@ResponseBody
@GetMapping("/sms/sendCode")
public R sendCode(@RequestParam(name = "phone", required = true) String phone) {
// 1.判断60秒间隔发送,防刷
String _code = redisTemplate.opsForValue().get(AuthConstant.SMS_CODE_CACHE_PREFIX + phone);
if (StringUtils.isNotBlank(_code) && System.currentTimeMillis() - Long.parseLong(_code.split("_")[1]) < 60000) {
// 调用接口小于60秒间隔不允许重新发送新的验证码
return R.error(BizCodeEnume.SMS_CODE_EXCEPTION);
}
// 2.验证码存入缓存
String code = UUID.randomUUID().toString().substring(0, 5);
// 验证码缓存到redis中(并且记录当前时间戳)
redisTemplate.opsForValue().set(AuthConstant.SMS_CODE_CACHE_PREFIX + phone, code + "_" + System.currentTimeMillis(), 10, TimeUnit.MINUTES);
// 3.发送验证码
thirdPartFeignService.sendCode(phone, code);
return R.ok();
}