根據java實現企業微信訊息推送功能
阿新 • • 發佈:2022-03-14
第一步:申請企業微信註冊企業(連結:https://work.weixin.qq.com/nl/sem/registe?s=c&from=1011017189&bd_vid=11628667012427618020)
第二步:登入自己的企業微信找到應用管理———>新增應用
第三步:獲取到應用的AgentId、Secret、企業id
第四步,準備程式碼編寫:
model層程式碼:
package com.toone.itop.formula.function.inte.model; /** * @desc : 微信通用介面憑證 **/ public class AccessToken { // 獲取到的憑證 private String token; // 憑證有效時間,單位:秒 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; /** * 訊息基類(企業號 -> 普通使用者) * */ public class BaseMessage { // 否 成員ID列表(訊息接收者,多個接收者用‘|’分隔,最多支援1000個)。特殊情況:指定為@all,則向該企業應用的全部成員傳送private String touser; // 否 部門ID列表,多個接收者用‘|’分隔,最多支援100個。當touser為@all時忽略本引數 private String toparty; // 否 標籤ID列表,多個接收者用‘|’分隔,最多支援100個。當touser為@all時忽略本引數 private String totag; // 是 訊息型別 private String msgtype; // 是 企業應用的id,整型。可在應用的設定頁面檢視 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 { //是 訊息內容,最長不超過2048個位元組 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表示是,預設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); } }
所需引入的依賴
測試效果圖: