1.导入依赖
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>dysmsapi20170525</artifactId>
<version>2.0.9</version>
</dependency>
2.代码实现
package com.demo.service;
import com.alibaba.fastjson.JSON;
import com.aliyun.dysmsapi20170525.models.*;
import com.aliyun.teaopenapi.models.*;
import lombok.extern.slf4j.Slf4j;
import java.util.HashMap;
@Slf4j
public class SmsService {
public static com.aliyun.dysmsapi20170525.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
Config config = new Config()
//AccessKey ID
.setAccessKeyId(accessKeyId)
//AccessKey Secret
.setAccessKeySecret(accessKeySecret);
//访问的域名
config.endpoint = "dysmsapi.aliyuncs.com";
return new com.aliyun.dysmsapi20170525.Client(config);
}
public static boolean sendSms(String phoneNumber, String content) {
try {
com.aliyun.dysmsapi20170525.Client client = createClient(Const.ACCESSKEY_ID, Const.ACCESSKEY_SECRET);
SendSmsRequest sendSmsRequest = new SendSmsRequest()
.setPhoneNumbers(phoneNumber)
.setSignName("测试")//内容自行替换
.setTemplateCode("SMS_111111");//内容自行替换
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("code", content);//内容自行替换
sendSmsRequest.setTemplateParam(JSON.toJSONString(hashMap));
SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
log.info("短信发送返回值:" + sendSmsResponse.getBody().getMessage());
if ("OK".equals(sendSmsResponse.getBody().getCode())) {
return true;
}
return false;
} catch (Exception e) {
log.error("异常:短信验证码发送失败", e);
return false;
}
}
}