阿里云短信验证服务配置

场景:

业务开发中,有时需要通过短信验证就行身份验证,此时可以调用阿里云的短信服务

步骤一:导入依赖和配置参数

<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>dysmsapi20170525</artifactId>
    <version>2.0.23</version>
</dependency>

//创建一个参数配置类

@Data
//从application.yml中找到对应的值,自动映射到配置类的属性中
@ConfigurationProperties(prefix = "aliyun.sms")
public class AliyunSMSProperties {

    private String accessKeyId;

    private String accessKeySecret;

    private String endpoint;
}

//在application.yml中添加

aliyun:
  sms:
    access-key-id: <自己的>
    access-key-secret: <自己的>
    endpoint: dysmsapi.aliyuncs.com

 步骤二:配置阿里云对象

@Configuration
//启用之前的参数配置类,使下面创建的配置类自带参数
@EnableConfigurationProperties(AliyunSMSProperties.class)
//此注解意为:只有当application.yml中参数不为空时,才会进行实例化
//如果此配置类只被当前包下的的启动类启动,则可不加
@ConditionalOnProperty(name = "aliyun.sms.endpoint")
public class AliyunSMSConfiguration {
    @Autowired
    private AliyunSMSProperties aliyunSMSProperties;
    @Bean
    public Client createClient(){
        Config config = new Config();
        config.setAccessKeyId(aliyunSMSProperties.getAccessKeyId());
        config.setAccessKeySecret(aliyunSMSProperties.getAccessKeySecret());
        config.setEndpoint(aliyunSMSProperties.getEndpoint());

        try {
            return new Client(config);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

步骤三:创建阿里云对象并使用

@Service
public class SmsServiceImpl implements SmsService {
//创建阿里云对象,创建时,会自动调用步骤二,为此对象进行参数配置
    @Autowired
    private Client client;
     //主要调用此方法,就可以发送短信
    @Override
    public void sendCode(String phone, String code) {
        //固定写法
        SendSmsRequest smsRequest = new SendSmsRequest();
        smsRequest.setPhoneNumbers(phone);
        smsRequest.setSignName("阿里云短信测试");
        smsRequest.setTemplateCode("SMS_154950909");
        smsRequest.setTemplateParam("{\"code\":\"" + code + "\"}");
        try {
            client.sendSms(smsRequest);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值