Commit 7d413306 by 吕明尚

增加通知消息示例

parent 3648e7a6
......@@ -53,6 +53,11 @@
<artifactId>hutool-all</artifactId>
<version>5.8.16</version>
</dependency>
<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>weixin-java-miniapp</artifactId>
<version>4.5.0</version>
</dependency>
</dependencies>
<build>
......
package share.web.controller.common;
import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage;
import cn.hutool.core.date.LocalDateTimeUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import share.system.service.WxMsgPushConService;
import share.system.util.WXMsgPushUtils;
import share.web.core.config.WxMaProperties;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
/**
......@@ -18,15 +24,16 @@ import java.util.Map;
**/
@RestController
@Slf4j
@AllArgsConstructor
@RequestMapping("/weixinpublic")
public class WxMsgPushController {
@Value("${wechat.token}")
private String token;
// @Autowired
// private WxMsgPushConService wxMsgPushConService;
private final WxMaService wxMaService;
private final WxMaProperties properties;
/**
* // * 跳转的小程序页面
* //
*/
private static final String PAGES_ZP = "pages/draft-review/list/list";
/**
* 正确响应微信发送的Token验证,注意 这里是 get请求
......@@ -44,7 +51,7 @@ public class WxMsgPushController {
String nonce = params.get("nonce");
// 验证
String msgSignature = WXMsgPushUtils.getSHA1(token, timestamp, nonce);
String msgSignature = WXMsgPushUtils.getSHA1(properties.getConfigs().get(0).getToken(), timestamp, nonce);
// 验证失败
if (!signature.equals(msgSignature)) {
......@@ -54,5 +61,29 @@ public class WxMsgPushController {
return echostr;
}
@GetMapping("/getOpenId")
public void getOpenId(String openId) throws Exception {
Map<String, String> map = new HashMap<>();
map.put("thing4", "预约门店");
map.put("thing7", "服务名称");
map.put("date3", LocalDateTimeUtil.format(LocalDateTime.now(), "yyyy-MM-dd HH:mm:ss"));
map.put("thing5", "地址");
WxMaSubscribeMessage wxMaSubscribeMessage = WxMaSubscribeMessage.builder()
.toUser(openId)
.templateId("oTc000e4NHkoc7v9OLBZiwM6Q6SFzguemrx6d0iuVS8")
.page(PAGES_ZP)
.build();
// 设置将推送的消息
map.forEach((k, v) -> {
wxMaSubscribeMessage.addData(new WxMaSubscribeMessage.MsgData(k, v));
});
try {
log.info("开始发送消息!!!!");
wxMaService.getMsgService().sendSubscribeMsg(wxMaSubscribeMessage);
log.info("消息发送成功!!!!");
} catch (WxErrorException e) {
e.printStackTrace();
}
}
}
package share.web.core.config;
import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.bean.WxMaKefuMessage;
import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import cn.binarywang.wx.miniapp.message.WxMaMessageHandler;
import cn.binarywang.wx.miniapp.message.WxMaMessageRouter;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.result.WxMediaUploadResult;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.error.WxRuntimeException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.io.File;
import java.util.List;
import java.util.stream.Collectors;
/**
* @author <a href="https://github.com/binarywang">Binary Wang</a>
*/
@Slf4j
@Configuration
@EnableConfigurationProperties(WxMaProperties.class)
public class WxMaConfiguration {
private final WxMaProperties properties;
@Autowired
public WxMaConfiguration(WxMaProperties properties) {
this.properties = properties;
}
@Bean
public WxMaService wxMaService() {
List<WxMaProperties.Config> configs = this.properties.getConfigs();
if (configs == null) {
throw new WxRuntimeException("大哥,拜托先看下项目首页的说明(readme文件),添加下相关配置,注意别配错了!");
}
WxMaService maService = new WxMaServiceImpl();
maService.setMultiConfigs(
configs.stream()
.map(a -> {
WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();
// WxMaDefaultConfigImpl config = new WxMaRedisConfigImpl(new JedisPool());
// 使用上面的配置时,需要同时引入jedis-lock的依赖,否则会报类无法找到的异常
config.setAppid(a.getAppid());
config.setSecret(a.getSecret());
config.setToken(a.getToken());
config.setAesKey(a.getAesKey());
config.setMsgDataFormat(a.getMsgDataFormat());
return config;
}).collect(Collectors.toMap(WxMaDefaultConfigImpl::getAppid, a -> a, (o, n) -> o)));
return maService;
}
@Bean
public WxMaMessageRouter wxMaMessageRouter(WxMaService wxMaService) {
final WxMaMessageRouter router = new WxMaMessageRouter(wxMaService);
router
.rule().handler(logHandler).next()
.rule().async(false).content("订阅消息").handler(subscribeMsgHandler).end()
.rule().async(false).content("文本").handler(textHandler).end()
.rule().async(false).content("图片").handler(picHandler).end()
.rule().async(false).content("二维码").handler(qrcodeHandler).end();
return router;
}
private final WxMaMessageHandler subscribeMsgHandler = (wxMessage, context, service, sessionManager) -> {
service.getMsgService().sendSubscribeMsg(WxMaSubscribeMessage.builder()
.templateId("此处更换为自己的模板id")
.data(Lists.newArrayList(
new WxMaSubscribeMessage.MsgData("keyword1", "339208499")))
.toUser(wxMessage.getFromUser())
.build());
return null;
};
private final WxMaMessageHandler logHandler = (wxMessage, context, service, sessionManager) -> {
log.info("收到消息:" + wxMessage.toString());
service.getMsgService().sendKefuMsg(WxMaKefuMessage.newTextBuilder().content("收到信息为:" + wxMessage.toJson())
.toUser(wxMessage.getFromUser()).build());
return null;
};
private final WxMaMessageHandler textHandler = (wxMessage, context, service, sessionManager) -> {
service.getMsgService().sendKefuMsg(WxMaKefuMessage.newTextBuilder().content("回复文本消息")
.toUser(wxMessage.getFromUser()).build());
return null;
};
private final WxMaMessageHandler picHandler = (wxMessage, context, service, sessionManager) -> {
try {
WxMediaUploadResult uploadResult = service.getMediaService()
.uploadMedia("image", "png",
ClassLoader.getSystemResourceAsStream("tmp.png"));
service.getMsgService().sendKefuMsg(
WxMaKefuMessage
.newImageBuilder()
.mediaId(uploadResult.getMediaId())
.toUser(wxMessage.getFromUser())
.build());
} catch (WxErrorException e) {
e.printStackTrace();
}
return null;
};
private final WxMaMessageHandler qrcodeHandler = (wxMessage, context, service, sessionManager) -> {
try {
final File file = service.getQrcodeService().createQrcode("123", 430);
WxMediaUploadResult uploadResult = service.getMediaService().uploadMedia("image", file);
service.getMsgService().sendKefuMsg(
WxMaKefuMessage
.newImageBuilder()
.mediaId(uploadResult.getMediaId())
.toUser(wxMessage.getFromUser())
.build());
} catch (WxErrorException e) {
e.printStackTrace();
}
return null;
};
}
//package share.web.core.config;
//
//import lombok.Data;
//import org.springframework.boot.context.properties.ConfigurationProperties;
//
//import java.util.List;
//
//@Data
//@ConfigurationProperties(prefix = "wx.miniapp")
//public class WxMaProperties {
//
// private List<Config> configs;
//
// @Data
// public static class Config {
// /**
// * 设置微信小程序的appid
// */
// private String appid;
//
// /**
// * 设置微信小程序的Secret
// */
// private String secret;
//
// /**
// * 设置微信小程序消息服务器配置的token
// */
// private String token;
//
// /**
// * 设置微信小程序消息服务器配置的EncodingAESKey
// */
// private String aesKey;
//
// /**
// * 消息格式,XML或者JSON
// */
// private String msgDataFormat;
// }
//
//}
//
package share.web.core.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import java.util.List;
@Data
@ConfigurationProperties(prefix = "wx.miniapp")
public class WxMaProperties {
private List<Config> configs;
@Data
public static class Config {
/**
* 设置微信小程序的appid
*/
private String appid;
/**
* 设置微信小程序的Secret
*/
private String secret;
/**
* 设置微信小程序消息服务器配置的token
*/
private String token;
/**
* 设置微信小程序消息服务器配置的EncodingAESKey
*/
private String aesKey;
/**
* 消息格式,XML或者JSON
*/
private String msgDataFormat;
}
}
//package share.web.interceptor;
//
//import cn.binarywang.wx.miniapp.api.WxMaService;
//import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
//import cn.binarywang.wx.miniapp.bean.WxMaKefuMessage;
//import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage;
//import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
//import cn.binarywang.wx.miniapp.message.WxMaMessageHandler;
//import cn.binarywang.wx.miniapp.message.WxMaMessageRouter;
//import com.google.common.collect.Lists;
//import lombok.extern.slf4j.Slf4j;
//import me.chanjar.weixin.common.bean.result.WxMediaUploadResult;
//import me.chanjar.weixin.common.error.WxErrorException;
//import me.chanjar.weixin.common.error.WxRuntimeException;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.boot.context.properties.EnableConfigurationProperties;
//import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Configuration;
//import share.web.core.config.WxMaProperties;
//
//import java.io.File;
//import java.util.List;
//import java.util.stream.Collectors;
//
//@Slf4j
//@Configuration
//@EnableConfigurationProperties(WxMaProperties.class)
//public class WxMaConfiguration {
// private final WxMaProperties properties;
//
// @Autowired
// public WxMaConfiguration(WxMaProperties properties) {
// this.properties = properties;
// }
//
// @Bean
// public WxMaService wxMaService() {
// List<WxMaProperties.Config> configs = this.properties.getConfigs();
// if (configs == null) {
// throw new WxRuntimeException("大哥,拜托先看下项目首页的说明(readme文件),添加下相关配置,注意别配错了!");
// }
// WxMaService maService = new WxMaServiceImpl();
// maService.setMultiConfigs(
// configs.stream()
// .map(a -> {
// WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();
//// WxMaDefaultConfigImpl config = new WxMaRedisConfigImpl(new JedisPool());
// // 使用上面的配置时,需要同时引入jedis-lock的依赖,否则会报类无法找到的异常
// config.setAppid(a.getAppid());
// config.setSecret(a.getSecret());
// config.setToken(a.getToken());
// config.setAesKey(a.getAesKey());
// config.setMsgDataFormat(a.getMsgDataFormat());
// return config;
// }).collect(Collectors.toMap(WxMaDefaultConfigImpl::getAppid, a -> a, (o, n) -> o)));
// return maService;
// }
//
// @Bean
// public WxMaMessageRouter wxMaMessageRouter(WxMaService wxMaService) {
// final WxMaMessageRouter router = new WxMaMessageRouter(wxMaService);
// router
// .rule().handler(logHandler).next()
// .rule().async(false).content("订阅消息").handler(subscribeMsgHandler).end()
// .rule().async(false).content("文本").handler(textHandler).end()
// .rule().async(false).content("图片").handler(picHandler).end()
// .rule().async(false).content("二维码").handler(qrcodeHandler).end();
// return router;
// }
//
// private final WxMaMessageHandler subscribeMsgHandler = (wxMessage, context, service, sessionManager) -> {
// service.getMsgService().sendSubscribeMsg(WxMaSubscribeMessage.builder()
// .templateId("此处更换为自己的模板id")
// .data(Lists.newArrayList(
// new WxMaSubscribeMessage.MsgData("keyword1", "339208499")))
// .toUser(wxMessage.getFromUser())
// .build());
// return null;
// };
//
// private final WxMaMessageHandler logHandler = (wxMessage, context, service, sessionManager) -> {
// log.info("收到消息:" + wxMessage.toString());
// service.getMsgService().sendKefuMsg(WxMaKefuMessage.newTextBuilder().content("收到信息为:" + wxMessage.toJson())
// .toUser(wxMessage.getFromUser()).build());
// return null;
// };
//
// private final WxMaMessageHandler textHandler = (wxMessage, context, service, sessionManager) -> {
// service.getMsgService().sendKefuMsg(WxMaKefuMessage.newTextBuilder().content("回复文本消息")
// .toUser(wxMessage.getFromUser()).build());
// return null;
// };
//
// private final WxMaMessageHandler picHandler = (wxMessage, context, service, sessionManager) -> {
// try {
// WxMediaUploadResult uploadResult = service.getMediaService()
// .uploadMedia("image", "png",
// ClassLoader.getSystemResourceAsStream("tmp.png"));
// service.getMsgService().sendKefuMsg(
// WxMaKefuMessage
// .newImageBuilder()
// .mediaId(uploadResult.getMediaId())
// .toUser(wxMessage.getFromUser())
// .build());
// } catch (WxErrorException e) {
// e.printStackTrace();
// }
//
// return null;
// };
//
// private final WxMaMessageHandler qrcodeHandler = (wxMessage, context, service, sessionManager) -> {
// try {
// final File file = service.getQrcodeService().createQrcode("123", 430);
// WxMediaUploadResult uploadResult = service.getMediaService().uploadMedia("image", file);
// service.getMsgService().sendKefuMsg(
// WxMaKefuMessage
// .newImageBuilder()
// .mediaId(uploadResult.getMediaId())
// .toUser(wxMessage.getFromUser())
// .build());
// } catch (WxErrorException e) {
// e.printStackTrace();
// }
//
// return null;
// };
//
//}
......@@ -129,6 +129,11 @@
<artifactId>spring-integration-mqtt</artifactId>
</dependency>
<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>weixin-java-miniapp</artifactId>
<version>4.5.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
......@@ -139,5 +144,4 @@
<scope>compile</scope>
</dependency>
</dependencies>
</project>
\ No newline at end of file
package share.system.service;
public interface WxMsgPushConService {
void sendSmallMsg(String openID);
}
//package share.system.service.impl;
//
//import cn.binarywang.wx.miniapp.api.WxMaService;
//import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage;
//import cn.hutool.core.date.LocalDateTimeUtil;
//import lombok.RequiredArgsConstructor;
//import lombok.extern.slf4j.Slf4j;
//import me.chanjar.weixin.common.error.WxErrorException;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Repository;
//import org.springframework.stereotype.Service;
//import share.system.service.WxMsgPushConService;
//
//import javax.annotation.Resource;
//import java.time.LocalDateTime;
//import java.util.HashMap;
//import java.util.Map;
//
//@Slf4j
//@Service
//public class WxMsgPushConServiceeImpl implements WxMsgPushConService {
// @Resource
// private WxMaService wxMaService;
// /**
// * 跳转的小程序页面
// */
// private static final String PAGES_ZP = "pages/draft-review/list/list";
//
// @Override
// public void sendSmallMsg(String openID) {
// Map<String, String> map = new HashMap<>();
// map.put("thing4", "预约门店");
// map.put("thing7", "服务名称");
// map.put("date3", LocalDateTimeUtil.format(LocalDateTime.now(), "yyyy-MM-dd HH:mm:ss"));
// map.put("thing5", "地址");
// WxMaSubscribeMessage wxMaSubscribeMessage = WxMaSubscribeMessage.builder()
// .toUser(openID)
// .templateId("oTc000e4NHkoc7v9OLBZiwM6Q6SFzguemrx6d0iuVS8")
// .page(PAGES_ZP)
// .build();
// // 设置将推送的消息
// map.forEach((k, v) -> {
// wxMaSubscribeMessage.addData(new WxMaSubscribeMessage.MsgData(k, v));
// });
// try {
// log.info("开始发送消息!!!!");
// wxMaService.getMsgService().sendSubscribeMsg(wxMaSubscribeMessage);
// log.info("消息发送成功!!!!");
// } catch (WxErrorException e) {
// e.printStackTrace();
// }
// }
//}
Markdown is supported
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