1、引言
- 阿里云短信对接相关博客不少,但是都是互相抄袭,现有的帖子99%都是旧的原版SDK
- 官网贴了demo,我直接给大家整理好
- 关于 key、secret 大家需要自己进行准备,这不是开发者关注的东西
- 依赖截至 2021.11 是最新的
2、代码
(1)依赖
- 一个依赖足够,原版sdk还需要引入
aliyun-java-sdk-core
、 aliyun-java-sdk-dysmsapi
,这里无需引入
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>dysmsapi20170525</artifactId>
<version>2.0.6</version>
</dependency>
(2)代码
import com.alibaba.fastjson.JSONObject;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.*;
import com.aliyun.teaopenapi.models.*;
public boolean sendSms(String phone, int code) {
Client client;
try {
client = createClient(accessKeyId, accessKeySecret);
} catch (Exception e) {
log.error("发送短信,使用初始化账号Client异常, {}", e.getMessage());
return false;
}
SendSmsRequest sendSmsRequest = new SendSmsRequest()
.setPhoneNumbers(phone)
.setSignName(signName)
.setTemplateCode(templateCode)
.setTemplateParam("{\"code\":" + code + "}");
SendSmsResponse resp;
try {
resp = client.sendSms(sendSmsRequest);
} catch (Exception e) {
log.error("发送短信失败, {}", e.getMessage());
return false;
}
log.debug("发送短信【{}】, 验证码【{}】, 结果【{}】", phone, code, JSONObject.toJSONString(resp));
if (resp == null || !Objects.equals(resp.getBody().getCode(), "OK")) {
log.error("发送短信失败【{}】, 验证码【{}】, 结果【{}】", phone, code, JSONObject.toJSONString(resp));
return false;
}
return true;
}
private static 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);
}