需要的maven依赖
<!-- 升级版 SDK这是一个短信 -->
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>dysmsapi20170525</artifactId>
<version>2.0.23</version>
</dependency>
package com.service.thereService;
import com.Common.constants.Constants;
import com.Common.exception.BaseException;
import com.Common.result.ResultEnum;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
/**
* @Author 陈厚德
* @Version 2.2
*/
@Service
public class AliYunService {
private static final Logger log = LoggerFactory.getLogger(AliYunService.class);
/**
* 阿里云发送短信
* @param phone 手机号
* @param code 需要发送的验证码
* @return
*/
public boolean sendSms(String phone ,String code){
//初始化client
Config config = new Config();
config.setAccessKeyId("你的密钥");
config.setAccessKeySecret("你的密钥");
//准备request请求体
config.endpoint="dysmsapi.aliyuncs.com";
try {
Client client= new Client(config);
SendSmsRequest sendSmsRequest= new SendSmsRequest();
sendSmsRequest.setPhoneNumbers(phone)
.setSignName("阿里云短信测试")
.setTemplateCode("SMS_154950909")
.setTemplateParam("{\"code\":"+code+"}");
//执行发送 --通过client发送
SendSmsResponse response= client.sendSms(sendSmsRequest);
log.info("短信响应体为{}", response.getBody().toString());
if (response.getBody().code.equals(Constants.Sms.ALI_SMS_RESULT)){
return true;
}
return false;
} catch (Exception e) {
log.error("短信发送失败:{}",e.getMessage());
throw new BaseException(ResultEnum.SMS_SENDING_ERROR);
}
}
}