Springboot集成阿里云短信实现短信发送功能
概要
Springboot集成阿里云短信实现短信发送功能
涉及:pom引用,相关功能类,短信模板配置,demo方法等
1,pom.xml
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.10.2</version>
</dependency>
2,核心方法
2.1 实现类
主要涉及3个参数:①发送到哪个手机号;②短信模板是什么;③模板里的参数有啥
// 发送短信
private final SmsService smsService;
public R testMsg(){
Map<String, String> params = new HashMap<>();
params.put("param1","参数1");
params.put("param2","参数2");
params.put("param3","参数3");
...
// 手机号,短信模板(阿里云审核成功后给的编码),模板参数
smsService.sendMsg("157****", MessageTemplate.SMS_1234567, params);
}
2.2 发送短信Service类
@Slf4j
@Component
public class SmsService {
@Autowired
private AliDayuSendMessage aliDayuSendMessage;
/**
*
* @param mobile 发送到哪个手机号
* @param temp 短信模板
* @param param 模板里的动态参数
* @return
*/
public boolean sendMsg(String mobile, MessageTemplate temp, Map<String, String> param) {
MessageResult sendMessage = aliDayuSendMessage.sendMessage(mobile, temp, param);
log.info("短信发送返回信息:{}", JSON.toJSON(sendMessage));
return sendMessage.isSuccess();
}
}
2.3 短信模板枚举类
public enum MessageTemplate {
//
SMS_1234567("这是测试短信模板,参数1${param1},参数2${param2},参数3${param3}");
public String desc;
MessageTemplate(String desc) {
this.desc = desc;
}
}
2.4 AliDayuSendMessage(核心类)
涉及的几个参数需要联系自己公司的运维工程师要,主要有accessKeyId,accessKeySecret,productName(这个联系产品或者业务定义)
import com.alibaba.fastjson.JSON;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import org.muyuan.core.log.logger.MuyuanLogger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import java.util.Map;
@Service
public class AliDayuSendMessage {
// 产品名称:云通信短信API产品,开发者无需替换
static final String product = "Dysmsapi";
// 产品域名,开发者无需替换
static final String domain = "dysmsapi.aliyuncs.com";
static final String productName = "";// 类似于我们收到的【中国移动】
private String accessKeyId = "";
private String accessKeySecret = "";
private IAcsClient acsClient;
@SuppressWarnings("deprecation")
@PostConstruct
public void init() throws ClientException {
// 可自助调整超时时间
System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
System.setProperty("sun.net.client.defaultReadTimeout", "10000");
// 初始化acsClient,暂不支持region化
IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
acsClient = new DefaultAcsClient(profile);
}
public MessageResult sendMessage(String mobile, MessageTemplate temp, Map<String, String> param) {
MessageResult result = new MessageResult();
// 组装请求对象-具体描述见控制台-文档部分内容
SendSmsRequest request = new SendSmsRequest();
// 必填:待发送手机号
request.setPhoneNumbers(mobile);
// 必填:短信签名-可在短信控制台中找到
request.setSignName(productName);
// 必填:短信模板-可在短信控制台中找到
request.setTemplateCode(temp.name());
// 可选:模板中的变量替换JSON串,如模板内容为"参数1${param1},参数2${param2}"时,此处的值为
request.setTemplateParam(JSON.toJSONString(param));
// hint 此处可能会抛出异常,注意catch
try {
SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
if ("OK".equals(sendSmsResponse.getCode())) {
result.setSuccess(true);
// 发送短信成功
return result;
} else {// 发送错误
result.setSuccess(false);
result.setRemark(sendSmsResponse.getMessage());
// 发送短信失败
return result;
}
} catch (Exception e) {
result.setSuccess(false);
result.setRemark("未知错误");
// 发送短信异常
return result;
}
}
}
2.5 MessageResult
public class MessageResult {
private boolean success;
private String remark;
/**
* @return the success
*/
public boolean isSuccess() {
return success;
}
/**
* @param success the success to set
*/
public void setSuccess(boolean success) {
this.success = success;
}
/**
* @return the remark
*/
public String getRemark() {
return remark;
}
/**
* @param remark the remark to set
*/
public void setRemark(String remark) {
this.remark = remark;
}
}
2.6 SendSmsRequest
public class SendSmsRequest extends RpcAcsRequest<SendSmsResponse> {
public SendSmsRequest() {
super("Dysmsapi", "2017-05-25", "SendSms");
}
private String templateCode;
private String phoneNumbers;
private String signName;
private String resourceOwnerAccount;
private String templateParam;
private Long resourceOwnerId;
private Long ownerId;
private String smsUpExtendCode;
private String outId;
public String getTemplateCode() {
return this.templateCode;
}
public void setTemplateCode(String templateCode) {
this.templateCode = templateCode;
if (templateCode != null) {
putQueryParameter("TemplateCode", templateCode);
}
}
public String getPhoneNumbers() {
return this.phoneNumbers;
}
public void setPhoneNumbers(String phoneNumbers) {
this.phoneNumbers = phoneNumbers;
if (phoneNumbers != null) {
putQueryParameter("PhoneNumbers", phoneNumbers);
}
}
public String getSignName() {
return this.signName;
}
public void setSignName(String signName) {
this.signName = signName;
if (signName != null) {
putQueryParameter("SignName", signName);
}
}
public String getResourceOwnerAccount() {
return this.resourceOwnerAccount;
}
public void setResourceOwnerAccount(String resourceOwnerAccount) {
this.resourceOwnerAccount = resourceOwnerAccount;
if (resourceOwnerAccount != null) {
putQueryParameter("ResourceOwnerAccount", resourceOwnerAccount);
}
}
public String getTemplateParam() {
return this.templateParam;
}
public void setTemplateParam(String templateParam) {
this.templateParam = templateParam;
if (templateParam != null) {
putQueryParameter("TemplateParam", templateParam);
}
}
public Long getResourceOwnerId() {
return this.resourceOwnerId;
}
public void setResourceOwnerId(Long resourceOwnerId) {
this.resourceOwnerId = resourceOwnerId;
if (resourceOwnerId != null) {
putQueryParameter("ResourceOwnerId", resourceOwnerId.toString());
}
}
public Long getOwnerId() {
return this.ownerId;
}
public void setOwnerId(Long ownerId) {
this.ownerId = ownerId;
if (ownerId != null) {
putQueryParameter("OwnerId", ownerId.toString());
}
}
public String getSmsUpExtendCode() {
return this.smsUpExtendCode;
}
public void setSmsUpExtendCode(String smsUpExtendCode) {
this.smsUpExtendCode = smsUpExtendCode;
if (smsUpExtendCode != null) {
putQueryParameter("SmsUpExtendCode", smsUpExtendCode);
}
}
public String getOutId() {
return this.outId;
}
public void setOutId(String outId) {
this.outId = outId;
if (outId != null) {
putQueryParameter("OutId", outId);
}
}
@Override
public Class<SendSmsResponse> getResponseClass() {
return SendSmsResponse.class;
}
}
2.7 SendSmsResponse
public class SendSmsResponse extends AcsResponse {
private String requestId;
private String bizId;
private String code;
private String message;
public String getRequestId() {
return this.requestId;
}
public void setRequestId(String requestId) {
this.requestId = requestId;
}
public String getBizId() {
return this.bizId;
}
public void setBizId(String bizId) {
this.bizId = bizId;
}
public String getCode() {
return this.code;
}
public void setCode(String code) {
this.code = code;
}
public String getMessage() {
return this.message;
}
public void setMessage(String message) {
this.message = message;
}
@Override
public SendSmsResponse getInstance(UnmarshallerContext context) {
return SendSmsResponseUnmarshaller.unmarshall(this, context);
}
}
2.8 SendSmsResponseUnmarshaller
import com.aliyuncs.transform.UnmarshallerContext;
public class SendSmsResponseUnmarshaller {
public static SendSmsResponse unmarshall(SendSmsResponse sendSmsResponse, UnmarshallerContext context) {
sendSmsResponse.setRequestId(context.stringValue("SendSmsResponse.RequestId"));
sendSmsResponse.setBizId(context.stringValue("SendSmsResponse.BizId"));
sendSmsResponse.setCode(context.stringValue("SendSmsResponse.Code"));
sendSmsResponse.setMessage(context.stringValue("SendSmsResponse.Message"));
return sendSmsResponse;
}
}
总结
本文详细描述Springboot集成阿里云短信实现短信发送功能,涉及全部实现代码,可直接cv操作。
创作不易,尊重知识,转载请附带本文链接