1. 인트라넷 매핑
WeChat Enterprise 계정 콜백 모드의 URL은 도메인 이름 액세스를 지원하기 때문에 땅콩 쉘을 등록하고 인트라넷 침투를 수행 해야하는 것으로 추정됩니다 (무료 버전을 구매하는 데 16 위안이 소요되며 구매 후 다음날 도메인 이름 만 추가 할 수 있습니다).
2. WeChat Enterprise 계정
WeChat Enterprise 계정 등록 : https://qy.weixin.qq.com/ (팀 선택, 팀은 인증이 필요하지 않음)
연락처 : 새 조직 만들기 -> 회원을 따르십시오
엔터프라이즈 계정 -> 애플리케이션 센터 -> 새 응용 프로그램 -> 메시지 응용 프로그램 -> 모드 선택 (콜백 모드) -> wechat 메시지 전달,
콜백 모드 설명 : 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에 나와 있습니다.
설정 -> 기능 설정 -> 권한 관리 -> 신규 관리 그룹 -> 응용 프로그램 권한 (비밀)
3. Jersey를 사용하여 웹 서비스 서비스를 개발하십시오
3.1 수업에서 토큰 정의, 임의 암호 43 자리, 회사 Corpid, Secret
3.2 검증 방법
/ * * ---------------------------------------------------------------------------------------------------------------------------------------------------------은 엔터프라이즈가 콜백 모드를 켜면 Enterprise 번호는 확인 URL에 GET 요청을 보냅니다. × 탬프 * = 1409659589 & nonce = 263014780 & echostr = p9nazczydtytweshep1vc5x9xho% * 2fqyx3zpb4yka9skld1dsh3iyt3tp3zndtp%2b4rpcs8tgae7oabo%2bfzxvnaqqq%3d 3d * http/1.1 호스트 : qy.weixin.qq.com * *이 요청을받을 때, Enterprise는 * 1. 서명 (msg_signature), timestamp (timestamp), 임의 번호 문자열 (nonce *) 및 공개 플랫폼에 의해 푸시 된 랜덤 암호화 문자열 (echostr). 이 단계에서 URL 디코딩에주의하십시오. 2. 메시지 본문 서명의 정확성을 확인하십시오. 2 단계. 3은 공개 플랫폼에서 제공 한 라이브러리 함수 verifyUrl을 사용하여 구현할 수 있습니다. *// ** * 콜백 URL, weChat은 검증을 위해이 메소드를 호출합니다 * @return */ @get @Path ( "station") public String verify () {String msgsignature = request.getParameter ( "msg_signature"); String timestamp = request.getParameter ( "timestamp"); 문자열 nonce = request.getParameter ( "nonce"); System.out.println (timestamp + "" + nonce); 문자열 echostr = request.getParameter ( "echostr"); 문자열 sechostr = null; try {sechostr = wxcpt.verifyurl (msgsignature, timestamp, nonce, echostr); } catch (예외 e) {e.printstacktrace (); // 확인 URL이 실패했습니다. 오류 이유에 대한 예외를 참조하십시오} return sechostr; }3.3 사용자 정보를 받고 해독합니다
/ * * -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- * <tousername> <! +RTK1I9QCA6AM/WVQNLSV5ZEPEUSUIX5L5X/0LWFRF0QADHHHHHHGD3QCZCDCUPJ911L3VG3W/ * SYYVUJTS3TUUKSUXXACCAS0QHXCHRRYT66WISPGLLYL42AC8DTT * +6k4asknmpj48kzjs8qljvd4xgpue06dodnlxauhzm6 * +kdz +hmzfjyur +ltwgc2hgf5gsijff0ekunxziqatp7pf5mzxz3izoun1s4zg4lumnvw2r * +kqckkiw * +3iqh03v +bca9nmelnqbsf6tiwsrxjb3lavgucallcrw8vt9el4ehzjwrquax5wlvmns0 * +rupa3k22ncxzs9o0mbh27bo6bpnelzps * +/uh9ksnly6bhcmju9p8g7m3fvkn28h3kdya5pl */t8z1ptdave0lxdq2yoyyh2uypighbzzis2pdbs8r07+qn+e7q ==]]> </entiD> <! Enterprise는 게시물 요청을 수신합니다. * 1. * 1. 메시지 본체 서명 (msg_signature), timestamp (timestamp) 및 Random Number String (nonce) * 2를 포함하여 URL의 매개 변수를 구문 분석합니다. 메시지 본문 서명의 정확성을 확인하십시오. * 3. 게시물 요청 된 데이터는 XML에 의해 구문 분석되고 <Encrypt> 태그의 내용을 해독합니다. 해독 된 일반 텍스트는 사용자 답변 메시지의 일반 텍스트입니다. 일반 텍스트 형식의 공식 문서를 참조하십시오.* 공개 플랫폼에서 제공 한 라이브러리 함수 decryptmsg를 사용하여 2 단계와 3 단계를 구현할 수 있습니다. */ @post @pot ( "station") public String inceiveMesg (String reqData) {String msgsignature = request.getParameter ( "msg_signature"); String timestamp = request.getParameter ( "timestamp"); 문자열 nonce = request.getParameter ( "nonce"); // ciphertext 데이터 post // string sreqdata = // "<xml> <tousername> <! ATA [RYPEVHKD8QQKKFHVQ6QLEEB4J58TIPDVO+RTK1I9QCA6AM/WVQNLSV5ZEPEUSUIX5L5X/0LWF RF0QADHHHHGD3QCZCDCUPJ911L3VG3W/SYYVUJTS3TUUKSXACCAS0QHXCHRRYT66WISPGLYL42A m6a8dtt+6k4asknmpj48kzjs8qljvd4xgpue06dodnlxauhzm6+kdz+hmzfjyur+ltwgc2hgf5gs IJFF0EKUNXZIQATP7PF5MZXZ3IZOUN1S4ZG4LUMNVW2R+KQCKIW+3IQH03V+BCA9NMELNQBSF6T IWSRXJB3LAVGUCALLCRW8V2T9EL4EHZJWRQUAX5WLVMNS0+RUPA3K2NCX4XXZS9O0MBH27BO6BP nelzps+/uh9ksnly6bhcmju9p8g7m3fvkn28h3kdya5pl/t8z1ptdave0lxdq2yoyyh2uypighbzzis2pdbs8r07+qn+e7q ==]> </encrypt> <! [cdata [218]]]; try {String smsg = wxcpt.decryptmsg (msgsignature, timestamp, nonce, reqdata); // DocumentBuilDerFactory DBF를 처리하기위한 일반 텍스트 XML 태그의 내용을 구문 분석합니다. DocumentBuilder db = dbf.newDocumentBuilder (); StringReader sr = new StringReader (SMSG); InputSource는 = New InputSource (SR); 문서 문서 = db.parse (IS); 요소 root = document.getDocumentElement (); NODELIST NODELIST1 = root.getElementsByTagName ( "Content"); if (nodelist1.item (0) == null) "OK"를 반환합니다. 문자열 content = nodelist1.item (0) .getTextContent (); System.out.println ( "내용 :" + 컨텐츠); } catch (예외 e) {e.printstacktrace (); // 암호 해독 실패, 실패의 예외를 확인하십시오} return "ok"; }3.4 WeChat에 정보를 보내십시오
설정 -> 함수 설정 -> 권한 관리 -> 새 관리 그룹 생성; 비밀을 얻으십시오
/** *이 방법은 모든 유형의 메시지를 보낼 수 있습니다 * * @param msgtype * 텍스트 | 이미지 | 음성 | 비디오 | 파일 | 뉴스 * @param touser * 회원 ID 목록 (메시지 수신자, 여러 수신자가 '|'로 분리되고 최대 1,000 명이 지원됩니다). 특별 사례 : @all로 지정되며 * @param topy * 부서 ID 목록을 Enterprise 애플리케이션을 따르는 모든 회원에게 보냅니다. 여러 수신자가 '|'로 분리되고 최대 100 개가 지원됩니다. touser가 @all * @param totag * tag id 목록 인 경우이 매개 변수를 무시하십시오. 여러 수신자가 '|'로 분리됩니다. touser가 @all * @param content * 일 때 msgtype = 텍스트, 문자 메시지 내용 * @param mediaid * msgtype = msgtype = im @param picurl * msgtype = 뉴스, 이미지 경로 * @param safe *가 기밀 메시지인지, 0을 나타냅니다. 0을 나타냅니다. 1을 나타냅니다. 1은 yes, default 0 */ public void sendwechatmsg (string msgtype, String touser, String topy, String totag, 문자열 미디어, 문자열 제목, 문자열 설명, string picurl, string url) {url url); 문자열 access_token = getAccessToken (); // 문자열 요청 문자열 문자열 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 ( "음성")) {sb.append ( "/"msgtype/":" + "/" " + msgtype +"/","); sb.append ( "/"음성/":" + "{"); 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 ( "}"); 문자열 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")); // 매개 변수의 PASS inputStream은 = http.getInputStream (); int size = is.available (); 바이트 [] JSONBYTES = 새로운 바이트 [크기]; is.read (jsonbytes); 문자열 결과 = 새 문자열 (JSONBYTES, "UTF-8"); System.out.println ( "요청 반환 결과 :" + 결과); os.flush (); os.close (); } catch (예외 e) {e.printstacktrace (); }} // 인터페이스 액세스 코드 가져 오기 공개 문자열 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), 새로운 namevaluepair ( "corpsecret", Secret)}; // 쿠키 오류가보고되는 것을 방지하기위한 정책 설정 defaulthttpparams.getDefaultParams (). setParameter ( "http.protocol.cookie-policy", cookiepolicy.browser_compatibility); // 사후 포스트 포스트 포스트 포스트에 대한 매개 변수 설정. 문자열 결과 = ""; try {client.executemethod (post); result = new String (post.getResponseBodyAsString (). getBytes ( "gbk")); } catch (ioexception e) {e.printstacktrace (); } // 데이터 변환 JSON jsonObject jasonObject; jasonobject = jsonobject.fromobject (결과); 결과 = (문자열) jasonobject.get ( "access_token"); post.releaseconnection (); System.out.println (결과); 반환 결과; } public static void main (String [] args) {StationResource wechat = new StateResource (); // wechat.sendwechatmsgtext ( "@all", "2", "", "Information Center Notification", "0"); wechat.sendwechatmsg ( "News", "@all", "", "," ","Test Senmsg "," ","테스트 ","실제로 테스트 ","http://www.baidu.com ", "http://file27.mafengwo.net/m00/b2/12/wkgb6lo0ahwamhl8aav1ybfjdjw20.jpeg", "0"); }4. 개발이 완료되었습니다. 이 클래스는 webx.xml에서 휴식을 위해 추가해야합니다.
<!-편안한 지원-> <!-WebSerivce 서비스. 서비스가 추가되면 서비스의 패키지 경로는 Param-value에 추가해야합니다-> <servlet> <servlet-name> jax-rs rest servlet </servlet-name> <servlet-class> com.sun.jersey.spi.container.servlet.servletcontainer </servletconds> <initt-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> </servping> <servlet-mapping> jax-rs rs rest serv </servlet-name> <Url-pattern>/rest/*</url-pattern> </servlet-mapping>
5. 전체 코드가 완료되었습니다
패키지 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; com.qq.weixin.mp.aes.aesexception import; import com.qq.weixin.mp.aes.wxbizmsgcrypt; /** * WeChat Enterprise 계정 개발 * * @Author Zhen.l * */@path ( "wx") 공개 클래스 스테이션 소스 {// http://hichinamobile.xicp.net/security/rest/wx // https://qy.weixin.qqen = "spm"; // 엔터프라이즈 번호-> 응용 프로그램 센터-> 새 응용 프로그램-> 메시지 유형 응용 프로그램 개인 문자열 agentid = "1"; // 엔터프라이즈 번호> 응용 프로그램 센터-> 응용 프로그램을 클릭하십시오-> 응용 프로그램 ID 개인 문자열 encodingAeskey = "nt6zwtvflynxohfoggozwdjpagefsv8ln5cneyw7mwl"; // 엔터프라이즈 번호> 응용 프로그램 센터-> 새 응용 프로그램-> 메시지 유형 응용 프로그램 개인 문자열 corpid = "WXE49318EB604CF00B"; // 엔터프라이즈 번호-> 설정-> 엔터프라이즈 번호 정보-> 계정 정보 개인 문자열 비밀 = "m-yfkmgl_kxbvetginzh3RQWBZ4XB6MFEQXXLK77MKPXZENFDYQ-UGERXDUF8REL"; // 엔터프라이즈 번호-> 설정-> 기능 설정-> 허가 관리 @context httpservletRequest 요청; @context httpservletResponse 응답; wxbizmsgcrypt wxcpt = null; Public StationResource () {try {wxcpt = new Wxbizmsgcrypt (Token, encodingaeskey, corpid); } catch (aesexception e) {e.printstacktrace (); }} // 액세스 코드 가져 오기 URL 개인 정적 문자열 access_token_url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken"; // 세션 요청 생성 URL 개인 정적 문자열 create_session_url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="; // 인터페이스 액세스 코드 공개 문자열 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), 새로운 namevaluepair ( "corpsecret", Secret)}; // 쿠키 오류가보고되는 것을 방지하기위한 정책 설정 defaulthttpparams.getDefaultParams (). setParameter ( "http.protocol.cookie-policy", cookiepolicy.browser_compatibility); // 포스트 포스트 포스트 포스트 포스트에 대한 매개 변수를 설정합니다. 문자열 결과 = ""; try {client.executemethod (post); result = new String (post.getResponseBodyAsString (). getBytes ( "gbk")); } catch (ioexception e) {e.printstacktrace (); } // 데이터 변환 JSON jsonObject jasonObject; jasonobject = jsonobject.fromobject (결과); 결과 = (문자열) jasonobject.get ( "access_token"); post.releaseconnection (); System.out.println (결과); 반환 결과; } / * * ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------은 엔터프라이즈가 콜백 모드를 켜는 기업이 콜백 모드를 켜면 엔터프라이즈 번호는 gET 요청을 확인 URL에 전송합니다. /cgi-bin /wxpush? msg_signature = 5c45ff5e21c57e6ad56bac8758b79b1d9ac89fd3 * × 탬핑 * = 1409659589 & nonce = 263014780 & echostr = p9nazczydtytweshsph1vc5x9xho% 2fqyx3zpb4yka9skld1dsh3iyt3tp3zndtp%2b4rpcs8tgae7oabo%2bfzxvnaqqq%3d 3d * http/1.1 호스트 : qy.weixin.qq.com * *이 요청을받을 때, Enterprise는 * 1. Signature (MSG_Signature), Timestamp (Timestamp) 및 임의 번호 문자열 (Nonce *) 및 임의의 암호화 문자열 (ECHOSTR) 공개 플랫폼에 의해 푸시됩니다. 이 단계에서 URL 디코딩에주의하십시오. 2. 메시지 본문 서명의 정확성을 확인하십시오. 2 단계. 3은 공개 플랫폼에서 제공 한 라이브러리 함수 verifyUrl을 사용하여 구현할 수 있습니다. *// ** * Callback URL, WeChat은 검증을 위해이 메소드를 호출합니다 * * @return */ @get @path ( "station") public string verify () {String msgsignature = request.getParameter ( "msg_signature"); String timestamp = request.getParameter ( "timestamp"); 문자열 nonce = request.getParameter ( "nonce"); System.out.println (timestamp + "" + nonce); 문자열 echostr = request.getParameter ( "echostr"); 문자열 sechostr = null; try {sechostr = wxcpt.verifyurl (msgsignature, timestamp, nonce, echostr); } catch (Exception e) {e.printstacktrace (); // URL이 실패한 경우 오류 이유에 대한 예외를 확인하십시오} return sechostr; } /* * ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- msg_signature = 477715d11cdb4164915debcba66cb864d751f3e6 * × tamp = 1409659813 & nonce = 1372623149 http/1.1 cont : qy.weixin.qq.com * 컨텐츠-613 <xml * <tousername> <! +RTK1I9QCA6AM/WVQNLSV5ZEPEUSUIX5L5X/0LWFRF0QADHHHHHHGD3QCZCDCUPJ911L3VG3W/ * SYYVUJTS3TUUKSUXXACCAS0QHXCHRRYT66WISPGLLYL42AC8DTT * +6k4asknmpj48kzjs8qljvd4xgpue06dodnlxauhzm6 * +kdz +hmzfjyur +ltwgc2hgf5gsijff0ekunxziqatp7pf5mzxz3izoun1s4zg4lumnvw2r * +kqckkiw * +3iqh03v +bca9nmelnqbsf6tiwsrxjb3lavgucallcrw8vt9el4ehzjwrquax5wlvmns0 * +rupa3k22ncxzs9o0mbh27bo6bpnelzps * +/uh9ksnly6bhcmju9p8g7m3fvkn28h3kdya5pl */t8z1ptdave0lxdq2yoyyh2uypighbzzis2pdbs8r07+qn+e7q ==]]> </entiD> <! Enterprise는 게시물 요청을 수신합니다. * 1. * 1. 메시지 본체 서명 (msg_signature), timestamp (timestamp) 및 Random Number String (nonce) * 2를 포함하여 URL의 매개 변수를 구문 분석합니다. 메시지 본문 서명의 정확성을 확인하십시오. * 3. 게시물 요청 된 데이터는 XML에 의해 구문 분석되고 <Encrypt> 태그의 내용을 해독합니다. 해독 된 일반 텍스트는 사용자 답변 메시지의 일반 텍스트입니다. 일반 텍스트 형식의 공식 문서를 참조하십시오.* 공개 플랫폼에서 제공 한 라이브러리 함수 decryptmsg를 사용하여 2 단계와 3 단계를 구현할 수 있습니다. */ @post @pot ( "station") public String inceiveMesg (String reqData) {String msgsignature = request.getParameter ( "msg_signature"); String timestamp = request.getParameter ( "timestamp"); 문자열 nonce = request.getParameter ( "nonce"); // ciphertext 데이터 post // string sreqdata = // "<xml> <tousername> <! ATA [RYPEVHKD8QQKKFHVQ6QLEEB4J58TIPDVO+RTK1I9QCA6AM/WVQNLSV5ZEPEUSUIX5L5X/0LWF RF0QADHHHHGD3QCZCDCUPJ911L3VG3W/SYYVUJTS3TUUKSXACCAS0QHXCHRRYT66WISPGLYL42A m6a8dtt+6k4asknmpj48kzjs8qljvd4xgpue06dodnlxauhzm6+kdz+hmzfjyur+ltwgc2hgf5gs IJFF0EKUNXZIQATP7PF5MZXZ3IZOUN1S4ZG4LUMNVW2R+KQCKIW+3IQH03V+BCA9NMELNQBSF6T IWSRXJB3LAVGUCALLCRW8V2T9EL4EHZJWRQUAX5WLVMNS0+RUPA3K2NCX4XXZS9O0MBH27BO6BP nelzps+/uh9ksnly6bhcmju9p8g7m3fvkn28h3kdya5pl/t8z1ptdave0lxdq2yoyyh2uypighbzzis2pdbs8r07+qn+e7q ==]> </encrypt> <! [cdata [218]]]; try {String smsg = wxcpt.decryptmsg (msgsignature, timestamp, nonce, reqdata); // DocumentBuilDerFactory DBF를 처리하기위한 일반 텍스트 XML 태그의 내용을 구문 분석합니다. DocumentBuilder db = dbf.newDocumentBuilder (); StringReader sr = new StringReader (SMSG); InputSource는 = New InputSource (SR); 문서 문서 = db.parse (IS); 요소 root = document.getDocumentElement (); NODELIST NODELIST1 = root.getElementsByTagName ( "Content"); if (nodelist1.item (0) == null) "OK"를 반환합니다. 문자열 content = nodelist1.item (0) .getTextContent (); System.out.println ( "내용 :" + 컨텐츠); } catch (예외 e) {e.printstacktrace (); // 암호 해독 실패, 실패의 예외를 확인하십시오} return "ok"; } / * * ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 회사가 다음과 같이 사용자의 일반 텍스트에 답장해야한다고 가정 해 봅시다 : <xml> * <tousername> <! <sgtype> <! 메시지 본문 서명을 생성하거나 공개 플랫폼의 우편 * URL에서 구문 분석 된 해당 값을 직접 사용하는 임의의 숫자 문자열 (Nonce). 2. 암호 텍스트를 얻기 위해 일반 텍스트를 암호화합니다. * 3. 1 단계에서 생성 된 암호 텍스트, 타임 스탬프, 공개 플랫폼에서 엔터프라이즈가 설정 한 토큰을 사용하여 메시지 본문 서명을 생성하십시오. * 4. 암호 텍스트, 메시지 본문 서명, 타임 스탬프 및 랜덤 번호 문자열을 XML 형식의 문자열로 스플 라이스하고 엔터프라이즈로 보냅니다. * 위의 2, 3 및 4 단계는 공개 플랫폼에서 제공하는 라이브러리 기능 EncryptMSG를 사용하여 구현할 수 있습니다. */ // @get // @path ( "send") public void sendmsg (String timestamp, String nonce) {String srespdata = "<xml> <tousername> <! username> <createTime> 1348831860 </createTime> <msgtype> <! [cdata [text]]> </msgtype> <content> <! 테스트]]> </content> <sgid> 1234567890123456 </msgid> <entid> 1 </agentid> </xml> "; try {string sencryptmsg = wxcpt.encryptmsg (srespdata, timestamp, nonce); System.out.println ( "Sencrytmsg를 암호화 한 후 :" + sencryptmsg); Response.getWriter (). print (sencryptmsg); } catch (예외 e) {e.printstacktrace (); // 암호화 실패} // srespdata를 반환합니다. } /** *이 방법은 모든 유형의 메시지를 보낼 수 있습니다 * * @param msgtype * 텍스트 | 이미지 | 음성 | 비디오 | 파일 | 뉴스 * @param touser * 회원 ID 목록 (메시지 수신자, 여러 수신자가 '|'로 분리되고 최대 1,000 명이 지원됩니다). 특별 사례 : @all로 지정되며 * @param topy * 부서 ID 목록을 Enterprise 애플리케이션을 따르는 모든 회원에게 보냅니다. 여러 수신자가 '|'로 분리되고 최대 100 개가 지원됩니다. touser가 @all * @param totag * tag id 목록 인 경우이 매개 변수를 무시하십시오. 여러 수신자가 '|'로 분리됩니다. touser가 @all * @param content * 일 때 msgtype = 텍스트, 문자 메시지 내용 * @param mediaid * msgtype = msgtype = im @param picurl * msgtype = 뉴스, 이미지 경로 * @param safe *가 기밀 메시지인지, 0을 나타냅니다. 0을 나타냅니다. 1을 나타냅니다. 1은 yes, default 0 */ public void sendwechatmsg (string msgtype, String touser, String topy, String totag, 문자열 미디어, 문자열 제목, 문자열 설명, string picurl, string url) {url url); 문자열 access_token = getAccessToken (); // 문자열 요청 문자열 문자열 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 ( "음성")) {sb.append ( "/"msgtype/":" + "/" " + msgtype +"/","); sb.append ( "/"음성/":" + "{"); 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 ( "}"); 문자열 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")); // 매개 변수의 PASS inputStream은 = http.getInputStream (); int size = is.available (); 바이트 [] JSONBYTES = 새로운 바이트 [크기]; is.read (jsonbytes); 문자열 결과 = 새 문자열 (JSONBYTES, "UTF-8"); System.out.println ( "요청 반환 결과 :" + 결과); os.flush (); os.close (); } catch (예외 e) {e.printstacktrace (); }} public static void main (String [] args) {StationResource wechat = new StateResource (); // wechat.sendwechatmsgtext ( "@all", "2", "", "Information Center Notification", "0"); wechat.sendwechatmsg ( "News", "@all", "", "", "", "", "Test Senmsg", "", "테스트", "실제 테스트", "http://www.baidu.com", "http://file27.mafengwo.net/m00/b2/12/wkgb6lo0ahwamhl8aav1ybfjdjw20.jpeg", "0"); }}위는 편집자가 귀하에게 소개 한 WeChat Enterprise 계정 확인/보내기/수신 메시지입니다. 나는 그것이 당신에게 도움이되기를 바랍니다. 궁금한 점이 있으면 메시지를 남겨 주시면 편집자가 제 시간에 답장을 드리겠습니다. Wulin.com 웹 사이트를 지원해 주셔서 대단히 감사합니다!