1、阿里云短息服务注册
阿里云官网:https://www.aliyun.com/
①进入短信服务
②免费开通
③选择国内消息–>签名管理–>添加签名
签名内容
④添加模版
⑤安全设置、发送频率设置
⑥账户充值
⑦AccessKey管理
2、Java代码引入
①导入依赖包
<dependencies>
<!--原版 SDK - 阿里云Java SDK核心库-->
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
<version>4.5.16</version>
</dependency>
<!--阿里 FastJSON,json格式转换-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.39</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
③测试工具类
/**
* 短信发送工具类
*/
public class SMSUtils {
/**
* 发送短信
* @param signName 签名
* @param templateCode 模板
* @param phoneNumbers 手机号
* @param param 参数
*/
public static void sendMessage(String signName, String templateCode,String phoneNumbers,String param){
DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "LTAI5tMfFL3veTQthSxpBWKd", "l38UcRzcPrXDlHEg0HhqUBH7HZSdc8");
IAcsClient client = new DefaultAcsClient(profile);
SendSmsRequest request = new SendSmsRequest();
request.setSysRegionId("cn-hangzhou");
request.setPhoneNumbers(phoneNumbers);
request.setSignName(signName);
request.setTemplateCode(templateCode);
request.setTemplateParam("{\"code\":\""+param+"\"}");
try {
SendSmsResponse response = client.getAcsResponse(request);
System.out.println("短信发送成功");
}catch (ClientException e) {
e.printStackTrace();
}
}
}
④测试
@PostMapping("/sendMsg")
public R<String> sendMsg(@RequestBody User user, HttpSession session){
//获取手机号
String phone=user.getPhone();
if(StringUtils.isNotEmpty(phone)){
//生成随机的6位验证码
String code= ValidateCodeUtils.generateValidateCode(6).toString();
log.info("code={}",code);
//调用阿里云提供的短信服务API完成发送短信
SMSUtils.sendMessage("好食餐饮","SMS_462585304",phone,code);
//需要将生成的验证码保存到Session
session.setAttribute(phone,code);
return R.success("手机验证码短信发送成功");
}
return R.error("短信发送失败");
}
标签:code,服务,String,boot,request,param,阿里,短信 From: https://www.cnblogs.com/xdqx/p/17643124.html