一、引入依赖
<!-- 阿里云短信服务-->
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
<version>4.5.17</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-dysmsapi</artifactId>
<version>2.2.1</version>
</dependency>
二、创建工具类
@Service
@Slf4j
public class EpidemicMsmUtils implements EpidemicMsm {
private static String endpoint = "cn-hangzhou";
private static String accessKeyId = "LTAI5tDvuHomL95pvrQSWYsH";
private static String accessSecret = "fZovzcSrpLIY4AHpbWPVwRCIsWi1gl";
/**
* 发送短信验证码
* @param param 验证码
* @param phone 手机号
* @return
*/
@Override
public boolean send(String content, String phone){
DefaultProfile profile = DefaultProfile.getProfile(endpoint,accessKeyId,accessSecret);
IAcsClient client = new DefaultAcsClient(profile);
CommonRequest request = new CommonRequest();
request.setSysMethod(MethodType.POST);
//域名,勿改
request.setSysDomain("dysmsapi.aliyuncs.com");
//API版本号,请勿修改
request.setSysVersion("2017-05-25");
//API名称
request.setSysAction("SendSms");
//接收号码,格式为:号码,必填
request.putQueryParameter("PhoneNumbers", phone);
//申请阿里云 签名名称
request.putQueryParameter("SignName","阿里云短信测试");
//申请阿里云 模板code SMS_ 219890080
request.putQueryParameter("TemplateCode","SMS_154950909");
// 此处是进行验证码短信参数设置
Map<String, Object> param = new HashMap<>();
param.put("code", content);
//短信内容,必填
request.putQueryParameter("TemplateParam", JSONObject.toJSONString(param));
try {
CommonResponse response = client.getCommonResponse(request);
return response.getHttpResponse().isSuccess();
} catch (ClientException e) {
e.printStackTrace();
return false;
}
}
/**
* 批量发送短信
* @param content 短信内容
* @param phone 手机号
* @return
*/
@Override
public boolean sendBatch(String content, String[] phone){
DefaultProfile profile = DefaultProfile.getProfile(endpoint,accessKeyId,accessSecret);
IAcsClient client = new DefaultAcsClient(profile);
CommonRequest request = new CommonRequest();
request.setSysMethod(MethodType.POST);
//域名,勿改
request.setSysDomain("dysmsapi.aliyuncs.com");
//API版本号,请勿修改
request.setSysVersion("2017-05-25");
//API名称
request.setSysAction("SendBatchSms");
//接收号码,格式为:国际码+号码,必填
request.putQueryParameter("PhoneNumberJson", Arrays.toString(phone));
//申请阿里云 签名名称
request.putQueryParameter("SignNameJson","阿里云短信测试");
//申请阿里云 模板code
request.putQueryParameter("TemplateCode","SMS_154950909");
//短信内容,必填
request.putQueryParameter("TemplateParamJson", JSONObject.toJSONString(content));
try {
CommonResponse response = client.getCommonResponse(request);
return response.getHttpResponse().isSuccess();
} catch (ClientException e) {
e.printStackTrace();
return false;
}
}
}