Commit 3e4de28d authored by qinxunjia's avatar qinxunjia

更改对接碧桂园接口

parent 99c7201b
......@@ -10,7 +10,6 @@
<name>插件服务</name>
<description>DM hub集成插件服务</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
......@@ -36,7 +35,6 @@
<scope>test</scope>
</dependency>
<!-- Spring-Mybatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
......
package com.bgy;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan(" com.bgy.sms.repository.mapper")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
package com.bgy.exception;
import com.bgy.sms.config.ResponseCode;
public class ServiceException extends RuntimeException {
private static final long serialVersionUID = 1L;
private String msg;
private String code = "500";
public ServiceException(String msg) {
super(msg);
this.msg = msg;
}
public ServiceException(String msg, Throwable e) {
super(msg, e);
this.msg = msg;
}
public ServiceException(String msg, String code) {
super(msg);
this.msg = msg;
this.code = code;
}
public ServiceException(String msg, String code, Throwable e) {
super(msg, e);
this.msg = msg;
this.code = code;
}
public ServiceException(ResponseCode responseCode) {
super(responseCode.getMsg());
this.msg = responseCode.getMsg();
this.code = responseCode.getCode();
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
}
package com.bgy.sms.channel.api;
import com.alibaba.fastjson.JSONObject;
import com.bgy.sms.channel.bgy.dto.CLNotifyRequest;
import com.bgy.sms.channel.bgy.dto.ReportDto;
import com.bgy.sms.channel.bgy.service.BgySmsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RequestMapping("/byg/")
@RestController
public class BgyApi {
private static final Logger log = LoggerFactory.getLogger(BgyApi.class);
@PostMapping("/notify")
public String notify(@RequestParam CLNotifyRequest notifyInfo) {
log.info("创蓝异步通知接口入参:{}", JSONObject.toJSONString(notifyInfo));
String response = "success";
try {
// bgySmsService.asyncNotify(notifyInfo);
} catch (Exception e) {
log.error("处理创建模板异步通知异常:", e);
response = "fail";
}
log.info("创蓝异步通知接口出参:{}", response);
return response;
}
@GetMapping("/report")
public String report(ReportDto report) {
log.info("回送报告接口入参:{}", JSONObject.toJSONString(report));
String response = "success";
try {
// CLBizResponse responses = chuangLanSmsService.report(report);
} catch (Exception e) {
log.error("处理回执逻辑异常:", e);
response = "fail";
}
log.info("创蓝异步通知接口出参:{}", response);
return response;
}
}
package com.bgy.sms.channel.api;
import com.alibaba.fastjson.JSONObject;
import com.bgy.sms.channel.dto.*;
import com.bgy.sms.config.ResponseCode;
import com.bgy.sms.service.MessageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping()
public class DmHubApi {
private static final Logger log = LoggerFactory.getLogger(DmHubApi.class);
@Autowired
private MessageService messageService;
/**
* 创建短信模板
*
* @return
*/
@PostMapping("/sms/template")
public DmHubTemplateResponse template(@RequestBody DmHubTemplateRequest params) {
log.info("**********创建模板接口入参*******:{}", JSONObject.toJSONString(params));
DmHubTemplateResponse template;
try {
template = messageService.createTemplate(params);
} catch (Exception e) {
log.error("创建模板短信异常", e);
template = new DmHubTemplateResponse(ResponseCode.SYSTEM_ERROR);
}
log.info("**********创建模板接口出参*******:{}", JSONObject.toJSONString(template));
return template;
}
/**
* 批量发送(通知或营销类)
*
* @return
*/
@PostMapping("/sms/batch")
public DmHubSendResponse batch(@RequestBody DmHubBatchSendRequest request) {
log.info("**********批量发送入参*******:{}", JSONObject.toJSONString(request));
DmHubSendResponse response;
try {
response = messageService.batchSendOneByOne(request);
} catch (Exception e) {
log.error("发送批量短信异常", e);
response = new DmHubSendResponse(ResponseCode.SYSTEM_ERROR);
}
log.info("**********批量发送出参*******:{}", response);
return response;
}
/**
* 发送单条(通知或营销类)
*
* @return
*/
@RequestMapping("/sms/send")
public DmHubSendResponse send(@RequestBody DmHubSendRequest request) {
log.info("**********单条发送入参*******:{}", JSONObject.toJSONString(request));
DmHubSendResponse response;
try {
response = messageService.send(request);
} catch (Exception e) {
log.error("发送单条短信异常", e);
response = new DmHubSendResponse(ResponseCode.SYSTEM_ERROR);
}
log.info("**********单条发送出参*******:{}", JSONObject.toJSONString(response));
return response;
}
}
package com.bgy.sms.channel.bgy.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* 短信参数配置
*/
@Component
public class BgySMSConfig {
// appId
public static String appId;
// 安全码
public static String securityCode;
// 请求地址
public static String url;
// 项目楼盘id
public static String areaId;
// api
public static String api;
@Value("${system.config.bgy.appId}")
public void setAppId(String appId) {
BgySMSConfig.appId = appId;
}
@Value("${system.config.bgy.securityCode}")
public void setSecurityCode(String securityCode) {
BgySMSConfig.securityCode = securityCode;
}
@Value("${system.config.bgy.url}")
public void setUrl(String url) {
BgySMSConfig.url = url;
}
@Value("${system.config.bgy.areaId}")
public void setAreaId(String areaId) {
BgySMSConfig.areaId = areaId;
}
@Value("${system.config.bgy.api}")
public void setApi(String api) {
BgySMSConfig.api = api;
}
}
package com.bgy.sms.channel.bgy.config;
/**
* 内容枚举类
*/
public enum ContentEnum {
SMS_TYPE_NOTIFICATION("notification", "通知类短信标识"),
SMS_TYPE_MARKETING("marketing", "营销类短信标识"),
SMS_STATUS_SUCCESS("DELIVRD", "创蓝短信发送状态--成功"),
SMS_STATUS_UNKNOWN("UNKNOWN", "创蓝短信发送状态--未知"),
SMS_STATUS_REFUSE("REJECTD", "创蓝短信发送状态--短信中心拒绝"),
SMS_STATUS_MBBLACK("MBBLACK", "创蓝短信发送状态--黑名单号码"),
SMS_STATUS_REJECT("REJECT", "创蓝短信发送状态--驳回");
private final String value;
private final String desc;
ContentEnum(String value, String desc) {
this.value = value;
this.desc = desc;
}
public String getValue() {
return value;
}
public String getDesc() {
return desc;
}
}
package com.bgy.sms.channel.bgy.dto;
import com.alibaba.fastjson.JSONObject;
import com.bgy.sms.config.ResponseCode;
import java.io.Serializable;
public class CLBizResponse implements Serializable {
private static final long serialVersionUID = 8100192126279967648L;
private String code;
private String msg;
private String id;
private JSONObject data;
public CLBizResponse() {
}
public CLBizResponse(ResponseCode responseCode) {
this.code = responseCode.getCode();
this.msg = responseCode.getMsg();
}
public CLBizResponse(ResponseCode responseCode,JSONObject data) {
this.code = responseCode.getCode();
this.msg = responseCode.getMsg();
this.data = data;
}
public CLBizResponse(ResponseCode responseCode, String id) {
this.code = responseCode.getCode();
this.msg = responseCode.getMsg();
this.id = id;
}
public CLBizResponse(ResponseCode responseCode, String msg, int nullInfo) {
this.code = responseCode.getCode();
this.msg = responseCode.getMsg()+msg;
}
public CLBizResponse(String code, String msg) {
this.code = code;
this.msg = msg;
}
public CLBizResponse(String code, String msg, String id) {
this.code = code;
this.msg = msg;
this.id = id;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public JSONObject getData() {
return data;
}
public void setData(JSONObject data) {
this.data = data;
}
}
package com.bgy.sms.channel.bgy.dto;
import java.io.Serializable;
public class CLNotifyRequest implements Serializable {
private static final long serialVersionUID = 1L;
// 接口用户名
private String username;
// 十位时间戳
private String timestamp;
// 签名串
private String signature;
// 模块
private String action;
// 模板id
private String id;
// 审核状态(模板(1审核,2驳回),签名(2通过,3驳回))
private String auditStatus;
// 驳回原因
private String auditReason;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getTimestamp() {
return timestamp;
}
public void setTimestamp(String timestamp) {
this.timestamp = timestamp;
}
public String getSignature() {
return signature;
}
public void setSignature(String signature) {
this.signature = signature;
}
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getAuditStatus() {
return auditStatus;
}
public void setAuditStatus(String auditStatus) {
this.auditStatus = auditStatus;
}
public String getAuditReason() {
return auditReason;
}
public void setAuditReason(String auditReason) {
this.auditReason = auditReason;
}
}
package com.bgy.sms.channel.bgy.dto;
import java.io.Serializable;
public class CLSendFixedRequest implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 创蓝API账号,必填
*/
private String account;
/**
* 创蓝API密码,必填
*/
private String password;
/**
* 短信内容。长度不能超过536个字符,必填
*/
private String msg;
/**
* 机号码。多个手机号码使用英文逗号分隔,必填
*/
private String phone;
/**
* 定时发送短信时间。格式为yyyyMMddHHmm,值小于或等于当前时间则立即发送,默认立即发送,选填
*/
private String sendtime;
/**
* 是否需要状态报告(默认false),选填
*/
private String report;
/**
* 下发短信号码扩展码,纯数字,建议1-3位,选填
*/
private String extend;
/**
* 该条短信在您业务系统内的ID,如订单号或者短信发送记录流水号,选填
*/
private String uid;
public CLSendFixedRequest() {
}
public CLSendFixedRequest(String account, String password, String msg, String phone) {
super();
this.account = account;
this.password = password;
this.msg = msg;
this.phone = phone;
}
public CLSendFixedRequest(String account, String password, String msg, String phone, String report) {
super();
this.account = account;
this.password = password;
this.msg = msg;
this.phone = phone;
this.report = report;
}
public CLSendFixedRequest(String account, String password, String msg, String phone, String report, String uid) {
super();
this.account = account;
this.password = password;
this.msg = msg;
this.phone = phone;
this.report = report;
this.uid = uid;
}
public CLSendFixedRequest(String account, String password, String msg, String phone, String sendtime, String report, String uid) {
super();
this.account = account;
this.password = password;
this.msg = msg;
this.phone = phone;
this.sendtime = sendtime;
this.report = report;
this.uid = uid;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getSendtime() {
return sendtime;
}
public void setSendtime(String sendtime) {
this.sendtime = sendtime;
}
public String getReport() {
return report;
}
public void setReport(String report) {
this.report = report;
}
public String getExtend() {
return extend;
}
public void setExtend(String extend) {
this.extend = extend;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
}
package com.bgy.sms.channel.bgy.dto;
import java.io.Serializable;
public class CLSendSMSResponse implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 响应时间
*/
private String time;
/**
* 消息id
*/
private String msgId;
/**
* 状态码说明(成功返回空)
*/
private String errorMsg;
/**
* 状态码(详细参考提交响应状态码)
*/
private String code;
private String failNum;
private String successNum;
public CLSendSMSResponse() {
}
public CLSendSMSResponse(String code, String errorMsg) {
this.code = code;
this.errorMsg = errorMsg;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getMsgId() {
return msgId;
}
public void setMsgId(String msgId) {
this.msgId = msgId;
}
public String getErrorMsg() {
return errorMsg;
}
public void setErrorMsg(String errorMsg) {
this.errorMsg = errorMsg;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getFailNum() {
return failNum;
}
public void setFailNum(String failNum) {
this.failNum = failNum;
}
public String getSuccessNum() {
return successNum;
}
public void setSuccessNum(String successNum) {
this.successNum = successNum;
}
@Override
public String toString() {
return "SmsSingleResponse [time=" + time + ", msgId=" + msgId + ", errorMsg=" + errorMsg + ", code=" + code
+ "]";
}
}
package com.bgy.sms.channel.bgy.dto;
import java.io.Serializable;
public class CLSendVariableRequest implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 创蓝API账号,必填
*/
private String account;
/**
* 创蓝API密码,必填
*/
private String password;
/**
* 短信内容。长度不能超过536个字符,必填
*/
private String msg;
/**
* 手机号码和变量参数,多组参数使用英文分号;区分,必填
*/
private String params;
/**
* 定时发送短信时间。格式为yyyyMMddHHmm,值小于或等于当前时间则立即发送,默认立即发送,选填
*/
private String sendtime;
/**
* 是否需要状态报告(默认false),选填
*/
private String report;
/**
* 下发短信号码扩展码,纯数字,建议1-3位,选填
*/
private String extend;
/**
* 该条短信在您业务系统内的ID,如订单号或者短信发送记录流水号,选填
*/
private String uid;
public CLSendVariableRequest() {
}
public CLSendVariableRequest(String account, String password, String msg, String params) {
super();
this.account = account;
this.password = password;
this.msg = msg;
this.params = params;
}
public CLSendVariableRequest(String account, String password, String msg, String params, String report) {
super();
this.account = account;
this.password = password;
this.msg = msg;
this.params = params;
this.report = report;
}
public CLSendVariableRequest(String account, String password, String msg, String params, String report,String uid) {
super();
this.account = account;
this.password = password;
this.msg = msg;
this.params = params;
this.report = report;
this.uid = uid;
}
// public SmsVarableRequest(String account, String password, String msg, String params, String sendtime) {
// super();
// this.account = account;
// this.password = password;
// this.msg = msg;
// this.params = params;
// this.sendtime = sendtime;
// }
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getSendtime() {
return sendtime;
}
public void setSendtime(String sendtime) {
this.sendtime = sendtime;
}
public String getReport() {
return report;
}
public void setReport(String report) {
this.report = report;
}
public String getExtend() {
return extend;
}
public void setExtend(String extend) {
this.extend = extend;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public String getParams() {
return params;
}
public void setParams(String params) {
this.params = params;
}
}
package com.bgy.sms.channel.bgy.dto;
import java.io.Serializable;
public class CLSendVariableResponse implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 响应时间
*/
private String time;
/**
* 消息id
*/
private String msgId;
/**
* 状态码说明(成功返回空)
*/
private String errorMsg;
/**
* 失败的个数
*/
private String failNum;
/**
* 成功的个数
*/
private String successNum;
/**
* 状态码(详细参考提交响应状态码)
*/
private String code;
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getMsgId() {
return msgId;
}
public void setMsgId(String msgId) {
this.msgId = msgId;
}
public String getErrorMsg() {
return errorMsg;
}
public void setErrorMsg(String errorMsg) {
this.errorMsg = errorMsg;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getFailNum() {
return failNum;
}
public void setFailNum(String failNum) {
this.failNum = failNum;
}
public String getSuccessNum() {
return successNum;
}
public void setSuccessNum(String successNum) {
this.successNum = successNum;
}
@Override
public String toString() {
return "SmsVarableResponse [time=" + time + ", msgId=" + msgId + ", errorMsg=" + errorMsg + ", failNum="
+ failNum + ", successNum=" + successNum + ", code=" + code + "]";
}
}
package com.bgy.sms.channel.bgy.dto;
public class CLTemplateRequest {
}
package com.bgy.sms.channel.bgy.dto;
import java.io.Serializable;
public class ReportDto implements Serializable {
private static final long serialVersionUID = 1L;
private String receiver;
private String pswd;
private String msgid;
private String reportTime;
private String mobile;
private String notifyTime;
private String uid;
private String length;
private String status;
private String statusDesc;
public String getReceiver() {
return receiver;
}
public void setReceiver(String receiver) {
this.receiver = receiver;
}
public String getPswd() {
return pswd;
}
public void setPswd(String pswd) {
this.pswd = pswd;
}
public String getMsgid() {
return msgid;
}
public void setMsgid(String msgid) {
this.msgid = msgid;
}
public String getReportTime() {
return reportTime;
}
public void setReportTime(String reportTime) {
this.reportTime = reportTime;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getNotifyTime() {
return notifyTime;
}
public void setNotifyTime(String notifyTime) {
this.notifyTime = notifyTime;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public String getLength() {
return length;
}
public void setLength(String length) {
this.length = length;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getStatusDesc() {
return statusDesc;
}
public void setStatusDesc(String statusDesc) {
this.statusDesc = statusDesc;
}
@Override
public String toString() {
return "ReportDto{" +
"receiver='" + receiver + '\'' +
", pswd='" + pswd + '\'' +
", msgid='" + msgid + '\'' +
", reportTime='" + reportTime + '\'' +
", mobile='" + mobile + '\'' +
", notifyTime='" + notifyTime + '\'' +
", uid='" + uid + '\'' +
", length='" + length + '\'' +
", status='" + status + '\'' +
", statusDesc='" + statusDesc + '\'' +
'}';
}
}
package com.bgy.sms.channel.bgy.service;
import com.bgy.sms.channel.bgy.dto.CLBizResponse;
public interface BgySmsService {
CLBizResponse sendSms(String mobile, String content) throws Exception;
}
package com.bgy.sms.channel.bgy.service.impl;
import com.alibaba.fastjson.JSONObject;
import com.bgy.sms.channel.bgy.config.BgySMSConfig;
import com.bgy.sms.channel.bgy.dto.CLBizResponse;
import com.bgy.sms.channel.bgy.service.BgySmsService;
import com.bgy.sms.channel.bgy.utils.SendSmsUtil;
import com.bgy.sms.channel.dmHub.service.DmHubService;
import com.bgy.sms.config.ResponseCode;
import com.bgy.sms.service.SmsTemplateService;
import com.bgy.util.Md5Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
@SuppressWarnings("DuplicatedCode")
@Service
public class BgySmsServiceImpl implements BgySmsService {
private static final Logger log = LoggerFactory.getLogger(BgySmsServiceImpl.class);
private static final String SUCCESS = "success";
private static final String sendSuccessCode = "0"; // 发送响应成功字段
private static final String createTemplateStatus = "status"; // 响应状态字段
private static final String retMsg = "msg"; // 响应描述
private static final String createTemplateData = "data"; // 创建模板响应数据
private static final String notificationId = "49"; // 创蓝通知类短信ID
private static final String marketingId = "52"; // 创蓝营销类短信ID
@Autowired
private SmsTemplateService templateService;
@Autowired
private DmHubService dmHubService;
@Override
public CLBizResponse sendSms(String mobile, String content) throws Exception {
String appId = BgySMSConfig.appId;
String securityCode = BgySMSConfig.securityCode;
String url = BgySMSConfig.url;
String areaId = BgySMSConfig.areaId;
String api = BgySMSConfig.api;
Map<String, String> requestParams = new HashMap<>();
requestParams.put("api", api);
requestParams.put("appId", appId);
requestParams.put("security", Md5Util.encrypt(appId + securityCode.toUpperCase()));
requestParams.put("areaId", areaId);
requestParams.put("content", content);
requestParams.put("mobile", mobile);
String retStr = SendSmsUtil.sendSmsByPost(url, JSONObject.toJSONString(requestParams));
if (retStr == null) {
return new CLBizResponse(ResponseCode.UPSTREAM_BLANK);
}
JSONObject retJson = JSONObject.parseObject(retStr);
String err = retJson.getString("err");
String retPack = retJson.getString("package");
String retCode = retJson.getString("ret");
if (!sendSuccessCode.equals(retCode)) {
return new CLBizResponse(ResponseCode.UPSTREAM_FAIL.getCode(), err);
} else {
return new CLBizResponse(ResponseCode.SUCCESS);
}
}
}
package com.bgy.sms.channel.bgy.utils;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
//import java.io.PrintWriter;
/**
* @author tianyh
* @Description:HTTP 请求
*/
@SuppressWarnings("Duplicates")
public class SendSmsUtil {
/**
* @param path
* @param postContent
* @return String
* @throws
* @author tianyh
* @Description
*/
public static String sendSmsByPost(String path, String postContent) {
URL url = null;
try {
url = new URL(path);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");// 提交模式
httpURLConnection.setConnectTimeout(10000);//连接超时 单位毫秒
httpURLConnection.setReadTimeout(10000);//读取超时 单位毫秒
// 发送POST请求必须设置如下两行
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
httpURLConnection.setRequestProperty("Charset", "UTF-8");
httpURLConnection.setRequestProperty("Content-Type", "application/json");
// PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
// printWriter.write(postContent);
// printWriter.flush();
httpURLConnection.connect();
OutputStream os = httpURLConnection.getOutputStream();
os.write(postContent.getBytes("UTF-8"));
os.flush();
StringBuilder sb = new StringBuilder();
int httpRspCode = httpURLConnection.getResponseCode();
if (httpRspCode == HttpURLConnection.HTTP_OK) {
// 开始获取数据
BufferedReader br = new BufferedReader(
new InputStreamReader(httpURLConnection.getInputStream(), "utf-8"));
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
return sb.toString();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static String sendTemplateByPost(String path, String postContent) {
URL url = null;
try {
url = new URL(path);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");// 提交模式
httpURLConnection.setConnectTimeout(10000);//连接超时 单位毫秒
httpURLConnection.setReadTimeout(10000);//读取超时 单位毫秒
// 发送POST请求必须设置如下两行
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
httpURLConnection.setRequestProperty("Charset", "UTF-8");
httpURLConnection.setRequestProperty("Content-Type", "application/json");
// PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
// printWriter.write(postContent);
// printWriter.flush();
httpURLConnection.connect();
OutputStream os = httpURLConnection.getOutputStream();
os.write(postContent.getBytes("UTF-8"));
os.flush();
StringBuilder sb = new StringBuilder();
int httpRspCode = httpURLConnection.getResponseCode();
if (httpRspCode == HttpURLConnection.HTTP_OK) {
// 开始获取数据
BufferedReader br = new BufferedReader(
new InputStreamReader(httpURLConnection.getInputStream(), "utf-8"));
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
return sb.toString();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
package com.bgy.sms.channel.dmHub.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class DmHubConfig {
// 应用过id
public static String applicationId;
// 应用key
public static String applicationKey;
public static String tokenUrl;
public static String report;
@Value("${system.config.dmHub.applicationId}")
public void setApplicationId(String applicationId) {
DmHubConfig.applicationId = applicationId;
}
@Value("{system.config.dmHub.applicationKey}")
public void setApplicationKey(String applicationKey) {
DmHubConfig.applicationKey = applicationKey;
}
@Value("{system.config.dmHub.tokenUrl}")
public void setTokenUrl(String tokenUrl) {
DmHubConfig.tokenUrl = tokenUrl;
}
@Value("{system.config.dmHub.report}")
public void setReport(String report) {
DmHubConfig.report = report;
}
}
package com.bgy.sms.channel.dmHub.service;
import com.bgy.sms.channel.bgy.dto.ReportDto;
import java.util.Map;
public interface DmHubService {
/**
* 获取DM hub token,用户请求DM hub接口
*
* @return token信息
*/
String getToken() ;
/**
* 回执报告给DM hub
*
* @param dto
* @return
*/
Map<String, Object> smsReport(ReportDto dto) throws Exception;
}
package com.bgy.sms.channel.dmHub.service.impl;
import com.alibaba.fastjson.JSONObject;
import com.bgy.sms.channel.bgy.config.ContentEnum;
import com.bgy.sms.channel.bgy.dto.ReportDto;
import com.bgy.sms.channel.dmHub.config.DmHubConfig;
import com.bgy.sms.channel.dmHub.service.DmHubService;
import com.bgy.sms.channel.dto.DmhubReport;
import com.bgy.sms.channel.dto.ReportDetail;
import com.bgy.util.HttpUtil;
import com.bgy.util.OkHttpUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
* Dm hub系统交互业务层
*/
@Service
public class DmHubServiceImpl implements DmHubService {
private static final Logger log = LoggerFactory.getLogger(DmHubServiceImpl.class);
private static final String TOKEN_KEY = "DM_HUB_API_TOKEN";
@Autowired
private RedisTemplate<String, Object> redisTemplate;
@Override
public String getToken() {
try {
Long expire = redisTemplate.getExpire(TOKEN_KEY, TimeUnit.SECONDS);
Object token = redisTemplate.opsForValue().get(TOKEN_KEY);
if (expire != null && expire > 0L && token != null) {
return token.toString();
} else {
String appid = DmHubConfig.applicationId;
String secret = DmHubConfig.applicationKey;
String tokenUrl = DmHubConfig.tokenUrl;
String grantType = "client_credentials";
Map<String, String> requestMap = new HashMap<>();
requestMap.put("appid", appid);
requestMap.put("secret", secret);
requestMap.put("grant_type", grantType);
String retStr = OkHttpUtil.get(tokenUrl, requestMap);
JSONObject retJson = JSONObject.parseObject(retStr);
String errorCode = retJson.getString("error_code");
if ("0".equals(errorCode)) {
String accessToken = retJson.getString("access_token");
String expires = retJson.getString("expires_in");
long exTime = Long.parseLong(expires) - 60 * 10L;
redisTemplate.opsForValue().set(TOKEN_KEY, accessToken, exTime, TimeUnit.SECONDS);
return accessToken;
} else {
// TODO 系统告警,获取API接口TOKEN失败。
return null;
}
}
} catch (Exception e) {
log.error("获取API接口TOKEN业务逻辑异常,异常信息:\r\n", e);
return null;
}
}
@Override
public Map<String, Object> smsReport(ReportDto dto) throws Exception {
try {
String token = getToken();
if (StringUtils.isBlank(token)) {
return null;
}
String uidStr = dto.getUid();
JSONObject uidJson = JSONObject.parseObject(uidStr);
String dmHubBatchId = uidJson.getString("dmHubId");
String sysBatchId = uidJson.getString("sysBatchId");
DmhubReport report = new DmhubReport();
report.setAccess_token(token);
report.setType("sms");
ReportDetail detail = new ReportDetail();
detail.setAudienceId(dto.getMobile());
detail.setBatchId(dmHubBatchId);
detail.setReportDate(dto.getReportTime());
detail.setMobile(dto.getMobile());
detail.setChargeNum(Integer.valueOf(dto.getLength()));
detail.setSendDate(dto.getReportTime());
if (ContentEnum.SMS_STATUS_SUCCESS.getValue().equals(dto.getStatus())) {
detail.setIsReceive(true);
} else {
detail.setIsReceive(false);
}
detail.setErrMessage(dto.getStatusDesc());
report.setReports(detail);
log.info("短信状态回执参数:{}", JSONObject.toJSONString(report));
String retStr = HttpUtil.sendPost(DmHubConfig.report, JSONObject.toJSONString(report));
log.info("短信状态回执响应:{}", retStr);
//TODO 目前没有测试环境的请求地址
} catch (Exception e) {
log.info("发送短信回执到DMHub异常\r\n短信信息:{},\r\n,异常:", dto, e);
}
return null;
}
}
package com.bgy.sms.channel.dto;
import com.alibaba.fastjson.JSONObject;
import java.io.Serializable;
import java.util.List;
public class DmHubBatchSendRequest implements Serializable {
private static final long serialVersionUID = 1L;
// 批量发送短信的模板id
private String templateId;
// 批次号
private String batchId;
// 账号类型(mobile就传手机号)
private String audienceIdType;
// 短信数据
private List<JSONObject> data;
public String getTemplateId() {
return templateId;
}
public void setTemplateId(String templateId) {
this.templateId = templateId;
}
public String getBatchId() {
return batchId;
}
public void setBatchId(String batchId) {
this.batchId = batchId;
}
public List<JSONObject> getData() {
return data;
}
public void setData(List<JSONObject> data) {
this.data = data;
}
public String getAudienceIdType() {
return audienceIdType;
}
public void setAudienceIdType(String audienceIdType) {
this.audienceIdType = audienceIdType;
}
}
package com.bgy.sms.channel.dto;
import com.alibaba.fastjson.JSONObject;
import java.io.Serializable;
public class DmHubSendRequest implements Serializable {
private static final long serialVersionUID = 1L;
// 发送短信的模板ID
private String templateId;
// DMHUb的批次号
private String batchId;
// 渠道类型(初期给到DMHUb系统库的类型,如果是sms,data里面会直接反手机号,
// 如果是customerIdentity.memberId,data返回memberId,需要查询系统memberId用户对应的手机号发送短信)
private String audienceIdType;
// 发送数据
private JSONObject data;
public String getTemplateId() {
return templateId;
}
public void setTemplateId(String templateId) {
this.templateId = templateId;
}
public String getBatchId() {
return batchId;
}
public void setBatchId(String batchId) {
this.batchId = batchId;
}
public String getAudienceIdType() {
return audienceIdType;
}
public void setAudienceIdType(String audienceIdType) {
this.audienceIdType = audienceIdType;
}
public JSONObject getData() {
return data;
}
public void setData(JSONObject data) {
this.data = data;
}
}
package com.bgy.sms.channel.dto;
import com.bgy.sms.config.ResponseCode;
import java.io.Serializable;
public class DmHubSendResponse implements Serializable {
private static final long serialVersionUID = 1L;
private String code;
private String msg;
public DmHubSendResponse() {
}
public DmHubSendResponse(String code, String msg) {
this.code = code;
this.msg = msg;
}
public DmHubSendResponse(ResponseCode responseCode) {
this.code = responseCode.getCode();
this.msg = responseCode.getMsg();
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
@Override
public String toString() {
return "DmHubSendResponse{" +
"code='" + code + '\'' +
", msg='" + msg + '\'' +
'}';
}
}
package com.bgy.sms.channel.dto;
import java.io.Serializable;
public class DmHubTemplateRequest implements Serializable {
private static final long serialVersionUID = 1L;
private String tenantId;
private String templateId;
private String templateContent;
private String smsType;
private String signature;
private String templateName;
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getTemplateId() {
return templateId;
}
public void setTemplateId(String templateId) {
this.templateId = templateId;
}
public String getTemplateContent() {
return templateContent;
}
public void setTemplateContent(String templateContent) {
this.templateContent = templateContent;
}
public String getSmsType() {
return smsType;
}
public void setSmsType(String smsType) {
this.smsType = smsType;
}
public String getSignature() {
return signature;
}
public void setSignature(String signature) {
this.signature = signature;
}
public String getTemplateName() {
return templateName;
}
public void setTemplateName(String templateName) {
this.templateName = templateName;
}
}
package com.bgy.sms.channel.dto;
import com.bgy.sms.config.ResponseCode;
import java.io.Serializable;
public class DmHubTemplateResponse implements Serializable {
private static final long serialVersionUID = 1L;
private String code;
private String msg;
public DmHubTemplateResponse() {
}
public DmHubTemplateResponse(String code, String msg) {
this.code = code;
this.msg = msg;
}
public DmHubTemplateResponse(ResponseCode responseCode) {
this.code = responseCode.getCode();
this.msg = responseCode.getMsg();
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
package com.bgy.sms.channel.dto;
import java.io.Serializable;
public class DmhubReport implements Serializable {
private static final long serialVersionUID = 810019212627996764L;
private String type;
private String access_token;
private ReportDetail reports;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public ReportDetail getReports() {
return reports;
}
public void setReports(ReportDetail reports) {
this.reports = reports;
}
public String getAccess_token() {
return access_token;
}
public void setAccess_token(String access_token) {
this.access_token = access_token;
}
}
package com.bgy.sms.channel.dto;
import java.io.Serializable;
public class ReportDetail implements Serializable {
private static final long serialVersionUID = 810019212627996764L;
private String audienceId;
private String batchId;
private String reportDate;
private Boolean isReceive;
private String mobile;
private Integer chargeNum;
private String sendDate;
private String errMessage;
private String content;
private String msgCode;
private String campaign;
public String getAudienceId() {
return audienceId;
}
public void setAudienceId(String audienceId) {
this.audienceId = audienceId;
}
public String getBatchId() {
return batchId;
}
public void setBatchId(String batchId) {
this.batchId = batchId;
}
public String getReportDate() {
return reportDate;
}
public void setReportDate(String reportDate) {
this.reportDate = reportDate;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getSendDate() {
return sendDate;
}
public void setSendDate(String sendDate) {
this.sendDate = sendDate;
}
public String getErrMessage() {
return errMessage;
}
public void setErrMessage(String errMessage) {
this.errMessage = errMessage;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getMsgCode() {
return msgCode;
}
public void setMsgCode(String msgCode) {
this.msgCode = msgCode;
}
public String getCampaign() {
return campaign;
}
public void setCampaign(String campaign) {
this.campaign = campaign;
}
public Boolean getIsReceive() {
return isReceive;
}
public void setIsReceive(Boolean receive) {
isReceive = receive;
}
public Integer getChargeNum() {
return chargeNum;
}
public void setChargeNum(Integer chargeNum) {
this.chargeNum = chargeNum;
}
}
package com.bgy.sms.config;
import com.baomidou.mybatisplus.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.plugins.PerformanceInterceptor;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
//@MapperScan("com.baomidou.springboot.mapper*")//这个注解,作用相当于下面的@Bean MapperScannerConfigurer,2者配置1份即可
public class MybatisPlusConfig {
/**
* SQL输出拦截器,性能分析器,不建议生产环境使用,开发环境使用(方便)
*/
@Bean
public PerformanceInterceptor performanceInterceptor() {
PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
//sql格式化
performanceInterceptor.setFormat(true);
return performanceInterceptor;
}
/**
* mybatis-plus分页插件<br>
* 文档:http://mp.baomidou.com<br>
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
//paginationInterceptor.setDialectType("mysql"); //指定数据库类型,不写自动匹配
return paginationInterceptor;
};
@Bean
public MapperScannerConfigurer mapperScannerConfigurer() {
MapperScannerConfigurer scannerConfigurer = new MapperScannerConfigurer();
scannerConfigurer.setBasePackage("com.baomidou.springboot.mapper*");
return scannerConfigurer;
}
}
\ No newline at end of file
package com.bgy.sms.config;
import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;
@Component
public class OkHttpConfig {
@Bean
public OkHttpClient okHttpClient() {
return new OkHttpClient().newBuilder().retryOnConnectionFailure(false).connectionPool(pool())
.connectTimeout(5, TimeUnit.SECONDS).readTimeout(5, TimeUnit.SECONDS).writeTimeout(5, TimeUnit.SECONDS)
.build();
}
@Bean
public ConnectionPool pool() {
return new ConnectionPool(50, 5, TimeUnit.MINUTES);
}
}
package com.bgy.sms.config;
import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.support.spring.FastJsonRedisSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
public class RedisConfig{
@Bean
public RedisTemplate<String, Object> getRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
//全局开启
ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
//key序列化
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
//value序列化
redisTemplate.setValueSerializer(new FastJsonRedisSerializer<>(Object.class));
redisTemplate.setHashValueSerializer(new FastJsonRedisSerializer<>(Object.class));
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
}
package com.bgy.sms.config;
public enum ResponseCode {
// 系统判断错误
SUCCESS("200", "处理成功"),
UNKNOWN_TEMPLATE_TYPE("500", "未知模板类型"),
TEMPLATE_ALREADY_EXISTED("500", "DM Hub模板ID冲突"),
SYSTEM_ERROR("99", "系统异常:"),
// 渠道异常错误
UPSTREAM_FAIL("US01", "渠道交易失败"),
UPSTREAM_UNKNOWN_MODEL("US01", "未知通知模式"),
UPSTREAM_BLANK("US00", "渠道同步响应为空");
private String code;
private String msg;
ResponseCode(String code, String msg) {
this.code = code;
this.msg = msg;
}
public String getCode() {
return code;
}
public String getMsg() {
return msg;
}
}
package com.bgy.sms.repository.domain;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.io.Serializable;
import java.util.Date;
public class BaseEntity implements Serializable {
private static final long serialVersionUID = 8100192126279967648L;
// 表关键字
protected Long id;
// 记录是否逻辑删除(默认为false)
private Boolean delFlag = false;
// 记录创建人信息
private String creater;
// 记录创建日期
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date createTime;
// 记录更新人信息
private String updater;
// 记录最近修改日期
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date updateTime;
//获取redis的key值
private String key;
}
package com.bgy.sms.repository.domain;
import com.baomidou.mybatisplus.annotations.TableName;
import java.util.Date;
@TableName("dm_batch")
public class DmBatchInfo {
private Long id;
private String dmBatchId;
private String dmTemplateId;
private Integer smsNum;
private Integer successNum;
private Integer failNum;
private Date dateCreated;
private Date lastUpdated;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getDmBatchId() {
return dmBatchId;
}
public void setDmBatchId(String dmBatchId) {
this.dmBatchId = dmBatchId;
}
public String getDmTemplateId() {
return dmTemplateId;
}
public void setDmTemplateId(String dmTemplateId) {
this.dmTemplateId = dmTemplateId;
}
public Integer getSmsNum() {
return smsNum;
}
public void setSmsNum(Integer smsNum) {
this.smsNum = smsNum;
}
public Integer getSuccessNum() {
return successNum;
}
public void setSuccessNum(Integer successNum) {
this.successNum = successNum;
}
public Integer getFailNum() {
return failNum;
}
public void setFailNum(Integer failNum) {
this.failNum = failNum;
}
public Date getDateCreated() {
return dateCreated;
}
public void setDateCreated(Date dateCreated) {
this.dateCreated = dateCreated;
}
public Date getLastUpdated() {
return lastUpdated;
}
public void setLastUpdated(Date lastUpdated) {
this.lastUpdated = lastUpdated;
}
}
package com.bgy.sms.repository.domain;
import com.baomidou.mybatisplus.annotations.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.util.Date;
@TableName("sms_template")
public class SmsTemplateInfo {
private Long id;
private String dmTemplateId;
private String type;
private String status;
// DM 模板内容
private String content;
// 上游模板内容
private String upContent;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date dateCreated;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date lastUpdated;
private String signature;
private String tenantId;
private String templateName;
private String upTemplateId;
private String upRejectMsg;
private String params;
public SmsTemplateInfo() {
}
public String getUpContent() {
return upContent;
}
public void setUpContent(String upContent) {
this.upContent = upContent;
}
public String getTemplateName() {
return templateName;
}
public void setTemplateName(String templateName) {
this.templateName = templateName;
}
public SmsTemplateInfo(String dmTemplateId) {
this.dmTemplateId = dmTemplateId;
}
public String getSignature() {
return signature;
}
public void setSignature(String signature) {
this.signature = signature;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getDmTemplateId() {
return dmTemplateId;
}
public void setDmTemplateId(String dmTemplateId) {
this.dmTemplateId = dmTemplateId;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Date getDateCreated() {
return dateCreated;
}
public void setDateCreated(Date dateCreated) {
this.dateCreated = dateCreated;
}
public Date getLastUpdated() {
return lastUpdated;
}
public void setLastUpdated(Date lastUpdated) {
this.lastUpdated = lastUpdated;
}
public String getUpTemplateId() {
return upTemplateId;
}
public void setUpTemplateId(String upTemplateId) {
this.upTemplateId = upTemplateId;
}
public String getUpRejectMsg() {
return upRejectMsg;
}
public void setUpRejectMsg(String upRejectMsg) {
this.upRejectMsg = upRejectMsg;
}
public String getParams() {
return params;
}
public void setParams(String params) {
this.params = params;
}
}
package com.bgy.sms.repository.domain;
import com.baomidou.mybatisplus.annotations.TableName;
import java.util.Date;
@TableName("sys_batch")
public class SysBatchInfo {
private Long id;