群发消息推送实现,示例:
InputStream inputStream = null;
/*
HttpURLConnection conn = (HttpURLConnection) new URL("https://pics7.baidu.com/feed/9213b07eca806538e25ecfecc0c86441ac3482b0.jpeg?token=e3bdfe7afe89a75346280bf9fb7f105e&s=DA90138E8A2724070D8C8A830300F086").openConnection();
conn.setReadTimeout(5000);
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
inputStream = conn.getInputStream();
} */
String path = this.getClass().getResource("/").getPath();
path = path.substring(0, path.indexOf("WEB-INF")) + "images/index_bg.png";
logger.info(path);
inputStream = new FileInputStream(new File(path));
// 上传图文消息的封面图片
WxMediaUploadResult uploadMediaRes = wxMpService.getMaterialService().mediaUpload(WxConsts.MediaFileType.IMAGE, "png", inputStream);
WxMpMassNews news = new WxMpMassNews();
WxMpMassNews.WxMpMassNewsArticle article1 = new WxMpMassNews.WxMpMassNewsArticle();
article1.setTitle("标题1");
article1.setContent("内容1");
article1.setThumbMediaId(uploadMediaRes.getMediaId());
//article1.setThumbMediaId("67MYWryQ20BhSCeG8DPavcpHubxbjk9OPBlDJpkywXJi16kec7Pjs7Ul-H8ubN3T");
news.addArticle(article1);
WxMpMassNews.WxMpMassNewsArticle article2 = new WxMpMassNews.WxMpMassNewsArticle();
article2.setTitle("标题2");
article2.setContent("内容2");
article2.setThumbMediaId(uploadMediaRes.getMediaId());
//article2.setThumbMediaId("67MYWryQ20BhSCeG8DPavcpHubxbjk9OPBlDJpkywXJi16kec7Pjs7Ul-H8ubN3T");
article2.setShowCoverPic(true);
article2.setAuthor("作者2");
article2.setContentSourceUrl("www.baidu.com");
article2.setDigest("摘要2");
news.addArticle(article2);
WxMpMassUploadResult massUploadResult = wxMpService.getMassMessageService().massNewsUpload(news);
WxMpMassOpenIdsMessage massMessage = new WxMpMassOpenIdsMessage();
massMessage.setMsgType(WxConsts.MassMsgType.MPNEWS);
massMessage.setMediaId(massUploadResult.getMediaId());
//massMessage.setMediaId("67MYWryQ20BhSCeG8DPavcpHubxbjk9OPBlDJpkywXJi16kec7Pjs7Ul-H8ubN3T");
massMessage.getToUsers().add("otAIM6PimOuARRXXTWcloLL-XLU0");
massMessage.getToUsers().add("otAIM6OlscpCu4PSFb8dSM0jwIxE");
WxMpMassSendResult massResult = wxMpService.getMassMessageService().massOpenIdsMessageSend(massMessage);
下面用用户列表群发(WxMpMassOpenIdsMessage
)做例子,如果要使用标签群发,则使用me.chanjar.weixin.mp.bean.WxMpMassTagMessage
即可。 更多用例,请参考单元测试类:me.chanjar.weixin.mp.api.impl.WxMpMassMessageServiceImplTest,测试类连接:
https://github.com/Wechat-Group/WxJava/blob/master/weixin-java-mp/src/test/java/me/chanjar/weixin/mp/api/impl/WxMpMassMessageServiceImplTest.java
WxMpMassOpenIdsMessage massMessage = new WxMpMassOpenIdsMessage();
massMessage.setMsgType(WxConsts.MASS_MSG_TEXT);
massMessage.setContent("消息内容");
massMessage.getToUsers().add(openid);
WxMpMassSendResult massResult = wxMpService.getMassMessageService().massOpenIdsMessageSend(massMessage);
WxMediaUploadResult uploadMediaRes = wxMpService.getMaterialService().mediaUpload(WxConsts.MEDIA_VIDEO, "mp4", inputStream);
// 把视频变成可被群发的媒体
WxMpMassVideo video = new WxMpMassVideo();
video.setTitle("测试标题");
video.setDescription("测试描述");
video.setMediaId(uploadMediaRes.getMediaId());
WxMpMassUploadResult uploadResult = wxMpService.getMassMessageService().massVideoUpload(video);
WxMpMassOpenIdsMessage massMessage = new WxMpMassOpenIdsMessage();
massMessage.setMsgType(WxConsts.MASS_MSG_VIDEO);
massMessage.setMediaId(uploadResult.getMediaId());
massMessage.getToUsers().add(openid);
WxMpMassSendResult massResult = wxMpService.getMassMessageService().massOpenIdsMessageSend(massMessage);
WxMediaUploadResult uploadMediaRes = wxMpService.getMaterialService().mediaUpload(WxConsts.MEDIA_IMAGE, "jpg", inputStream);
WxMpMassOpenIdsMessage massMessage = new WxMpMassOpenIdsMessage();
massMessage.setMsgType(WxConsts.MASS_MSG_IMAGE);
massMessage.setMediaId(uploadMediaRes.getMediaId());
massMessage.getToUsers().add(openid);
WxMpMassSendResult massResult = wxMpService.getMassMessageService().massOpenIdsMessageSend(massMessage);
WxMediaUploadResult uploadMediaRes = wxMpService.getMaterialService().mediaUpload(WxConsts.MEDIA_VOICE, "mp3", inputStream);
WxMpMassOpenIdsMessage massMessage = new WxMpMassOpenIdsMessage();
massMessage.setMsgType(WxConsts.MASS_MSG_VOICE);
massMessage.setMediaId(uploadMediaRes.getMediaId());
massMessage.getToUsers().add(openid);
WxMpMassSendResult massResult = wxMpService.getMassMessageService().massOpenIdsMessageSend(massMessage);
// 上传图文消息的封面图片
WxMediaUploadResult uploadMediaRes = wxMpService.getMaterialService().mediaUpload(WxConsts.MEDIA_IMAGE, "jpg", inputStream);
// 上传图文消息的正文图片(返回的url拼在正文的<img>标签中)
WxMediaImgUploadResult imagedMediaRes = wxMpService.getMaterialService().mediaImgUpload(file);
String url=imagedMediaRes.getUrl();
WxMpMassNews news = new WxMpMassNews();
WxMpMassNews.WxMpMassNewsArticle article1 = new WxMpMassNews.WxMpMassNewsArticle();
article1.setTitle("标题1");
article1.setContent("内容1");
article1.setThumbMediaId(uploadMediaRes.getMediaId());
news.addArticle(article1);
WxMpMassNews.WxMpMassNewsArticle article2 = new WxMpMassNews.WxMpMassNewsArticle();
article2.setTitle("标题2");
article2.setContent("内容2");
article2.setThumbMediaId(uploadMediaRes.getMediaId());
article2.setShowCoverPic(true);
article2.setAuthor("作者2");
article2.setContentSourceUrl("www.baidu.com");
article2.setDigest("摘要2");
news.addArticle(article2);
WxMpMassUploadResult massUploadResult = wxMpService.getMassMessageService().massNewsUpload(news);
WxMpMassOpenIdsMessage massMessage = new WxMpMassOpenIdsMessage();
massMessage.setMsgType(WxConsts.MASS_MSG_NEWS);
massMessage.setMediaId(uploadResult.getMediaId());
massMessage.getToUsers().add(openid);
WxMpMassSendResult massResult = wxMpService.getMassMessageService().massOpenIdsMessageSend(massMessage);
参考文档地址:
官方文档(群发接口及原创校验):https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Batch_Sends_and_Originality_Checks.html
基于WxJava (微信开发 Java SDK)框架的文档:
https://github.com/Wechat-Group/WxJava/wiki/MP_%E7%BE%A4%E5%8F%91%E6%B6%88%E6%81%AF
WxJava框架学习文档:
完!!!
注意1:
报错{"errcode":-1,"errmsg":"system error hint: [zttteq44664"},可能是图文消息素材id放错了,放的封面图片素材id。
报错{"errcode":48008,"errmsg":"no permission for this msgtype hint: [hDBAwa0376ge20]"},测试公众号没有调用此接口的权限,需要用认证过的服务号。
注意2:
1、该接口暂时仅提供给已微信认证的服务号
2、高级群发接口的每日调用限制为10次,请小心测试
3、无论在公众平台网站上,还是使用接口群发,用户每月只能接收4条群发消息,多于4条的群发将对该用户发送失败。
示例:
/**
* 图文消息推送(客服消息推送)
*
* @param req
* @param resp
* @return
* @throws Exception
*/
@RequestMapping(value = "/notifyPreferential.api")
@ResponseBody
public Map<String, Object> notifyPreferential(HttpServletRequest req, HttpServletResponse resp) {
wxMpService.setMaxRetryTimes(1);
// 获取用户手机号、密码、action
String phone = (String) req.getParameter("tellphone");
String openid = (String) req.getParameter("openid");
String title = (String) req.getParameter("title");
String desc = (String) req.getParameter("desc");
String picUrl = (String) req.getParameter("picUrl");
String status = (String) req.getParameter("status");
String startTime = (String) req.getParameter("startTime");
String endTime = (String) req.getParameter("endTime");
logger.info("收到服务器图文消息推送:请求参数为" + phone + "," + openid + "," + title + "," + picUrl + "," + status);
try { /*
// 客服消息、图文消息
// 图文消息1
WxMpKefuMessage.WxArticle article1 = new WxMpKefuMessage.WxArticle();
article1.setUrl("http://xial9527.w3.luyouxia.net/wx/jsp/login.html");
article1.setPicUrl("http://test.iwocloud.com/wx/images/index_bg.png");
article1.setDescription("今天天气很好,适合出去玩");
article1.setTitle("测试测试测试一下啦啦啦");
// 图文消息2
WxMpKefuMessage.WxArticle article2 = new WxMpKefuMessage.WxArticle();
article2.setUrl("http://xial9527.w3.luyouxia.net/wx/index?code=1YF00137");
article2.setPicUrl("http://test.iwocloud.com/wx/images/index_bg.png");
article2.setDescription("晚上去吃火锅吧,逛超市");
article2.setTitle("今日安排");
// 封装 xml
WxMpKefuMessage wxMpKefuMessage = WxMpKefuMessage.NEWS()
.toUser("otAIM6PimOuARRXXTWcloLL-XLU0")
.addArticle(article1)
//.addArticle(article2)
.build();
// 发送给指定openid
wxMpService.getKefuService().sendKefuMessage(wxMpKefuMessage); */
InputStream inputStream = null;
HttpURLConnection conn = (HttpURLConnection) new URL("http://test.iwocloud.com/wx/images/index_bg.png").openConnection();
conn.setReadTimeout(5000);
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
inputStream = conn.getInputStream();
}
/*
String path = this.getClass().getResource("/").getPath();
path = path.substring(0, path.indexOf("WEB-INF")) + "images/index_bg.png";
logger.info(path);
inputStream = new FileInputStream(new File(path)); */
// 上传图文消息的封面图片
WxMediaUploadResult uploadMediaRes = wxMpService.getMaterialService().mediaUpload(WxConsts.MediaFileType.IMAGE, "png", inputStream);
WxMpMassNews news = new WxMpMassNews();
WxMpMassNews.WxMpMassNewsArticle article1 = new WxMpMassNews.WxMpMassNewsArticle();
article1.setTitle("标题1");
article1.setContent("内容1");
article1.setThumbMediaId(uploadMediaRes.getMediaId());
//article1.setThumbMediaId("67MYWryQ20BhSCeG8DPavcpHubxbjk9OPBlDJpkywXJi16kec7Pjs7Ul-H8ubN3T");
news.addArticle(article1);
WxMpMassNews.WxMpMassNewsArticle article2 = new WxMpMassNews.WxMpMassNewsArticle();
article2.setTitle("标题2");
article2.setContent("内容2");
article2.setThumbMediaId(uploadMediaRes.getMediaId());
//article2.setThumbMediaId("67MYWryQ20BhSCeG8DPavcpHubxbjk9OPBlDJpkywXJi16kec7Pjs7Ul-H8ubN3T");
article2.setShowCoverPic(true);
article2.setAuthor("作者2");
article2.setContentSourceUrl("www.baidu.com");
article2.setDigest("摘要2");
news.addArticle(article2);
WxMpMassUploadResult massUploadResult = wxMpService.getMassMessageService().massNewsUpload(news);
WxMpMassOpenIdsMessage massMessage = new WxMpMassOpenIdsMessage();
massMessage.setMsgType(WxConsts.MassMsgType.MPNEWS);
massMessage.setMediaId(massUploadResult.getMediaId());
//massMessage.setMediaId("67MYWryQ20BhSCeG8DPavcpHubxbjk9OPBlDJpkywXJi16kec7Pjs7Ul-H8ubN3T");
massMessage.getToUsers().add("otAIM6PimOuARRXXTWcloLL-XLU0");
massMessage.getToUsers().add("otAIM6OlscpCu4PSFb8dSM0jwIxE");
WxMpMassSendResult massResult = wxMpService.getMassMessageService().massOpenIdsMessageSend(massMessage);
} catch (Exception e) {
logger.error(e.getMessage());
}
// 封装返回结果
Map<String, Object> returnMap = new HashMap<String, Object>();
returnMap.put(GlobalDeclare.RETURN_CODE, 0);
returnMap.put(GlobalDeclare.RETURN_MSG, "success");
returnMap.put(GlobalDeclare.RETURN_DATA, "{}");
return returnMap;
}
/**
* 图文消息推送(客服消息推送)
*
* @param req
* @param resp
* @return
* @throws Exception
*/
@RequestMapping(value = "/notifyPreferential.api")
@ResponseBody
public Map<String, Object> notifyPreferential(HttpServletRequest req, HttpServletResponse resp) {
wxMpService.setMaxRetryTimes(1);
// 获取用户手机号、密码、action
String phone = (String) req.getParameter("tellphone");
String openid = (String) req.getParameter("openid");
String title = (String) req.getParameter("title");
String desc = (String) req.getParameter("desc");
String picUrl = (String) req.getParameter("picUrl");
String status = (String) req.getParameter("status");
String startTime = (String) req.getParameter("startTime");
String endTime = (String) req.getParameter("endTime");
logger.info("收到服务器图文消息推送:请求参数为" + phone + "," + openid + "," + title + "," + picUrl + "," + status);
// 封装返回结果
Map<String, Object> returnMap = new HashMap<String, Object>();
// 获取网络图片输入流
InputStream inputStream = null;
try {
HttpURLConnection connection = (HttpURLConnection) new URL(picUrl).openConnection();
connection.setReadTimeout(5000);
connection.setConnectTimeout(5000);
connection.setRequestMethod("GET");
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
inputStream = connection.getInputStream();
}
} catch (IOException e) {
e.printStackTrace();
logger.info("获取网络图片出现异常,图片路径为:" + picUrl);
}
if (inputStream == null) {
returnMap.put(GlobalDeclare.RETURN_CODE, 101);
returnMap.put(GlobalDeclare.RETURN_MSG, "获取网络图片出现异常,图片路径为:" + picUrl);
return returnMap;
}
// 判断图片类型
String imgType = getUrlSuffixes(picUrl);
if(imgType == null){
returnMap.put(GlobalDeclare.RETURN_CODE, 102);
returnMap.put(GlobalDeclare.RETURN_MSG, "图片格式错误,图片必须为:jpeg|gif|jpg|png");
return returnMap;
}
// 图文消息跳转链接
String url = req.getScheme() + "://" + req.getServerName() + req.getContextPath() + "/template?phone=" + phone;
// 群发用户openid,openID最少2个,最多10000个
String[] openids = openid.split(",");
if(openids == null || openids.length < 2){
returnMap.put(GlobalDeclare.RETURN_CODE, 103);
returnMap.put(GlobalDeclare.RETURN_MSG, "openid不能为空,且群发用户至少为2个,最多10000个");
return returnMap;
}
// 发送图文消息
WxMpMassSendResult massResult = null;
try {
// 上传图文消息的封面图片
WxMediaUploadResult uploadMediaRes = wxMpService.getMaterialService().mediaUpload(WxConsts.MediaFileType.IMAGE, imgType, inputStream);
// 第一条图文消息
WxMpMassNews news = new WxMpMassNews();
WxMpMassNews.WxMpMassNewsArticle article1 = new WxMpMassNews.WxMpMassNewsArticle();
article1.setTitle(title);
article1.setContent(desc);
article1.setThumbMediaId(uploadMediaRes.getMediaId());
article1.setContentSourceUrl(url);
article1.setShowCoverPic(true);
news.addArticle(article1);
// 上传图文消息素材
WxMpMassUploadResult massUploadResult = wxMpService.getMassMessageService().massNewsUpload(news);
// 依据openid列表群发图文消息
WxMpMassOpenIdsMessage massMessage = new WxMpMassOpenIdsMessage();
massMessage.setMsgType(WxConsts.MassMsgType.MPNEWS);
massMessage.setMediaId(massUploadResult.getMediaId());
// 遍历openid
for(int i = 0; i < openids.length; i++){
massMessage.getToUsers().add(openids[i]);
}
// 发送消息
massResult = wxMpService.getMassMessageService().massOpenIdsMessageSend(massMessage);
} catch (Exception e) {
logger.error(e.getMessage());
}
if (massResult == null) {
returnMap.put(GlobalDeclare.RETURN_CODE, 104);
returnMap.put(GlobalDeclare.RETURN_MSG, "请求微信服务器出现异常");
} else {
returnMap.put(GlobalDeclare.RETURN_CODE, 0);
returnMap.put(GlobalDeclare.RETURN_MSG, "success");
}
returnMap.put(GlobalDeclare.RETURN_DATA, "{}");
return returnMap;
}