依赖
<!--阿里云短信平台-->
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>dysmsapi20170525</artifactId>
<version>2.0.23</version>
</dependency>
service接口
BaseResult sendMessage(String phoneNumber, String code);
impl
@Value("${message.accessKeyId}")
private String accessKeyId;
@Value("${message.accessKeySecret}")
private String accessKeySecret;
public Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
Config config = new Config()
.setAccessKeyId(accessKeyId)
.setAccessKeySecret(accessKeySecret);
config.endpoint = "dysmsapi.aliyuncs.com";
return new Client(config);
}
@Override
@SneakyThrows
public BaseResult sendMessage(String phoneNumber, String code) {
Client client = createClient(accessKeyId, accessKeySecret);
SendSmsRequest sendSmsRequest = new SendSmsRequest()
.setSignName("阿里云短信测试")
.setTemplateCode("SMS_154950909")
.setPhoneNumbers(phoneNumber)
.setTemplateParam("{\"code\":\"" + code + "\"}");
RuntimeOptions runtime = new RuntimeOptions();
SendSmsResponse sendSmsResponse = client.sendSmsWithOptions(sendSmsRequest, runtime);
SendSmsResponseBody body = sendSmsResponse.getBody();
String code1 = body.getCode();
if ("OK".equals(code1)) {
return new BaseResult(200, body.getCode(), body.getMessage());
} else {
return new BaseResult(500, body.getCode(), body.getMessage());
}
}
验证码
public static String buildCheckCode(int digit){
String str = "0123456789";
StringBuilder s = new StringBuilder();
Random random = new Random();
for (int i = 0; i < digit; i++) {
char ch = str.charAt(random.nextInt(str.length()));
sb.append(ch);
}
return s.toString();
}