一、阿里云短信服务条件
1.阿里云帐号开通短信服务
2.申请短信签名signName和模版templateCode,并通过。模版中的code不要变
添加短信签名(个人开发者建议选择验证码,通用的话需要补充企业信息),添加短信模版(推荐使用推荐模版,审核快一点)
3.设置accessKeyId和Secret,且确保账户有钱或者可以考虑购买短信套餐
二、代码开始
1.创建Springboot项目hello-rabbit,导入核心依赖,官方依赖(尽量最新版)
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.2.RELEASE</version>
<relativePath/>
</parent>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 阿里云短信 SDK for Java -->
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
<version>4.4.6</version>
</dependency>
2.application.yml配置
alisms:
accessKeyId: AccessKey管理里的accessKeyId
accessSecret: AccessKey管理里的Secret
signName: 短信签名名称
templateCode: 模版code
3.修改官方demo进行封装,SendSmsUtil.java
package com.basic.hellorabbit.util;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.Map;
/**
* @Description: 短信发送工具
* @Author: Joe
* @CreateDate: 2020/3/21 15:49
*/
@Service
public class SendSmsUtil {
@Value("${alisms.accessKeyId}")
private String accessKeyId;
@Value("${alisms.accessSecret}")
private String accessSecret;
@Value("${alisms.signName}")
private String signName;
@Value("${alisms.templateCode}")
private String templateCode;
public String aliSendSms(String PhoneNumbers,String TemplateParam){
String result = "";
DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessSecret);
IAcsClient client = new DefaultAcsClient(profile);
CommonRequest request = new CommonRequest();
request.setSysMethod(MethodType.POST);
request.setSysDomain("dysmsapi.aliyuncs.com");
request.setSysVersion("2017-05-25");
request.setSysAction("SendSms");
request.putQueryParameter("RegionId", "cn-hangzhou");
request.putQueryParameter("PhoneNumbers", PhoneNumbers);
request.putQueryParameter("SignName", signName);
request.putQueryParameter("TemplateCode", templateCode);
request.putQueryParameter("TemplateParam", TemplateParam);
try {
CommonResponse response = client.getCommonResponse(request);
System.out.println(response.getData());
String infojson = response.getData();
Gson gson2 = new Gson();
Map map = gson2.fromJson(infojson, Map.class);
String codes = map.get("Message").toString();
System.out.println("codes="+codes);
if(codes.equals("OK")){
result="ok";
}else {
result="not_ok";
}
} catch (ServerException e) {
e.printStackTrace();
} catch (ClientException e) {
e.printStackTrace();
}
System.out.println("result="+result);
return result;
}
}
4.在resources/templates下新建sms.html进行测试
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>短信测试页面</title>
</head>
<body>
<h3>短信验证码发送</h3>
<br>
<br>
<br>
<a href="/sendSms/手机号码">阿里云短信发送</a>
<hr>
<h3>短信验证</h3>
<form method="post" action="/yanSms">
<p>
手机号码:<input type="text" name="PhoneNumbers"/>
</p>
<p>
验证码:<input type="text" name="code"/>
</p>
<p>
<input type="submit" value="开始验证"/>
</p>
</form>
</body>
</html>
5.使用SmsController.java进行发送和验证
package com.basic.hellorabbit.controller;
import com.basic.hellorabbit.util.SendSmsUtil;
import com.basic.hellorabbit.util.VerificationCode;
import com.google.gson.Gson;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
/**
* @Description: 短信
* @Author: Joe
* @CreateDate: 2020/3/21 16:31
*/
@Controller
public class SmsController {
@Autowired
private SendSmsUtil sendSmsUtil;
@Data
public static class SmsData{
String code;
public SmsData(String code) {
this.code = code;
}
}
/**
* 跳转到短信测试页面
* @return
*/
@RequestMapping(value = "/toSms",method = RequestMethod.GET)
public String toSms(){
return "sms";
}
/**
* 发送验证码
* @param PhoneNumbers 手机号
* @return
*/
@ResponseBody
@RequestMapping(value = "/sendSms/{PhoneNumbers}",method = RequestMethod.GET)
public String sendSms(@PathVariable String PhoneNumbers, HttpServletRequest request){
HttpSession session = request.getSession();
//随机生成验证码
String numeral = VerificationCode.getNumeral();
SmsData smsData = new SmsData(numeral);
Gson gson = new Gson();
String code = gson.toJson(smsData);
String information = sendSmsUtil.aliSendSms(PhoneNumbers, code);
session.setAttribute(PhoneNumbers,numeral);
session.setMaxInactiveInterval(3 * 60);
if(information.equals("ok")){
return "成功发送给"+PhoneNumbers+";验证码是"+numeral;
}
return "失败了"+PhoneNumbers;
}
/**
* 验证
* @param PhoneNumbers
* @param code
* @param request
* @return
*/
@ResponseBody
@RequestMapping(value = "/yanSms",method = RequestMethod.POST)
public String yanSms(String PhoneNumbers, String code,HttpServletRequest request){
HttpSession session = request.getSession();
String ycode = (String) session.getAttribute(PhoneNumbers);
if(ycode.equals(code)){
return PhoneNumbers+"验证成功";
}
return PhoneNumbers+"验证失败";
}
}
6.生成随机验证码工具类VerificationCode.java:java实现随机生成验证码工具类
代码初步测试通过,至于其中涉及到的手机号码校验等在此忽略