要用到
accessKeyId
accessKeySecret
你的短信签名
你的短信模板
pom.xml依赖
<!-- 阿里云短信验证码 核心 -->
<!-- https://mvnrepository.com/artifact/com.aliyun/aliyun-java-sdk-core -->
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
<version>3.5.0</version>
</dependency>
<!-- 阿里云短信验证码 -->
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-dysmsapi</artifactId>
<version>1.0.0</version>
</dependency>
html页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no" id="viewport" name="viewport">
<title></title>
<style type="text/css">
body,div{
padding: 0;
margin: 0;
}
.wraper{
padding: 100px;
}
.phone{
width: 220px;
height: 40px;
box-sizing: border-box;
outline: none;
padding: 0 10px;
}
.getverify-code-btn{
display: inline-block;
width: 140px;
height: 40px;
line-height: 40px;
text-align: center;
background-color: blue;
border: 1px solid #ccc;
box-sizing: border-box;
vertical-align: middle;
cursor: pointer;
color: #fff;
}
.getverify-code-btn.unabled{
background-color: lightblue;
color: #eee;
cursor: default;
}
</style>
<script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"></script>
<!-- <link rel="shortcut icon" href="#" />-->
<script type="text/javascript">
var countdown=60;
function settime() {
var obj=document.getElementById("btn");
if (countdown == 0) {
obj.removeAttribute("disabled");
obj.value="免费获取验证码";
countdown = 60;
return;
} else {
obj.setAttribute("disabled", true);
obj.value="重新发送(" + countdown + ")";
countdown--;
}
setTimeout(function() {
settime(obj) }
,1000)
}
function sendInfo(){
var phoneReg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/,
flag = phoneReg.test($("#phone").val());
if(!flag){
alert("电话号码填写不正确!");
return false;
}
settime();//倒计时
yzm(); //console.log(2);//生成验证码 并存储
}
function yzm(){
// alert(JSON.stringify($("#phone").val()));
$.ajax({
url: "/dxyanz1",
type:'post',
data:{
phone:$("#phone").val(),
},
dataType: 'json',
success:function (result) {
alert(result)
}
})
}
</script>
</head>
<body>
<form action="/dxyanz2" method="post">
<div class="wraper">
<h1>获取手机验证码</h1>
手机号:<input type="text" id="phone" name="phone" class="phone">
<input type="button" id="btn" class="getverify-code-btn" value="免费获取验证码" onclick="sendInfo()" ><br>
验证码:<input type="text" class="phone" name="yzm" id="yzm"/><br>
<input name="sub" type="submit" value="提交">
</div>
</form>
</body>
</html>
util工具包
package com.jwt.demo.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.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
/**
* @Auther: 小宇不吃饭
* @Date: 2020/12/16 10:49
* @Description: 短信验证码测试
*/
public class DXutil {
// 产品名称:API产品,开发者无需替换
static final String product = "Dysmsapi";
// 产品域名,开发者无需替换
static final String domain = "dysmsapi.aliyuncs.com";
// TODO 此处需要替换成开发者自己的AK(在阿里云访问控制台寻找)
static final String accessKeyId = "accessKeyId"; // TODO 改这里
static final String accessKeySecret = "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", "cn-hangzhou", product, domain);
IAcsClient acsClient = new DefaultAcsClient(profile);
// 组装请求对象-具体描述见控制台-文档部分内容
SendSmsRequest request = new SendSmsRequest();
// 必填:待发送手机号
request.setPhoneNumbers(telephone);
// 必填:短信签名-可在短信控制台中找到
request.setSignName("你的短信签名"); // TODO 改这里 ==你的短信签名
// 必填:短信模板-可在短信控制台中找到
request.setTemplateCode("你的短信模板"); // TODO 改这里===你的短信模板
// 可选:模板中的变量替换JSON串,如模板内容为"亲爱的用户,您的验证码为${code}"时,此处的值为
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;
}
//以下为测试代码,随机生成验证码
private static int newcode;
public static int getNewcode() {
return newcode;
}
public static void setNewcode(){
newcode = (int)(Math.random()*9999)+100; //每次调用生成一次四位数的随机数
}
}
controller层
package com.jwt.demo.controller;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Random;
import static com.jwt.demo.util.DXutil.*;
@Controller
public class Verification {
public static int Aa;
public static String Bb;
@RequestMapping("/dxyanz")
public String verification(){
return "yanz";
}
@PostMapping("/dxyanz1")
@ResponseBody
// public static void main(String[] args) throws Exception {
public void DXyz(HttpServletRequest request) throws Exception {
String phone = request.getParameter("phone");
System.out.println("11111111111111");
System.out.println(phone);
// String phone = "15194069931";
setNewcode();
//给全局变量赋值
Aa=getNewcode();
Bb=phone;
System.out.println(Aa);
// System.out.println(Bb);
String code = Integer.toString(getNewcode());//15762971759
SendSmsResponse sendSms =sendSms(phone,code);//填写你需要测试的手机号码
System.out.println("短信接口返回的数据----------------");
System.out.println("Code=" + sendSms.getCode());
System.out.println("Message=" + sendSms.getMessage());
System.out.println("RequestId=" + sendSms.getRequestId());
System.out.println("BizId=" + sendSms.getBizId());
// return getNewcode();
}
@PostMapping("/dxyanz2")
@ResponseBody
public String DXyz2(HttpServletRequest request) throws Exception{
String phone = request.getParameter("phone");
String yzm = request.getParameter("yzm");
if (phone==""){
System.out.println("手机号不能为空");
return "手机号不能为空";
}
if (yzm==""){
System.out.println("验证码不能为空");
return "验证码不能为空";
}
System.out.println(phone);
System.out.println(Bb);
System.out.println(yzm);
System.out.println(Aa);
//equals用的都是String类型的,所以需要先转换类型
String AA = ""+Aa;
if(phone.equals(Bb) && yzm.equals(AA)){
return "验证码对了,成功";
}else {
return "验证码不对,失败";
}
}
// @RequestMapping("/yanz1")
// @ResponseBody
// public String testRandom(){
// String msg="您的注册码为%s,谢谢注册!";
// System.out.println("Math.random得到小数");
// System.out.println(Math.round((Math.random()+1) * 1000));
// System.out.println("Random");
// System.out.println(new Random().nextInt(9999));
// System.out.println("字符串前面补0的话就这样String.format");
// System.out.println(String.format("%04d",new Random().nextInt(9999)));
// return msg;
// }
}