调用企业微信消息推送接口,企业微信如何推送消息
第一步:申请企业微信注册企业(链接:https://work.weixin.qq.com/nl/sem/registe?s=cf rom=1011017189 BD _ vid=11628667012427618020)
第二步:登录自己的企业微信找到应用管理———添加应用
第三步:获取到应用的代理身份证,机密、企业编号
第四步,准备代码编写:
模型层代码:
包com。托恩。itop。公式。功能。因特。模型;/* * * * @ desc :微信通用接口凭证* */公共类AccessToken { //获取到的凭证私有字符串标记;//凭证有效时间,单位:秒私有inter expi resin公共字符串getToken(){返回标记;} public void setToken(String token){ this。token=令牌;public int get expi resin(){ return expi resin;public void setexpirish(int expi resin){ this。expi树脂=expi树脂;}包com。托恩。itop。公式。功能。因特。模型;/** * 消息基类(企业号-普通用户)* */公共类BaseMessage { //否成员身份列表(消息接收者,多个接收者用分隔,最多支持1000个)。特殊情况:指定为@all,则向该企业应用的全部成员发送私有字符串用户;//否部门身份列表,多个接收者用分隔,最多支持100个。当图瑟为@全部时忽略本参数私有字符串toparty//否标签身份列表,多个接收者用分隔,最多支持100个。当图瑟为@全部时忽略本参数私有字符串totag//是消息类型私有字符串msgtype//是企业应用的id,整型。可在应用的设置页面查看私有int agentid公共字符串getTouser(){返回给用户;} public void setTouser(String touser){ this。touser=touser公共字符串getToparty(){返回参与方;public void setto party(String to party){ this。to party=to party公共字符串get totag(){ return totag;public void setTotag(String totag){ this。totag=totag公共字符串getMsgtype(){ return msgtype;public void setMsgtype(String msg type){ this。消息类型=消息类型;public int geta gentid(){ return agentid;public void setAgentid(int agentid){ this。agentid=agentid}包com。托恩。itop。公式。功能。因特。模型;/** * 文本* */公共类文本{ //是消息内容,最长不超过2048个字节私有字符串内容;公共字符串get content(){ return content;}
public void setContent(String content) { this.content = content;}
package com.toone.itop.formula.function.inte.model;/** * 文本消息 * */public class TextMessage extends BaseMessage { // 文本 private Text text; // 否 表示是否是保密消息,0表示否,1表示是,默认0 private int safe; public Text getText() { return text; } public void setText(Text text2) { this.text = text2; } public int getSafe() { return safe; } public void setSafe(int safe) { this.safe = safe; }}
通用工具类:
package com.toone.itop.formula.function.inte.util;import java.security.cert.CertificateException;import java.security.cert.X509Certificate;import javax.net.ssl.X509TrustManager;/** * 证书信任管理器(用于https请求 * */public class MyX509TrustManager implements X509TrustManager { public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { public X509Certificate[] getAcceptedIssuers() { return null;}
package com.toone.itop.formula.function.inte.util;/** * 企业微信参数 * */public class WeChatParamesUtil { // 1.微信参数 // 企业ID public final static String corpId = "ww0b7de3b4c25ba7881"; // 企业应用私钥OA public final static String corpsecret = "xbV7an7Mev8yqsnSzzzSn0L_cCnOTJxbo9gVZR7ObpY1"; // 企业应用的id public final static int agentId = 1000008; public final static String aws6url = "http://localhost:8088";}
package com.toone.itop.formula.function.inte.util;import java.io.BufferedReader;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.net.ConnectException;import java.net.URL;import javax.net.ssl.HttpsURLConnection;import javax.net.ssl.SSLContext;import javax.net.ssl.SSLSocketFactory;import javax.net.ssl.TrustManager;import net.sf.json.JSONException;import net.sf.json.JSONObject;import com.toone.itop.formula.function.inte.model.AccessToken;public class WeChatUtil { // 微信的请求url // 获取access_token的接口地址(GET) 限200(次/天) public final static String access_token_url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={corpId}&corpsecret={corpsecret}"; /** * 1.发起https请求并获取结果 * * @param requestUrl * 请求地址 * @param requestMethod * 请求方式(GET、POST) * @param outputStr * 提交的数据 * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值) */ public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) { JSONObject jsonObject = null; StringBuffer buffer = new StringBuffer(); try { // 创建SSLContext对象,并使用我们指定的信任管理器初始化 TrustManager[] tm = { new MyX509TrustManager() }; SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE"); sslContext.init(null, tm, new java.security.SecureRandom()); // 从上述SSLContext对象中得到SSLSocketFactory对象 SSLSocketFactory ssf = sslContext.getSocketFactory(); URL url = new URL(requestUrl); HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection(); httpUrlConn.setSSLSocketFactory(ssf); httpUrlConn.setDoOutput(true); httpUrlConn.setDoInput(true); httpUrlConn.setUseCaches(false); // 设置请求方式(GET/POST) httpUrlConn.setRequestMethod(requestMethod); if ("GET".equalsIgnoreCase(requestMethod)) httpUrlConn.connect(); // 当有数据需要提交时 if (null != outputStr) { OutputStream outputStream = httpUrlConn.getOutputStream(); // 注意编码格式,防止中文乱码 outputStream.write(outputStr.getBytes("UTF-8")); outputStream.close(); } // 将返回的输入流转换成字符串 InputStream inputStream = httpUrlConn.getInputStream(); InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8"); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String str = null; while ((str = bufferedReader.readLine()) != null) { buffer.append(str); bufferedReader.close(); inputStreamReader.close(); // 释放资源 inputStream.close(); inputStream = null; httpUrlConn.disconnect(); jsonObject = JSONObject.fromObject(buffer.toString()); } catch (ConnectException ce) { // Weixin server connection timed out } catch (Exception e) { // https request error:{} // e.printStackTrace(); } return jsonObject; } * 2.获取access_token * @param appid * 凭证 * @param appsecret * 密钥 * @return public static AccessToken getAccessToken(String appid, String appsecret) { AccessToken accessToken = null; String requestUrl = access_token_url.replace("{corpId}", appid).replace("{corpsecret}", appsecret); JSONObject jsonObject = httpRequest(requestUrl, "GET", null); // 如果请求成功 if (null != jsonObject) { try { accessToken = new AccessToken(); accessToken.setToken(jsonObject.getString("access_token")); accessToken.setExpiresIn(jsonObject.getInt("expires_in")); } catch (JSONException e) { accessToken = null; // 获取token失败 // log.error("获取token失败 errcode:{} errmsg:{}"+ // jsonObject.getInt("errcode")+jsonObject.getString("errmsg")); return accessToken;}
service层:
package com.toone.itop.formula.function.inte.service;import net.sf.json.JSONObject;import com.google.gson.Gson;import com.toone.itop.formula.function.inte.model.Text;import com.toone.itop.formula.function.inte.model.TextMessage;import com.toone.itop.formula.function.inte.util.WeChatParamesUtil;import com.toone.itop.formula.function.inte.util.WeChatUtil;/** * @desc : 发送消息 * */public class WeChatService { private static String sendMessage_url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=ACCESS_TOKEN"; /** * @desc :0.公共方法:发送消息 * @param accessToken * @param message * void */ public static String sendMessage(String uid, String content) { // 1.获取access_token:根据企业id和应用密钥获取access_token,并拼接请求url String accessToken = WeChatUtil.getAccessToken(WeChatParamesUtil.corpId, WeChatParamesUtil.corpsecret).getToken(); // 2.获取发送对象,并转成json Gson gson = new Gson(); TextMessage message = new TextMessage(); // 1.1非必需 message.setTouser(uid); // 不区分大小写 //message.setToparty("1"); //message.getTouser(totag); // txtMsg.setSafe(0); // 1.2必需 message.setMsgtype("text"); message.setAgentid(WeChatParamesUtil.agentId); Text text = new Text(); text.setContent(content); message.setText(text); String jsonMessage = gson.toJson(message); // 3.获取请求的url String url = sendMessage_url.replace("ACCESS_TOKEN", accessToken); // 4.调用接口,发送消息 JSONObject jsonObject = WeChatUtil.httpRequest(url, "POST", jsonMessage); // 4.错误消息处理 if (null != jsonObject) { if (0 != jsonObject.getInt("errcode")) { System.out.println("消息发送失败 errcode:{} errmsg:{}" + jsonObject.getInt("errcode") + jsonObject.getString("errmsg")); } } return jsonObject.toString(); } public static void main(String[] args) { // 0.设置消息内容 String content = "这是一条测试消息"; //userId为企业用户的id String userId = "qianxia"; // 3.发送消息:调用业务类,发送消息 WeChatService.sendMessage(userId, content); }}
所需引入的依赖
测试效果图:
到此这篇关于Java实现企业微信消息推送功能的文章就介绍到这了,更多相关java企业微信消息推送内容请搜索盛行IT以前的文章或继续浏览下面的相关文章希望大家以后多多支持盛行IT!
郑重声明:本文由网友发布,不代表盛行IT的观点,版权归原作者所有,仅为传播更多信息之目的,如有侵权请联系,我们将第一时间修改或删除,多谢。