1. Intranet mapping
Since the URL of WeChat enterprise account callback mode supports domain name access, it is estimated that you need to register a peanut shell and do an intranet penetration (it costs 16 yuan to purchase a free version, and you can only add the domain name the next day after you purchase it)
2. WeChat enterprise account
Register a WeChat enterprise account: https://qy.weixin.qq.com/ (Select a team, the team does not require certification)
Contacts: Create a new organization - > Follow members
Enterprise Account -> Application Center -> New Application -> Message Application -> Mode Selection (Callback Mode) -> Turn on WeChat Message Forwarding,
Callback mode description: http://qydev.weixin.qq.com/wiki/index.PHP?title=%E5%9B%9E%E8%B0%83%E6%A8%A1%E5%BC%8F
Callback mode encryption and decryption code: 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
As shown in Figure 1:
Custom menu: The request path for the development application is shown in Figure 2:
Settings -> Function Settings -> Permission Management -> New Management Group -> Application Permissions (Secret)
3. Use Jersey to develop web service services
3.1 Define token in class, random password 43 digits, company corpId, secret
3.2 Verification method
/* * ----------------------------- When the enterprise turns on the callback mode, the enterprise number will send a get request to the verification url* Suppose that when clicking verification, the enterprise receives a similar request: 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 * * When receiving this request, the enterprise should * 1. parse out the parameters of the Get request, including the message body signature (msg_signature), timestamp (timestamp), random number string (nonce *) and the random encrypted string (echostr) pushed by the public platform. Pay attention to URL decoding in this step. 2. Verify the correctness of the message body signature 3. * Decrypt the original echostr text, treat the original text as the response of the Get request, and return it to the public platform. Step 2. 3 can be implemented using the library function VerifyURL provided by the public platform. */ /** * Callback URL, WeChat calls this method for verification* * @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();// Verification URL failed, please see the exception for the error reason} return sEchoStr; }3.3 Receive user information and decrypt it
/* * ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- * <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> * * After the enterprise receives the post request, it should * 1. Parses out the parameters on the url, including the message body signature (msg_signature), timestamp (timestamp) and random number string (nonce) * 2. Verify the correctness of the message body signature. * 3. The post requested data is parsed by XML and decrypt the content of the <Encrypt> tag. The decrypted plain text is the plain text of the user's reply message. Please refer to the official document for the plain text format* Step 2 and 3 can be implemented using the library function DecryptMsg provided by the public platform. */ @POST @Path("station") public String receiveMsg(String reqData) { String msgSignature = request.getParameter("msg_signature"); String timeStamp = request.getParameter("timestamp"); String nonce = request.getParameter("nonce"); // ciphertext data requested by post// String sReqData = // "<xml><ToUserName><![CDATA[wx5823bf96d3bd56c7]]></ToUserName><Encrypt><![CDATA[RypEvHKD8QQKFhvQ6QleEB4J58tiPdvo+rtK1I9qca6aM/wvqnLSV5zEPeusUiX5L5X/0lWf rf0QADHHhGd3QczcdCUpj911L3vg3W/sYYvuJTs3TUUkSUXxaccAS0qhxchrRYt66wiSpGLYL42aM6A8dTT+6k4aSknmPj48kzJs8qLjvd4Xgpue06DOdnLxAUHzM6+kDZ+HMZfJYuR+LtwGc2hgf5gs ijff0ekUNXZiqATP7PF5mZxZ3Izoun1s4zG4LUMnvw2r+KqCKIw+3IQH03v+BCA9nMELNqbSf6tiWSrXJB3LAVGUcallcrw8V2t9EL4EhzJWrQUax5wLVMNS0+rUPA3k22Ncx4XXZS9o0MBH27Bo6Bp NelZpS+/uh9KsNlY6bHCmJU9p8g7m3fVKn28H3KDYA5Pl/T8Z1ptDAVe0lXdQ2YoyyH2uyPIGHBZZIs2pDBS8R07+qN+E7Q==]]></Encrypt><AgentID><![CDATA[218]]></AgentID></xml>"; try { String sMsg = wxcpt.DecryptMsg(msgSignature, timeStamp, nonce, reqData); // parse out the content of the plaintext xml tag for processing 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();// The decryption failed, please check the exception for the failure} return "ok"; }3.4 Send information to WeChat
Settings -> Function Settings -> Permission Management -> Create a new management group; Get secret
/** * This method can send messages of any type* * @param msgType * text|image|voice|video|file|news * @param touser * Member ID list (message recipients, multiple recipients are separated by '|', and up to 1,000 are supported). Special case: specified as @all, * will send * @param topy * department ID list to all members who follow the enterprise application. Multiple recipients are separated by '|', and up to 100 are supported. Ignore this parameter when touser is @all * @param totag * Tag ID list, multiple recipients are separated by '|'. Ignore this parameter when touser is @all* @param content * When msgType=text, text message content* @param mediaId * When msgType=image|voice|video, corresponding message information ID (-------) * @param title * When msgType=news|video, message title* @param description * When msgType=news|video, message description* @param url * When msgType=news, message link* @param picurl * When msgType=news, image path* @param safe * indicates whether it is a confidential message, 0 indicates no, 1 indicates yes, default 0 */ public void sendWeChatMsg(String msgType, String touser, String topy, String totag, String content, String mediaId, String title, String description, String url, String picurl, String safe) { URL uRl; String ACCESS_TOKEN = getAccessToken(); // String request string String action = CREATE_SESSION_URL + ACCESS_TOKEN; // Encapsulate send message request 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");// // Connection timeout 30 seconds System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // // Read timeout 30 seconds http.connect(); OutputStream os = http.getOutputStream(); os.write(json.getBytes("UTF-8")); // Pass in parameter 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("Request returns result:" + result); os.flush(); os.close(); } catch (Exception e) { e.printStackTrace(); } } // Get the interface access code 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) }; // Set policy to prevent cookie errors from being reported DefaultHttpParams.getDefaultParams().setParameter( "http.protocol.cookie-policy", CookiePolicy.BROWSER_COMPATIBILITY); // Set parameters for post post post post post.setRequestBody(param); String result = ""; try { client.executeMethod(post); result = new String(post.getResponseBodyAsString().getBytes("gbk")); } catch (IOException e) { e.printStackTrace(); } // Convert data to 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", "", "Information Center Notification", "0"); weChat.sendWeChatMsg("news", "@all", "", "", "test senMsg", "", "tested", "really tested", "http://www.baidu.com", "http://file27.mafengwo.net/M00/B2/12/wKgB6lO0ahWAMhL8AAV1yBFJDJw20.jpeg", "0"); }4. Development is completed. This class needs to be added to rest in webx.xml to manage
<!-- RESTful support--> <!-- webserivce service. If a service is added, the package path of the service needs to be added to the 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. Full code completed
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.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; /** * WeChat enterprise account development* * @author ZHEN.L * */ @Path("wx") public class StationResource { // http://hichinamobile.xicp.net/security/rest/wx // https://qy.weixin.qq.com private String token = "spm"; // Enterprise number-> Application center-> New application-> Message-type application private String agentId = "1"; // Enterprise number-> Application center-> Click on the application-> Application ID private String encodingAesKey = "nT6ZWTVFlyNXOhFOGGOZWdJpAgeFSV8ln5CNeYw7mwl"; // Enterprise number-> Application center-> New application-> Message-type application private String corpId = "wxe49318eb604cf00b"; // Enterprise number-> Settings-> Enterprise number information-> Account information private String secret = "M-YFKmgl_kXBVEtginZH3RQWbz4xb6MFeQXXLk77mkpxZenFDYq-UgerxdUF8rel"; // Enterprise number-> Settings-> Functional settings-> Permission management @Context HttpServletRequest request; @Context HttpServletResponse response; WXBizMsgCrypt wxcpt = null; public StationResource() { try { wxcpt = new WXBizMsgCrypt(token, encodingAesKey, corpId); } catch (AesException e) { e.printStackTrace(); } } // Get access code URL private final static String ACCESS_TOKEN_URL = "https://qyapi.weixin.qq.com/cgi-bin/gettoken"; // Create a session request URL private final static String CREATE_SESSION_URL = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="; // Get the interface access code 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) }; // Set policy to prevent cookie errors from being reported DefaultHttpParams.getDefaultParams().setParameter( "http.protocol.cookie-policy", CookiePolicy.BROWSER_COMPATIBILITY); // Set parameters for post post post post.setRequestBody(param); String result = ""; try { client.executeMethod(post); result = new String(post.getResponseBodyAsString().getBytes("gbk")); } catch (IOException e) { e.printStackTrace(); } // Convert data to json JSONObject jasonObject; jasonObject = JSONObject.fromObject(result); result = (String) jasonObject.get("access_token"); post.releaseConnection(); System.out.println(result); return result; } /* * --------------------------------- When the enterprise turns on the callback mode, the enterprise number will send a get request to the verification url* Suppose that when clicking verification, the enterprise receives a similar request: 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 * * When receiving this request, the enterprise should * 1. parse out the parameters of the Get request, including the message body signature (msg_signature), timestamp (timestamp), and random number string (nonce * ) and random encrypted strings (echostr) pushed by the public platform. Pay attention to URL decoding in this step. 2. Verify the correctness of the message body signature 3. * Decrypt the original echostr text, treat the original text as the response of the Get request, and return it to the public platform. Step 2. 3 can be implemented using the library function VerifyURL provided by the public platform. */ /** * Callback URL, WeChat calls this method for verification* * @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();// Verify URL failed, please check the exception for the error reason} return sEchoStr; } /* * ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 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> * * After the enterprise receives the post request, it should * 1. Parses out the parameters on the URL, including the message body signature (msg_signature), timestamp (timestamp) and random number string (nonce) * 2. Verify the correctness of the message body signature. * 3. The post requested data is parsed by XML and decrypt the content of the <Encrypt> tag. The decrypted plain text is the plain text of the user's reply message. Please refer to the official document for the plain text format* Step 2 and 3 can be implemented using the library function DecryptMsg provided by the public platform. */ @POST @Path("station") public String receiveMsg(String reqData) { String msgSignature = request.getParameter("msg_signature"); String timeStamp = request.getParameter("timestamp"); String nonce = request.getParameter("nonce"); // ciphertext data requested by post// String sReqData = // "<xml><ToUserName><![CDATA[wx5823bf96d3bd56c7]]></ToUserName><Encrypt><![CDATA[RypEvHKD8QQKFhvQ6QleEB4J58tiPdvo+rtK1I9qca6aM/wvqnLSV5zEPeusUiX5L5X/0lWf rf0QADHHhGd3QczcdCUpj911L3vg3W/sYYvuJTs3TUUkSUXxaccAS0qhxchrRYt66wiSpGLYL42aM6A8dTT+6k4aSknmPj48kzJs8qLjvd4Xgpue06DOdnLxAUHzM6+kDZ+HMZfJYuR+LtwGc2hgf5gs ijff0ekUNXZiqATP7PF5mZxZ3Izoun1s4zG4LUMnvw2r+KqCKIw+3IQH03v+BCA9nMELNqbSf6tiWSrXJB3LAVGUcallcrw8V2t9EL4EhzJWrQUax5wLVMNS0+rUPA3k22Ncx4XXZS9o0MBH27Bo6Bp NelZpS+/uh9KsNlY6bHCmJU9p8g7m3fVKn28H3KDYA5Pl/T8Z1ptDAVe0lXdQ2YoyyH2uyPIGHBZZIs2pDBS8R07+qN+E7Q==]]></Encrypt><AgentID><![CDATA[218]]></AgentID></xml>"; try { String sMsg = wxcpt.DecryptMsg(msgSignature, timeStamp, nonce, reqData); // parse out the content of the plaintext xml tag for processing 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();// The decryption failed, please check the exception for the failure} return "ok"; } /* * -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Suppose the company needs to reply to the user's plain text as follows: <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> * * In order to reply this plain text to the user, the enterprise should: * 1. Generate the time-stamp and a random number string (nonce) to generate the message body signature, or directly use the corresponding value parsed from the post * url of the public platform. 2. Encrypt the plain text to get the cipher text. * 3. Use the cipher text, timestamp, nonce generated in step 1 and token set by the enterprise on the public platform to generate message body signatures. * 4. Splice the ciphertext, message body signature, timestamp, and random number string into a string in XML format and send it to the enterprise. * The above 2, 3, and 4 steps can be implemented using the library function EncryptMsg provided by the public platform. */ // @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();// Encryption failed} // return sRespData; } /** * This method can send any type of messages* * @param msgType * text|image|voice|video|file|news * @param touser * Member ID list (message recipients, multiple recipients are separated by '|', and up to 1,000 are supported). Special case: specified as @all, * will send * @param topy * department ID list to all members who follow the enterprise application. Multiple recipients are separated by '|', and up to 100 are supported. Ignore this parameter when touser is @all * @param totag * Tag ID list, multiple recipients are separated by '|'. Ignore this parameter when touser is @all* @param content * When msgType=text, text message content* @param mediaId * When msgType=image|voice|video, corresponding message information ID (-------) * @param title * When msgType=news|video, message title* @param description * When msgType=news|video, message description* @param url * When msgType=news, message link* @param picurl * When msgType=news, image path* @param safe * indicates whether it is a confidential message, 0 indicates no, 1 indicates yes, default 0 */ public void sendWeChatMsg(String msgType, String touser, String topy, String totag, String content, String mediaId, String title, String description, String url, String picurl, String safe) { URL uRl; String ACCESS_TOKEN = getAccessToken(); // String request string String action = CREATE_SESSION_URL + ACCESS_TOKEN; // Encapsulate send message request 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");// // Connection timeout 30 seconds System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // // Read timeout 30 seconds http.connect(); OutputStream os = http.getOutputStream(); os.write(json.getBytes("UTF-8")); // Pass in parameter 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("Request returns result:" + result); os.flush(); os.close(); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { StationResource weChat = new StationResource(); // weChat.sendWeChatMsgText("@all", "2", "", "Information Center Notification", "0"); weChat.sendWeChatMsg("news", "@all", "", "", "", "test senMsg", "", "tested", "really tested", "http://www.baidu.com", "http://file27.mafengwo.net/M00/B2/12/wKgB6lO0ahWAMhL8AAV1yBFJDJw20.jpeg", "0"); } }The above is the WeChat enterprise account verification/send/receive messages introduced to you by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support to Wulin.com website!