1. 登录阿里云进入控制台
进入阿里云控制台,home.console.aliyun.com/在个人头像位置点击进入AccessKey管理:
2. 创建用户和用户组
创建用户组
添加完成后进入用户组,并为其添加权限:
创建用户
注意:用户创建完成后,将其添加到用户组中,点击进入该用户,在认证管理下方会有该用户对应的AccessKeyId和AccessKeySecret!要将其保存下来,不然忘记后,还得删除用户,重新创建,在之后使用代码整合短信业务时候需要用到!
3. 开通阿里云短信服务
阿里云短信服务地址:dysms.console.aliyun.com/dysms.htm
在概览中直接点击立即开通短信服务!接下来点击快速学习:
点击添加签名,添加模板,去向阿里云申请自己定义的签名和短信模板!
模板和签名申请提交后等待申请结果通过即可!
注意:由于阿里云通信短信服务审核管理规则升级,12月17日以后,个人身份申请审核短信签名更加严格了
这里我审核用的是自己的公众号名称作为SMS短信签名,去申请的!
4. 代码整合阿里云SMS短信服务
官方SDK文档:help.aliyun.com/document_de…
官方APIDemo:api.aliyun.com/new#/?produ…
4.1 pom.xml 中引入SDK依赖
Spring Boot版本我使用的是2.3.x:
<!-- aliyun sms SDK -->
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
<version>4.5.3</version>
</dependency>
<!-- fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.68</version>
</dependency>
<!-- redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
4.2 测试官方提供的实例Demo
@SpringBootTest
class AliyunSmsDemoApplicationTests {
@Test
void contextLoads() {
/**
* 连接阿里云:
*
* 三个参数:
* regionId 不要动,默认使用官方的
* accessKeyId 自己的用户accessKeyId
* accessSecret 自己的用户accessSecret
*/
DefaultProfile profile = DefaultProfile.getProfile(
"cn-hangzhou", "LTAI4GKDZbrcaESV1fBV8V9B", "1bc8phOIbAbfvMXSWFt2AlLctBMMCI");
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("PhoneNumbers", "xxxxx0440");// 接收短信的手机号
request.putQueryParameter("SignName", "CSP网上商城");// 短信签名
request.putQueryParameter("TemplateCode", "SMS_20xxxxx74");// 短信模版CODE
// 构建短信验证码
Map<String,Object> map = new HashMap<>();
map.put("code",1234);// 这里仅用于测试,所以验证码写死
request.putQueryParameter("TemplateParam", JSONObject.toJSONString(map));
try {
CommonResponse response = client.getCommonResponse(request);
System.out.println(response.getData());
} catch (ServerException e) {
e.printStackTrace();
} catch (ClientException e) {
e.printStackTrace();
}
}
}
执行发送测试,结果如下图:
4.3 构建短信发送微服务
4.3.1 service
/**
* @Auther: csp1999
* @Date: 2020/12/18/12:08
* @Description: 阿里云SMS短信服务Service
*/
@Service
public class AliyunSendSmsService {
@Value("${aliyun.sms.accessKeyId}")
private String accessKeyId;
@Value("${aliyun.sms.accessKeySecret}")
private String accessKeySecret;
/**
* 发送短信验证码
*
* @param phone 接收短信的手机号
* @param templateCode 短信模板CODE
* @param codeMap 验证码map 集合
* @return
*/
public Boolean sendMessage(String phone, String templateCode, Map<String, Object> codeMap) {
/**
* 连接阿里云:
*
* 三个参数:
* regionId 不要动,默认使用官方的
* accessKeyId 自己的用户accessKeyId
* accessSecret 自己的用户accessSecret
*/
DefaultProfile profile = DefaultProfile.getProfile(
"cn-hangzhou", accessKeyId, accessKeySecret);
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("PhoneNumbers", phone);// 手机号
request.putQueryParameter("SignName", "CSP网上商城");// 短信签名
request.putQueryParameter("TemplateCode", templateCode);// 短信模版CODE
// 构建短信验证码
request.putQueryParameter("TemplateParam", JSONObject.toJSONString(codeMap));
try {
CommonResponse response = client.getCommonResponse(request);
System.out.println(response.getData());
return response.getHttpResponse().isSuccess();
} catch (ServerException e) {
e.printStackTrace();
} catch (ClientException e) {
e.printStackTrace();
}
return false;
}
}
4.3.2 controller
/**
* @Auther: csp1999
* @Date: 2020/12/18/12:21
* @Description: 阿里云SMS短信发送API
*/
@RestController
public class AliyunSmsApiController {
@Autowired
private AliyunSendSmsService aliyunSendSmsService;
@Autowired
private RedisTemplate<String, String> redisTemplate;
@Value("${aliyun.sms.templateCode}")
private String templateCode;
/**
* 短信发送
*
* @param phone
* @return
*/
@GetMapping("/send/{phone}")
public String sendCode(@PathVariable("phone") String phone) {
// 根据手机号从redis中拿验证码
String code = redisTemplate.opsForValue().get(phone);
if (!StringUtils.isEmpty(code)) {
return phone + " : " + code + "已经存在,还没有过期!";
}
// 如果redis 中根据手机号拿不到验证码,则生成4位随机验证码
code = UUID.randomUUID().toString().substring(0, 4);
// 验证码存入codeMap
Map<String, Object> codeMap = new HashMap<>();
codeMap.put("code", code);
// 调用aliyunSendSmsService发送短信
Boolean bool = aliyunSendSmsService.sendMessage(phone, templateCode, codeMap);
if (bool) {
// 如果发送成功,则将生成的4位随机验证码存入redis缓存,5分钟后过期
redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
return phone + " : " + code + "发送成功!";
} else {
return phone + " : " + code + "发送失败!";
}
}
}
4.3.3 application.yml
server:
port: 8080
# spring相关配置
spring:
redis:
# Redis数据库索引(默认为0)
database: 0
# Redis服务器地址
host: 8.xxx.xx.xx6
# Redis服务器连接端口
port: 6379
# Redis服务器连接密码(默认为空)
password: cspxxxxxxx
jedis:
pool:
# 连接池最大连接数(使用负值表示没有限制)
max-active: 8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
max-wait: -1
# 连接池中的最大空闲连接
max-idle: 8
# 连接池中的最小空闲连接
min-idle: 0
# 连接超时时间(毫秒)
timeout: 8000
4.3.4 application.properties
# accessKeyId
aliyun.sms.accessKeyId=LTAI4xxxxxxxxxxV9B
# accessKeySecret
aliyun.sms.accessKeySecret=LTAI4xxxxxxxxxxV8V9B
# 短信模板Code
aliyun.sms.templateCode=SMS_xxxxx74
4.4 启动项目测试发送
手机收到短信验证码!
5. Demo地址
Demo案例源码参考:gitee.com/caoshipeng/…
- 如果对大家有帮助,请三连支持一下!
- 有问题欢迎评论区留言,及时帮大家解决!