使用阿里云短信接口发送验证码
1. 引入依赖
springboot 工程引入web 引入 lombok
关键代码引入
<!--阿里云短信服务-->
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>dysmsapi20170525</artifactId>
<version>2.0.23</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>tea-openapi</artifactId>
<version>0.2.8</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>tea-console</artifactId>
<version>0.0.1</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>tea-util</artifactId>
<version>0.2.16</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>tea</artifactId>
<version>1.1.14</version>
</dependency>
2.创建配置文件
aliyun.accessKeyId=你的accessKeyId
aliyun.accessKeySecret=你的accessKeySecret
aliyun.securityToken="test";
3. SMSConfig.java
@PropertySource("classpath:aliyun.properties")
//前缀
@ConfigurationProperties(prefix = "aliyun")
@Component
@Data
public class SMSConfig {
private String accessKeyId;
private String accessKeySecret;
private String securityToken ;
public SMSConfig() {
}
/**
* 使用AK&SK初始化账号Client
* @return
* @throws Exception
*/
@Bean
@Qualifier("createClient")
public Client createClient() throws Exception {
Config config = new Config()
// 必填,您的 AccessKey ID
.setAccessKeyId(this.accessKeyId)
// 必填,您的 AccessKey Secret
.setAccessKeySecret(this.accessKeySecret);
// 访问的域名
config.endpoint = "dysmsapi.aliyuncs.com";
return new Client(config);
}
/**
* 使用STS鉴权方式初始化账号Client,推荐此方式。
* @return
* @throws Exception
*/
@Bean
@Qualifier("createClientWithSTS")
public Client createClientWithSTS( ) throws Exception {
Config config = new Config()
// 必填,您的 AccessKey ID
.setAccessKeyId(this.accessKeyId)
// 必填,您的 AccessKey Secret
.setAccessKeySecret(this.accessKeySecret)
// 必填,您的 Security Token
.setSecurityToken(this.securityToken)
// 必填,表明使用 STS 方式
.setType("sts");
// 访问的域名
config.endpoint = "dysmsapi.aliyuncs.com";
return new Client(config);
}
}
4. 创建控制层
@Autowired
private SMSServie smsServie;
@GetMapping("/sms/send/{mobile}")
public ResultVO send(@PathVariable("mobile") String mobile) throws Exception {
return smsServie.send(mobile);
}
5. Service层
public interface SMSServie {
ResultVO send(String mobile) throws Exception;
}
@Service
public class SMSServiceImp implements SMSServie {
@Autowired
@Qualifier("createClient")
private Client client;
public ResultVO send(String mobile) throws Exception {
// 请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID 和 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
// 工程代码泄露可能会导致 AccessKey 泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考,建议使用更安全的 STS 方式,更多鉴权访问方式请参见:https://help.aliyun.com/document_detail/378657.html
SendSmsRequest sendSmsRequest = new SendSmsRequest()
.setSignName("阿里云短信测试")
.setTemplateCode("SMS_154950909")
.setPhoneNumbers(mobile)
.setTemplateParam("{\"code\":\"123456\"}");
RuntimeOptions runtime = new RuntimeOptions();
SendSmsResponse resp = client.sendSmsWithOptions(sendSmsRequest, runtime);
log(Common.toJSONString(resp));
return ResultVO.success("短信发送成功");
}
}
启动项目,访问接口,短信发送成功!