Commit df84264e authored by Menethil's avatar Menethil
Browse files

修改通知类逻辑,添加微信模版通知,修改配置为yaml

parent e97e32fc
......@@ -47,6 +47,15 @@
<artifactId>qcloudsms</artifactId>
<version>1.0.5</version>
</dependency>
<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>weixin-java-miniapp</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
<build>
......
......@@ -19,11 +19,11 @@ import java.util.concurrent.ThreadPoolExecutor;
@EnableAsync
class ExecutorConfig {
@Value("${spring.notify.corePoolSize}")
@Value("${NotifyPoolConfig.corePoolSize}")
private int corePoolSize;
@Value("${spring.notify.maxPoolSize}")
@Value("${NotifyPoolConfig.maxPoolSize}")
private int maxPoolSize;
@Value("${spring.notify.queueCapacity}")
@Value("${NotifyPoolConfig.queueCapacity}")
private int queueCapacity;
@Bean(name = "notifyAsync")
......@@ -37,4 +37,4 @@ class ExecutorConfig {
executor.initialize();
return executor;
}
}
}
\ No newline at end of file
package org.linlinjava.litemall.core.notify;
import org.linlinjava.litemall.core.notify.util.ConfigUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
/**
* Litemall商城通知服务类
*/
@PropertySource(value = "classpath:notify.properties")
@Service("litemallNotifyService")
public class LitemallNotifyService {
@Autowired
MailSendService mailSendService;
private MailSendService mailSendService;
@Autowired
SMSSendService smsSendService;
private SMSSendService smsSendService;
@Autowired
Environment environment;
private WXTemplateSendService wxTemplateSendService;
@Value("${sprint.mail.enable}")
private boolean sendMailEnable;
@Value("${spring.sms.enable}")
private boolean sendSMSEnable;
public void notifySMSMessage(String phoneNumber,String message) {
if (!sendSMSEnable)
@Async("notifyAsync")
public void notifySMSMessage(String phoneNumber, String message) {
if (!smsSendService.config.isEnable())
return;
smsSendService.sendSMS(phoneNumber, message);
}
/**
* 短信模版通知
* @param phoneNumber 接收通知的电话号码
* 微信模版消息通知
* @param token 通过wxMAService获取token或者通过url请求token
* @param touser 接收者openId
* @param formId 表单ID或者 prepayId
* @param notifyType 通知类别,通过该枚举值在配置文件中获取相应的模版ID
* @param params 通知模版内容里的参数,类似"您的验证码为{1}"中{1}的值
*/
public void notifySMSTemplate(String phoneNumber, NotifyUtils.NotifyType notifyType, String[] params) {
if (!sendSMSEnable)
@Async("notifyAsync")
public void notifyWXTemplate(String token,String touser, String formId, ConfigUtil.NotifyType notifyType, String[] params) {
if (!wxTemplateSendService.config.isEnable())
return;
int templateId = -1;
switch (notifyType) {
case PAY_SUCCEED:
templateId = Integer.parseInt(environment.getProperty("spring.sms.template.paySucceed"));
break;
case CAPTCHA:
templateId = Integer.parseInt(environment.getProperty("spring.sms.template.captcha"));
break;
}
String templateId = ConfigUtil.getTemplateId(notifyType, wxTemplateSendService.config.getTemplate());
if (templateId != "")
wxTemplateSendService.sendWechatMsg(token,touser, templateId, formId, "", "", params);
}
/**
* 短信模版通知
*
* @param phoneNumber 接收通知的电话号码
* @param notifyType 通知类别,通过该枚举值在配置文件中获取相应的模版ID
* @param params 通知模版内容里的参数,类似"您的验证码为{1}"中{1}的值
*/
@Async("notifyAsync")
public void notifySMSTemplate(String phoneNumber, ConfigUtil.NotifyType notifyType, String[] params) {
if (!smsSendService.config.isEnable())
return;
int templateId = Integer.parseInt(ConfigUtil.getTemplateId(notifyType, smsSendService.config.getTemplate()));
if (templateId != -1)
smsSendService.sendSMSWithTemplate(phoneNumber, templateId, params);
......@@ -57,24 +64,28 @@ public class LitemallNotifyService {
/**
* 短信模版通知
* @param phoneNumber 接收通知的电话号码
* @param templateId 模板ID
* @param params 通知模版内容里的参数,类似"您的验证码为{1}"中{1}的值
*
* @param phoneNumber 接收通知的电话号码
* @param templateId 模板ID
* @param params 通知模版内容里的参数,类似"您的验证码为{1}"中{1}的值
*/
@Async("notifyAsync")
public void notifySMSTemplate(String phoneNumber, int templateId, String[] params) {
if (!sendSMSEnable)
if (!smsSendService.config.isEnable())
return;
smsSendService.sendSMSWithTemplate(phoneNumber, templateId, params);
smsSendService.sendSMSWithTemplate(phoneNumber, templateId, params);
}
/**
* 发送邮件通知,接收者在spring.mail.sendto中指定
* @param setSubject 邮件标题
* @param setText 邮件内容
*
* @param setSubject 邮件标题
* @param setText 邮件内容
*/
@Async("notifyAsync")
public void notifyMailMessage(String setSubject, String setText) {
if(!sendMailEnable)
if (!mailSendService.config.isEnable())
return;
mailSendService.sendEmail(setSubject, setText);
......
package org.linlinjava.litemall.core.notify;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.mail.javamail.JavaMailSender;
import org.linlinjava.litemall.core.notify.config.MailNotifyConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
@PropertySource(value = "classpath:notify.properties")
@Service("mailSendService")
class MailSendService {
@Resource
private JavaMailSender mailSender;
@Autowired
MailNotifyConfig config;
@Value("${spring.mail.username}")
private String from;
private JavaMailSenderImpl mailSender;
@Value("${spring.mail.sendto}")
private String sendto;
private JavaMailSenderImpl getMailSender() {
if (mailSender == null) {
mailSender = new JavaMailSenderImpl();
mailSender.setHost(config.getHost());
mailSender.setUsername(config.getUsername());
mailSender.setPassword(config.getPassword());
}
return mailSender;
}
/**
* 异步发送邮件通知
* 发送邮件通知
*
* @param setSubject 邮件标题
* @param setText 邮件内容
* @param setText 邮件内容
*/
@Async("notifyAsync")
public void sendEmail(String setSubject, String setText) {
try {
final MimeMessage mimeMessage = mailSender.createMimeMessage();
final MimeMessage mimeMessage = getMailSender().createMimeMessage();
final MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
message.setFrom(from);
message.setTo(sendto);
message.setFrom(config.getUsername());
message.setTo(config.getSendto());
message.setSubject(setSubject);
message.setText(setText);
mailSender.send(mimeMessage);
getMailSender().send(mimeMessage);
} catch (Exception ex) {
ex.printStackTrace();
......
package org.linlinjava.litemall.core.notify;
public class NotifyUtils {
/**
* 该枚举定义了所有的需要通知的事件,调用通知时作为参数
*
* PAY_SUCCEED 支付成功,通常用于用户支付成功
* CAPTCHA 验证码,通常用于登录、注册、找回密码
*/
public enum NotifyType {
PAY_SUCCEED,
CAPTCHA
}
}
......@@ -4,29 +4,21 @@ import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import com.github.qcloudsms.httpclient.HTTPException;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.scheduling.annotation.Async;
import org.linlinjava.litemall.core.notify.config.SMSNotifyConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.IOException;
@PropertySource(value = "classpath:notify.properties")
@Service("smsSendService")
class SMSSendService {
@Value("${spring.sms.appid}")
private int appid;
@Value("${spring.sms.appkey}")
private String appkey;
@Value("${spring.sms.sign}")
private String smsSign;
@Autowired
SMSNotifyConfig config;
@Async("notifyAsync")
public void sendSMS(String phoneNumber, String content) {
try {
SmsSingleSender ssender = new SmsSingleSender(appid, appkey);
SmsSingleSender ssender = new SmsSingleSender(config.getAppid(), config.getAppkey());
SmsSingleSenderResult result = ssender.send(0, "86", phoneNumber,
content, "", "");
......@@ -43,12 +35,17 @@ class SMSSendService {
}
}
@Async("notifyAsync")
/**
* 通过模版发送短信息
* @param phoneNumber
* @param templateId
* @param params
*/
public void sendSMSWithTemplate(String phoneNumber, int templateId, String[] params) {
try {
SmsSingleSender ssender = new SmsSingleSender(appid, appkey);
SmsSingleSender ssender = new SmsSingleSender(config.getAppid(), config.getAppkey());
SmsSingleSenderResult result = ssender.sendWithParam("86", phoneNumber,
templateId, params, smsSign, "", ""); // 签名参数未提供或者为空时,会使用默认签名发送短信
templateId, params, config.getSign(), "", ""); // 签名参数未提供或者为空时,会使用默认签名发送短信
// System.out.println(result);
} catch (HTTPException e) {
// HTTP响应码错误
......
package org.linlinjava.litemall.core.notify;
import org.json.JSONObject;
import org.springframework.context.annotation.PropertySource;
import org.linlinjava.litemall.core.notify.config.WXNotifyConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.net.ssl.*;
......@@ -16,11 +17,13 @@ import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
/**
* 微信模版消息通知,未完成
* 微信模版消息通知
*/
@PropertySource(value = "classpath:notify.properties")
@Service("wxTemplateMsgSendService")
public class WXTemplateMsgSendService {
class WXTemplateSendService {
@Autowired
WXNotifyConfig config;
/**
* 发送微信消息(模板消息)
*
......@@ -29,19 +32,20 @@ public class WXTemplateMsgSendService {
* @param formId payId或者表单ID
* @param clickurl URL置空,则在发送后,点击模板消息会进入一个空白页面(ios),或无法点击(android)。
* @param topcolor 标题颜色
* @param data 详细内容
* @param parms 详细内容
* @return
*/
public String sendWechatMsgToUser(String token, String touser, String templatId, String formId, String clickurl, String topcolor, JSONObject data) {
String tmpurl = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=" + token;
JSONObject json = new JSONObject();
json.put("touser", touser);
json.put("template_id", templatId);
json.put("form_id", formId);
json.put("url", clickurl);
json.put("topcolor", topcolor);
json.put("data", data);
public String sendWechatMsg(String token, String touser, String templatId, String formId, String clickurl, String topcolor, String[] parms) {
try {
String tmpurl = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=" + token;
JSONObject json = new JSONObject();
json.put("touser", touser);
json.put("template_id", templatId);
json.put("form_id", formId);
json.put("url", clickurl);
json.put("topcolor", topcolor);
json.put("data", createParmData(parms));
JSONObject result = httpsRequest(tmpurl, "POST", json.toString());
// log.info("发送微信消息返回信息:" + resultJson.get("errcode"));
String errmsg = (String) result.get("errmsg");
......@@ -55,6 +59,23 @@ public class WXTemplateMsgSendService {
return "success";
}
/**
* 根据参数生成对应的 json 数据
* @param parms
* @return
*/
private JSONObject createParmData(String[] parms) {
JSONObject json = new JSONObject();
for (int i = 1; i <= parms.length; i++) {
JSONObject json2 = new JSONObject();
json2.put("value", parms[i-1]);
json.put("keyword" + i, json2);
}
return json;
}
/**
* 发送https请求
*
......@@ -125,7 +146,6 @@ public class WXTemplateMsgSendService {
@Override
public X509Certificate[] getAcceptedIssuers() {
// return new X509Certificate[0];
return null;
}
}
......
package org.linlinjava.litemall.core.notify.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "MailNotifyConfig")
public class MailNotifyConfig {
private boolean enable;
private String host;
private String username;
private String password;
private String sendto;
public boolean isEnable() {
return enable;
}
public void setEnable(boolean enable) {
this.enable = enable;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getSendto() {
return sendto;
}
public void setSendto(String sendto) {
this.sendto = sendto;
}
}
package org.linlinjava.litemall.core.notify.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Component
@ConfigurationProperties(prefix = "SMSNotifyConfig")
public class SMSNotifyConfig {
private boolean enable;
private int appid;
private String appkey;
private String sign;
private List<Map<String,String>> template = new ArrayList<>();
public boolean isEnable() {
return enable;
}
public void setEnable(boolean enable) {
this.enable = enable;
}
public int getAppid() {
return appid;
}
public void setAppid(int appid) {
this.appid = appid;
}
public String getAppkey() {
return appkey;
}
public void setAppkey(String appkey) {
this.appkey = appkey;
}
public String getSign() {
return sign;
}
public void setSign(String sign) {
this.sign = sign;
}
public List<Map<String, String>> getTemplate() {
return template;
}
public void setTemplate(List<Map<String, String>> template) {
this.template = template;
}
}
package org.linlinjava.litemall.core.notify.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Component
@ConfigurationProperties(prefix = "WXNotifyConfig")
public class WXNotifyConfig {
private boolean enable;
private List<Map<String,String>> template = new ArrayList<>();
public boolean isEnable() {
return enable;
}
public void setEnable(boolean enable) {
this.enable = enable;
}
public List<Map<String, String>> getTemplate() {
return template;
}
public void setTemplate(List<Map<String, String>> template) {
this.template = template;
}
}
package org.linlinjava.litemall.core.notify.util;
import java.util.List;
import java.util.Map;
public class ConfigUtil {
/**
* 通过枚举获取对应的 templateId,注意 application.yaml 里字段名必须一致
* @param notifyType
* @param values
* @return
*/
public static String getTemplateId(NotifyType notifyType, List<Map<String, String>> values) {
for (Map<String, String> item : values) {
String notifyTypeStr = getNotifyType(notifyType);
if (item.get("name").equals(notifyTypeStr))
return item.get("templateId");
}
return "";
}
/**
* 该处字符串对应 application.yaml 里 template.name 的值,请注意
* @param notifyType
* @return
*/
private static String getNotifyType(NotifyType notifyType)
{
switch (notifyType) {
case PAY_SUCCEED:
return "paySucceed";
case CAPTCHA:
return "captcha";
}
return "";
}
/**
* 该枚举定义了所有的需要通知的事件,调用通知时作为参数
*
* PAY_SUCCEED 支付成功,通常用于用户支付成功
* CAPTCHA 验证码,通常用于登录、注册、找回密码
*/
public enum NotifyType {
PAY_SUCCEED,
CAPTCHA
}
}
# 邮件通知配置,邮箱一般用于接收业务通知例如收到新的订单,sendto 定义邮件接收者,通常为商城运营人员
MailNotifyConfig:
enable: false
host: smtp.exmail.qq.com
username: ex@ex.com.cn
password: XXXXXXXXXXXXX
sendto: ex@qq.com
# 短消息模版通知配置
# 短信息用于通知客户,例如发货短信通知,注意配置格式;template-name,template-templateId 请参考 ConfigUtil 内枚举值
SMSNotifyConfig:
enable: false
appid: 111111111
appkey: xxxxxxxxxxxxxx
sign: xxxxxxxxx
template:
- name: paySucceed
templateId: 156349
- name: captcha
templateId: 156433
# 微信模版通知配置
# 微信模版用于通知客户或者运营者,注意配置格式;template-name,template-templateId 请参考 ConfigUtil 内枚举值
WXNotifyConfig:
enable: false
template:
- name: paySucceed
templateId: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
- name: captcha
templateId: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
# 发送线程池配置
NotifyPoolConfig:
corePoolSize: 5
maxPoolSize: 100
queueCapacity: 50
\ No newline at end of file
# \u90AE\u4EF6\u53D1\u9001\u914D\u7F6E
sprint.mail.enable=false
spring.mail.host=smtp.exmail.qq.com
spring.mail.username=xxxxxx
spring.mail.password=xxxxxx
spring.mail.sendto=example@qq.com
# \u77ED\u4FE1\u53D1\u9001\u914D\u7F6E
spring.sms.enable=false
spring.sms.appid=111111
spring.sms.appkey=xxxxxx
spring.sms.sign=xxxxxx
# \u77ED\u4FE1\u6A21\u677F\u6D88\u606F\u914D\u7F6E
# \u8BF7\u5728\u817E\u8BAF\u77ED\u4FE1\u5E73\u53F0\u914D\u7F6E\u901A\u77E5\u6D88\u606F\u6A21\u677F\uFF0C\u7136\u540E\u8FD9\u91CC\u8BBE\u7F6E\u4E0D\u540C\u77ED\u4FE1\u6A21\u677FID
# \u8BF7\u53C2\u8003LitemallNotifyService.notifySMSTemplate
spring.sms.template.paySucceed=111111
spring.sms.template.captcha=222222
# \u53D1\u9001\u7EBF\u7A0B\u6C60\u914D\u7F6E
spring.notify.corePoolSize=5
spring.notify.maxPoolSize=100
spring.notify.queueCapacity=50
\ No newline at end of file
......@@ -3,7 +3,7 @@ package org.linlinjava.litemall.core;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.linlinjava.litemall.core.notify.LitemallNotifyService;
import org.linlinjava.litemall.core.notify.NotifyUtils;
import org.linlinjava.litemall.core.notify.util.ConfigUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
......@@ -47,7 +47,7 @@ public class SmsTest {
String phone = "xxxxxxxxxxx";
String[] params = new String[] {"123456"};
litemallNotifyService.notifySMSTemplate(phone, NotifyUtils.NotifyType.CAPTCHA, params);
litemallNotifyService.notifySMSTemplate(phone, ConfigUtil.NotifyType.CAPTCHA, params);
try {
Thread.sleep(5000);
......@@ -61,7 +61,7 @@ public class SmsTest {
String phone = "xxxxxxxxxxx";
String[] params = new String[] {"123456"};
litemallNotifyService.notifySMSTemplate(phone, NotifyUtils.NotifyType.PAY_SUCCEED, params);
litemallNotifyService.notifySMSTemplate(phone, ConfigUtil.NotifyType.PAY_SUCCEED, params);
try {
Thread.sleep(5000);
......
......@@ -10,7 +10,7 @@ import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.linlinjava.litemall.core.notify.LitemallNotifyService;
import org.linlinjava.litemall.core.notify.NotifyUtils;
import org.linlinjava.litemall.core.notify.util.ConfigUtil;
import org.linlinjava.litemall.core.util.JacksonUtil;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.*;
......@@ -554,7 +554,7 @@ public class WxOrderController {
//TODO 发送邮件和短信通知,这里采用异步发送
// 订单支付成功以后,会发送短信给用户,以及发送邮件给管理员
litemallNotifyService.notifyMailMessage("新订单通知", order.toString());
litemallNotifyService.notifySMSTemplate(order.getMobile(), NotifyUtils.NotifyType.PAY_SUCCEED, new String[]{orderSn});
litemallNotifyService.notifySMSTemplate(order.getMobile(), ConfigUtil.NotifyType.PAY_SUCCEED, new String[]{orderSn});
return WxPayNotifyResponse.success("处理成功!");
} catch (Exception e) {
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment