Browse Source

#907 企业微信增加应用推送消息到群聊会话的接口

master
Binary Wang 6 years ago
parent
commit
a47d91fc24
7 changed files with 388 additions and 58 deletions
  1. +42
    -0
      weixin-java-cp/src/main/java/me/chanjar/weixin/cp/WxCpConsts.java
  2. +30
    -16
      weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/WxCpChatService.java
  3. +23
    -16
      weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/impl/WxCpChatServiceImpl.java
  4. +154
    -0
      weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpAppChatMessage.java
  5. +8
    -2
      weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/article/NewArticle.java
  6. +126
    -14
      weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/impl/WxCpChatServiceImplTest.java
  7. +5
    -10
      weixin-java-cp/src/test/java/me/chanjar/weixin/cp/demo/WxCpDemoInMemoryConfigStorage.java

+ 42
- 0
weixin-java-cp/src/main/java/me/chanjar/weixin/cp/WxCpConsts.java View File

@@ -126,4 +126,46 @@ public class WxCpConsts {
public static final String UPDATE_TAG = "update_tag";

}

/**
* 应用推送消息的消息类型.
*/
public static class AppChatMsgType {
/**
* 文本消息.
*/
public static final String TEXT = "text";
/**
* 图片消息.
*/
public static final String IMAGE = "image";
/**
* 语音消息.
*/
public static final String VOICE = "voice";
/**
* 视频消息.
*/
public static final String VIDEO = "video";
/**
* 发送文件(CP专用).
*/
public static final String FILE = "file";
/**
* 文本卡片消息(CP专用).
*/
public static final String TEXTCARD = "textcard";
/**
* 图文消息(点击跳转到外链).
*/
public static final String NEWS = "news";
/**
* 图文消息(点击跳转到图文消息页面).
*/
public static final String MPNEWS = "mpnews";
/**
* markdown消息.
*/
public static final String MARKDOWN = "markdown";
}
}

+ 30
- 16
weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/WxCpChatService.java View File

@@ -3,46 +3,60 @@ package me.chanjar.weixin.cp.api;
import java.util.List;

import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.bean.WxCpAppChatMessage;
import me.chanjar.weixin.cp.bean.WxCpChat;

/**
* 群聊服务
* 群聊服务.
*
* @author gaigeshen
*/
public interface WxCpChatService {
String APPCHAT_CREATE = "https://qyapi.weixin.qq.com/cgi-bin/appchat/create";
String APPCHAT_UPDATE = "https://qyapi.weixin.qq.com/cgi-bin/appchat/update";
String APPCHAT_GET_CHATID = "https://qyapi.weixin.qq.com/cgi-bin/appchat/get?chatid=";

/**
* 创建群聊会话,注意:刚创建的群,如果没有下发消息,在企业微信不会出现该群。
* 创建群聊会话,注意:刚创建的群,如果没有下发消息,在企业微信不会出现该群.
*
* @param name 群聊名,最多50个utf8字符,超过将截断
* @param owner 指定群主的id。如果不指定,系统会随机从userlist中选一人作为群主
* @param users 群成员id列表。至少2人,至多500人
* @param name 群聊名,最多50个utf8字符,超过将截断
* @param owner 指定群主的id。如果不指定,系统会随机从userlist中选一人作为群主
* @param users 群成员id列表。至少2人,至多500人
* @param chatId 群聊的唯一标志,不能与已有的群重复;字符串类型,最长32个字符。只允许字符0-9及字母a-zA-Z。如果不填,系统会随机生成群id
* @return 创建群聊会话的结果,群聊的唯一标志
* @return 创建的群聊会话chatId
* @throws WxErrorException 发生异常
*/
String chatCreate(String name, String owner, List<String> users, String chatId) throws WxErrorException;
/**
* 修改群聊会话
*
* @param chatId 群聊id
* @param name 新的群聊名。若不需更新,请忽略此参数(null or empty)。最多50个utf8字符,超过将截断
* @param owner 新群主的id。若不需更新,请忽略此参数(null or empty)
* @param usersToAdd 添加成员的id列表,若不需要更新,则传递空对象或者空集合
* 修改群聊会话.
*
* @param chatId 群聊id
* @param name 新的群聊名。若不需更新,请忽略此参数(null or empty)。最多50个utf8字符,超过将截断
* @param owner 新群主的id。若不需更新,请忽略此参数(null or empty)
* @param usersToAdd 添加成员的id列表,若不需要更新,则传递空对象或者空集合
* @param usersToDelete 踢出成员的id列表,若不需要更新,则传递空对象或者空集合
* @throws WxErrorException 发生异常
*/
void chatUpdate(String chatId, String name, String owner, List<String> usersToAdd, List<String> usersToDelete) throws WxErrorException;

/**
* 获取群聊会话
*
* 获取群聊会话.
*
* @param chatId 群聊编号
* @return 群聊会话
* @throws WxErrorException 发生异常
*/
WxCpChat chatGet(String chatId) throws WxErrorException;

/**
* 应用支持推送文本、图片、视频、文件、图文等类型.
* 请求方式: POST(HTTPS)
* 请求地址: https://qyapi.weixin.qq.com/cgi-bin/appchat/send?access_token=ACCESS_TOKEN
* 文档地址:https://work.weixin.qq.com/api/doc#90000/90135/90248
*
* @param message 要发送的消息内容对象
*/
void sendMsg(WxCpAppChatMessage message) throws WxErrorException;

}

