> 文档中心 > Springboot 实现阿里云发送短信

Springboot 实现阿里云发送短信

项目目录
Springboot 实现阿里云发送短信

一、导入依赖

<dependency><groupId>com.aliyun</groupId>    <artifactId>aliyun-java-sdk-core</artifactId>    <version>4.0.6</version></dependency><dependency>    <groupId>com.aliyun</groupId>    <artifactId>aliyun-java-sdk-dysmsapi</artifactId>    <version>1.1.0</version></dependency>

二、配置阿里云

在 resources 目录下新建配置文件 oss-conf.properties

# 阿里云配置# 配置自己的accessKeyIdaliyun.access-key-id=xxxx# 配置自己的accessKeySecretaliyun.access-key-secret=xxxx

三、添加配置类

添加配置类 AliYunProperties

@Data@ConfigurationProperties(prefix = "aliyun")@PropertySource(value = {"classpath:oss-conf.properties"}, encoding = "UTF-8")public class AliYunProperties {    private String accessKeyId;    private String accessKeySecret;}

四、激活配置类

新建配置类 EnableConfig

@Configuration@EnableConfigurationProperties({AliYunOssProperties.class, AliYunProperties.class})@EnableRetrypublic class EnableConfig {}

五、添加 AliYunSmsService

添加类 AliYunSmsService 和 AliYunSmsServiceImpl

public interface AliYunSmsService {    /     * 发送短信     * @param phone     * @return     * @throws Exception     */    Boolean sendSms(String phone);}
@Service@Slf4j@RequiredArgsConstructorpublic class AliYunSmsServiceImpl implements AliYunSmsService {    private final AliYunProperties aliYunProperties;    @Override    public Boolean sendSms(String phone) { // 短信API产品名称(无需修改) final String product = "Dysmsapi"; // 短信API产品域名(无需修改) final String domain = "dysmsapi.aliyuncs.com"; IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou",  aliYunProperties.getAccessKeyId(),  aliYunProperties.getAccessKeySecret()); DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain); IAcsClient acsClient = new DefaultAcsClient(profile); SendSmsRequest sendSmsRequest = getSendSmsRequest(phone); SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(sendSmsRequest); log.info("[发送短信]phone={}, result={}", phone, sendSmsResponse.getCode()); return sendSmsResponse.getCode() != null && "OK".equals(sendSmsResponse.getCode());    }    /     * 获取请求     * @param phone     * @return     */    private SendSmsRequest getSendSmsRequest(String phone) { SendSmsRequest request = new SendSmsRequest(); request.setMethod(MethodType.POST); // 多个手机号逗号分割 上限1000个 request.setPhoneNumbers(phone); // 短信签名(替换自己的签名) request.setSignName("连连商城"); // 短信模板(替换自己的模板) request.setTemplateCode("SMS_222860055"); request.setTemplateParam("{\"code\": \"" + getCode() + "\"}"); return request;    }    /     * 生成验证码     * @return     */    public String getCode() { Random random = new Random(); StringBuilder result = new StringBuilder(); for (int i = 0; i < 6; i++) {     result.append(random.nextInt(10)); } return result.toString();    }}

至此,就可以使用 AliYunSmsService 来发送短信了!!

六、测试

新建一个 Controller 来测试一下
Springboot 实现阿里云发送短信
使用 Postman 发送请求
Springboot 实现阿里云发送短信
发送成功
在这里插入图片描述
Springboot 实现阿里云发送短信