SpringBoot集成阿里云短信的实战指南
作者:悟空码字
在SpringBoot项目中集成阿里云短信服务,核心是完成一系列前置申请,并调用其官方SDK发送短信,下面小编就和大家详细介绍一下具体的实现方法吧
在SpringBoot项目中集成阿里云短信服务,核心是完成一系列前置申请,并调用其官方SDK发送短信。整个流程从前置准备到代码集成,步骤清晰。
阿里云短信服务概述
阿里云短信服务提供高并发、安全的全球短信发送能力,支持验证码、通知、营销等场景。其主要特点如下:
| 特性维度 | 具体说明 |
|---|---|
| 核心能力 | 提供三网合一通道,秒级可达,支持国内及全球200多个国家/地区。 |
| 安全与管控 | 基于阿里云账户与RAM权限管理,支持设置日发送量上限、单用户频次阈值,并具备验证码防盗刷监控。 |
| 计费模式 | 采用短信套餐包优先抵扣,超出后按量计费的模式。国内验证码/通知短信低至0.045元/条起。 |
| 使用限制 | 仅支持企业认证账号;发送前需完成资质、签名、模板的申请与审核;对发送频率有严格限制(例如验证码同一号码最多1条/分钟)。 |
集成前必须完成的控制台配置
编写代码前,你必须在阿里云控制台 完成一系列配置,这是短信发送的前提。
1.开通服务与购买资源包
- 完成企业实名认证并登录短信服务控制台开通服务。
- 根据业务需要(国内或国际)购买短信套餐包。
2.创建AccessKey
- 为安全起见,建议为应用创建RAM子用户并授权
AliyunDysmsFullAccess策略。 - 为该子用户创建AccessKey(AccessKey ID和AccessKey Secret),后续代码将使用它调用API。切勿直接使用主账号的AccessKey。
3.申请短信签名与模板
- 签名:在“国内消息”或“国际/港澳台消息”菜单下申请。签名是显示在短信开头的标识,如
【企业名称】,用于标识发送方。审核通常需2小时。 - 模板:短信内容模板,支持变量。例如验证码模板:“您的验证码为:$[code],5分钟内有效。”模板审核同样约需2小时。
- 重要提示:签名和模板均审核通过后方可使用。国内签名还需完成运营商实名报备(需7-15个工作日),报备成功前发送可能失败。
SpringBoot项目集成详细步骤
完成控制台配置后,即可在SpringBoot项目中集成。
第1步:添加Maven依赖 在项目的pom.xml中添加阿里云短信服务SDK的依赖。
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>dysmsapi20180501</artifactId>
<version>2.0.24</version> <!-- 请使用Maven仓库中的最新版本 -->
</dependency>
第2步:配置应用参数 在application.yml或application.properties中配置必要的参数。
# application.yml 配置示例
aliyun:
sms:
# 从控制台获取的AccessKey信息
access-key-id: your-access-key-id
access-key-secret: your-access-key-secret
# 短信服务接入点(Endpoint),国内一般为 dysmsapi.aliyuncs.com
endpoint: dysmsapi.aliyuncs.com
# 控制台申请并通过审核的签名名称(无需加【】)
sign-name: 你的签名
# 控制台申请并通过审核的模板CODE
template-code: SMS_123456789
第3步:创建配置类与Service 创建一个配置类来初始化SDK客户端,并编写发送短信的服务类。
import com.aliyun.dysmsapi20180501.Client;
import com.aliyun.teaopenapi.models.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
@Configuration
public class AliyunSmsConfig {
@Value("${aliyun.sms.access-key-id}")
private String accessKeyId;
@Value("${aliyun.sms.access-key-secret}")
private String accessKeySecret;
@Value("${aliyun.sms.endpoint}")
private String endpoint;
/**
* 创建并返回阿里云短信服务的Client实例。
* 该Bean可用于整个Spring容器。
*/
@Bean
public Client createClient() throws Exception {
Config config = new Config()
.setAccessKeyId(accessKeyId)
.setAccessKeySecret(accessKeySecret);
config.endpoint = endpoint;
return new Client(config);
}
}
import com.aliyun.dysmsapi20180501.Client;
import com.aliyun.dysmsapi20180501.models.SendMessageWithTemplateRequest;
import com.aliyun.dysmsapi20180501.models.SendMessageWithTemplateResponse;
import com.aliyun.teautil.models.RuntimeOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
@Service
public class SmsService {
@Autowired
private Client smsClient;
@Value("${aliyun.sms.sign-name}")
private String signName;
@Value("${aliyun.sms.template-code}")
private String templateCode;
/**
* 发送短信验证码
* @param phoneNumber 目标手机号(国内号码需带国际区号86)
* @param templateParam 模板变量对应的JSON字符串,如:{"code":"123456"}
* @return 是否发送成功
*/
public boolean sendSms(String phoneNumber, String templateParam) {
try {
SendMessageWithTemplateRequest request = new SendMessageWithTemplateRequest()
.setTo(phoneNumber) // 接收方手机号
.setSignName(signName) // 短信签名
.setTemplateCode(templateCode) // 短信模板CODE
.setTemplateParam(templateParam); // 模板变量JSON
RuntimeOptions runtime = new RuntimeOptions();
SendMessageWithTemplateResponse response = smsClient.sendMessageWithTemplateWithOptions(request, runtime);
// 根据响应判断是否成功,"OK"表示成功[citation:4]
return "OK".equals(response.getBody().getResponseCode());
} catch (Exception e) {
// 此处应记录日志,并根据业务需要进行异常处理
e.printStackTrace();
return false;
}
}
}
第4步:在Controller中调用 创建一个简单的控制器来提供发送短信的HTTP接口。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class SmsController {
@Autowired
private SmsService smsService;
@GetMapping("/sendCode")
public String sendVerificationCode(@RequestParam String phone) {
// 生成随机验证码(示例)
String code = String.valueOf((int)((Math.random() * 9 + 1) * 100000));
// 构造模板参数(必须与申请模板时的变量名一致)
String templateParam = "{\"code\":\"" + code + "\"}";
boolean isSuccess = smsService.sendSms(phone, templateParam);
if (isSuccess) {
// 在实际业务中,此处应将验证码与手机号关联并存入缓存(如Redis),设置有效期
return "验证码发送成功!";
} else {
return "验证码发送失败,请稍后重试。";
}
}
}
总结
按照上述步骤,即可在SpringBoot项目中集成阿里云短信。最后,有几个关键点需要注意:
- 资质与审核是关键前提:务必确保使用企业认证账号,并提前完成签名、模板的申请和审核。国内签名还需要等待运营商报备成功,否则发送会失败。
- 安全第一:AccessKey相当于账号密码,务必通过环境变量或配置服务器管理,切忌硬编码在代码中提交至版本库。
- 关注限制与成本:严格遵守发送频率限制(如1条/分钟/号)。发送测试短信也会产生费用,请注意账户余额。
- 生产环境建议:应考虑异步发送、失败重试、发送状态回执(SmsReport)接收等机制以提升稳定性和可靠性。
到此这篇关于SpringBoot集成阿里云短信的实战指南的文章就介绍到这了,更多相关SpringBoot集成阿里云短信内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
