前提:
- 开通阿里云短信服务(www.aliyun.com/)。
- 创建短信签名和模板。
流程:
1) 引入依赖
<!-- Alibaba SMS -->
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>dysmsapi20170525</artifactId>
<version>2.0.24</version>
</dependency>
2)配置Aliyun Sms
aliyun:
sms:
AccessKeyId: ${aliyun.sms.key}
AccessKeySecret: ${aliyun.sms.secret}
Endpoint: ${aliyun.sms.endpoint}
TemplateCode: ${aliyun.sms.template}
SignName: ${aliyun.sms.sign}
3)编写工具类
@Component
public class AliyunSms {
@Value("${aliyun.sms.AccessKeyId}")
private String accessKeyId;
@Value("${aliyun.sms.AccessKeySecret}")
private String accessKeySecret;
@Value("${aliyun.sms.Endpoint}")
private String endpoint;
@Value("${aliyun.sms.SignName}")
private String signName;
@Value("${aliyun.sms.TemplateCode}")
private String templateCode;
private Client client;
public boolean sendSms(String phone, int code) throws Exception {
if (client == null) {
Config config = new Config()
.setAccessKeyId(accessKeyId)
.setAccessKeySecret(accessKeySecret)
.setEndpoint(endpoint);
try {
client = new Client(config);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
SendSmsRequest sendSmsRequest = new SendSmsRequest()
.setPhoneNumbers(phone)
.setSignName(signName)
.setTemplateCode(templateCode)
.setTemplateParam("{\"code\":\""+code+"\"}");
RuntimeOptions runtime = new RuntimeOptions();
try {
SendSmsResponse sendSmsResponse = client.sendSmsWithOptions(sendSmsRequest, runtime);
if (sendSmsResponse.statusCode == 200) {
return true;
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return false;
}
}
4)使用
@Slf4j
@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
public class UserController {
private final AliyunSms aliyunSms;
@PostMapping("/send-sms")
public void sendSms(String phone) {
Random random = new Random();
try {
if (aliyunSms.sendSms(phone, random.nextInt(9000) + 1000)) {
log.info("短信发送成功");
} else {
log.error("短信发送失败");
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}