Java實(shí)現(xiàn)企業(yè)微信消息推送功能的詳細(xì)步驟
第一步:申請(qǐng)企業(yè)微信注冊(cè)企業(yè)(鏈接:https://work.weixin.qq.com/nl/sem/registe?s=c&from=1011017189&bd_vid=11628667012427618020)

第二步:登錄自己的企業(yè)微信找到應(yīng)用管理———>添加應(yīng)用

第三步:獲取到應(yīng)用的AgentId、Secret、企業(yè)id

第四步,準(zhǔn)備代碼編寫:

model層代碼:
package com.toone.itop.formula.function.inte.model;
/**
* @desc : 微信通用接口憑證
*
*/
public class AccessToken {
// 獲取到的憑證
private String token;
// 憑證有效時(shí)間,單位:秒
private int expiresIn;
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
public int getExpiresIn() {
return expiresIn;
public void setExpiresIn(int expiresIn) {
this.expiresIn = expiresIn;
} package com.toone.itop.formula.function.inte.model;
/**
* 消息基類(企業(yè)號(hào) -> 普通用戶)
*
*/
public class BaseMessage {
// 否 成員ID列表(消息接收者,多個(gè)接收者用‘|'分隔,最多支持1000個(gè))。特殊情況:指定為@all,則向該企業(yè)應(yīng)用的全部成員發(fā)送
private String touser;
// 否 部門ID列表,多個(gè)接收者用‘|'分隔,最多支持100個(gè)。當(dāng)touser為@all時(shí)忽略本參數(shù)
private String toparty;
// 否 標(biāo)簽ID列表,多個(gè)接收者用‘|'分隔,最多支持100個(gè)。當(dāng)touser為@all時(shí)忽略本參數(shù)
private String totag;
// 是 消息類型
private String msgtype;
// 是 企業(yè)應(yīng)用的id,整型。可在應(yīng)用的設(shè)置頁面查看
private int agentid;
public String getTouser() {
return touser;
}
public void setTouser(String touser) {
this.touser = touser;
public String getToparty() {
return toparty;
public void setToparty(String toparty) {
this.toparty = toparty;
public String getTotag() {
return totag;
public void setTotag(String totag) {
this.totag = totag;
public String getMsgtype() {
return msgtype;
public void setMsgtype(String msgtype) {
this.msgtype = msgtype;
public int getAgentid() {
return agentid;
public void setAgentid(int agentid) {
this.agentid = agentid;
}
package com.toone.itop.formula.function.inte.model;
/**
* 文本
*
*/
public class Text {
//是 消息內(nèi)容,最長不超過2048個(gè)字節(jié)
private String content;
public String getContent() {
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表示是,默認(rèn)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請(qǐng)求
*
*/
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;
/**
* 企業(yè)微信參數(shù)
*
*/
public class WeChatParamesUtil {
// 1.微信參數(shù)
// 企業(yè)ID
public final static String corpId = "ww0b7de3b4c25ba7881";
// 企業(yè)應(yīng)用私鑰OA
public final static String corpsecret = "xbV7an7Mev8yqsnSzzzSn0L_cCnOTJxbo9gVZR7ObpY1";
// 企業(yè)應(yīng)用的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 {
// 微信的請(qǐng)求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.發(fā)起https請(qǐng)求并獲取結(jié)果
*
* @param requestUrl
* 請(qǐng)求地址
* @param requestMethod
* 請(qǐng)求方式(GET、POST)
* @param outputStr
* 提交的數(shù)據(jù)
* @return JSONObject(通過JSONObject.get(key)的方式獲取json對(duì)象的屬性值)
*/
public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) {
JSONObject jsonObject = null;
StringBuffer buffer = new StringBuffer();
try {
// 創(chuàng)建SSLContext對(duì)象,并使用我們指定的信任管理器初始化
TrustManager[] tm = { new MyX509TrustManager() };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
// 從上述SSLContext對(duì)象中得到SSLSocketFactory對(duì)象
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);
// 設(shè)置請(qǐng)求方式(GET/POST)
httpUrlConn.setRequestMethod(requestMethod);
if ("GET".equalsIgnoreCase(requestMethod))
httpUrlConn.connect();
// 當(dāng)有數(shù)據(jù)需要提交時(shí)
if (null != outputStr) {
OutputStream outputStream = httpUrlConn.getOutputStream();
// 注意編碼格式,防止中文亂碼
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
// 將返回的輸入流轉(zhuǎn)換成字符串
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);
// 如果請(qǐng)求成功
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 : 發(fā)送消息
*
*/
public class WeChatService {
private static String sendMessage_url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=ACCESS_TOKEN";
/**
* @desc :0.公共方法:發(fā)送消息
* @param accessToken
* @param message
* void
*/
public static String sendMessage(String uid, String content) {
// 1.獲取access_token:根據(jù)企業(yè)id和應(yīng)用密鑰獲取access_token,并拼接請(qǐng)求url
String accessToken = WeChatUtil.getAccessToken(WeChatParamesUtil.corpId, WeChatParamesUtil.corpsecret).getToken();
// 2.獲取發(fā)送對(duì)象,并轉(zhuǎn)成json
Gson gson = new Gson();
TextMessage message = new TextMessage();
// 1.1非必需
message.setTouser(uid); // 不區(qū)分大小寫
//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.獲取請(qǐng)求的url
String url = sendMessage_url.replace("ACCESS_TOKEN", accessToken);
// 4.調(diào)用接口,發(fā)送消息
JSONObject jsonObject = WeChatUtil.httpRequest(url, "POST", jsonMessage);
// 4.錯(cuò)誤消息處理
if (null != jsonObject) {
if (0 != jsonObject.getInt("errcode")) {
System.out.println("消息發(fā)送失敗 errcode:{} errmsg:{}" + jsonObject.getInt("errcode") + jsonObject.getString("errmsg"));
}
}
return jsonObject.toString();
}
public static void main(String[] args) {
// 0.設(shè)置消息內(nèi)容
String content = "這是一條測(cè)試消息";
//userId為企業(yè)用戶的id
String userId = "qianxia";
// 3.發(fā)送消息:調(diào)用業(yè)務(wù)類,發(fā)送消息
WeChatService.sendMessage(userId, content);
}
}所需引入的依賴

測(cè)試效果圖:

到此這篇關(guān)于Java實(shí)現(xiàn)企業(yè)微信消息推送功能的文章就介紹到這了,更多相關(guān)java企業(yè)微信消息推送內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Java中websocket消息推送的實(shí)現(xiàn)代碼
- java WebSocket實(shí)現(xiàn)聊天消息推送功能
- java實(shí)現(xiàn)釘釘機(jī)器人消息推送的示例代碼
- SpringBoot整合WxJava開啟消息推送的實(shí)現(xiàn)
- java實(shí)現(xiàn)web實(shí)時(shí)消息推送的七種方案
- 從零開始講解Java微信公眾號(hào)消息推送實(shí)現(xiàn)
- Java應(yīng)用層協(xié)議WebSocket實(shí)現(xiàn)消息推送
- Java 服務(wù)端消息推送的實(shí)現(xiàn)小結(jié)
相關(guān)文章
基于jmeter實(shí)現(xiàn)跨線程組傳遞token過程圖解
這篇文章主要介紹了基于jmeter實(shí)現(xiàn)跨線程組傳遞token,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-04-04
Eclipse中導(dǎo)入Maven Web項(xiàng)目并配置其在Tomcat中運(yùn)行圖文詳解
這篇文章主要介紹了Eclipse中導(dǎo)入Maven Web項(xiàng)目并配置其在Tomcat中運(yùn)行圖文詳解,需要的朋友可以參考下2017-12-12
java構(gòu)建Stream流的多種方式總結(jié)
Java?8引入了Stream流作為一項(xiàng)新的特性,它是用來處理集合數(shù)據(jù)的一種函數(shù)式編程方式,本文為大家整理了多種java構(gòu)建Stream流的方式,希望對(duì)大家有所幫助2023-11-11
解決MultipartFile.transferTo(dest) 報(bào)FileNotFoundExcep的問題
這篇文章主要介紹了解決MultipartFile.transferTo(dest) 報(bào)FileNotFoundExcep的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-07-07
Maven dependencies與dependencyManagement的區(qū)別詳解
這篇文章主要介紹了Maven dependencies與dependencyManagement的區(qū)別詳解,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2019-04-04
解決eclipse中maven引用不到已經(jīng)存在maven中jar包的問題
這篇文章主要介紹了解決eclipse中maven引用不到已經(jīng)存在maven中jar包的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-10-10
Java中private關(guān)鍵字詳細(xì)用法實(shí)例以及解釋
這篇文章主要給大家介紹了關(guān)于Java中private關(guān)鍵字詳細(xì)用法實(shí)例以及解釋的相關(guān)資料,在Java中private是一種訪問修飾符,它可以用來控制類成員的訪問權(quán)限,文中將用法介紹的非常詳細(xì),需要的朋友可以參考下2024-01-01
SpringBoot監(jiān)聽Nacos動(dòng)態(tài)修改日志級(jí)別的操作方法
線上系統(tǒng)的日志級(jí)別一般都是 INFO 級(jí)別,有時(shí)候需要查看 WARN 級(jí)別的日志,所以需要?jiǎng)討B(tài)修改日志級(jí)別,微服務(wù)項(xiàng)目中使用 Nacos 作為注冊(cè)中心,我們可以監(jiān)聽 Nacos 配置,修改日志級(jí)別,這篇文章主要介紹了SpringBoot監(jiān)聽Nacos動(dòng)態(tài)修改日志級(jí)別的操作方法,需要的朋友可以參考下2023-12-12

