Java+阿里云手机验证码发送和验证
1.注册阿里云账号,找到产品与服务里面的云通信模块,然后找到短信服务
2.开通短信服务
我这里已经开通,可直接进入管理控制台,没开通的话这里显示开开通短信服务
3.进入管理控制台之后选择国内消息,可以看到签名管理和模板管理
4.在此之前必须设置好AccessKey
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-p9jit6AQ-1572527330522)(C:\Users\Administrator\Desktop\短信服务\img\accesskeys.png)]
5.签名和模板具体可以参考右上角签名和模板,一般个人用户审核很快就通过了
6.一般签名就是收到的短信的开头(项目名或者公司名)
7.短信模板
模板内容就是收到短信的内容,${code}代表收到的验证码,模板名称就跟签名一样吧,申请说明就写个人网站使用。
8.Java代码实现
添加maven依赖
<!-- =========================阿里云短信验证服务======================== -->
<!-- https://mvnrepository.com/artifact/com.aliyun/aliyun-java-sdk-core -->
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
<version>4.4.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.aliyun/aliyun-java-sdk-dysmsapi -->
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-dysmsapi</artifactId>
<version>1.1.0</version>
</dependency>
配置AliyunSmsUtils(新建一个AliyunSmsUtils工具类)
public class AliyunSmsUtils {
//产品名称:云通信短信API产品,开发者无需替换
static final String product = "Dysmsapi";
//产品域名,开发者无需替换
static final String domain = "dysmsapi.aliyuncs.com";
// TODO 此处需要替换成开发者自己的AK(在阿里云访问控制台寻找)
static final String accessKeyId = ""; // TODO 修改成自己的
static final String accessKeySecret = ""; // TODO 修改成自己的
public static SendSmsResponse sendSms(String telephone, String code) throws ClientException {
//可自助调整超时时间
System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
System.setProperty("sun.net.client.defaultReadTimeout", "10000");
//初始化acsClient,暂不支持region化
IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
DefaultProfile.addEndpoint("cn-hangzhou", product, domain);
IAcsClient acsClient = new DefaultAcsClient(profile);
//组装请求对象-具体描述见控制台-文档部分内容
SendSmsRequest request = new SendSmsRequest();
//必填:待发送手机号
request.setPhoneNumbers(telephone);
//必填:短信签名-可在短信控制台中找到
request.setSignName(""); // TODO 修改成自己的 自己申请的签名
//必填:短信模板-可在短信控制台中找到
request.setTemplateCode("SMS_174991040"); // TODO 修改成自己的 模板管理中模板CODE
//可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
// request.setTemplateParam("{\"name\":\"Tom\", \"code\":\"123\"}");
request.setTemplateParam("{\"code\":\"" + code + "\"}");
//选填-上行短信扩展码(无特殊需求用户请忽略此字段)
//request.setSmsUpExtendCode("90997");
//可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
request.setOutId("yourOutId");
//hint 此处可能会抛出异常,注意catch
SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
if (sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
System.out.println("短信发送成功!");
} else {
System.out.println("短信发送失败!");
}
return sendSmsResponse;
}
/* 不删 留着 以后可能有用
public static QuerySendDetailsResponse querySendDetails(String bizId) throws ClientException {
//可自助调整超时时间
System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
System.setProperty("sun.net.client.defaultReadTimeout", "10000");
//初始化acsClient,暂不支持region化
IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
IAcsClient acsClient = new DefaultAcsClient(profile);
//组装请求对象
QuerySendDetailsRequest request = new QuerySendDetailsRequest();
//必填-号码
request.setPhoneNumber("15000000000");
//可选-流水号
request.setBizId(bizId);
//必填-发送日期 支持30天内记录查询,格式yyyyMMdd
SimpleDateFormat ft = new SimpleDateFormat("yyyyMMdd");
request.setSendDate(ft.format(new Date()));
//必填-页大小
request.setPageSize(10L);
//必填-当前页码从1开始计数
request.setCurrentPage(1L);
//hint 此处可能会抛出异常,注意catch
QuerySendDetailsResponse querySendDetailsResponse = acsClient.getAcsResponse(request);
return querySendDetailsResponse;
}
*/
private static int newcode;
public static int getNewcode() {
return newcode;
}
public static void setNewcode(){
newcode = (int)(Math.random()*999999)+100; //每次调用生成一位六位数的随机数
}
// 传入手机号获得验证码的方法
public static String getTelnoCode(Long userTelno) {
String telno = Long.toString(userTelno);
setNewcode();
String code = Integer.toString(getNewcode());
System.out.println("发送的验证码为:" + code);
//发短信
SendSmsResponse response = null; // TODO 填写你需要测试的手机号码
try {
response = sendSms(telno, code);
} catch (ClientException e) {
e.printStackTrace();
}
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());
return code;
}
/* public static void main(String[] args) throws ClientException, InterruptedException {
setNewcode();
String code = Integer.toString(getNewcode());
System.out.println("发送的验证码为:"+code);
//发短信
SendSmsResponse response =sendSms("13955410398",code); // TODO 填写你需要测试的手机号码
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());
*/
/* 不删 留着 以后可能有用
System.out.println(" ============================================== ");
Thread.sleep(3000L);
//查明细
if(response.getCode() != null && response.getCode().equals("OK")) {
QuerySendDetailsResponse querySendDetailsResponse = querySendDetails(response.getBizId());
System.out.println("短信明细查询接口返回数据----------------");
System.out.println("Code=" + querySendDetailsResponse.getCode());
System.out.println("Message=" + querySendDetailsResponse.getMessage());
int i = 0;
for(QuerySendDetailsResponse.SmsSendDetailDTO smsSendDetailDTO : querySendDetailsResponse.getSmsSendDetailDTOs())
{
System.out.println("SmsSendDetailDTO["+i+"]:");
System.out.println("Content=" + smsSendDetailDTO.getContent());
System.out.println("ErrCode=" + smsSendDetailDTO.getErrCode());
System.out.println("OutId=" + smsSendDetailDTO.getOutId());
System.out.println("PhoneNum=" + smsSendDetailDTO.getPhoneNum());
System.out.println("ReceiveDate=" + smsSendDetailDTO.getReceiveDate());
System.out.println("SendDate=" + smsSendDetailDTO.getSendDate());
System.out.println("SendStatus=" + smsSendDetailDTO.getSendStatus());
System.out.println("Template=" + smsSendDetailDTO.getTemplateCode());
}
System.out.println("TotalCount=" + querySendDetailsResponse.getTotalCount());
System.out.println("RequestId=" + querySendDetailsResponse.getRequestId());
}*/
}
前端页面
前端注册我用的模态框做的 附代码
<!-- //注册-->
<div class="modal-body regist-show" >
<form class="form-horizontal" role="form">
<div class="form-group">
<span class="col-sm-2 phone-icon"></span>
<div class="col-sm-10">
<input type="text" class="form-control phone-num" id="firstname phone-num" placeholder="请输入手机号码">
</div>
</div>
<div class="form-group">
<span class="col-sm-2 code-icon"></span>
<div class="col-sm-10">
<input type="text" class="form-control phone-code" id="lastname phone-code" placeholder="请输入手机收到的验证码">
<input type="button" value="获取验证码" class="get-code" id="get-code">
</div>
</div>
<div class="form-group">
<span class="col-sm-2 pw-icon" ></span>
<div class="col-sm-10 ">
<input type="password" class="form-control password" id="password" placeholder="密码为6-18个字符">
</div>
</div>
Ajax向服务器传数据
/**
* 获取验证码
*/
var get_code = document.querySelector("#get-code");//获取验证码按钮
var phone_num = document.querySelector(".phone-num");//注册时候手机号
get_code.onclick = function () {
console.log(phone_num.value);
if (phone_num_verification() == true){
$.ajax({
url: "/btdev/user/getCode",
type: "POST",
data:{
"telno": phone_num.value //将手机号传到服务器
},
datatype: "json",
success:function (result) { //result后台返回的数据
if(result.code==1){
console.log("可以注册");
sms=result.data;
console.log(sms);
}else{
console.log("该手机号已经被注册,请直接登录");
console.log(result.data);
validation_tip.innerText = result.data;
}
}
})
}
};
Java处理收到的手机号
@PostMapping("user/getCode")
public JsonResult getCode(long telno){
AliyunSmsUtils aliyunSmsUtils = new AliyunSmsUtils();
JsonResult jsonResult = userService.getByTelno(telno);
System.out.println(jsonResult);
if (jsonResult.getCode()==1){ //判断用户是否存在 1代表没用查到
return new JsonResult(1,"没查到,可直接注册", AliyunSmsUtils.getTelnoCode(telno));
} else {
return new JsonResult(0,"用户已注册 可直接登录","该手机号已经被注册,请直接登录");
}
}
userService.getByTelno方法
//判断手机号是否已经注册
public JsonResult getByTelno(Long userTelno) {
User user = null;
UserExample example = new UserExample();
UserExample.Criteria criteria = example.createCriteria();
criteria.andUsersTelnoEqualTo(userTelno);
criteria.andStatusEqualTo(0);
List<User> users = userMapper.selectByExample(example);
if (users.size()!=0){
user = users.get(0);
return new JsonResult(0,"查询到该用户,手机号已注册",user);
}else{
return new JsonResult(1,"没有查询到该手机用户 可以注册",user);
}
}
JsonResult类(自定义的一种json格式)
package com.baitiao.util;
public class JsonResult {
/**
* 0 成功,1 失败
*/
private int code;
private String message;
private Object data;
public JsonResult(){}
public JsonResult(int code, String message, Object data) {
this.code = code;
this.message = message;
this.data = data;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
@Override
public String toString() {
return "JsonResult{" +
"code=" + code +
", message='" + message + '\'' +
", data=" + data +
'}';
}
}
进行验证注册 注意:我是在前端验证发送的验证码与用户输入是否一致,这是不安全的,可以通过转包获取。实际开发中需要在后端判断发送的验证码与用户输入是否一致
/**
* 单击注册按钮后的操作
*/
var phone_code = document.querySelector(".phone-code");//输入验证码得值
regist_mit.onclick = function () {
password_verification();
console.log(sms);
console.log(phone_code.value);
console.log(phone_num.value);
console.log(pw.value);
if (phone_code.value==""){
validation_tip.innerText = "验证码不能为空"
} else {
if (password_verification()== true && (sms==phone_code.value) ) {//password_verification()是自己写的一个密码格式验证的方法,
$.ajax({
url:"/btdev/user/regist",
type:"POST",
data:{
"telno" :phone_num.value,//将数据传输到服务器
"pw":pw.value
},
datatyep:"json",
success:function (result) {
console.log("kk");
console.log(sms);
console.log(result.code);
console.log(result.data);
if (result.code==0){
layer.msg("注册成功,正在前往登录界面",{icon:1,time:1500,offset: '300px',shade: 0.3},function(){ //layui的提示框 大家可以用用很方便
regist_show.style.display = "none";
login_show.style.display = "block";
login.style.borderBottom = "2px solid #b9def0"
regist.style.borderBottom = "none";
/* motai.style.display = "none";*/
welcome.innerHTML = "欢迎您、";
username.innerHTML = result.data;
});
}
}
})
}else {
validation_tip.innerText = "验证码输入错误,请重新输入"
}
}
};
算了,我把完整的js代码贴上吧
window.onload=function () {
console.log("引用");
//模态顶部登陆注册
var regist = document.querySelector(".regist-btn");
var login = document.querySelector('.login-btn');
//登陆注册模态框主体
var regist_show = document.querySelector(".regist-show");
var login_show = document.querySelector(".login-show");
var phone_num = document.querySelector(".phone-num");//注册时候手机号
var login_phone_num = document.querySelector(".login-phone-num");//登陆时号码
var login_password = document.querySelector("#login-password");
var get_code = document.querySelector("#get-code");//获取验证码按钮
var pw = document.querySelector("#password");
var validation_tip = document.querySelector(".validation_tip");
var loging_tip = document.querySelector(".login-tips");//登陆的提示
var regist_mit = document.querySelector(".regist-mit"); //注册按钮
var login_mit = document.querySelector(".login-mit"); //登陆按钮按钮
var welcome = document.querySelector(".welcome"); //欢迎你
var username = document.querySelector(".username");
var motai = document.querySelector("#register") //获取模态框
var phone_code = document.querySelector(".phone-code");//输入验证码得值
var sms="";
var logout = document.querySelector("#logout");
/**
* 单击登陆按钮后的操作
*/
login_mit.onclick = function () {
console.log(login_phone_num.value);
console.log(login_password.value);
if (login_phone_num_verification()==true && login_password_verification()== true) {
console.log(44);
$.ajax({
url: "/btdev/user/login",
type : "post",
data:{
"telno" :login_phone_num.value,//将数据传输到服务器
"pw":login_password.value
},
datatype:"json",
success:function (result) {
console.log(result.code);
if (result.code== 0 ) {
layer.msg("登录成功",{icon:1,time:1500,offset: '300px',shade: 0.3},function(){
console.log(result);
welcome.innerHTML = "欢迎您";
username.innerHTML = result.data.usersTelno;
/* motai.style.display = "none";*/
show_motai()
});
}else {
loging_tip.innerText = "没有账号 立即注册?";
}
}
})
}
};
/**
* 登陆与注册界面切换
*/
login.onclick = function () {
/* window.location.href="http://192.168.2.101:8081/btsy/user/login.html";*/
console.log("login");
regist_show.style.display = "none";
login_show.style.display = "block";
login.style.borderBottom = "2px solid #b9def0"
regist.style.borderBottom = "none";
};
/**
* 登陆与注册界面切换
*/
regist.onclick = function () {
console.log("regist");
regist_show.style.display = "block";
login_show.style.display = "none";
regist.style.borderBottom = "2px solid #b9def0";
login.style.borderBottom = "none"
};
/**
* 获取验证码
*/
get_code.onclick = function () {
console.log(phone_num.value);
if (phone_num_verification() == true){
$.ajax({
url: "/btdev/user/getCode",
type: "POST",
data:{
"telno": phone_num.value
},
datatype: "json",
success:function (result) {
if(result.code==1){
console.log("可以注册");
sms=result.data;
console.log(sms);
}else{
console.log("该手机号已经被注册,请直接登录");
console.log(result.data);
validation_tip.innerText = result.data;
}
}
})
}
};
/**
* 单击注册按钮后的操作
*/
regist_mit.onclick = function () {
password_verification();
console.log(sms);
console.log(phone_code.value);
console.log(phone_num.value);
console.log(pw.value);
if (phone_code.value==""){
validation_tip.innerText = "验证码不能为空"
} else {
if (password_verification()== true && (sms==phone_code.value) ) {
$.ajax({
url:"/btdev/user/regist",
type:"POST",
data:{
"telno" :phone_num.value,//将数据传输到服务器
"pw":pw.value
},
datatyep:"json",
success:function (result) {
console.log("kk");
console.log(sms);
console.log(result.code);
console.log(result.data);
if (result.code==0){
layer.msg("注册成功,正在前往登录界面",{icon:1,time:1500,offset: '300px',shade: 0.3},function(){
regist_show.style.display = "none";
login_show.style.display = "block";
login.style.borderBottom = "2px solid #b9def0"
regist.style.borderBottom = "none";
/* motai.style.display = "none";*/
welcome.innerHTML = "欢迎您、";
username.innerHTML = result.data;
});
}
}
})
}else {
validation_tip.innerText = "验证码输入错误,请重新输入"
}
}
};
/**
* 注册时手机号验证函数
* @returns {boolean}
*/
function phone_num_verification() {
var flag = false;
if (!/^[1][3,4,5,7,8][0-9]{9}$/.test(phone_num.value)) {
validation_tip.innerText = "请输入正确的手机号码";
} else {
validation_tip.innerText = "";
flag = true;
}
return flag;
};
/**
* 登陆时手机号验证函数
* @returns {boolean}
*/
function login_phone_num_verification() {
var flag = false;
if (!/^[1][3,4,5,7,8][0-9]{9}$/.test(login_phone_num.value)) {
loging_tip.innerText = "请输入正确的手机号码";
} else {
loging_tip.innerText = "";
flag = true;
}
return flag;
}
/**
* 注册时候密码验证
* @returns {boolean}
*/
function password_verification() {
var flag = false;
if (!/^[a-zA-Z]\w{5,17}$/.test(pw.value)) {
validation_tip.innerText = "密码长度在6~18之间,只能包含字符、数字和下划线";
} else {
validation_tip.innerText = "";
flag = true;
}
return flag;
};
/**
* 登陆时候密码验证
* @returns {boolean}
*/
function login_password_verification() {
var flag = false;
if (!/^[a-zA-Z]\w{5,17}$/.test(login_password.value)) {
loging_tip.innerText = "密码长度在6~18之间,只能包含字符、数字和下划线";
} else {
loging_tip.innerText = "";
flag = true;
}
return flag;
}
/**
* 让模态框内容消失
*/
function show_motai() {
console.log(222);
$("#register").modal('hide');//隐藏modal
/* motai.modal('hide');//隐藏modal*/
$('.modal-backdrop').remove();//去掉遮罩层
console.log("模态框消失");
}
/* /!**
* 单击退出按钮
*!/
$("#logout").click(function () {
//获取当前页面连接
var route = window.location.href;
console.log(route);
console.log("退出");
$.ajax({
url:"/btdev/user/logout",
type:"POST",
data:"",
datatype:"JSON",
success:function (data) {
window.location.replace(route)
}
})
})*/
}
整个过程就是 前端通过ajax把手机号传到服务器,服务器首先要判断手机号是否已经注册,如果没注册就通过调用 AliyunSmsUtils.getTelnoCode(telno)方法将得到的验证码返回前端。前端通过判断用户输入的验证码和服务器返回的验证码是否一致
整个过程就是 前端通过ajax把手机号传到服务器,服务器首先要判断手机号是否已经注册,如果没注册就通过调用 AliyunSmsUtils.getTelnoCode(telno)方法将得到的验证码返回前端。前端通过判断用户输入的验证码和服务器返回的验证码是否一致