增加短信实现

This commit is contained in:
TinyAnts 2022-08-23 17:30:50 +08:00
parent 9efdbf96a6
commit 45d2717313
6 changed files with 221 additions and 29 deletions

View File

@ -0,0 +1,40 @@
package com.mdd.admin.controller;
import com.mdd.common.core.AjaxResult;
import com.mdd.common.plugin.sms.SmsDriver;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
@RestController
@RequestMapping("api/test")
public class TestController {
@GetMapping("/sms")
public Object sms() {
Map<String, String> params = new LinkedHashMap<>();
// 阿里云的
params.put("user_name", "小明");
params.put("order_sn", "22026655656");
params.put("ff", "eee");
params.put("gg", "gg");
params.put("eee", "ee");
// 腾讯云的
(new SmsDriver())
.setMobile("15627119239")
// .setTemplateCode("SMS_222463029")
.setTemplateCode("1074928")
.setTemplateParam(params)
.sendSms();
return AjaxResult.success();
}
}

View File

@ -0,0 +1,28 @@
package com.mdd.common.entity.system;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.Data;
import java.io.Serializable;
/**
* 系统短信日志实体
*/
@Data
public class SystemLogSms implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(value="id", type= IdType.AUTO)
private Integer id; // 主键
private String scene; // 场景编号
private String mobile; // 手机号码
private String content; // 发送内容
private Integer status; // 发送状态[0=发送中, 1=发送成功, 2=发送失败]
private String results; // 发送结果
private Long sendTime; // 发送时间
private Long createTime; // 创建时间
private Long updateTime; // 更新时间
}

View File

@ -0,0 +1,12 @@
package com.mdd.common.mapper.system;
import com.mdd.common.core.basics.IBaseMapper;
import com.mdd.common.entity.system.SystemLogSms;
import org.apache.ibatis.annotations.Mapper;
/**
* 系统短信日志Mapper
*/
@Mapper
public interface SystemLogSmsMapper extends IBaseMapper<SystemLogSms> {
}

View File

