小弟初次写,写的不好,大神多多关照

总共分为两部分:

1.授权,微信每10分钟会给第三方平台推送一次,这里有需要用到的 COMPONENT_VERIFY_TICKET,并且需要响应 success。

请求的内容(通过request.getParameter()可以取到):

msg_signature、signature、timestamp、nonce

请求内容主体(通过流的方式可以读取):

<xml>    <AppId><![CDATA[wxde4c1]]></AppId>    <Encrypt><![CDATA[AjNYHkpxXdv99o/AV0HyklxjMFtPpRlP1VGKiAm92dyUusRZ8tpuzxBocKxtOFV04NABs7vchuRM2sBTjvb8emGMRDmhHGkMeb9933Usl8eOcFo60yj32BnxkxrmRUx8BeNRtAu98qfE72kfsUsbTyZE9FHp2xNjM75KEq8jh29eK/Rt6GVadzz9DO+qSEu+XRB0A3m5CzQ6nYDyTwDz7w01kKhx9PBHFBvnkh3p4bWV3ATNPR5+xm5/z0p8O6VGMeWkhv7XjGgk3WPcHYRtZMn/CZB2aKuxsosl3MCr1OADLLSJ+J4vGNdShMxLmUSJKR7E8SANFZUOiKOMFPmh62x3sJu4PXaLX15kzfT8DB1A3BW6g/ErEE9n+c3N4MIUW/ac/5sKeG7IjsJOgH3tfJfG4qSYuOyBKbqFyWqaZWxW/L+M=]]></Encrypt></xml>

需要注意的是,并不是整个xml都加密,只是加密了<Encrypt></Encrypt>

解密后可以得到新的xml:

<xml><AppId><![CDATA[wxde71bfe4c1]]></AppId>
<CreateTime>1558420435</CreateTime>
<InfoType><![CDATA[componencket]]></InfoType>
<ComponentVerifyTicket><![CDATA[ticket@@@DVkcsSTOEjZIwpJe5Wzwx9eZM1eZVQnzi2Y3KrorUL8vg]]></ComponentVerifyTicket>
</xml>

其中<ComponentVerifyTicket>是我们需要的ticket(建议缓存起来),需要注意的是ticket@@@需要接去掉。

2.文本消息和事件消息

文本消息分为两种:a.固定内容  b.不响应,使用客服消息

代码:

@RestController
@RequestMapping("/wx")
public class WxController {/*** 微信全网测试账号*/private final static String COMPONENT_APPID = "";//第三方平台APPIDprivate final String COMPONENT_APPSECRET = "";//第三方平台APPSECRETprivate final static String COMPONENT_ENCODINGAESKEY = "";//消息加解密Keyprivate final static String COMPONENT_TOKEN = "";//消息校验Token/*** 消息和事件* 消息与事件接收URL   http://xxxxxxx/nrm/wx/$APPID$/callback* @throws IOException*/@RequestMapping("/{appid}/callback")public void acceptMessageAndEvent(HttpServletRequest request, HttpServletResponse response) throws DocumentException, IOException, AesException {System.out.println("--------------------------------微信公众号第三方平台全网发布---------------------------------------");System.out.println("--------------------------------普通消息和事件消息--------------------------------");System.out.println("--------------------------------验证 msg_signature--------------------------------");String msgSignature = request.getParameter("msg_signature");System.out.println("msg_signature=" + msgSignature);if (!StringUtils.isNotBlank(msgSignature))return;// 微信推送给第三方开放平台的消息一定是加过密的,无消息加密无法解密消息StringBuilder sb = new StringBuilder();BufferedReader in = request.getReader();String line;while ((line = in.readLine()) != null) {sb.append(line);}in.close();String xml = sb.toString();System.out.println("--------------------------------接收到请求内容(加密)--------------------------------");System.out.println("--------------------------------原始 xml=" + xml);checkWeixinAllNetworkCheck(request,response,xml);}public void checkWeixinAllNetworkCheck(HttpServletRequest request, HttpServletResponse response,String xml) throws DocumentException, 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_APPID);xml = pc.decryptMsg(msgSignature, timestamp, nonce, xml);System.out.println("--------------------------------解密  xml=" + xml);Document doc = DocumentHelper.parseText(xml);Element rootElt = doc.getRootElement();String msgType = rootElt.elementText("MsgType");String toUserName = rootElt.elementText("ToUserName");String fromUserName = rootElt.elementText("FromUserName");if("event".equals(msgType)){String event = rootElt.elementText("Event");replyEventMessage(request,response,event,toUserName,fromUserName);}else if("text".equals(msgType)){String content = rootElt.elementText("Content");processTextMessage(request,response,content,toUserName,fromUserName);}}/*** 文本消息处理* @param request       请求* @param response      响应* @param content       消息内容* @param toUserName    微信公众号* @param fromUserName  微信粉丝* @throws IOException* @throws DocumentException*/public void processTextMessage(HttpServletRequest request, HttpServletResponse response,String content,String toUserName, String fromUserName) throws IOException, DocumentException{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, "");//接下来客服API再回复一次消息replyApiTextMessage(request,response,content.split(":")[1],fromUserName);}}/*** 回复事件消息* @param request* @param response* @param event* @param toUserName* @param fromUserName* @throws DocumentException* @throws IOException*/public void replyEventMessage(HttpServletRequest request, HttpServletResponse response, String event, String toUserName, String fromUserName) throws DocumentException, IOException {System.out.println("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&回复事件消息&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&");String content = event + "from_callback";replyTextMessage(request,response,content,toUserName,fromUserName);}/*** 回复微信服务器"文本消息"* @param request           请求* @param response          响应* @param content           内容* @param toUserName        微信公众号* @param fromUserName      微信粉丝* @throws DocumentException* @throws IOException*/public void replyTextMessage(HttpServletRequest request, HttpServletResponse response, String content, String toUserName, String fromUserName) throws DocumentException, IOException {System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!回复微信的文本消息!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");Long createTime = System.currentTimeMillis();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");} catch (AesException e) {e.printStackTrace();}output(response, returnvaleue);}/*** 发送客服消息* @param auth_code     授权码* @param fromUserName* @throws DocumentException* @throws IOException*/public void replyApiTextMessage(HttpServletRequest request, HttpServletResponse response, String auth_code, String fromUserName) throws DocumentException, IOException {System.out.println("##############################################发送客服消息##############################################");CloseableHttpClient client = null;CloseableHttpResponse response1 = null;try {RedisUtil redisUtil = SpringUtil.getBean(RedisUtil.class);String authorizer_access_token = (String) redisUtil.get("so_release_access_token");if(authorizer_access_token == null || "".equals(authorizer_access_token))authorizer_access_token = getAuthorizerAccessToken(auth_code);System.out.println("##################################access_token#################################" + authorizer_access_token);String param = "{\"touser\":\"" + fromUserName + "\",\"msgtype\":\"text\",\"text\":{\"content\":\"" + auth_code + "_from_api\"}}";System.out.println("###################################请求主体#####################################" + param);HttpPost post = new HttpPost("https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + authorizer_access_token);post.setHeader("Content-Type","application/json");post.setEntity(new StringEntity(param));client = HttpClients.createDefault();response1 = client.execute(post);if(response1 != null && response1.getEntity() != null){String result = EntityUtils.toString(response1.getEntity(), "UTF-8");System.out.println("###############################发送客服消息响应结果:" + result);}} catch (Exception e) {e.printStackTrace();} finally {if(response1 != null){response1.close();}if(client != null){client.close();}}}//---------------------------------------------------------------以上是文本消息、普通消息和事件消息----------------------------------------------------------------------------------/*** 授权,获取component_verify_ticket* 此请求的连接需要和微信公众号第三方平台,开发资料,授权事件接收URL保持一致,可以获取到  COMPONENT_VERIFY_TICKET* 需要响应给微信success* 授权事件接收URL: http://xxxxxxxx/nrm/wx/authorization*/@RequestMapping("/authorization")public void authorization(HttpServletRequest request, HttpServletResponse response) throws IOException, DocumentException, AesException {System.out.println("********************************微信第三方平台  授权推送事件********************************");processAuthorizeEvent(request);output(response, "success");}/*** 处理授权事件的推送*/public void processAuthorizeEvent(HttpServletRequest request) throws IOException, DocumentException, 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;// 微信推送给第三方开放平台的消息一定是加过密的,无消息加密无法解密消息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();System.out.println("********************************解密前 xml=" + xml);WXBizMsgCrypt pc = new WXBizMsgCrypt(COMPONENT_TOKEN, COMPONENT_ENCODINGAESKEY, COMPONENT_APPID);Map<String, String> requestMap = XmlUtil.xmlToMap(xml);xml = pc.decrypt(requestMap.get("Encrypt"));System.out.println("********************************解密后 xml=" + xml);processAuthorizationEvent(xml);}}/*** 获取第三方平台component_access_token* 根据component_appid、component_appsecret(即在微信开放平台管理中心的第三方平台详情页中appId和appsecret)* 和component_verify_ticket来获取自己的接口调用凭证(component_access_token)* component_access_token 有效期2小时* @return*/String getAccessToken(){CloseableHttpClient client = null;CloseableHttpResponse response = null;try{RedisUtil redisUtil = SpringUtil.getBean(RedisUtil.class);String param = "{\"component_appid\":\"" + COMPONENT_APPID + "\",\"component_appsecret\":\"" + COMPONENT_APPSECRET + "\",\"component_verify_ticket\":\"" + (String)redisUtil.get("component_verify_ticket") + "\"}";HttpPost post = new HttpPost("https://api.weixin.qq.com/cgi-bin/component/api_component_token");post.setHeader("Content-Type","application/json");post.setEntity(new StringEntity(param));client = HttpClients.createDefault();response = client.execute(post);if(response != null && response.getEntity() != null){JSONObject result = JSONObject.parseObject(EntityUtils.toString(response.getEntity(), "UTF-8"));return result.getString("component_access_token");}} catch (Exception e){e.printStackTrace();} finally {if(response != null){try {response.close();} catch (IOException e) {e.printStackTrace();}}if(client != null){try {client.close();} catch (IOException e) {e.printStackTrace();}}}return null;}/*** 获取预授权码pre_auth_code* @return*/String getPreAuthCode(){CloseableHttpClient client = null;CloseableHttpResponse response = null;try{String component_access_token = getAccessToken();if(Strings.isNotEmpty(component_access_token)) {String parame = "{\"component_appid\":\"" + COMPONENT_APPID + "\"}";HttpPost post = new HttpPost("https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token=" + component_access_token);post.setHeader("Content-Type", "application/json");post.setEntity(new StringEntity(parame));client = HttpClients.createDefault();response = client.execute(post);if(response != null && response.getEntity() != null){JSONObject result = JSONObject.parseObject(EntityUtils.toString(response.getEntity(), "UTF-8"));return result.getString("pre_auth_code");}}else{System.out.println("获取 component_access_token 异常");}} catch (Exception e){e.printStackTrace();} finally {if(response != null){try {response.close();} catch (IOException e) {e.printStackTrace();}}if(client != null){try {client.close();} catch (IOException e) {e.printStackTrace();}}}return null;}/*** 使用授权码换取公众号的授权信息* @return  授权方令牌(在授权的公众号具备API权限时,才有此返回值)*/public String getAuthorizerAccessToken(String auth_code){CloseableHttpClient client = null;CloseableHttpResponse response = null;try {String component_access_token = getAccessToken();//使用授权码换取公众号的授权信息String data = "{\"component_appid\":\"" + COMPONENT_APPID + "\",\"authorization_code\":\"" + auth_code + "\"}";HttpPost post = new HttpPost("https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token=" + component_access_token);post.setHeader("Content-Type","application/json");post.setEntity(new StringEntity(data));client = HttpClients.createDefault();response = client.execute(post);if(response != null && response.getEntity() != null){//响应信息/*{"authorization_info": {"authorizer_appid": "wxf8b4f85f3a794e77","authorizer_access_token": "QXjUqNqfYVH0yBE1iI_7vuN_9gQbpjfK7hYwJ3P7xOa88a89-Aga5x1NMYJyB8G2yKt1KCl0nPC3W9GJzw0Zzq_dBxc8pxIGUNi_bFes0qM","expires_in": 7200,"authorizer_refresh_token": "dTo-YCXPL4llX-u1W1pPpnp8Hgm4wpJtlR6iV0doKdY","func_info": [{"funcscope_category": {"id": 1}},{"funcscope_category": {"id": 2}},{"funcscope_category": {"id": 3}}]}}*/JSONObject result = JSONObject.parseObject(EntityUtils.toString(response.getEntity(), "UTF-8"));JSONObject authorization_info = result.getJSONObject("authorization_info");String so_release_access_token = authorization_info.getString("authorizer_access_token");//授权access_tokenLong expires_in = authorization_info.getLong("expires_in");//有效期RedisUtil redisUtil = SpringUtil.getBean(RedisUtil.class);redisUtil.set("so_release_access_token", so_release_access_token, expires_in);return so_release_access_token;}} catch (Exception e){e.printStackTrace();} finally {if(response != null){try {response.close();} catch (IOException e) {e.printStackTrace();}}if(client != null){try {client.close();} catch (IOException e) {e.printStackTrace();}}}return null;}/*** 获取授权的Appid*/String getAuthorizerAppidFromXml(String xml) {Document doc;try {doc = DocumentHelper.parseText(xml);Element rootElt = doc.getRootElement();String toUserName = rootElt.elementText("ToUserName");return toUserName;} catch (DocumentException e) {e.printStackTrace();}return null;}//----------------------------------------------------------------以上是微信公众号全网发布检测授权----------------------------------------------------------------------------/*** 保存Ticket*/public void processAuthorizationEvent(String xml){Document doc;try {doc = DocumentHelper.parseText(xml);Element rootElt = doc.getRootElement();String ticket = rootElt.elementText("ComponentVerifyTicket");System.out.println("*****************************************ticket=" + ticket);if(ticket != null && !"".equals(ticket)) {RedisUtil redisUtil = SpringUtil.getBean(RedisUtil.class);redisUtil.set("component_verify_ticket", ticket.substring(ticket.indexOf("@@@") + 3));}} catch (DocumentException e) {e.printStackTrace();}}/*** 判断是否加密*/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;}/*** 工具类:回复微信服务器"文本消息"*/public void output(HttpServletResponse response,String returnvaleue){try {PrintWriter pw = response.getWriter();pw.write(returnvaleue);pw.flush();} catch (IOException e) {e.printStackTrace();}}//-------------------------------------------------------------------以上是通用工具方法---------------------------------------------------------------------------------------
}