+ 23
- 16
weixin-java-cp/src/main/java/me/chanjar/weixin/cp/api/impl/WxCpChatServiceImpl.java View File

@@ -7,30 +7,30 @@ import java.util.Map;
import org.apache.commons.lang3.StringUtils;

import com.google.gson.JsonParser;

import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.util.json.WxGsonBuilder;
import me.chanjar.weixin.cp.api.WxCpChatService;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.WxCpAppChatMessage;
import me.chanjar.weixin.cp.bean.WxCpChat;
import me.chanjar.weixin.cp.util.json.WxCpGsonBuilder;

/**
* 群聊服务实现
* 群聊服务实现.
*
* @author gaigeshen
*/
public class WxCpChatServiceImpl implements WxCpChatService {
public class WxCpChatServiceImpl implements WxCpChatService {
private static final JsonParser JSON_PARSER = new JsonParser();
private final WxCpService cpService;

private final WxCpService internalService;
/**
* 创建群聊服务实现的实例
*
* @param internalService 企业微信的服务
* 创建群聊服务实现的实例.
*
* @param cpService 企业微信的服务
*/
public WxCpChatServiceImpl(WxCpService internalService) {
this.internalService = internalService;
WxCpChatServiceImpl(WxCpService cpService) {
this.cpService = cpService;
}

@Override
@@ -48,12 +48,13 @@ public class WxCpChatServiceImpl implements WxCpChatService {
if (StringUtils.isNotBlank(chatId)) {
data.put("chatid", chatId);
}
String result = internalService.post("https://qyapi.weixin.qq.com/cgi-bin/appchat/create", WxGsonBuilder.create().toJson(data));
String result = this.cpService.post(APPCHAT_CREATE, WxGsonBuilder.create().toJson(data));
return new JsonParser().parse(result).getAsJsonObject().get("chatid").getAsString();
}

@Override
public void chatUpdate(String chatId, String name, String owner, List<String> usersToAdd, List<String> usersToDelete) throws WxErrorException {
public void chatUpdate(String chatId, String name, String owner, List<String> usersToAdd, List<String> usersToDelete)
throws WxErrorException {
Map<String, Object> data = new HashMap<>(5);
if (StringUtils.isNotBlank(chatId)) {
data.put("chatid", chatId);
@@ -70,14 +71,20 @@ public class WxCpChatServiceImpl implements WxCpChatService {
if (usersToDelete != null && !usersToDelete.isEmpty()) {
data.put("del_user_list", usersToDelete);
}
internalService.post("https://qyapi.weixin.qq.com/cgi-bin/appchat/update", WxGsonBuilder.create().toJson(data));

this.cpService.post(APPCHAT_UPDATE, WxGsonBuilder.create().toJson(data));
}

@Override
public WxCpChat chatGet(String chatId) throws WxErrorException {
String result = internalService.get("https://qyapi.weixin.qq.com/cgi-bin/appchat/get?chatid=" + chatId, null);
return WxCpGsonBuilder.create().fromJson(
new JsonParser().parse(result).getAsJsonObject().getAsJsonObject("chat_info").toString(), WxCpChat.class);
String result = this.cpService.get(APPCHAT_GET_CHATID + chatId, null);
return WxCpGsonBuilder.create()
.fromJson(JSON_PARSER.parse(result).getAsJsonObject().getAsJsonObject("chat_info").toString(), WxCpChat.class);
}

@Override
public void sendMsg(WxCpAppChatMessage message) throws WxErrorException {
this.cpService.post("https://qyapi.weixin.qq.com/cgi-bin/appchat/send", message.toJson());
}

}

+ 154
- 0
weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/WxCpAppChatMessage.java View File

@@ -0,0 +1,154 @@
package me.chanjar.weixin.cp.bean;

import java.io.Serializable;
import java.util.List;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.cp.WxCpConsts;
import me.chanjar.weixin.cp.bean.article.MpnewsArticle;
import me.chanjar.weixin.cp.bean.article.NewArticle;

/**
* <pre>
* 应用推送消息
* Created by Binary Wang on 2019/1/26.
* </pre>
*
* @author <a href="https://github.com/binarywang">Binary Wang</a>
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class WxCpAppChatMessage implements Serializable {
private static final long serialVersionUID = -5469013416372240229L;

private String msgType;
private String content;
private String chatId;
private String mediaId;
private String title;
private String description;
private Boolean safe;
private String url;
private String btnTxt;
private List<NewArticle> articles;
private List<MpnewsArticle> mpnewsArticles;

/**
* 构建文本消息.
*/
public static WxCpAppChatMessage buildTextMsg(String chatId, String content, boolean safe) {
final WxCpAppChatMessage message = new WxCpAppChatMessage();
message.setMsgType(WxCpConsts.AppChatMsgType.TEXT);
message.setContent(content);
message.setChatId(chatId);
message.setSafe(safe);
return message;
}

/**
* 生成json字符串.
*/
public String toJson() {
JsonObject messageJson = new JsonObject();
messageJson.addProperty("msgtype", this.getMsgType());
messageJson.addProperty("chatid", this.getChatId());

if (WxConsts.KefuMsgType.TEXT.equals(this.getMsgType())) {
JsonObject text = new JsonObject();
text.addProperty("content", this.getContent());
messageJson.add("text", text);
}

if (WxConsts.KefuMsgType.MARKDOWN.equals(this.getMsgType())) {
JsonObject text = new JsonObject();
text.addProperty("content", this.getContent());
messageJson.add("markdown", text);
}

if (WxConsts.KefuMsgType.TEXTCARD.equals(this.getMsgType())) {
JsonObject text = new JsonObject();
text.addProperty("title", this.getTitle());
text.addProperty("description", this.getDescription());
text.addProperty("url", this.getUrl());
text.addProperty("btntxt", this.getBtnTxt());
messageJson.add("textcard", text);
}

if (WxConsts.KefuMsgType.IMAGE.equals(this.getMsgType())) {
JsonObject image = new JsonObject();
image.addProperty("media_id", this.getMediaId());
messageJson.add("image", image);
}

if (WxConsts.KefuMsgType.FILE.equals(this.getMsgType())) {
JsonObject image = new JsonObject();
image.addProperty("media_id", this.getMediaId());
messageJson.add("file", image);
}

if (WxConsts.KefuMsgType.VOICE.equals(this.getMsgType())) {
JsonObject voice = new JsonObject();
voice.addProperty("media_id", this.getMediaId());
messageJson.add("voice", voice);
}

if (this.getSafe() != null && this.getSafe()) {
messageJson.addProperty("safe", 1);
}

if (WxConsts.KefuMsgType.VIDEO.equals(this.getMsgType())) {
JsonObject video = new JsonObject();
video.addProperty("media_id", this.getMediaId());
video.addProperty("title", this.getTitle());
video.addProperty("description", this.getDescription());
messageJson.add("video", video);
}

if (WxConsts.KefuMsgType.NEWS.equals(this.getMsgType())) {
JsonObject newsJsonObject = new JsonObject();
JsonArray articleJsonArray = new JsonArray();
for (NewArticle article : this.getArticles()) {
JsonObject articleJson = new JsonObject();
articleJson.addProperty("title", article.getTitle());
articleJson.addProperty("description", article.getDescription());
articleJson.addProperty("url", article.getUrl());
articleJson.addProperty("picurl", article.getPicUrl());
articleJsonArray.add(articleJson);
}
newsJsonObject.add("articles", articleJsonArray);
messageJson.add("news", newsJsonObject);
}

if (WxConsts.KefuMsgType.MPNEWS.equals(this.getMsgType())) {
JsonObject newsJsonObject = new JsonObject();
if (this.getMediaId() != null) {
newsJsonObject.addProperty("media_id", this.getMediaId());
} else {
JsonArray articleJsonArray = new JsonArray();
for (MpnewsArticle article : this.getMpnewsArticles()) {
JsonObject articleJson = new JsonObject();
articleJson.addProperty("title", article.getTitle());
articleJson.addProperty("thumb_media_id", article.getThumbMediaId());
articleJson.addProperty("author", article.getAuthor());
articleJson.addProperty("content_source_url", article.getContentSourceUrl());
articleJson.addProperty("content", article.getContent());
articleJson.addProperty("digest", article.getDigest());
articleJsonArray.add(articleJson);
}

newsJsonObject.add("articles", articleJsonArray);
}
messageJson.add("mpnews", newsJsonObject);
}

return messageJson.toString();
}
}

+ 8
- 2
weixin-java-cp/src/main/java/me/chanjar/weixin/cp/bean/article/NewArticle.java View File

@@ -1,9 +1,12 @@
package me.chanjar.weixin.cp.bean.article;

import lombok.Data;

import java.io.Serializable;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
* <pre>
* Created by BinaryWang on 2017/3/27.
@@ -12,6 +15,9 @@ import java.io.Serializable;
* @author Binary Wang
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class NewArticle implements Serializable {
private static final long serialVersionUID = 4087852055781140659L;



+ 126
- 14
weixin-java-cp/src/test/java/me/chanjar/weixin/cp/api/impl/WxCpChatServiceImplTest.java View File

@@ -2,15 +2,21 @@ package me.chanjar.weixin.cp.api.impl;

import java.util.Arrays;

import me.chanjar.weixin.cp.bean.WxCpChat;
import org.testng.Assert;
import org.testng.annotations.Guice;
import org.testng.annotations.Test;
import org.testng.*;
import org.testng.annotations.*;

import com.google.common.collect.Lists;
import com.google.inject.Inject;

import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.WxCpConsts.AppChatMsgType;
import me.chanjar.weixin.cp.api.ApiTestModule;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.WxCpAppChatMessage;
import me.chanjar.weixin.cp.bean.WxCpChat;
import me.chanjar.weixin.cp.bean.article.MpnewsArticle;
import me.chanjar.weixin.cp.bean.article.NewArticle;

import static org.assertj.core.api.Assertions.assertThat;

/**
* 测试群聊服务
@@ -19,28 +25,134 @@ import me.chanjar.weixin.cp.api.WxCpService;
*/
@Guice(modules = ApiTestModule.class)
public class WxCpChatServiceImplTest {
private String chatId;
private String userId;

@Inject
private WxCpService wxCpService;
private WxCpService cpService;

@BeforeTest
public void init() {
this.chatId = "mychatid";
this.userId = ((ApiTestModule.WxXmlCpInMemoryConfigStorage) this.cpService.getWxCpConfigStorage()).getUserId();
}

@Test
public void create() throws Exception {
wxCpService.getChatService().chatCreate("测试群聊", "gaige_shen", Arrays.asList("gaige_shen", "ZhangXiaoMing"), "mychatid");
public void testChatCreate() throws Exception {
final String result = cpService.getChatService().chatCreate("测试群聊", userId,
Arrays.asList(userId, userId), chatId);
assertThat(result).isNotEmpty();
assertThat(result).isEqualTo(chatId);
}

@Test
public void get() throws Exception {
WxCpChat chat = wxCpService.getChatService().chatGet("mychatid");
public void testChatGet() throws Exception {
WxCpChat chat = this.cpService.getChatService().chatGet(chatId);
System.out.println(chat);
Assert.assertEquals(chat.getName(), "测试群聊");
}

@Test
public void update() throws Exception {
wxCpService.getChatService().chatUpdate("mychatid", "", "", Arrays.asList("ZhengWuYao"), null);
WxCpChat chat = wxCpService.getChatService().chatGet("mychatid");
public void testChatUpdate() throws Exception {
this.cpService.getChatService().chatUpdate(chatId, "", "", Arrays.asList("ZhengWuYao"), null);
WxCpChat chat = this.cpService.getChatService().chatGet(chatId);
System.out.println(chat);
Assert.assertEquals(chat.getUsers().size(), 3);
}

@DataProvider
public Object[][] messages() {
return new Object[][]{
{WxCpAppChatMessage.builder()
.msgType(AppChatMsgType.TEXT)
.chatId(chatId)
.content("你的快递已到\n请携带工卡前往邮件中心领取")
.build()
},
{WxCpAppChatMessage.builder()
.msgType(AppChatMsgType.IMAGE)
.chatId(chatId)
.mediaId("3_xWGPXZhpOKZrlRISWrjhPrDUZqZ-jIEVzxd56jLuqM")
.build()
},
{WxCpAppChatMessage.builder()
.msgType(AppChatMsgType.VOICE)
.chatId(chatId)
.mediaId("3X5t6HkdN1hUgB7OzrdRnc8v0yI0CqlAxFxnCkS3msTnTLanpYrV4esLv4foZVnlf")
.build()
},
{WxCpAppChatMessage.builder()
.msgType(AppChatMsgType.VIDEO)
.chatId(chatId)
.mediaId("3otWyy_acbID8fyltmCOW5hGVD8oa0_p0za5jhukxKTUDoGT71lqTvtQAWoycXpQf")
.title("aaaa")
.description("ddddd")
.build()
},
{WxCpAppChatMessage.builder()
.msgType(AppChatMsgType.FILE)
.chatId(chatId)
.mediaId("34AyVyDdndVhB4Z2tT-_FYKZ7Xqrr47LPC11GHH4oy7o")
.build()
},
{WxCpAppChatMessage.builder()
.msgType(AppChatMsgType.TEXTCARD)
.chatId(chatId)
.btnTxt("更多")
.title("领奖通知")
.url("https://zhidao.baidu.com/question/2073647112026042748.html")
.description("<div class=\"gray\">2016年9月26日</div> <div class=\"normal\"> 恭喜你抽中iPhone 7一台,领奖码:520258</div><div class=\"highlight\">请于2016年10月10日前联系行 政同事领取</div>")
.build()
},
{WxCpAppChatMessage.builder()
.msgType(AppChatMsgType.NEWS)
.chatId(chatId)
.articles(Lists.newArrayList(NewArticle.builder()
.title("领奖通知")
.url("https://zhidao.baidu.com/question/2073647112026042748.html")
.description("今年中秋节公司有豪礼相送")
.picUrl("http://res.mail.qq.com/node/ww/wwopenmng/images/independent/doc/test_pic_msg1.png")
.build()
))
.build()
},
{WxCpAppChatMessage.builder()
.msgType(AppChatMsgType.MPNEWS)
.chatId(chatId)
.mpnewsArticles(Lists.newArrayList(MpnewsArticle.newBuilder()
.title("地球一小时")
.thumbMediaId("3_xWGPXZhpOKZrlRISWrjhPrDUZqZ-jIEVzxd56jLuqM")
.author("Author")
.contentSourceUrl("https://work.weixin.qq.com")
.content("3月24日20:30-21:30 \n办公区将关闭照明一小时,请各部门同事相互转告")
.digest("3月24日20:30-21:30 \n办公区将关闭照明一小时")
.build()
))
.build()
},
{WxCpAppChatMessage.builder()
.msgType(AppChatMsgType.MARKDOWN)
.chatId(chatId)
.content("您的会议室已经预定,稍后会同步到`邮箱` \n" +
" >**事项详情** \n" +
" >事 项:<font color=\\\"info\\\">开会</font> \n" +
" >组织者:@miglioguan \n" +
" >参与者:@miglioguan、@kunliu、@jamdeezhou、@kanexiong、@kisonwang \n" +
" > \n" +
" >会议室:<font color=\\\"info\\\">广州TIT 1楼 301</font> \n" +
" >日 期:<font color=\\\"warning\\\">2018年5月18日</font> \n" +
" >时 间:<font color=\\\"comment\\\">上午9:00-11:00</font> \n" +
" > \n" +
" >请准时参加会议。 \n" +
" > \n" +
" >如需修改会议信息,请点击:[修改会议信息](https://work.weixin.qq.com)")
.build()
},
};
}

@Test(dataProvider = "messages")
public void testSendMsg(WxCpAppChatMessage message) throws WxErrorException {
this.cpService.getChatService().sendMsg(message);
}
}

+ 5
- 10
weixin-java-cp/src/test/java/me/chanjar/weixin/cp/demo/WxCpDemoInMemoryConfigStorage.java View File

@@ -1,28 +1,23 @@
package me.chanjar.weixin.cp.demo;

import java.io.InputStream;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import lombok.ToString;
import me.chanjar.weixin.common.util.xml.XStreamInitializer;
import me.chanjar.weixin.cp.config.WxCpInMemoryConfigStorage;

import java.io.InputStream;

/**
* @author Daniel Qian
*/
@XStreamAlias("xml")
class WxCpDemoInMemoryConfigStorage extends WxCpInMemoryConfigStorage {
@ToString
public class WxCpDemoInMemoryConfigStorage extends WxCpInMemoryConfigStorage {
public static WxCpDemoInMemoryConfigStorage fromXml(InputStream is) {
XStream xstream = XStreamInitializer.getInstance();
xstream.processAnnotations(WxCpDemoInMemoryConfigStorage.class);
return (WxCpDemoInMemoryConfigStorage) xstream.fromXML(is);
}

@Override
public String toString() {
return "SimpleWxConfigProvider [appidOrCorpid=" + this.corpId + ", corpSecret=" + this.corpSecret + ", accessToken=" + this.accessToken
+ ", expiresTime=" + this.expiresTime + ", token=" + this.token + ", aesKey=" + this.aesKey + "]";
}

}

Loading…
Cancel
Save