发送短信验证码
开通阿里云短信服务
- 根据阿里云短信服务官方指引开通服务,获取到
AccessKey ID
和AccessKey Secret
、短信签名
、短信模板
查看AccessKey
短信服务管理控制台
Springboot后台接口
pom.xml
增加加短信服务相关依赖
com.aliyun
aliyun-java-sdk-core
4.0.8
com.aliyun
aliyun-java-sdk-dysmsapi
1.1.0
- 短信发送模块,
MsgSend 类
package com.education.edu_server.util;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
public class MsgSend {
static final String product = "Dysmsapi";
static final String domain = "dysmsapi.aliyuncs.com";
static final String accessKeyId = "XXXX";
static final String accessKeySecret = "XXXX";
public SendSmsResponse sendSms(String telephone, String code) throws ClientException {
System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
System.setProperty("sun.net.client.defaultReadTimeout", "10000");
IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
IAcsClient acsClient = new DefaultAcsClient(profile);
SendSmsRequest request = new SendSmsRequest();
request.setPhoneNumbers(telephone);
request.setSignName("XXXX");
request.setTemplateCode("XXXXX");
request.setTemplateParam("{\"code\":\"" + code + "\"}");
request.setOutId("yourOutId");
SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
if(sendSmsResponse.getCode()!= null && sendSmsResponse.getCode().equals("OK")){
System.out.println("短信发送成功!");
}else {
System.out.println("短信发送失败!");
}
return sendSmsResponse;
}
}
- 处理6位数字短信验证码生成、发送及校验,
controller
package com.education.edu_server.controller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.exceptions.ClientException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.education.edu_server.util.MsgSend;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import java.util.Date;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/msg")
public class SendMsgController {
@Autowired
@Qualifier("jdbcTemplate")
private JdbcTemplate jdbcTemplate;
@RequestMapping("/sendMsg")
public String sendMsg(@RequestBody Map map) throws ClientException {
System.out.println(map.get("phoneNum"));
String phoneNum = (String) map.get("phoneNum");
JSONObject res = new JSONObject();
StringBuffer stringBuffer = new StringBuffer();
for (int x = 0; x <= 5; x++) {
int random = (int) (Math.random() * (10 - 1));
stringBuffer.append(random);
}
String code = stringBuffer.toString();
System.out.println("发送的验证码为:"+code);
MsgSend msgSend=new MsgSend();
SendSmsResponse response =msgSend.sendSms(phoneNum,code);
System.out.println("短信接口返回的数据----------------");
System.out.println("Code=" + response.getCode());
System.out.println("Message=" + response.getMessage());
System.out.println("RequestId=" + response.getRequestId());
System.out.println("BizId=" + response.getBizId());
String sql = "insert into msg (phone,code,requestid,bizid,msg,datetime) values (?,?,?,?,?,?)";
int count=jdbcTemplate.update(sql, phoneNum,code, response.getRequestId(), response.getBizId(), response.getCode(),new Date().getTime());
System.out.println(count);
res.put("code",response.getCode());
res.put("requestId", response.getRequestId());
return JSON.toJSONString(res);
}
@RequestMapping("/checkCode")
public String checkCode(@RequestBody Map map){
String phoneNum = (String) map.get("phoneNum");
String code = (String)map.get("code");
String requestId = (String) map.get("requestId");
String sql = "select datetime from msg where code=? and phone=? and requestid=? order by datetime desc";
List<Map<String, Object>> list = jdbcTemplate.queryForList(sql,code,phoneNum,requestId);
JSONObject res = new JSONObject();
if(list.size()>0&&list!=null){
Object str=list.get(0).get("datetime");
Long time= Long.parseLong(str.toString());
Date now=new Date();
if(now.getTime()-time>1000*60*30){
res.put("code", false);
res.put("msg", "超时");
}else{
res.put("code", true);
res.put("msg", "验证成功");
}
}else {
res.put("code", false);
res.put("msg", "验证码错误");
}
return JSON.toJSONString(res);
}
}
前端验证demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>api-test</title>
<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
<div>
<div>
<label for="phonenum">手机号:<input id="phonenum" name="phonenum" type="text" /></label>
<button id="sendMsg">发送</button>
</div>
<div>
<label for="code">验证码:<input id="code" name="code" type="text" /></label>
</div>
<div><button id="checkMsg">提交</button></div>
</div>
<script>
var requestId = "",codeNum="";
$('#sendMsg').click(() => {
let phonenum = $("#phonenum").val()
console.log(phonenum)
$.ajax({
type: "POST",
dataType: "json",
contentType: 'application/json;charset=UTF-8',
url: "http://127.0.0.1:8082/msg/sendMsg",
data: JSON.stringify({ "phoneNum": phonenum }),
error: function (request) {
console.log(request)
},
success: function (data) {
$('#sendMsg').hide()
requestId=data.requestId
codeNum=data.code
}
});
});
$('#checkMsg').click(() => {
let phonenum = $("#phonenum").val()
let code = $("#code").val()
$.ajax({
type: "POST",
dataType: "json",
contentType: 'application/json;charset=UTF-8',
url: "http://127.0.0.1:8082/msg/checkCode",
data: JSON.stringify({ "phoneNum": phonenum ,"code":code,"requestId": requestId}),
error: function (request) {
console.log(request)
},
success: function (data) {
if(data.code){
$('#checkMsg').hide()
alert("成功")
}else{
alert(data.msg)
}
}
});
});
</script>
</body>
</html>