加密解密(此部分是我从微信官网下载,修改了其中一个解密的作用域):

package jc.wx.networkreleasemonitoring.networkreleasemonitoring.utils;
/*** 对公众平台发送给公众账号的消息加解密示例代码.** @copyright Copyright (c) 1998-2014 Tencent Inc.*/// ------------------------------------------------------------------------/*** 针对org.apache.commons.codec.binary.Base64,* 需要导入架包commons-codec-1.9(或commons-codec-1.8等其他版本)* 官方下载地址:http://commons.apache.org/proper/commons-codec/download_codec.cgi*/import java.io.StringReader;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;import org.apache.commons.codec.binary.Base64;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;/*** 提供接收和推送给公众平台消息的加解密接口(UTF8编码的字符串).* <ol>*  <li>第三方回复加密消息给公众平台</li>*    <li>第三方收到公众平台发送的消息,验证消息的安全性,并对消息进行解密。</li>* </ol>* 说明:异常java.security.InvalidKeyException:illegal Key Size的解决方案* <ol>*     <li>在官方网站下载JCE无限制权限策略文件(JDK7的下载地址:*      http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html</li>*     <li>下载后解压,可以看到local_policy.jar和US_export_policy.jar以及readme.txt</li>*    <li>如果安装了JRE,将两个jar文件放到%JRE_HOME%\lib\security目录下覆盖原来的文件</li>*   <li>如果安装了JDK,将两个jar文件放到%JDK_HOME%\jre\lib\security目录下覆盖原来文件</li>* </ol>*/
public class WXBizMsgCrypt {static Charset CHARSET = Charset.forName("utf-8");Base64 base64 = new Base64();byte[] aesKey;String token;String appId;/*** 构造函数* @param token 公众平台上,开发者设置的token* @param encodingAesKey 公众平台上,开发者设置的EncodingAESKey* @param appId 公众平台appid** @throws AesException 执行失败,请查看该异常的错误码和具体的错误信息*/public WXBizMsgCrypt(String token, String encodingAesKey, String appId) throws AesException {if (encodingAesKey.length() != 43) {throw new AesException(AesException.IllegalAesKey);}this.token = token;this.appId = appId;aesKey = Base64.decodeBase64(encodingAesKey + "=");}// 生成4个字节的网络字节序byte[] getNetworkBytesOrder(int sourceNumber) {byte[] orderBytes = new byte[4];orderBytes[3] = (byte) (sourceNumber & 0xFF);orderBytes[2] = (byte) (sourceNumber >> 8 & 0xFF);orderBytes[1] = (byte) (sourceNumber >> 16 & 0xFF);orderBytes[0] = (byte) (sourceNumber >> 24 & 0xFF);return orderBytes;}// 还原4个字节的网络字节序int recoverNetworkBytesOrder(byte[] orderBytes) {int sourceNumber = 0;for (int i = 0; i < 4; i++) {sourceNumber <<= 8;sourceNumber |= orderBytes[i] & 0xff;}return sourceNumber;}// 随机生成16位字符串String getRandomStr() {String base = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";Random random = new Random();StringBuffer sb = new StringBuffer();for (int i = 0; i < 16; i++) {int number = random.nextInt(base.length());sb.append(base.charAt(number));}return sb.toString();}/*** 对明文进行加密.** @param text 需要加密的明文* @return 加密后base64编码的字符串* @throws AesException aes加密失败*/String encrypt(String randomStr, String text) throws AesException {ByteGroup byteCollector = new ByteGroup();byte[] randomStrBytes = randomStr.getBytes(CHARSET);byte[] textBytes = text.getBytes(CHARSET);byte[] networkBytesOrder = getNetworkBytesOrder(textBytes.length);byte[] appidBytes = appId.getBytes(CHARSET);// randomStr + networkBytesOrder + text + appidbyteCollector.addBytes(randomStrBytes);byteCollector.addBytes(networkBytesOrder);byteCollector.addBytes(textBytes);byteCollector.addBytes(appidBytes);// ... + pad: 使用自定义的填充方式对明文进行补位填充byte[] padBytes = PKCS7Encoder.encode(byteCollector.size());byteCollector.addBytes(padBytes);// 获得最终的字节流, 未加密byte[] unencrypted = byteCollector.toBytes();try {// 设置加密模式为AES的CBC模式Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");SecretKeySpec keySpec = new SecretKeySpec(aesKey, "AES");IvParameterSpec iv = new IvParameterSpec(aesKey, 0, 16);cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv);// 加密byte[] encrypted = cipher.doFinal(unencrypted);// 使用BASE64对加密后的字符串进行编码String base64Encrypted = base64.encodeToString(encrypted);return base64Encrypted;} catch (Exception e) {e.printStackTrace();throw new AesException(AesException.EncryptAESError);}}/*** 对密文进行解密.** @param text 需要解密的密文* @return 解密得到的明文* @throws AesException aes解密失败*/public String decrypt(String text) throws AesException {byte[] original;try {// 设置解密模式为AES的CBC模式Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");SecretKeySpec key_spec = new SecretKeySpec(aesKey, "AES");IvParameterSpec iv = new IvParameterSpec(Arrays.copyOfRange(aesKey, 0, 16));cipher.init(Cipher.DECRYPT_MODE, key_spec, iv);// 使用BASE64对密文进行解码byte[] encrypted = Base64.decodeBase64(text);// 解密original = cipher.doFinal(encrypted);} catch (Exception e) {e.printStackTrace();throw new AesException(AesException.DecryptAESError);}String xmlContent, from_appid;try {// 去除补位字符byte[] bytes = PKCS7Encoder.decode(original);// 分离16位随机字符串,网络字节序和AppIdbyte[] networkOrder = Arrays.copyOfRange(bytes, 16, 20);int xmlLength = recoverNetworkBytesOrder(networkOrder);xmlContent = new String(Arrays.copyOfRange(bytes, 20, 20 + xmlLength), CHARSET);from_appid = new String(Arrays.copyOfRange(bytes, 20 + xmlLength, bytes.length),CHARSET);} catch (Exception e) {e.printStackTrace();throw new AesException(AesException.IllegalBuffer);}// appid不相同的情况if (!from_appid.equals(appId)) {throw new AesException(AesException.ValidateAppidError);}return xmlContent;}/*** 将公众平台回复用户的消息加密打包.* <ol>*    <li>对要发送的消息进行AES-CBC加密</li>*    <li>生成安全签名</li>*    <li>将消息密文和安全签名打包成xml格式</li>* </ol>** @param replyMsg 公众平台待回复用户的消息,xml格式的字符串* @param timeStamp 时间戳,可以自己生成,也可以用URL参数的timestamp* @param nonce 随机串,可以自己生成,也可以用URL参数的nonce** @return 加密后的可以直接回复用户的密文,包括msg_signature, timestamp, nonce, encrypt的xml格式的字符串* @throws AesException 执行失败,请查看该异常的错误码和具体的错误信息*/public String encryptMsg(String replyMsg, String timeStamp, String nonce) throws AesException {// 加密String encrypt = encrypt(getRandomStr(), replyMsg);// 生成安全签名if (timeStamp == "") {timeStamp = Long.toString(System.currentTimeMillis());}String signature = SHA1.getSHA1(token, timeStamp, nonce, encrypt);// System.out.println("发送给平台的签名是: " + signature[1].toString());// 生成发送的xmlString result = XMLParse.generate(encrypt, signature, timeStamp, nonce);return result;}/*** 检验消息的真实性,并且获取解密后的明文.* <ol>*    <li>利用收到的密文生成安全签名,进行签名验证</li>*   <li>若验证通过,则提取xml中的加密消息</li>*     <li>对消息进行解密</li>* </ol>** @param msgSignature 签名串,对应URL参数的msg_signature* @param timeStamp 时间戳,对应URL参数的timestamp* @param nonce 随机串,对应URL参数的nonce* @param postData 密文,对应POST请求的数据** @return 解密后的原文* @throws AesException 执行失败,请查看该异常的错误码和具体的错误信息*/public String decryptMsg(String msgSignature, String timeStamp, String nonce, String postData)throws AesException {// 密钥,公众账号的app secret// 提取密文Object[] encrypt = XMLParse.extract(postData);// 验证安全签名String signature = SHA1.getSHA1(token, timeStamp, nonce, encrypt[1].toString());// 和URL中的签名比较是否相等// System.out.println("第三方收到URL中的签名:" + msg_sign);// System.out.println("第三方校验签名:" + signature);if (!signature.equals(msgSignature)) {throw new AesException(AesException.ValidateSignatureError);}// 解密String result = decrypt(encrypt[1].toString());return result;}/*** 验证URL* @param msgSignature 签名串,对应URL参数的msg_signature* @param timeStamp 时间戳,对应URL参数的timestamp* @param nonce 随机串,对应URL参数的nonce* @param echoStr 随机串,对应URL参数的echostr** @return 解密之后的echostr* @throws AesException 执行失败,请查看该异常的错误码和具体的错误信息*/public String verifyUrl(String msgSignature, String timeStamp, String nonce, String echoStr)throws AesException {String signature = SHA1.getSHA1(token, timeStamp, nonce, echoStr);if (!signature.equals(msgSignature)) {throw new AesException(AesException.ValidateSignatureError);}String result = decrypt(echoStr);return result;}}class ByteGroup {ArrayList<Byte> byteContainer = new ArrayList<Byte>();public byte[] toBytes() {byte[] bytes = new byte[byteContainer.size()];for (int i = 0; i < byteContainer.size(); i++) {bytes[i] = byteContainer.get(i);}return bytes;}public ByteGroup addBytes(byte[] bytes) {for (byte b : bytes) {byteContainer.add(b);}return this;}public int size() {return byteContainer.size();}
}/*** SHA1 class** 计算公众平台的消息签名接口.*/
class SHA1 {/*** 用SHA1算法生成安全签名* @param token 票据* @param timestamp 时间戳* @param nonce 随机字符串* @param encrypt 密文* @return 安全签名* @throws AesException*/public static String getSHA1(String token, String timestamp, String nonce, String encrypt) throws AesException{try {String[] array = new String[] { token, timestamp, nonce, encrypt };StringBuffer sb = new StringBuffer();// 字符串排序Arrays.sort(array);for (int i = 0; i < 4; i++) {sb.append(array[i]);}String str = sb.toString();// SHA1签名生成MessageDigest md = MessageDigest.getInstance("SHA-1");md.update(str.getBytes());byte[] digest = md.digest();StringBuffer hexstr = new StringBuffer();String shaHex = "";for (int i = 0; i < digest.length; i++) {shaHex = Integer.toHexString(digest[i] & 0xFF);if (shaHex.length() < 2) {hexstr.append(0);}hexstr.append(shaHex);}return hexstr.toString();} catch (Exception e) {e.printStackTrace();throw new AesException(AesException.ComputeSignatureError);}}
}/*** XMLParse class** 提供提取消息格式中的密文及生成回复消息格式的接口.*/
class XMLParse {/*** 提取出xml数据包中的加密消息* @param xmltext 待提取的xml字符串* @return 提取出的加密消息字符串* @throws AesException*/public static Object[] extract(String xmltext) throws AesException     {Object[] result = new Object[3];try {DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();dbf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);dbf.setFeature("http://xml.org/sax/features/external-general-entities", false);dbf.setFeature("http://xml.org/sax/features/external-parameter-entities", false);dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);dbf.setXIncludeAware(false);dbf.setExpandEntityReferences(false);DocumentBuilder db = dbf.newDocumentBuilder();StringReader sr = new StringReader(xmltext);InputSource is = new InputSource(sr);Document document = db.parse(is);Element root = document.getDocumentElement();NodeList nodelist1 = root.getElementsByTagName("Encrypt");NodeList nodelist2 = root.getElementsByTagName("ToUserName");result[0] = 0;result[1] = nodelist1.item(0).getTextContent();result[2] = nodelist2.item(0).getTextContent();return result;} catch (Exception e) {e.printStackTrace();throw new AesException(AesException.ParseXmlError);}}/*** 生成xml消息* @param encrypt 加密后的消息密文* @param signature 安全签名* @param timestamp 时间戳* @param nonce 随机字符串* @return 生成的xml字符串*/public static String generate(String encrypt, String signature, String timestamp, String nonce) {String format = "<xml>\n" + "<Encrypt><![CDATA[%1$s]]></Encrypt>\n"+ "<MsgSignature><![CDATA[%2$s]]></MsgSignature>\n"+ "<TimeStamp>%3$s</TimeStamp>\n" + "<Nonce><![CDATA[%4$s]]></Nonce>\n" + "</xml>";return String.format(format, encrypt, signature, timestamp, nonce);}
}/*** 提供基于PKCS7算法的加解密接口.*/
class PKCS7Encoder {static Charset CHARSET = Charset.forName("utf-8");static int BLOCK_SIZE = 32;/*** 获得对明文进行补位填充的字节.** @param count 需要进行填充补位操作的明文字节个数* @return 补齐用的字节数组*/static byte[] encode(int count) {// 计算需要填充的位数int amountToPad = BLOCK_SIZE - (count % BLOCK_SIZE);if (amountToPad == 0) {amountToPad = BLOCK_SIZE;}// 获得补位所用的字符char padChr = chr(amountToPad);String tmp = new String();for (int index = 0; index < amountToPad; index++) {tmp += padChr;}return tmp.getBytes(CHARSET);}/*** 删除解密后明文的补位字符** @param decrypted 解密后的明文* @return 删除补位字符后的明文*/static byte[] decode(byte[] decrypted) {int pad = (int) decrypted[decrypted.length - 1];if (pad < 1 || pad > 32) {pad = 0;}return Arrays.copyOfRange(decrypted, 0, decrypted.length - pad);}/*** 将数字转化成ASCII码对应的字符,用于对明文进行补码** @param a 需要转化的数字* @return 转化得到的字符*/static char chr(int a) {byte target = (byte) (a & 0xFF);return (char) target;}}
package jc.wx.networkreleasemonitoring.networkreleasemonitoring.utils;import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;public class AddSHA1 {public static String SHA1(String inStr) {MessageDigest md = null;String outStr = null;try {md = MessageDigest.getInstance("SHA-1");     //选择SHA-1,也可以选择MD5byte[] digest = md.digest(inStr.getBytes());       //返回的是byet[],要转化为String存储比较方便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();}
}
package jc.wx.networkreleasemonitoring.networkreleasemonitoring.utils;@SuppressWarnings("serial")
public class AesException extends Exception {public final static int OK = 0;public final static int ValidateSignatureError = -40001;public final static int ParseXmlError = -40002;public final static int ComputeSignatureError = -40003;public final static int IllegalAesKey = -40004;public final static int ValidateAppidError = -40005;public final static int EncryptAESError = -40006;public final static int DecryptAESError = -40007;public final static int IllegalBuffer = -40008;//public final static int EncodeBase64Error = -40009;//public final static int DecodeBase64Error = -40010;//public final static int GenReturnXmlError = -40011;private int code;private static String getMessage(int code) {switch (code) {case ValidateSignatureError:return "签名验证错误";case ParseXmlError:return "xml解析失败";case ComputeSignatureError:return "sha加密生成签名失败";case IllegalAesKey:return "SymmetricKey非法";case ValidateAppidError:return "appid校验失败";case EncryptAESError:return "aes加密失败";case DecryptAESError:return "aes解密失败";case IllegalBuffer:return "解密后得到的buffer非法";
//      case EncodeBase64Error:
//          return "base64加密错误";
//      case DecodeBase64Error:
//          return "base64解密错误";
//      case GenReturnXmlError:
//          return "xml生成失败";default:return null; // cannot be}}public int getCode() {return code;}AesException(int code) {super(getMessage(code));this.code = code;}}

xml转map:

package jc.wx.networkreleasemonitoring.networkreleasemonitoring.utils;import org.w3c.dom.Node;
import org.w3c.dom.NodeList;import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;/*** 处理xml*/
public class XmlUtil {/*** xml 转 map* @param strXML    xml* @return* @throws Exception*/public static Map<String, String> xmlToMap(String strXML) {try {Map<String, String> data = new HashMap<String, String>();DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();InputStream stream = new ByteArrayInputStream(strXML.getBytes("UTF-8"));org.w3c.dom.Document doc = documentBuilder.parse(stream);doc.getDocumentElement().normalize();NodeList nodeList = doc.getDocumentElement().getChildNodes();for (int idx = 0; idx < nodeList.getLength(); ++idx) {Node node = nodeList.item(idx);if (node.getNodeType() == Node.ELEMENT_NODE) {org.w3c.dom.Element element = (org.w3c.dom.Element) node;data.put(element.getNodeName(), element.getTextContent());}}try {stream.close();} catch (Exception ex) {// do nothing}return data;} catch (Exception ex) {System.out.println("无效的XML,不能转换为MAP。错误消息:" + ex.getMessage() + "。XML内容:" + strXML);}return null;}
}

最后祝大家好运

微信公众平台第三方平台全网发布 java相关推荐

  1. 微信公众账号第三方平台全网发布源码(java)- 实战测试通过

    微信公众账号第三方平台全网发布源码(java)- 实战测试通过 (更多资料,关注论坛:www.jeecg.org) 技术交流请加:289709451.287090836 package org.jee ...

  2. 微赞config.修改php,微信公众号第三方平台 微赞WZ_V100.0版20170612整合包 整合人人商城V2新版+一键升级...

    php+mysql php版本5.3或者以上,OPENSSL必需开启,这是本程序与微信公众号通讯的需求. 我们建议您用云主机!Windows或者Linux皆可,windows主机不推荐用IIS环境,可 ...

  3. 微信公众号第三方平台开发PYTHON教程 PART 2

    github地址:cppfun@wechat-open-third-party-dev 微信公众号第三方平台开发python教程 Part 1 这一节肯定是在第一节的基础上,如果你没有看过第一节,可能 ...

  4. 公众平台模板消息所在行业_如何使用微信公众号第三方平台群发模板消息助手?...

    对于微信公众号群发模板消息助手的实现,公众号后台提供了接口编程实现,微号帮平台提供了模板消息群发功能实现,均可以让微信公众号群发模板消息,模板消息即按固定格式的文本模块消息,没有图文形式,纯固定格式的 ...

  5. mysql 推送微信公众号_10分钟完成微信公众号第三方平台全网发布

    背景:在微信公众平台配置服务器URL时,使用了新浪云SAE自带的二级域名,提交时出现一个安全风险的警告,网上查了下,许多服务平台和团队也遇到同样的问题. 经过一番研究 - 为什么会有安全风险的警告? ...

  6. 微信公众号第三方开发之一创建微信公众号第三方平台

    首先声明,在接下来一系列公众号第三方开发教程中,核心原理是参照下面博主的源码: http://www.cnblogs.com/sujingnan/p/4397203.html 拓展业务需求的. 为什么 ...

  7. 微信公众号第三方平台开发PYTHON教程 PART 1

    微信是一个时代的标志,虽然它现在不温不火,但我们大部分人离不开它.最近我帮朋友的公司接入了微信公众号第三方,使其成为第三方开发者. 网上公众号的开发教程,描述很多,但第三方的就几乎没有,可能是商业部分 ...

  8. 微信公众号官网平台与微信公众号第三方平台的区别

    微信公众号官网平台 普通的微信公众账号只能开启编辑模式,编辑模式缺点: 1)功能有限,无法开发API丶地理位置回复等信息: 2) 文字回复有300字限制,关键字回复上限为200条; 3)关键字回复较多 ...

  9. 微信公众号第三方平台开发笔记--02获取component_verify_ticket

    第三方平台审核通过后,微信服务器会每10分钟向创建第三方平台时填写的授权事件接收URL推送一次component_verify_ticket, 用于获取第三方平台接口调用凭据. /** * 接收微信服 ...

  10. 微信公众号第三方平台投票

    在微信公众号中我们会进行投票,那么投票我们该如何实现此功能呢?实现投票需要访问第三方网页,公众号可以通过微信网页授权机制,来获取用户基本信息,进而实现业务逻辑. 目录 1 第一步:用户同意授权,获取c ...

最新文章

  1. Kaggle神器LightGBM最全解读!
  2. 深入理解按位异或运算符
  3. python闭包锁住女神的心
  4. python任务调度平台 界面_任务调度平台Cuckoo-Schedule
  5. Request库的安装与使用
  6. python 读取单所有json数据写入mongodb(单个)
  7. python正确的输入语句_手把手教你在python中如何使用while True语句
  8. 一次C端线上缓存问题的总结
  9. Linux升级openssh一次成功版本
  10. java实现表达式求值_如何编写一个高效的Java表达式求值程序
  11. 非线性回归 - 案例按步骤详解 -(SPSS建模)
  12. Spring Boot + JPA +MySQL 数据操作及示例环境搭建(手动建表建类)
  13. [转载] Python里面numpy库中zeros()的一些问题
  14. UE4官方文档踩坑:FPS示例2.7 UCameraComponent
  15. itools苹果录屏大师_录屏大师限免|2019年1月最后一次苹果精选限时免费App 0131...
  16. CSS 字体加粗,导致布局宽度改变怎么处理?
  17. SQLSERVER走起微信公众帐号已经开通搜狗微信搜索
  18. android获取经纬度代码
  19. 《阿里巴巴 Java开发手册》读后感
  20. 【操作系统】进程、线程、协程和并发、并行

热门文章

  1. 【迅速解决出现蓝屏代码0X0000007b的问题】
  2. 传智教育|2022最新版Java学习路线图全集汇总——Java学习到底学什么?一文详解
  3. java用一张一元票换一分_一张一分纸币更换两张一元纸币,知道收藏价值后,你也会更换!...
  4. 【React-Native】集成微信官方安卓端SDK,实现微信登录、发送/分享小程序消息等功能
  5. Log4j又发新版2.17.0,只有彻底搞懂漏洞原因,才能以不变应万变,
  6. Maven deploy时排除指定的某个module
  7. Java中JRE指什么呢?
  8. php外文参考文献翻译,双语参考文献输出功能
  9. c语言作文的题目_c语言练习题目
  10. 数据百问系列之二:游戏DAU骤降分析