@ -1,18 +1,30 @@
package com.mdd.common.plugin.sms; package com.mdd.common.plugin.sms;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.mdd.common.entity.system.SystemLogSms;
import com.mdd.common.exception.OperateException;
import com.mdd.common.mapper.system.SystemLogSmsMapper;
import com.mdd.common.plugin.sms.engine.AliSms; import com.mdd.common.plugin.sms.engine.AliSms;
import com.mdd.common.plugin.sms.engine.TencentSms; import com.mdd.common.plugin.sms.engine.TencentSms;
import com.mdd.common.utils.ArrayUtil;
import com.mdd.common.utils.ConfigUtil; import com.mdd.common.utils.ConfigUtil;
import com.mdd.common.utils.SpringUtil;
import javax.annotation.Resource;
import javax.management.openmbean.OpenDataException;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Map; import java.util.Map;
public class SmsDriver { public class SmsDriver {
private final SystemLogSmsMapper systemLogSmsMapper;
private String mobile; // 手机号码 private String mobile; // 手机号码
private String templateId; // 短信模板 private String templateCode; // 短信模板
private String smsContent; // 短信内容 private String smsContent = ""; // 短信内容
private Map<String, String> param; // 短信参数 private Map<String, String> templateParam; // 短信参数
private final String engine; // 短信引擎 private final String engine; // 短信引擎
private final Map<String, String> config; // 短信配置 private final Map<String, String> config; // 短信配置
@ -20,8 +32,9 @@ public class SmsDriver {
* 构造方法 * 构造方法
*/ */
public SmsDriver() { public SmsDriver() {
this.engine = ConfigUtil.get("sms", "default", "aliyun"); this.engine = ConfigUtil.get("sms", "default", "");
this.config = ConfigUtil.getMap("sms", this.engine); this.config = ConfigUtil.getMap("sms", this.engine);
this.systemLogSmsMapper = SpringUtil.getBean(SystemLogSmsMapper.class);
} }
/** /**
@ -37,14 +50,38 @@ public class SmsDriver {
} }
/** /**
* 设置参数 * 设置模板编号
*
* @author fzr
* @param code 短信编码
* @return SmsDriver
*/
public SmsDriver setTemplateCode(String code) {
this.templateCode = code;
return this;
}
/**
* 设置模板参数
* *
* @author fzr * @author fzr
* @param param 参数 * @param param 参数
* @return SmsDriver * @return SmsDriver
*/ */
public SmsDriver setParam(Map<String, String> param) { public SmsDriver setTemplateParam(Map<String, String> param) {
this.param = param; this.templateParam = param;
return this;
}
/**
* 设置模板内容
*
* @author fze
* @param content 内容
* @return SmsDriver
*/
public SmsDriver setSmsContent(String content) {
this.smsContent = content;
return this; return this;
} }
@ -54,23 +91,75 @@ public class SmsDriver {
* @author fzr * @author fzr
*/ */
public void sendSms() { public void sendSms() {
String templateParam = JSON.toJSONString(param); String templateParam = JSON.toJSONString(this.templateParam);
Integer logId = this.writeSmsLog();
Integer sendResult = 0;
String results = "";
switch (this.engine) { switch (this.engine) {
case "aliyun": case "aliyun":
AliSms aliSms = new AliSms(this.config); AliSms aliSms = new AliSms(this.config);
aliSms.setMobile(this.mobile) results = aliSms.setMobile(this.mobile)
.setTemplateId(this.templateId) .setTemplateId(this.templateCode)
.setTemplateParams(templateParam) .setTemplateParams(templateParam)
.send(); .send();
sendResult = aliSms.getSendResult();
break; break;
case "tencent": case "tencent":
List<String> params = new LinkedList<>();
for (Map.Entry<String, String> MapString : this.templateParam.entrySet()) {
params.add(MapString.getValue());
}
TencentSms tencentSms = new TencentSms(this.config); TencentSms tencentSms = new TencentSms(this.config);
tencentSms.setMobile(this.mobile) results = tencentSms.setMobile(this.mobile)
.setTemplateId(this.templateId) .setTemplateId(this.templateCode)
.setTemplateParams(templateParam.split(",")) .setTemplateParams(params.toArray(new String[0]))
.send(); .send();
sendResult = tencentSms.getSendResult();
break; break;
} }
this.updateSmsLog(logId, sendResult, results);
if (sendResult == 2) {
throw new OperateException("短信发送失败");
}
}
/**
* 写入短信日志
*
* @author fzr
*/
private Integer writeSmsLog() {
SystemLogSms model = new SystemLogSms();
model.setMobile(this.mobile);
model.setContent(this.smsContent);
model.setResults("");
model.setStatus(0);
model.setCreateTime(System.currentTimeMillis() / 1000);
model.setUpdateTime(System.currentTimeMillis() / 1000);
systemLogSmsMapper.insert(model);
return model.getId();
}
/**
* 更新短信日志
*
* @author fzr
* @param id 主键
* @param status 状态
* @param result 结果
*/
private void updateSmsLog(Integer id, Integer status, String result) {
SystemLogSms model = new SystemLogSms();
model.setId(id);
model.setMobile(this.mobile);
model.setStatus(status);
model.setResults(result);
model.setSendTime(System.currentTimeMillis() / 1000);
model.setUpdateTime(System.currentTimeMillis() / 1000);
systemLogSmsMapper.updateById(model);
} }
} }

View File

@ -16,6 +16,7 @@ import java.util.Map;
*/ */
public class AliSms { public class AliSms {
private Integer sendResult; // 发送结果
private String mobile; // 手机号码 private String mobile; // 手机号码
private String templateId; // 短信模板 private String templateId; // 短信模板
private String templateParams; // 短信参数 private String templateParams; // 短信参数
@ -67,6 +68,16 @@ public class AliSms {
return this; return this;
} }
/**
* 获取发送结果
*
* @author fzr
* @return Integer [1=成功, 2=失败]
*/
public Integer getSendResult() {
return this.sendResult;
}
/** /**
* 发送短信 * 发送短信
* *
@ -74,7 +85,7 @@ public class AliSms {
* @return String * @return String
*/ */
public String send() { public String send() {
DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", this.config.get("app_key"), this.config.get("secret_key")); DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", this.config.get("appKey"), this.config.get("secretKey"));
IAcsClient client = new DefaultAcsClient(profile); IAcsClient client = new DefaultAcsClient(profile);
CommonRequest request = new CommonRequest(); CommonRequest request = new CommonRequest();
@ -87,19 +98,19 @@ public class AliSms {
request.putQueryParameter("TemplateCode", this.templateId); request.putQueryParameter("TemplateCode", this.templateId);
request.putQueryParameter("TemplateParam", this.templateParams); request.putQueryParameter("TemplateParam", this.templateParams);
try { try {
System.out.println("来来来来来");
CommonResponse response = client.getCommonResponse(request); CommonResponse response = client.getCommonResponse(request);
System.out.println(response);
JSONObject res = JSONObject.parseObject(response.getData()); JSONObject res = JSONObject.parseObject(response.getData());
if (!res.get("Code").equals("OK") || !res.get("Message").equals("OK")) { if (!res.get("Code").equals("OK") || !res.get("Message").equals("OK")) {
throw new OperateException(res.get("Message").toString()); this.sendResult = 2;
return res.get("Message").toString();
} }
this.sendResult = 1;
return response.getData(); return response.getData();
} catch (Exception e) { } catch (Exception e) {
System.out.println(e.getMessage()); this.sendResult = 2;
throw new OperateException("短信发送异常:" + e.getMessage()); return e.getMessage();
} }
} }

View File

@ -15,10 +15,10 @@ import java.util.Map;
*/ */
public class TencentSms { public class TencentSms {
private Integer sendResult; // 发送结果
private String mobile; private String mobile; // 手机号码
private String templateId; private String templateId; // 模板编号
private String[] templateParams; private String[] templateParams; // 模板参数
private final Map<String, String> config; private final Map<String, String> config;
public TencentSms(Map<String, String> config) { public TencentSms(Map<String, String> config) {
@ -58,16 +58,25 @@ public class TencentSms {
return this; return this;
} }
/**
* 获取发送结果
*
* @author fzr
* @return Integer [1=成功, 2=失败]
*/
public Integer getSendResult() {
return this.sendResult;
}
/** /**
* 发送短信 * 发送短信
* *
* @param config 配置
* @return String * @return String
*/ */
public String send() { public String send() {
try { try {
/*认证对象*/ /*认证对象*/
Credential cred = new Credential(this.config.get("secret_id").toString(), config.get("secret_key").toString()); Credential cred = new Credential(this.config.get("secretId"), config.get("secretKey"));
HttpProfile httpProfile = new HttpProfile(); HttpProfile httpProfile = new HttpProfile();
httpProfile.setReqMethod("POST"); httpProfile.setReqMethod("POST");
httpProfile.setConnTimeout(60); httpProfile.setConnTimeout(60);
@ -81,8 +90,8 @@ public class TencentSms {
/*参数配置*/ /*参数配置*/
SmsClient client = new SmsClient(cred, "ap-guangzhou",clientProfile); SmsClient client = new SmsClient(cred, "ap-guangzhou",clientProfile);
SendSmsRequest req = new SendSmsRequest(); SendSmsRequest req = new SendSmsRequest();
req.setSignName(config.get("sign").toString()); req.setSignName(config.get("sign"));
req.setSmsSdkAppId(config.get("app_id").toString()); req.setSmsSdkAppId(config.get("appId"));
req.setTemplateId(this.templateId); req.setTemplateId(this.templateId);
/*手机号码*/ /*手机号码*/
@ -96,12 +105,15 @@ public class TencentSms {
/*发起请求*/ /*发起请求*/
SendSmsResponse res = client.SendSms(req); SendSmsResponse res = client.SendSms(req);
if (!res.getSendStatusSet()[0].getCode().equals("Ok")) { if (!res.getSendStatusSet()[0].getCode().equals("Ok")) {
throw new Exception(res.getSendStatusSet()[0].getMessage()); this.sendResult = 2;
return res.getSendStatusSet()[0].getMessage();
} }
this.sendResult = 1;
return res.getSendStatusSet()[0].getMessage(); return res.getSendStatusSet()[0].getMessage();
} catch (Exception e) { } catch (Exception e) {
throw new OperateException("短信发送异常:" + e.getMessage()); this.sendResult = 2;
return e.getMessage();
} }
} }