微信企業號驗證/發送/吸收新聞。本站提示廣大學習愛好者:(微信企業號驗證/發送/吸收新聞)文章只能為提供參考,不一定能成為您想要的結果。以下是微信企業號驗證/發送/吸收新聞正文
1. 內網映照
因為微信企業號回調形式的URL盡支撐域名方法拜訪,估須要注冊花生殼,做一個內網穿透(須要花16塊錢,購置一個收費版,購置以後,第二天賦能添加上域名)
2. 微信企業號
注冊微信企業號:https://qy.weixin.qq.com/ (選擇團隊,團隊不須要認證)
通信錄:新建組織 - > 存眷成員
企業號 -> 運用中間 -> 新建運用 -> 新聞型運用 -> 形式選擇(回調形式) -> 開啟微信新聞轉發,
回調形式解釋:http://qydev.weixin.qq.com/wiki/index.PHP?title=%E5%9B%9E%E8%B0%83%E6%A8%A1%E5%BC%8F
回調形式加密解密代碼:http://qydev.weixin.qq.com/wiki/index.php?title=%E5%8A%A0%E8%A7%A3%E5%AF%86%E5%BA%93%E4%B8%8B%E8%BD%BD%E4%B8%8E%E8%BF%94%E5%9B%9E%E7%A0%81
如圖1:
自界說菜單: 開辟運用的要求途徑如圖2:
設置 -> 功效設置 -> 權限治理 -> 新建治理組 -> 運用權限( Secret )
3. 應用Jersey開辟web Service辦事
3.1 在類中界說token, 隨秘密碼43位,公司corpId, secret
3.2 驗證辦法
/* * ------------應用示例一:驗證回調URL---------------企業開啟回調形式時,企業號會向驗證url發送一個get要求 * 假定點擊驗證時,企業收到相似要求: GET * /cgi-bin/wxpush?msg_signature=5c45ff5e21c57e6ad56bac8758b79b1d9ac89fd3 * ×tamp * =1409659589&nonce=263014780&echostr=P9nAzCzyDtyTWESHep1vC5X9xho% * 2FqYX3Zpb4yKa9SKld1DsH3Iyt3tP3zNdtp%2B4RPcs8TgAE7OaBO%2BFZXvnaqQ%3D%3D * HTTP/1.1 Host: qy.weixin.qq.com * * 吸收到該要求時,企業應 * 1.解析出Get要求的參數,包含新聞體簽名(msg_signature),時光戳(timestamp),隨機數字串(nonce * )和"平台推送過去的隨機加密字符串(echostr), 這一步留意作URL解碼。 2.驗證新聞體簽名的准確性 3. * 解密出echostr原文,將原文看成Get要求的response,前往給"平台 第2,3步可以用"平台供給的庫函數VerifyURL來完成。 */ /** * 回調URL,微信挪用此辦法停止驗證 * * @return */ @GET @Path("station") public String verify() { String msgSignature = request.getParameter("msg_signature"); String timeStamp = request.getParameter("timestamp"); String nonce = request.getParameter("nonce"); System.out.println(timeStamp + " " + nonce); String echostr = request.getParameter("echostr"); String sEchoStr = null; try { sEchoStr = wxcpt.VerifyURL(msgSignature, timeStamp, nonce, echostr); } catch (Exception e) { e.printStackTrace();// 驗證URL掉敗,毛病緣由請檢查異常 } return sEchoStr; }
3.3 吸收用戶信息,並解密
/* * ------------對用戶答復的新聞解密--------------- * 用戶答復新聞或許點擊事宜呼應時,企業會收到回調新聞,此新聞是經由"平台加密以後的密文以post情勢發送給企業,密文格局請參考官方文檔 * 假定企業收到"平台的回調新聞以下: POST /cgi-bin/wxpush? * msg_signature=477715d11cdb4164915debcba66cb864d751f3e6 * ×tamp=1409659813&nonce=1372623149 HTTP/1.1 Host: qy.weixin.qq.com * Content-Length: 613 <xml> * <ToUserName><![CDATA[wx5823bf96d3bd56c7]]></ToUserName * ><Encrypt><![CDATA[RypEvHKD8QQKFhvQ6QleEB4J58tiPdvo * +rtK1I9qca6aM/wvqnLSV5zEPeusUiX5L5X/0lWfrf0QADHHhGd3QczcdCUpj911L3vg3W/ * sYYvuJTs3TUUkSUXxaccAS0qhxchrRYt66wiSpGLYL42aM6A8dTT * +6k4aSknmPj48kzJs8qLjvd4Xgpue06DOdnLxAUHzM6 * +kDZ+HMZfJYuR+LtwGc2hgf5gsijff0ekUNXZiqATP7PF5mZxZ3Izoun1s4zG4LUMnvw2r * +KqCKIw * +3IQH03v+BCA9nMELNqbSf6tiWSrXJB3LAVGUcallcrw8V2t9EL4EhzJWrQUax5wLVMNS0 * +rUPA3k22Ncx4XXZS9o0MBH27Bo6BpNelZpS * +/uh9KsNlY6bHCmJU9p8g7m3fVKn28H3KDYA5Pl * /T8Z1ptDAVe0lXdQ2YoyyH2uyPIGHBZZIs2pDBS8R07+qN+E7Q==]]></Encrypt> * <AgentID><![CDATA[218]]></AgentID> </xml> * * 企業收到post要求以後應當 * 1.解析出url上的參數,包含新聞體簽名(msg_signature),時光戳(timestamp)和隨機數字串(nonce) * 2.驗證新聞體簽名的准確性。 * 3.將post要求的數據停止xml解析,並將<Encrypt>標簽的內容停止解密,解密出來的明文等於用戶答復新聞的明文,明文格局請參考官方文檔 * 第2,3步可以用"平台供給的庫函數DecryptMsg來完成。 */ @POST @Path("station") public String receiveMsg(String reqData) { String msgSignature = request.getParameter("msg_signature"); String timeStamp = request.getParameter("timestamp"); String nonce = request.getParameter("nonce"); // post要求的密文數據 // String sReqData = // "<xml><ToUserName><![CDATA[wx5823bf96d3bd56c7]]></ToUserName><Encrypt><![CDATA[RypEvHKD8QQKFhvQ6QleEB4J58tiPdvo+rtK1I9qca6aM/wvqnLSV5zEPeusUiX5L5X/0lWfrf0QADHHhGd3QczcdCUpj911L3vg3W/sYYvuJTs3TUUkSUXxaccAS0qhxchrRYt66wiSpGLYL42aM6A8dTT+6k4aSknmPj48kzJs8qLjvd4Xgpue06DOdnLxAUHzM6+kDZ+HMZfJYuR+LtwGc2hgf5gsijff0ekUNXZiqATP7PF5mZxZ3Izoun1s4zG4LUMnvw2r+KqCKIw+3IQH03v+BCA9nMELNqbSf6tiWSrXJB3LAVGUcallcrw8V2t9EL4EhzJWrQUax5wLVMNS0+rUPA3k22Ncx4XXZS9o0MBH27Bo6BpNelZpS+/uh9KsNlY6bHCmJU9p8g7m3fVKn28H3KDYA5Pl/T8Z1ptDAVe0lXdQ2YoyyH2uyPIGHBZZIs2pDBS8R07+qN+E7Q==]]></Encrypt><AgentID><![CDATA[218]]></AgentID></xml>"; try { String sMsg = wxcpt.DecryptMsg(msgSignature, timeStamp, nonce, reqData); // 解析出明文xml標簽的內容停止處置 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); StringReader sr = new StringReader(sMsg); InputSource is = new InputSource(sr); Document document = db.parse(is); Element root = document.getDocumentElement(); NodeList nodelist1 = root.getElementsByTagName("Content"); if (nodelist1.item(0) == null) return "ok"; String Content = nodelist1.item(0).getTextContent(); System.out.println("Content:" + Content); } catch (Exception e) { e.printStackTrace();// 解密掉敗,掉敗緣由請檢查異常 } return "ok"; }
3.4 發送信息到微信
設置 -> 功效設置 -> 權限治理 -> 新建治理組; 獲得secret
/** * 此辦法可以發送隨意率性類型新聞 * * @param msgType * text|image|voice|video|file|news * @param touser * 成員ID列表(新聞吸收者,多個吸收者用‘|'分隔,最多支撐1000個)。特別情形:指定為@all, * 則向存眷該企業運用的全體成員發送 * @param toparty * 部分ID列表,多個吸收者用‘|'分隔,最多支撐100個。當touser為@all時疏忽本參數 * @param totag * 標簽ID列表,多個吸收者用‘|'分隔。當touser為@all時疏忽本參數 * @param content * msgType=text時 ,文本新聞內容 * @param mediaId * msgType=image|voice|video時 ,對應新聞信息ID(--------) * @param title * msgType=news|video時,新聞題目 * @param description * msgType=news|video時,新聞描寫 * @param url * msgType=news時,新聞鏈接 * @param picurl * msgType=news時,圖片途徑 * @param safe * 表現能否是保密新聞,0表現否,1表現是,默許0 */ public void sendWeChatMsg(String msgType, String touser, String toparty, String totag, String content, String mediaId, String title, String description, String url, String picurl, String safe) { URL uRl; String ACCESS_TOKEN = getAccessToken(); // 拼接要求串 String action = CREATE_SESSION_URL + ACCESS_TOKEN; // 封裝發送新聞要求json StringBuffer sb = new StringBuffer(); sb.append("{"); sb.append("\"touser\":" + "\"" + touser + "\","); sb.append("\"toparty\":" + "\"" + toparty + "\","); sb.append("\"totag\":" + "\"" + totag + "\","); if (msgType.equals("text")) { sb.append("\"msgtype\":" + "\"" + msgType + "\","); sb.append("\"text\":" + "{"); sb.append("\"content\":" + "\"" + content + "\""); sb.append("}"); } else if (msgType.equals("image")) { sb.append("\"msgtype\":" + "\"" + msgType + "\","); sb.append("\"image\":" + "{"); sb.append("\"media_id\":" + "\"" + mediaId + "\""); sb.append("}"); } else if (msgType.equals("voice")) { sb.append("\"msgtype\":" + "\"" + msgType + "\","); sb.append("\"voice\":" + "{"); sb.append("\"media_id\":" + "\"" + mediaId + "\""); sb.append("}"); } else if (msgType.equals("video")) { sb.append("\"msgtype\":" + "\"" + msgType + "\","); sb.append("\"video\":" + "{"); sb.append("\"media_id\":" + "\"" + mediaId + "\","); sb.append("\"title\":" + "\"" + title + "\","); sb.append("\"description\":" + "\"" + description + "\""); sb.append("}"); } else if (msgType.equals("file")) { sb.append("\"msgtype\":" + "\"" + msgType + "\","); sb.append("\"file\":" + "{"); sb.append("\"media_id\":" + "\"" + mediaId + "\""); sb.append("}"); } else if (msgType.equals("news")) { sb.append("\"msgtype\":" + "\"" + msgType + "\","); sb.append("\"news\":" + "{"); sb.append("\"articles\":" + "["); sb.append("{"); sb.append("\"title\":" + "\"" + title + "\","); sb.append("\"description\":" + "\"" + description + "\","); sb.append("\"url\":" + "\"" + url + "\","); sb.append("\"picurl\":" + "\"" + picurl + "\""); sb.append("}"); sb.append("]"); sb.append("}"); } sb.append(",\"safe\":" + "\"" + safe + "\","); sb.append("\"agentid\":" + "\"" + 1 + "\","); sb.append("\"debug\":" + "\"" + "1" + "\""); sb.append("}"); String json = sb.toString(); try { uRl = new URL(action); HttpsURLConnection http = (HttpsURLConnection) uRl.openConnection(); http.setRequestMethod("POST"); http.setRequestProperty("Content-Type", "application/json;charset=UTF-8"); http.setDoOutput(true); http.setDoInput(true); System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// // 銜接超時30秒 System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // // 讀取超時30秒 http.connect(); OutputStream os = http.getOutputStream(); os.write(json.getBytes("UTF-8"));// 傳入參數 InputStream is = http.getInputStream(); int size = is.available(); byte[] jsonBytes = new byte[size]; is.read(jsonBytes); String result = new String(jsonBytes, "UTF-8"); System.out.println("要求前往成果:" + result); os.flush(); os.close(); } catch (Exception e) { e.printStackTrace(); } } // 獲得接口拜訪權限碼 public String getAccessToken() { HttpClient client = new HttpClient(); PostMethod post = new PostMethod(ACCESS_TOKEN_URL); post.releaseConnection(); post.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); NameValuePair[] param = { new NameValuePair("corpid", corpId), new NameValuePair("corpsecret", secret) }; // 設置戰略,避免報cookie毛病 DefaultHttpParams.getDefaultParams().setParameter( "http.protocol.cookie-policy", CookiePolicy.BROWSER_COMPATIBILITY); // 給post設置參數 post.setRequestBody(param); String result = ""; try { client.executeMethod(post); result = new String(post.getResponseBodyAsString().getBytes("gbk")); } catch (IOException e) { e.printStackTrace(); } // 將數據轉換成json JSONObject jasonObject; jasonObject = JSONObject.fromObject(result); result = (String) jasonObject.get("access_token"); post.releaseConnection(); System.out.println(result); return result; } public static void main(String[] args) { StationResource weChat = new StationResource(); // weChat.sendWeChatMsgText("@all", "2", "", "信息中間告訴", "0"); weChat.sendWeChatMsg("news", "@all", "", "", "測試senMsg", "", "測試的", "真的是測試的", "http://www.百度.com", "http://file27.mafengwo.net/M00/B2/12/wKgB6lO0ahWAMhL8AAV1yBFJDJw20.jpeg", "0"); }
4. 開辟完成。 須要將該類在webx.xml中添加到rest中治理
<!-- RESTful支撐 --> <!-- webserivce辦事,如增長了辦事,須要在param-value中增長辦事的包途徑 --> <servlet> <servlet-name>JAX-RS REST Servlet</servlet-name> <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class> <init-param> <param-name>com.sun.jersey.config.property.packages</param-name> <param-value>com.base.pf.restful</param-value> </init-param> <load-on-startup>2</load-on-startup> </servlet> <servlet-mapping> <servlet-name>JAX-RS REST Servlet</servlet-name> <url-pattern>/rest/*</url-pattern> </servlet-mapping>
5. 開辟完成的全量代碼
package com.base.pf.restful; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.StringReader; import java.net.URL; import javax.net.ssl.HttpsURLConnection; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.core.Context; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import net.sf.json.JSONObject; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.cookie.CookiePolicy; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.params.DefaultHttpParams; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import com.qq.weixin.mp.aes.AesException; import com.qq.weixin.mp.aes.WXBizMsgCrypt; /** * 微信企業號開辟 * * @author ZHEN.L * */ @Path("wx") public class StationResource { // http://hichinamobile.xicp.net/security/rest/wx // https://qy.weixin.qq.com private String token = "spm"; // 企業號 -> 運用中間 -> 新建運用 -> 新聞型運用 private String agentId = "1"; // 企業號 -> 運用中間 -> 點開運用中 -> 運用ID private String encodingAesKey = "nT6ZWTVFlyNXOhFOGGOZWdJpAgeFSV8ln5CNeYw7mwl"; // 企業號 -> 運用中間 -> 新建運用 -> 新聞型運用 private String corpId = "wxe49318eb604cf00b"; // 企業號 -> 設置 -> 企業號信息 -> 賬號信息 private String secret = "M-YFKmgl_kXBVEtginZH3RQWbz4xb6MFeQXXLk77mkpxZenFDYq-UgerxdUF8rel"; // 企業號 -> 設置 -> 功效設置 -> 權限治理中 @Context HttpServletRequest request; @Context HttpServletResponse response; WXBizMsgCrypt wxcpt = null; public StationResource() { try { wxcpt = new WXBizMsgCrypt(token, encodingAesKey, corpId); } catch (AesException e) { e.printStackTrace(); } } // 獲得拜訪權限碼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="; // 獲得接口拜訪權限碼 public String getAccessToken() { HttpClient client = new HttpClient(); PostMethod post = new PostMethod(ACCESS_TOKEN_URL); post.releaseConnection(); post.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); NameValuePair[] param = { new NameValuePair("corpid", corpId), new NameValuePair("corpsecret", secret) }; // 設置戰略,避免報cookie毛病 DefaultHttpParams.getDefaultParams().setParameter( "http.protocol.cookie-policy", CookiePolicy.BROWSER_COMPATIBILITY); // 給post設置參數 post.setRequestBody(param); String result = ""; try { client.executeMethod(post); result = new String(post.getResponseBodyAsString().getBytes("gbk")); } catch (IOException e) { e.printStackTrace(); } // 將數據轉換成json JSONObject jasonObject; jasonObject = JSONObject.fromObject(result); result = (String) jasonObject.get("access_token"); post.releaseConnection(); System.out.println(result); return result; } /* * ------------應用示例一:驗證回調URL---------------企業開啟回調形式時,企業號會向驗證url發送一個get要求 * 假定點擊驗證時,企業收到相似要求: GET * /cgi-bin/wxpush?msg_signature=5c45ff5e21c57e6ad56bac8758b79b1d9ac89fd3 * ×tamp * =1409659589&nonce=263014780&echostr=P9nAzCzyDtyTWESHep1vC5X9xho% * 2FqYX3Zpb4yKa9SKld1DsH3Iyt3tP3zNdtp%2B4RPcs8TgAE7OaBO%2BFZXvnaqQ%3D%3D * HTTP/1.1 Host: qy.weixin.qq.com * * 吸收到該要求時,企業應 * 1.解析出Get要求的參數,包含新聞體簽名(msg_signature),時光戳(timestamp),隨機數字串(nonce * )和"平台推送過去的隨機加密字符串(echostr), 這一步留意作URL解碼。 2.驗證新聞體簽名的准確性 3. * 解密出echostr原文,將原文看成Get要求的response,前往給"平台 第2,3步可以用"平台供給的庫函數VerifyURL來完成。 */ /** * 回調URL,微信挪用此辦法停止驗證 * * @return */ @GET @Path("station") public String verify() { String msgSignature = request.getParameter("msg_signature"); String timeStamp = request.getParameter("timestamp"); String nonce = request.getParameter("nonce"); System.out.println(timeStamp + " " + nonce); String echostr = request.getParameter("echostr"); String sEchoStr = null; try { sEchoStr = wxcpt.VerifyURL(msgSignature, timeStamp, nonce, echostr); } catch (Exception e) { e.printStackTrace();// 驗證URL掉敗,毛病緣由請檢查異常 } return sEchoStr; } /* * ------------對用戶答復的新聞解密--------------- * 用戶答復新聞或許點擊事宜呼應時,企業會收到回調新聞,此新聞是經由"平台加密以後的密文以post情勢發送給企業,密文格局請參考官方文檔 * 假定企業收到"平台的回調新聞以下: POST /cgi-bin/wxpush? * msg_signature=477715d11cdb4164915debcba66cb864d751f3e6 * ×tamp=1409659813&nonce=1372623149 HTTP/1.1 Host: qy.weixin.qq.com * Content-Length: 613 <xml> * <ToUserName><![CDATA[wx5823bf96d3bd56c7]]></ToUserName * ><Encrypt><![CDATA[RypEvHKD8QQKFhvQ6QleEB4J58tiPdvo * +rtK1I9qca6aM/wvqnLSV5zEPeusUiX5L5X/0lWfrf0QADHHhGd3QczcdCUpj911L3vg3W/ * sYYvuJTs3TUUkSUXxaccAS0qhxchrRYt66wiSpGLYL42aM6A8dTT * +6k4aSknmPj48kzJs8qLjvd4Xgpue06DOdnLxAUHzM6 * +kDZ+HMZfJYuR+LtwGc2hgf5gsijff0ekUNXZiqATP7PF5mZxZ3Izoun1s4zG4LUMnvw2r * +KqCKIw * +3IQH03v+BCA9nMELNqbSf6tiWSrXJB3LAVGUcallcrw8V2t9EL4EhzJWrQUax5wLVMNS0 * +rUPA3k22Ncx4XXZS9o0MBH27Bo6BpNelZpS * +/uh9KsNlY6bHCmJU9p8g7m3fVKn28H3KDYA5Pl * /T8Z1ptDAVe0lXdQ2YoyyH2uyPIGHBZZIs2pDBS8R07+qN+E7Q==]]></Encrypt> * <AgentID><![CDATA[218]]></AgentID> </xml> * * 企業收到post要求以後應當 * 1.解析出url上的參數,包含新聞體簽名(msg_signature),時光戳(timestamp)和隨機數字串(nonce) * 2.驗證新聞體簽名的准確性。 * 3.將post要求的數據停止xml解析,並將<Encrypt>標簽的內容停止解密,解密出來的明文等於用戶答復新聞的明文,明文格局請參考官方文檔 * 第2,3步可以用"平台供給的庫函數DecryptMsg來完成。 */ @POST @Path("station") public String receiveMsg(String reqData) { String msgSignature = request.getParameter("msg_signature"); String timeStamp = request.getParameter("timestamp"); String nonce = request.getParameter("nonce"); // post要求的密文數據 // String sReqData = // "<xml><ToUserName><![CDATA[wx5823bf96d3bd56c7]]></ToUserName><Encrypt><![CDATA[RypEvHKD8QQKFhvQ6QleEB4J58tiPdvo+rtK1I9qca6aM/wvqnLSV5zEPeusUiX5L5X/0lWfrf0QADHHhGd3QczcdCUpj911L3vg3W/sYYvuJTs3TUUkSUXxaccAS0qhxchrRYt66wiSpGLYL42aM6A8dTT+6k4aSknmPj48kzJs8qLjvd4Xgpue06DOdnLxAUHzM6+kDZ+HMZfJYuR+LtwGc2hgf5gsijff0ekUNXZiqATP7PF5mZxZ3Izoun1s4zG4LUMnvw2r+KqCKIw+3IQH03v+BCA9nMELNqbSf6tiWSrXJB3LAVGUcallcrw8V2t9EL4EhzJWrQUax5wLVMNS0+rUPA3k22Ncx4XXZS9o0MBH27Bo6BpNelZpS+/uh9KsNlY6bHCmJU9p8g7m3fVKn28H3KDYA5Pl/T8Z1ptDAVe0lXdQ2YoyyH2uyPIGHBZZIs2pDBS8R07+qN+E7Q==]]></Encrypt><AgentID><![CDATA[218]]></AgentID></xml>"; try { String sMsg = wxcpt.DecryptMsg(msgSignature, timeStamp, nonce, reqData); // 解析出明文xml標簽的內容停止處置 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); StringReader sr = new StringReader(sMsg); InputSource is = new InputSource(sr); Document document = db.parse(is); Element root = document.getDocumentElement(); NodeList nodelist1 = root.getElementsByTagName("Content"); if (nodelist1.item(0) == null) return "ok"; String Content = nodelist1.item(0).getTextContent(); System.out.println("Content:" + Content); } catch (Exception e) { e.printStackTrace();// 解密掉敗,掉敗緣由請檢查異常 } return "ok"; } /* * ------------應用示例三:企業答復用戶新聞的加密--------------- * 企業主動答復用戶的新聞也須要停止加密,而且拼接成密文格局的xml串。 假定企業須要答復用戶的明文以下: <xml> * <ToUserName><![CDATA[mycreate]]></ToUserName> * <FromUserName><![CDATA[wx5823bf96d3bd56c7]]></FromUserName> * <CreateTime>1348831860</CreateTime> <MsgType><![CDATA[text]]></MsgType> * <Content><![CDATA[this is a test]]></Content> * <MsgId>1234567890123456</MsgId> <AgentID>128</AgentID> </xml> * * 為了將此段明文答復給用戶,企業應: * 1.本身生成時光時光戳(timestamp),隨機數字串(nonce)以便生成新聞體簽名,也能夠直接用從"平台的post * url上解析出的對應值。 2.將明文加密獲得密文。 * 3.用密文,步調1生成的timestamp,nonce和企業在"平台設定的token生成新聞體簽名。 * 4.將密文,新聞體簽名,時光戳,隨機數字串拼接成xml格局的字符串,發送給企業。 * 以上2,3,4步可以用"平台供給的庫函數EncryptMsg來完成。 */ // @GET // @Path("send") public void sendMsg(String timeStamp, String nonce) { String sRespData = "<xml><ToUserName><![CDATA[mycreate]]></ToUserName><FromUserName><![CDATA[wxe49318eb604cf00b]]></FromUserName><CreateTime>1348831860</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[this is a test]]></Content><MsgId>1234567890123456</MsgId><AgentID>1</AgentID></xml>"; try { String sEncryptMsg = wxcpt.EncryptMsg(sRespData, timeStamp, nonce); System.out.println("after encrypt sEncrytMsg: " + sEncryptMsg); response.getWriter().print(sEncryptMsg); } catch (Exception e) { e.printStackTrace();// 加密掉敗 } // return sRespData; } /** * 此辦法可以發送隨意率性類型新聞 * * @param msgType * text|image|voice|video|file|news * @param touser * 成員ID列表(新聞吸收者,多個吸收者用‘|'分隔,最多支撐1000個)。特別情形:指定為@all, * 則向存眷該企業運用的全體成員發送 * @param toparty * 部分ID列表,多個吸收者用‘|'分隔,最多支撐100個。當touser為@all時疏忽本參數 * @param totag * 標簽ID列表,多個吸收者用‘|'分隔。當touser為@all時疏忽本參數 * @param content * msgType=text時 ,文本新聞內容 * @param mediaId * msgType=image|voice|video時 ,對應新聞信息ID(--------) * @param title * msgType=news|video時,新聞題目 * @param description * msgType=news|video時,新聞描寫 * @param url * msgType=news時,新聞鏈接 * @param picurl * msgType=news時,圖片途徑 * @param safe * 表現能否是保密新聞,0表現否,1表現是,默許0 */ public void sendWeChatMsg(String msgType, String touser, String toparty, String totag, String content, String mediaId, String title, String description, String url, String picurl, String safe) { URL uRl; String ACCESS_TOKEN = getAccessToken(); // 拼接要求串 String action = CREATE_SESSION_URL + ACCESS_TOKEN; // 封裝發送新聞要求json StringBuffer sb = new StringBuffer(); sb.append("{"); sb.append("\"touser\":" + "\"" + touser + "\","); sb.append("\"toparty\":" + "\"" + toparty + "\","); sb.append("\"totag\":" + "\"" + totag + "\","); if (msgType.equals("text")) { sb.append("\"msgtype\":" + "\"" + msgType + "\","); sb.append("\"text\":" + "{"); sb.append("\"content\":" + "\"" + content + "\""); sb.append("}"); } else if (msgType.equals("image")) { sb.append("\"msgtype\":" + "\"" + msgType + "\","); sb.append("\"image\":" + "{"); sb.append("\"media_id\":" + "\"" + mediaId + "\""); sb.append("}"); } else if (msgType.equals("voice")) { sb.append("\"msgtype\":" + "\"" + msgType + "\","); sb.append("\"voice\":" + "{"); sb.append("\"media_id\":" + "\"" + mediaId + "\""); sb.append("}"); } else if (msgType.equals("video")) { sb.append("\"msgtype\":" + "\"" + msgType + "\","); sb.append("\"video\":" + "{"); sb.append("\"media_id\":" + "\"" + mediaId + "\","); sb.append("\"title\":" + "\"" + title + "\","); sb.append("\"description\":" + "\"" + description + "\""); sb.append("}"); } else if (msgType.equals("file")) { sb.append("\"msgtype\":" + "\"" + msgType + "\","); sb.append("\"file\":" + "{"); sb.append("\"media_id\":" + "\"" + mediaId + "\""); sb.append("}"); } else if (msgType.equals("news")) { sb.append("\"msgtype\":" + "\"" + msgType + "\","); sb.append("\"news\":" + "{"); sb.append("\"articles\":" + "["); sb.append("{"); sb.append("\"title\":" + "\"" + title + "\","); sb.append("\"description\":" + "\"" + description + "\","); sb.append("\"url\":" + "\"" + url + "\","); sb.append("\"picurl\":" + "\"" + picurl + "\""); sb.append("}"); sb.append("]"); sb.append("}"); } sb.append(",\"safe\":" + "\"" + safe + "\","); sb.append("\"agentid\":" + "\"" + agentId + "\","); sb.append("\"debug\":" + "\"" + "1" + "\""); sb.append("}"); String json = sb.toString(); try { uRl = new URL(action); HttpsURLConnection http = (HttpsURLConnection) uRl.openConnection(); http.setRequestMethod("POST"); http.setRequestProperty("Content-Type", "application/json;charset=UTF-8"); http.setDoOutput(true); http.setDoInput(true); System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// // 銜接超時30秒 System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // // 讀取超時30秒 http.connect(); OutputStream os = http.getOutputStream(); os.write(json.getBytes("UTF-8"));// 傳入參數 InputStream is = http.getInputStream(); int size = is.available(); byte[] jsonBytes = new byte[size]; is.read(jsonBytes); String result = new String(jsonBytes, "UTF-8"); System.out.println("要求前往成果:" + result); os.flush(); os.close(); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { StationResource weChat = new StationResource(); // weChat.sendWeChatMsgText("@all", "2", "", "信息中間告訴", "0"); weChat.sendWeChatMsg("news", "@all", "", "", "測試senMsg", "", "測試的", "真的是測試的", "http://www.百度.com", "http://file27.mafengwo.net/M00/B2/12/wKgB6lO0ahWAMhL8AAV1yBFJDJw20.jpeg", "0"); } }
以上所述是小編給年夜家引見的微信企業號驗證/發送/吸收新聞,願望對年夜家有所贊助,假如年夜家有任何疑問請給我留言,小編會實時答復年夜家的。在此也異常感激年夜家對網站的支撐!