Source code (java) released by a third-party platform with a public account on the entire network-proven in practice
Source code (java) released by a third-party platform with a public account on the entire network-proven in practice
Package org. jeecgframework. web. rest. controller; import java. io. bufferedReader; import java. io. IOException; import java. io. printWriter; import java. security. messageDigest; import java. security. noSuchAlgorithmException; import java. util. arrays; import java. util. calendar; import java. util. date; import java. util. hashMap; import java. util. list; import java. util. map; import javax. servlet. http. httpServletRequest; impo Rt javax. servlet. http. httpServletResponse; import org. apache. commons. lang. stringUtils; import org. dom4j. document; import org. dom4j. extends entexception; import org. dom4j. export enthelper; import org. dom4j. element; import org. jeecgframework. core. util. logUtil; import org. jeecgframework. core. util. resourceUtil; import org. jeecgframework. core. util. oConvertUtils; import org. jeecgframework. web. system. service. systemSer Vice; import org. jeewx. api. core. exception. wexinReqException; import org. jeewx. api. mp. aes. aesException; import org. jeewx. api. mp. aes. WXBizMsgCrypt; import org. jeewx. api. third. export thirdapi; import org. jeewx. api. third. model. apiComponentToken; import org. springframework. beans. factory. annotation. autowired; import org. springframework. stereotype. controller; import org. springframework. web. bind. annotation. requestMapp Ing; import weixin. open. entity. base. weixinOpenAccountEntity;/*** public account third-party platform released source code (java) * @ author: jeewx open source community * @ URL: www.jeewx.com * @ Forum: www.jeecg.org * @ date 20150801 */@ Controller @ RequestMapping (/openwx) public class OpenwxController {private final String APPID = ???; /*** Network-wide test account */private final static String COMPONENT_APPID = ???; Private final String COMPONENT_APPSECRET = ???; Private final static String COMPONENT_ENCODINGAESKEY = ?????; Private final static String COMPONENT_TOKEN = ?????; @ Autowiredprivate SystemService systemService; /*** authorize event receipt ** @ param request * @ param response * @ throws IOException * @ throws AesException * @ throws authorization entexception */@ RequestMapping (value =/event/authorize) public void acceptAuthorizeEvent (HttpServletRequest request, HttpServletResponse response) throws IOException, AesException, entexception {// LogUtil.info (third-party platform --------- push Ticket Message 10 Once every minute --------- + DataUtils. getDataString (DataUtils. yyyymmddhhmmss); processAuthorizeEvent (request); output (response, success); // output the response content.} @ RequestMapping (value =/authorCallback) public void authorCallback (HttpServletRequest request, HttpServletResponse response) throws IOException, AesException, incluentexception {String auth_code = request. getParameter (auth_code); String expires_in = request. getParameter (auth_code);}/*** one-click authorization function * @ param request * @ param response * @ throws IOException * @ throws AesException * @ throws Document Exception */@ RequestMapping (value =/goAuthor) public void goAuthor (HttpServletRequest request, HttpServletResponse response) throws IOException, AesException, entexception {condition = new condition (); condition. setComponent_appid (COMPONENT_APPID); apiComponentToken. setComponent_appsecret (COMPONENT_APPSECRET); WeixinOpenAccountEntity entity = getWe IxinOpenAccount (APPID); apiComponentToken. setComponent_verify_ticket (entity. getTicket (); try {String component_access_token = descrithirdapi. getAccessToken (apiComponentToken); // pre-authorization code String preAuthCode = descrithirdapi. getPreAuthCode (COMPONENT_APPID, component_access_token); String url = https://mp.weixin.qq.com/cgi-bin/componentloginpage? Component_appid = + COMPONENT_APPID + & pre_auth_code = + preAuthCode + & redirect_uri = + ResourceUtil. getConfigByName (domain) +/rest/openwx/authorCallback; response. sendRedirect (url);} catch (WexinReqException e) {e. printStackTrace () ;}@ RequestMapping (value = {appid}/callback) public void acceptMessageAndEvent (HttpServletRequest request, HttpServletResponse response) throws IOException, AesException, DocumentEx Ception {String msgSignature = request. getParameter (msg_signature); // LogUtil.info (third-party platform released ------------- {appid}/callback --------- verification started .... Msg_signature = + msgSignature); if (! StringUtils. isNotBlank (msgSignature) return; // messages pushed to a third-party open platform must be encrypted. Messages cannot be decrypted without message encryption. StringBuilder sb = new StringBuilder (); bufferedReader in = request. getReader (); String line; while (line = in. readLine ())! = Null) {sb. append (line);} in. close (); String xml = sb. toString (); Document doc = incluenthelper. parseText (xml); Element rootElt = doc. getRootElement (); String toUserName = rootElt. elementText (ToUserName); // network-wide test account // if (StringUtils. equalsIgnoreCase (toUserName, APPID) {// LogUtil.info (access detection message feedback is released across the network --------------- APPID = + APPID + ---------------------- toUserName = + toUserName); checkWeixinAllNetwo RkCheck (request, response, xml ); ///}/*** push for processing authorization events ** @ param request * @ throws IOException * @ throws AesException * @ throws define entexception */public void procesthorizeevent (HttpServletRequest request) throws IOException, incluentexception, AesException {String nonce = request. getParameter (nonce); String timestamp = request. getParameter (timestamp); String signature = request. getParameter (Signature); String msgSignature = request. getParameter (msg_signature); if (! StringUtils. isNotBlank (msgSignature) return; // messages pushed to a third-party open platform must be encrypted. Messages cannot be decrypted without message encryption. boolean isValid = checkSignature (COMPONENT_TOKEN, signature, timestamp, nonce); if (isValid) {StringBuilder sb = new StringBuilder (); BufferedReader in = request. getReader (); String line; while (line = in. readLine ())! = Null) {sb. append (line);} String xml = sb. toString (); // LogUtil.info (released on the third-party platform all over the internet --------------------- original Xml = + xml); String encodingAesKey = COMPONENT_ENCODINGAESKEY; // third-party platform component encryption key String appId = getAuthorizerAppidFromXml (xml); // ToUserName In the encrypted xml data is not encrypted at this time, parse xml to get it // LogUtil.info (released on the third-party platform ------------- appid ---------- getAuthorizerAppidFromXml (xml) ----------- appId = + appId); WXBizMsgCrypt pc = new WX BizMsgCrypt (COMPONENT_TOKEN, encodingAesKey, COMPONENT_APPID); xml = pc. decryptMsg (msgSignature, timestamp, nonce, xml); // LogUtil.info (released on the third-party platform all over the internet --------------------- decrypted Xml = + xml); processAuthorizationEvent (xml );}} /*** save Ticket * @ param xml */void processAuthorizationEvent (String xml) {Document doc; try {doc = DocumentHelper. parseText (xml); Element rootElt = doc. getRootElement (); String ticket = RootElt. elementText (ComponentVerifyTicket); if (oConvertUtils. isNotEmpty (ticket) {LogUtil.info (8. Push token protocol --------- ticket = + ticket); WeixinOpenAccountEntity entity = getWeixinOpenAccount (APPID); entity = null? New WeixinOpenAccountEntity (): entity; entity. setTicket (ticket); entity. setAppid (APPID); entity. setGetTicketTime (new Date (); systemService. saveOrUpdate (entity) ;}} catch (incluentexception e) {e. printStackTrace () ;}}/*** obtain authorization account information * @ param appid * @ return */WeixinOpenAccountEntity getWeixinOpenAccount (String appid) {WeixinOpenAccountEntity entity = null; List
Ls = systemService. findByProperty (WeixinOpenAccountEntity. class, appid, appid); if (ls! = Null & ls. size ()! = 0) {entity = ls. get (0);} return entity;}/*** obtain the authorized Appid * @ param xml * @ return */String getAuthorizerAppidFromXml (String xml) {Document doc; try {doc = incluenthelper. parseText (xml); Element rootElt = doc. getRootElement (); String toUserName = rootElt. elementText (ToUserName); return toUserName;} catch (incluentexception e) {// TODO Auto-generated catch blocke. printStackTrace ();} return null;} public v Oid checkWeixinAllNetworkCheck (HttpServletRequest request, HttpServletResponse response, String xml) throws disable entexception, IOException, AesException {String nonce = request. getParameter (nonce); String timestamp = request. getParameter (timestamp); String msgSignature = request. getParameter (msg_signature); WXBizMsgCrypt pc = new WXBizMsgCrypt (COMPONENT_TOKEN, COMPONENT_ENCODINGAESKEY, COMPONENT_AP PID); xml = pc. decryptMsg (msgSignature, timestamp, nonce, xml); Document doc = incluenthelper. parseText (xml); Element rootElt = doc. getRootElement (); String msgType = rootElt. elementText (MsgType); String toUserName = rootElt. elementText (ToUserName); String fromUserName = rootElt. elementText (FromUserName); // LogUtil.info (--- network-wide release access detection -- step.1 ----------- msgType = + msgType + --------------- toUserName = + t OUserName + ----------------- fromUserName = + fromUserName); // LogUtil.info (--- access detection for publishing across the network -- step.2 ----------- xml = + xml); if (event. equals (msgType) {// LogUtil.info (--- network-wide publish access detection -- step.3 ----------- event message --------); String event = rootElt. elementText (Event); replyEventMessage (request, response, event, toUserName, fromUserName);} else if (text. equals (msgType) {// LogUtil.info (--- network-wide publish access detection -- step.3 ----------- text message --------); String content = rootElt. elementText (Content); processTextMessage (request, response, content, toUserName, fromUserName) ;}} public void replyEventMessage (HttpServletRequest request, HttpServletResponse response, String event, String toUserName, String fromUserName) throws merge entexception, IOException {String content = event + from_callback; // LogUtil.info (--- publish access detection all over the network ------ step.4 ------- event reply message cont Ent = + content + toUserName = + toUserName + fromUserName = + fromUserName); replyTextMessage (request, response, content, toUserName, fromUserName);} public void processTextMessage (HttpServletRequest request, response, string content, String toUserName, String fromUserName) throws IOException, incluentexception {if (TESTCOMPONENT_MSG_TYPE_TEXT.equals (content) {String returnContent = content + _ Callback; replyTextMessage (request, response, returnContent, toUserName, fromUserName);} else if (StringUtils. startsWithIgnoreCase (content, QUERY_AUTH_CODE) {output (response,); // The Customer Service API then replies to the Message replyApiTextMessage (request, response, content. split (:) [1], fromUserName) ;}} public void replyApiTextMessage (HttpServletRequest request, HttpServletResponse response, String auth_code, String fromUserName) th Rows authorization entexception, IOException {String authorization_code = auth_code; // after the message is successfully authorized, it should be processed immediately !! The related information will only be pushed to System during the first authorization. out. println (------ step.1 ---- use the customer service message interface to reply to fans ---- logic start -----------------------); try {ApiComponentToken apiComponentToken = new ApiComponentToken (); apiComponentToken. setComponent_appid (COMPONENT_APPID); apiComponentToken. setComponent_appsecret (COMPONENT_APPSECRET); WeixinOpenAccountEntity entity = getWeixinOpenAccount (APPID); apiComponentToken. setComponent_verify_ticket (entity. getTicket (); String component_access_token = descrithirdapi. getAccessToken (apiComponentToken); System. out. println (------ step.2 ---- use the customer service message interface to reply to fans ------- component_access_token = + component_access_token + --------- authorization_code = + authorization_code); net. sf. json. JSONObject authorizationInfoJson = descrithirdapi. getApiQueryAuthInfo (COMPONENT_APPID, authorization_code, component_access_token); System. out. println (------ step.3 ---- use the customer service message interface to reply to fans -------------- get authorizationInfoJson = + authorizationInfoJson); net. sf. json. JSONObject infoJson = authorizationInfoJson. getJSONObject (authorization_info); String authorizer_access_token = infoJson. getString (authorizer_access_token); Map
Obj = new HashMap
(); Map
MsgMap = new HashMap
(); String msg = auth_code + _ from_api; msgMap. put (content, msg); obj. put (touser, fromUserName); obj. put (msgtype, text); obj. put (text, msgMap); descrithirdapi. sendMessage (obj, authorizer_access_token);} catch (WexinReqException e) {e. printStackTrace () ;}/ *** Verify validity * @ param accessTokenExpires * @ return */boolean isExpired (long accessTokenExpires) {return false ;} /*** reply to the server text message * @ param request * @ param response * @ param content * @ param toUserName * @ param fromUserName * @ throws reply entexception * @ throws IOException */public void replyTextMessage (HttpServletRequest request, httpServletResponse response, String content, String toUserName, String fromUserName) throws into entexception, IOException {Long createTime = Calendar. getInstance (). getTimeInMillis ()/1000; StringBuffer sb = new StringBuffer (); sb. append (
); Sb. append (
); Sb. append (
); Sb. append (
+ CreateTime +
); Sb. append (
); Sb. append (
); Sb. append (
); String replyMsg = sb. toString (); String returnvaleue =; try {WXBizMsgCrypt pc = new WXBizMsgCrypt (COMPONENT_TOKEN, COMPONENT_ENCODINGAESKEY, COMPONENT_APPID); returnvaleue = pc. encryptMsg (replyMsg, createTime. toString (), easemob); // System. out. println (------------------ encrypted returned content returnvaleue: + returnvaleue);} catch (AesException e) {e. printStackTrace ();} output (response, returnvaleue);} publ Ic static void main (String [] args) {Long createTime = Calendar. getInstance (). getTimeInMillis ()/1000; String replyMsg = LOCATIONfrom_callback; String returnvaleue =; try {export pc = new WXBizMsgCrypt (COMPONENT_TOKEN, Token, COMPONENT_APPID); returnvaleue = pc. encryptMsg (replyMsg, createTime. toString (), easemob); System. out. println (returnvaleue);} catch (AesException E) {e. printStackTrace () ;}}/*** tool class: reply to server text message * @ param response * @ param returnvaleue */public void output (HttpServletResponse response, String returnvaleue) {try {PrintWriter pw = response. getWriter (); pw. write (returnvaleue); // System. out. println (****************** returnvaleue **************** = + returnvaleue ); pw. flush ();} catch (IOException e) {e. printStackTrace () ;}}/*** determine whether to encrypt * @ param token * @ p Aram signature * @ param timestamp * @ param nonce * @ return */public static boolean checkSignature (String token, String signature, String timestamp, String nonce) {System. out. println (### token: + token +; signature: + signature +; timestamp: + timestamp + nonce: + nonce); boolean flag = false; if (signature! = Null &&! Signature. equals () & timestamp! = Null &&! Timestamp. equals () & nonce! = Null &&! Nonce. equals () {String sha1 =; String [] ss = new String [] {token, timestamp, nonce}; Arrays. sort (ss); for (String s: ss) {sha1 + = s;} sha1 = AddSHA1.SHA1 (sha1); if (sha1.equals (signature) {flag = true ;}} return flag ;}} class AddSHA1 {public static String SHA1 (String inStr) {MessageDigest md = null; String outStr = null; try {md = MessageDigest. getInstance (SHA-1); // select SHA-1 or MD5 byte [] digest = md. digest (inStr. getBytes (); // The returned value is byet []. It is easier to convert it to String for storage outStr = bytetoString (digest);} catch (NoSuchAlgorithmException nsae) {nsae. printStackTrace () ;}return outStr;} public static String bytetoString (byte [] digest) {String str =; String tempStr =; for (int I = 0; I <digest. length; I ++) {tempStr = (Integer. toHexString (digest [I] & 0xff); if (tempStr. length () = 1) {str = str + 0 + tempStr;} else {str = str + tempStr;} return str. toLowerCase ();}}