1.引入maven依赖:
<dependency> <groupId>com.github.binarywang</groupId> <artifactId>weixin-java-cp</artifactId> <version>3.8.0</version> </dependency>
2.重写WxCpExternalContactServiceImpl
(如果要扩充,可以自行查询官方文档-家校沟通进行扩展):
/** * description: 家校沟通消息发送实现 * create by: YangLinWei * create time: 2020/8/31 3:12 下午 */ public class WxCpExternalServiceImpl extends WxCpExternalContactServiceImpl { private final WxCpService mainService; public static final String GET_ALL_DEPARTMENT_LIST = "/cgi-bin/school/department/list"; public static final String GET_STUDENT_PARENT_LIST = "/cgi-bin/school/user/list"; private static final String MESSAGE_SEND_URL = "/cgi-bin/externalcontact/message/send"; private static final String SUBSCRIBE_QR_CODE = "/cgi-bin/externalcontact/get_subscribe_qr_code"; public WxCpExternalServiceImpl(WxCpService mainService) { super(mainService); this.mainService = mainService; } /** * 获取部门列表 * * @return 获取所有部门 */ public String getAllDepartmentList() throws WxErrorException { String url = this.mainService.getWxCpConfigStorage().getApiUrl(GET_ALL_DEPARTMENT_LIST); return this.mainService.get(url, null); } /** * 获取部门列表 * * @param departMentId 部门id * @return 获取指定部门及其下的子部门 */ public String getAllDepartmentList(int departMentId) throws WxErrorException { String url = this.mainService.getWxCpConfigStorage().getApiUrl(GET_ALL_DEPARTMENT_LIST); return this.mainService.get(url, "id=" + departMentId); } /** * 获取获取部门成员详情 * * @param departMentId 部门id * @param featchChild 是否递归获取子部门下面的成员 * @return * @throws WxErrorException */ public String getUserList(int departMentId, boolean featchChild) throws WxErrorException { String url = this.mainService.getWxCpConfigStorage().getApiUrl(GET_STUDENT_PARENT_LIST + "?department_id=" + departMentId + (featchChild ? "&fetch_child=FETCH_CHILD" : "")); return this.mainService.get(url, null); } /** * 消息发送 * * @param message 发送的消息 * @return * @throws WxErrorException */ public String messageSend(WxCpExternalMessage message) throws WxErrorException { String url = this.mainService.getWxCpConfigStorage().getApiUrl(MESSAGE_SEND_URL); return this.mainService.post(url, message.toJson()); } /** * 获取「学校通知」二维码 * * @return * @throws WxErrorException */ public String getQrCode() throws WxErrorException { String url = this.mainService.getWxCpConfigStorage().getApiUrl(SUBSCRIBE_QR_CODE); return this.mainService.get(url, null); } }
3.调用方式:
// 初始化工具类 WxCpDefaultConfigImpl config = new WxCpDefaultConfigImpl(); config.setCorpId("corpId企业id"); config.setCorpSecret("corpSecret应用秘钥"); config.setAgentId("agentId应用id"); WxCpServiceImpl wxCpService = new WxCpServiceImpl(); wxCpService.setWxCpConfigStorage(config); WxCpExternalServiceImpl wxCpExternalService = new WxCpExternalServiceImpl(wxCpService); //发送纯文本 WxCpExternalMessage message = WxCpExternalMessage.TEXT() .agentId("agentId应用id") .toParentUserid("家长id集合") .content("发送内容") .build(); wxCpExternalService.messageSend(message);
备注:这里的WxCpExternalMessage
我是仿照WxcpMessage
构造的,此处不再贴代码,需要的可以私聊。