项目需要开发一个消息推送插件,今天整理一下做一个记录。

消息推送插件实现了钉钉和企业微信推送消息的功能。

首先介绍的是钉钉的实现方式:

1.需要在钉钉后台创建一个应用,并且需要记录下agentId、appKey、appSecret三个值,具体的做法不会的请移步下面的链接;
钉钉开放平台:https://developers.dingtalk.com/document/;

2.获取钉钉的Token;

 public static OapiGettokenResponse getToken(String appKey, String appSecret) {DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");OapiGettokenRequest request = new OapiGettokenRequest();request.setAppkey(appKey);request.setAppsecret(appSecret);request.setHttpMethod("GET");try {OapiGettokenResponse response = client.execute(request);return response;} catch (ApiException | com.taobao.api.ApiException e) {e.printStackTrace();}return null;}

3.获取钉钉用户信息;

public static OapiV2UserGetbymobileResponse getByMobile(String appKey, String appSecret,String phone) {DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/getbymobile");OapiV2UserGetbymobileRequest req = new OapiV2UserGetbymobileRequest();req.setMobile(phone);OapiGettokenResponse oapiGettokenResponse =getToken(appKey,appSecret);String accessToken = oapiGettokenResponse.getAccessToken();try {OapiV2UserGetbymobileResponse rsp = client.execute(req, accessToken);return rsp;} catch (ApiException | com.taobao.api.ApiException e) {e.printStackTrace();}return null;}

4.推送钉钉消息;

public static OapiMessageCorpconversationAsyncsendV2Response asyncsendV2(Integer agentId, String appKey, String appSecret, String user, String content) {OapiV2UserGetbymobileResponse oapiV2UserGetbymobileResponse = getByMobile(appKey, appSecret,user);if (!oapiV2UserGetbymobileResponse.isSuccess()) {log.error(oapiV2UserGetbymobileResponse.getErrmsg());return null;}OapiV2UserGetbymobileResponse.UserGetByMobileResponse result = oapiV2UserGetbymobileResponse.getResult();DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2");OapiMessageCorpconversationAsyncsendV2Request request = new OapiMessageCorpconversationAsyncsendV2Request();// yourAgentIdrequest.setAgentId((long) agentId);request.setUseridList(result.getUserid());request.setToAllUser(false);OapiMessageCorpconversationAsyncsendV2Request.Msg msg = new OapiMessageCorpconversationAsyncsendV2Request.Msg();msg.setMsgtype("text");msg.setText(new OapiMessageCorpconversationAsyncsendV2Request.Text());msg.getText().setContent(content);request.setMsg(msg);OapiGettokenResponse oapiGettokenResponse = getToken(appKey, appSecret);String accessToken = oapiGettokenResponse.getAccessToken();try {OapiMessageCorpconversationAsyncsendV2Response rsp = client.execute(request, accessToken);log.info("推送消息成功:"+content);return rsp;} catch (ApiException | com.taobao.api.ApiException e) {e.printStackTrace();log.error("推送消息失败:"+content);log.error("推送消息失败错误信息:"+e.getMessage());}return null;}

接下来介绍的是企业微信的实现方式:

1.企业微信的实现方式和钉钉的实现方式大体上相同,也是需要agentId、appKey、appSecret三个值,大家需要做的时候可以自己注册一个企业微信做测试,链接放在下面了。
企业微信后台:https://work.weixin.qq.com/wework_admin/frame#index;

2.创建一个AccessToken的实体类用来接受获取到的AccessToken;

package com.fengtai.dingding.weixin;/*** @author 86158*/
public class AccessToken {/*** 获取到的access_token字符串*/private String access_token;/*** 有效时间(2h,7200s)*/private int expires_in;public String getAccess_token() {return access_token;}public void setAccess_token(String access_token) {this.access_token = access_token;}public int getExpires_in() {return expires_in;}public void setExpires_in(int valid_time) {this.expires_in = valid_time;}
}

3.获取access_token;

/*** 发送消息的类型*/private final static String MSGTYPE = "text";/*** 将消息发送给所有成员*/private final static String TOPARTY = "@all";/*** 获取企业微信的企业号,根据不同企业更改*/
//    private final static String CORPID = "wwce450763381385af";/*** 获取企业应用的密钥,根据不同应用更改*/
//    private final static String CORPSECRET = "OQejindlJRefHuQZgSo8UWOZbSvlfXW9w36BOE6pvzs";/*** 获取访问权限码URL*/private final static String ACCESS_TOKEN_URL = "https://qyapi.weixin.qq.com/cgi-bin/gettoken";/*** 创建会话请求URL*/private final static String CREATE_SESSION_URL = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=";/*** 获取access_token* @return AccessToken*/private static AccessToken getAccessToken(String corpid,String corpsecret) {//访问微信服务器String url = ACCESS_TOKEN_URL + "?corpid=" + corpid + "&corpsecret=" + corpsecret;AccessToken token = new AccessToken();try {URL getUrl = new URL(url);//开启连接,并返回一个URLConnection对象HttpURLConnection http = (HttpURLConnection)getUrl.openConnection();http.setRequestMethod("GET");http.setRequestProperty("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");//将URL连接用于输入和输出,一般输入默认为true,输出默认为falsehttp.setDoOutput(true);http.setDoInput(true);//进行连接,不返回对象http.connect();//获得输入内容,并将其存储在缓存区InputStream inputStream = http.getInputStream();int size = inputStream.available();byte[] buffer = new byte[size];inputStream.read(buffer);//将内容转化为JSON代码String message = new String(buffer, StandardCharsets.UTF_8);JSONObject json = JSONObject.parseObject(message);//提取内容,放入对象token.setAccess_token(json.getString("access_token"));token.setExpires_in(new Integer(json.getString("expires_in")));} catch (IOException e) {e.printStackTrace();}//返回access_token码return token;}

4.企业接口向下属关注用户发送给微信消息

package com.fengtai.dingding.weixin;import com.alibaba.fastjson.JSONObject;
import com.fengtai.dingding.SendMessage.SendMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;/*** @author 86158*/
@Service
@Slf4j
@Component(value = "weixin")
public class SendWeChatMessage implements SendMessage {/*** 企业接口向下属关注用户发送给微信消息** @param toUser 成员ID列表* @param toParty 部门ID列表* @param toTag 标签ID列表* @param content 消息内容* @param safe 是否保密** @return*/@SuppressWarnings("deprecation")private void sendWeChatMessage(Integer agentId, String appKey, String appSecret,String toUser, String toParty, String toTag, String content, String safe) {//从对象中提取凭证AccessToken accessToken = getAccessToken(appKey,appSecret);String ACCESS_TOKEN = accessToken.getAccess_token();String url = CREATE_SESSION_URL + ACCESS_TOKEN;//请求串//封装发送消息请求JSONStringBuffer stringBuffer = new StringBuffer();stringBuffer.append("{");stringBuffer.append("\"touser\":" + "\"" + toUser + "\",");stringBuffer.append("\"toparty\":" + "\"" + toParty + "\",");stringBuffer.append("\"totag\":" + "\"" + toTag + "\",");stringBuffer.append("\"msgtype\":" + "\"" + MSGTYPE + "\",");stringBuffer.append("\"text\":" + "{");stringBuffer.append("\"content\":" + "\"" + content + "\"");stringBuffer.append("}");stringBuffer.append(",\"safe\":" + "\"" + safe + "\",");stringBuffer.append("\"agentid\":" + "\"" + agentId + "\",");stringBuffer.append("\"debug\":" + "\"" + "1" + "\"");stringBuffer.append("}");String json = stringBuffer.toString();System.out.println(json);try {URL postUrl = new URL(url);HttpURLConnection http = (HttpURLConnection) postUrl.openConnection();http.setRequestMethod("POST");http.setRequestProperty("Content-Type", "application/json;charset=UTF-8");http.setDoOutput(true);http.setDoInput(true);// 连接超时30秒System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 读取超时30秒System.setProperty("sun.net.client.defaultReadTimeout", "30000");http.connect();//写入内容OutputStream outputStream = http.getOutputStream();outputStream.write(json.getBytes("UTF-8"));InputStream inputStream = http.getInputStream();int size = inputStream.available();byte[] jsonBytes = new byte[size];inputStream.read(jsonBytes);String result = new String(jsonBytes, "UTF-8");System.out.println("请求返回结果:" + result);//清空输出流outputStream.flush();//关闭输出通道outputStream.close();//打印推送消息日志log.info("推送消息成功:"+json);} catch (IOException e) {e.printStackTrace();log.error("推送消息失败:"+json);log.error("推送消息失败错误信息:"+e.getMessage());}}

5.向企业微信发送消息;

public void SendMessage(Integer agentId, String appKey, String appSecret, String user, String content) {sendWeChatMessage(agentId,appKey,appSecret,user, "1", "", content,"0");}

以上就是对钉钉和企业微信推送消息的介绍,有不会的地方可以私信。后续会把代码放到GitHub上面。

原创不易,转载请注明出处。

插件实现了钉钉和企业微信推送消息相关推荐

  1. java 通过企业微信推送消息

    首先我们要知道企业微信推送消息的步骤,企业微信官方提供了多个API供我们调用,这里我们只讲我们需要的API: 企业微信的官方开放的API地址:https://work.weixin.qq.com/ap ...

  2. sqlserver 调用接口往企业微信推送消息

    其实解决问题的方法有很多,对于定时推送的功能来说,.net和java 都有自己的定时功能,但对于这些不熟悉,只熟悉sqlserver 的人来说,肯定希望从sqlserver下手.于是,我就尝试做了下, ...

  3. 企业微信推送消息延迟_通过企业微信发送提醒消息 支持markdown

    师太大佬: 最近一直在使用方糖推送,看到LOC大佬的企业微信推送感觉NB,隧稍作修改发上来分享给大家食用~ LOC大佬的GITHUB:https://github.com/kaixin1995/Inf ...

  4. 企业微信推送消息延迟_iPhone手机微信推送消息总是延迟怎么办?

    在有些时候我们的苹果手机屏幕页面总是有微信消失提示,但是我们打开微信页面刷新很久也看不到相应的消息记录,让我们总是没有办法及时回复一些好友消息.如果是一些工作上的关键信息就很麻烦了,毕竟现在微信已经深 ...

  5. 持续集成之企业微信通知:5:在Jenkins中向企业微信推送消息

    在这篇文章中结合具体的示例来介绍在Jenkins中如何向企业微信群推送消息. 环境准备 这里使用Easypack的Jenkins 2.164.3来创建验证用的Jenkins环境.使用如下步骤即可完成. ...

  6. 驰骋工作流JFLOW版本企业微信推送消息总结

    简介:jflow的推送消息,简单地记录一下,并不是很详细,这里以企业微信的消息推送消息为例,钉钉与其差不多. 1.推送企业微信节点消息前台页面配置:节点属性>节点消息 Jflow.propert ...

  7. 企业微信推送消息延迟_一种基于企业微信的消息推送方法与流程

    本发明涉及消息推送技术领域,特别涉及一种基于企业微信的消息推送方法. 背景技术: 随着微信公众号的普及,微信企业号也越来越受到人们的关注.而腾讯公司在微信企业号的基础上又进行了进一步的升级,提供了类似 ...

  8. Java:企业微信推送消息到个人和部门

    第一步:我们需要组装请求参数,比如下面这种的JSON字符串 这里接收的个人企业微信ID和部门ID是用符号 | 隔开的 {"touser" : "UserID1|UserI ...

  9. 企业微信推送消息延迟_企业微信发送应用消息,员工无法接收到推送消息。

    请求消息体:[touser=18666211235,toparty=,totag=,agentid=1000040,msgtype=text,content=,media_id=,title=,des ...

最新文章

  1. lvs-nat负载均衡模式
  2. 异步I/O 设备内核对象,事件内核对象,可提醒I/O 接收I/O通知
  3. 从零打造聚合支付系统:一、浅谈聚合支付的核心价值
  4. 恢复【谷歌浏览器开发者工具】默认设置(亲测)
  5. Knative 快捷操作命令 Kn 介绍
  6. efcore 实体配置_创建并配置模型
  7. c语言float如何做减法,利用c语言设计开发一个简单计算器,可进行加减乘除运算....
  8. VS中展开和折叠代码,还有其他快捷操作
  9. Kafka常用命令之kafka-console-consumer.sh
  10. [NOIP2017 TG D2T2]宝藏(模拟退火)
  11. 腾讯惹谁了?为什么用QQ邮箱投简历不受人待见
  12. 心电图分析软件_心电图、心脏彩超、心脏冠脉造影、无创冠脉磁共振的区别及用途...
  13. 6.29--6.30郭天祥老师课程中的一些错误与我的存疑
  14. 个人网站怎么申请支付接口?
  15. 【智能制造】制造业信息化与工业4.0
  16. 独立看门狗和窗口看门狗的区别
  17. HTML5与CSS3基础教程笔记
  18. 智星云服务器之云主机使用教程简记
  19. stack、queue、priority_queue
  20. Java Web3j nonce 获取

热门文章

  1. 游戏音乐外包中,策划应该做什么
  2. Array.sort用法
  3. 机器人导论(第四版)学习笔记——第一章
  4. 企业看好你啤酒瓶清洗消泡剂,不要让他们对你失信
  5. 商务人士邮箱推荐?高大上邮箱来了!
  6. 产品读书《人月神话》
  7. 响铃:企业SaaS上演“三国”杀,谁才是决定生死的变量?
  8. 车辆运动控制(7)考虑道路倾角和曲率
  9. 学习笔记:YOLO(Python版)检测图片标注目标位置
  10. libhv教程13--创建一个简单的WebSocket客户端