Public Account third-party platform released source code (java) throughout the network-proven in practice, source code java
Source code (java) released by a third-party platform with a public account on the entire network-proven in practice
(For more information, visit the Forum: www.jeecg.org)
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, incluentexception {// LogUtil.info ("third-party platform --------- push Ticke T the message is sent once every 10 minutes --------- "+ 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 Do CumentException */@ RequestMapping (value = "/goAuthor") public void goAuthor (HttpServletRequest request, response) throws IOException, AesException, condition entexception {condition = new condition (); condition. setComponent_appid (COMPONENT_APPID); apiComponentToken. setComponent_appsecret (COMPONENT_APPSECRET); WeixinOpenAccountEntity entity = GetWeixinOpenAccount (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, Export entexception {String msgSignature = request. getParameter ("msg_signature"); // LogUtil.info ("third-party platform released all over the internet ----------- {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"); // test account/if (StringUtils. equalsIgnoreCase (toUserName, APPID) {// LogUtil.info ("Start of access detection message feedback for network-wide publishing ------------- APPID =" + APPID + "------------------------ toUserName =" + toUserName); checkWeixinAl LNetworkCheck (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. get Parameter ("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 ("third-party platform released across the network --------------------- 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 ("third-party platform released all over the internet ------------- appid ---------- getAuthorizerAppidFromXml (xml) ----------- appId =" + appId); WXBizMsgCrypt pc = ne W WXBizMsgCrypt (COMPONENT_TOKEN, encodingAesKey, COMPONENT_APPID); xml = pc. decryptMsg (msgSignature, timestamp, nonce, xml); // LogUtil.info ("published on the third-party platform on 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 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 <WeixinOpenAccountEntity> 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 Void 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, COMP ONENT_APPID); 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 access detection -- step.1 ----------- msgType =" + msgType + "------------- ---- ToUserName = "+ toUserName +" ----------------- fromUserName = "+ fromUserName); // LogUtil.info (" --- publish access detection on the entire 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 into entexception, IOException {String content = event + "from_callback"; // LogUtil.info ("--- All Network publish access detection ------ step.4 ------- event reply message content = "+ content +" toUserName = "+ toUserName +" fromUserName = "+ fromUserName); replyTextMessage (request, response, content, toUserName, fromUserName);} public void processTextMessage (HttpServletRequest request, HttpServletResponse response, String content, String toUserName, String fromUserName) throws IOException, incluentexception {if ("handle ". equa Ls (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, HttpServletRespons E response, String auth_code, String fromUserName) throws into 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 (ent Ity. 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); Sy Stem. 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 <String, Object> obj = new HashMap <String, Object> (); Map <String, Object> msgMap = new HashMap <String, object> (); S Tring msg = auth_code + "_ from_api"; msgMap. put ("content", msg); obj. put ("touser", fromUserName); obj. put ("msgtype", "text"); obj. put ("text", msgMap); implements thirdapi. 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 r Equest * @ param response * @ param content * @ param toUserName * @ param fromUserName * @ throws define entexception * @ throws IOException */public void replyTextMessage (HttpServletRequest request, response, String content, string toUserName, String fromUserName) throws into entexception, IOException {Long createTime = Calendar ar. getInstance (). getTimeInMillis ()/1000; StringBuffer Sb = new StringBuffer (); sb. append ("<xml>"); sb. append ("<ToUserName> <! [CDATA ["+ fromUserName +"]> </ToUserName> "); sb. append (" <FromUserName> <! [CDATA ["+ toUserName +"]> </FromUserName> "); sb. append ("<CreateTime>" + createTime + "</CreateTime>"); sb. append ("<MsgType> <! [CDATA [text]> </MsgType> "); sb. append (" <Content> <! [CDATA ["+ content +"]> </Content> "); sb. append ("</xml>"); 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 ("------------------ returnvaleue:" + returnvaleue);} catch (AesException e) {e. p RintStackTrace ();} output (response, returnvaleue);} public static void main (String [] args) {Long createTime = Calendar ar. getInstance (). getTimeInMillis ()/1000; String replyMsg = "LOCATIONfrom_callback"; String returnvaleue = ""; try {export pc = new partition (COMPONENT_TOKEN, partition, COMPONENT_APPID); returnvaleue = pc. encryptMsg (replyMsg, createTime. toString (), "ea Semob "); 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 (IOEx Ception e) {e. printStackTrace ();}} /*** determine whether to encrypt * @ param token * @ param 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 ();}}
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.