发送短信息工具类
以阿里平台为准
加入sdk
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>dysmsapi20170525</artifactId>
<version>[2.0.0,3.0.0)</version>
</dependency>
新版本
@Slf4j
public class AliSmsUtils {
private final static String accessKeyId = AliSmsConstant.ACCESS_KEY_ID;
private final static String accessKeySecret = AliSmsConstant.ACCESS_KEY_SECRET;
public static com.aliyun.dysmsapi20170525.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
Config config = new Config()
.setAccessKeyId(accessKeyId)
.setAccessKeySecret(accessKeySecret);
config.endpoint = "dysmsapi.aliyuncs.com";
return new com.aliyun.dysmsapi20170525.Client(config);
}
public static AjaxResult send(String mobile, String signName, String templateCode, String param) throws Exception {
com.aliyun.dysmsapi20170525.Client client = AliSmsUtils.createClient(accessKeyId, accessKeySecret);
SendSmsRequest request = new SendSmsRequest()
.setPhoneNumbers(mobile)
.setSignName(signName)
.setTemplateCode(templateCode)
.setTemplateParam(param);
SendSmsResponse response = client.sendSms(request);
if (!Objects.isNull(response) && response.getBody().code.equals("OK") && response.getBody().message.equals("OK")) {
log.info("[阿里短信]----发送成功");
return AjaxResult.success("", response.getBody());
}
log.error("[阿里短信]----发送失败, message:{}", response.getBody().getMessage());
return AjaxResult.error(-9, "",response.getBody());
}
}
对比旧版本
@Slf4j
public class AliSmsUtils {
public static void send(String mobile) {
DefaultProfile profile = DefaultProfile.getProfile("ap-northeast-1", "<accessKeyId>", "<accessSecret>");
IAcsClient client = new DefaultAcsClient(profile);
CommonRequest request = new CommonRequest();
request.setSysMethod(MethodType.POST);
request.setSysDomain("dysmsapi.ap-southeast-1.aliyuncs.com");
request.setSysVersion("2017-05-25");
request.setSysAction("SendSms");
request.putQueryParameter("PhoneNumbers", mobile);
request.putQueryParameter("SignName", "阿里大于测试专用");
request.putQueryParameter("TemplateCode", "SMS_209335004");
request.putQueryParameter("TemplateParam", "{\"code\":\"123456\"}");
try {
CommonResponse response = client.getCommonResponse(request);
System.out.println(response.getData());
} catch (ClientException e) {
e.printStackTrace();
}
}
}
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
<version>4.5.30</version>
</dependency>
|