1、引言
- 阿里云短信对接相关博客不少,但是都是互相抄袭,现有的帖子99%都是旧的原版SDK
- 官网贴了demo,我直接给大家整理好
- 关于 key、secret 大家需要自己进行准备,这不是开发者关注的东西
- 依赖截至 2021.11 是最新的
2、代码
(1)依赖
- 一个依赖足够,原版sdk还需要引入aliyun-java-sdk-core、 aliyun-java-sdk-dysmsapi,这里无需引入
com.aliyun
dysmsapi20170525
2.0.6
(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)
// 签名,比如 "xxx公司",问运营要
.setSignName(signName)
// 模板编号,比如 SMS_123456,问运营要
.setTemplateCode(templateCode)
// json格式String类型模板,比如 "{"k1", v1, "k2", v2}",问运营要
.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);
}