Java微信公众号开发(二:消息自动回复)

开发环境:

  • 环境:JDK1.8
  • 框架:springBoot

因为在上一篇文章的最后,我们提到过,为了让用户的信息更加安全,我们选择通过安全模式接入微信公众号平台,但这涉及到了加密与解密的问题,所以下面的代码,解释都是相对于安全模式而言。

首先解释一下:我们通过手机向公众号发送消息,微信公众号平台接收到消息时,会对我们的消息体进行加密处理,然后请求我们后台的消息回复接口,但这时我们是无法拿到发送的真实信息的,官方给出的解决方案大概分两步,第一步我们需要对URL中的签名和我们自己生成的签名做一下比对。如果通过了,那么进行第二步,通过‘aes’对加密体进行解密获取初始XML信息。这样我们才能拿到用户发送的真实信息。

https://developers.weixin.qq.com/doc/oplatform/Third-party_Platforms/Message_Encryption/Message_encryption_and_decryption.html

各位开发者可以看看这个官方文档

java实现微信公众号自动回复功能 公众号自动回复开发_java

我们可以看到,在微信公众平台请求我们接口的URL中会比接入时的请求多出两个参数,其中“消息体签名”我们后续会用到做比对,加密方式统一为“aes”.所以我们要做的就是生成我们的签名,与URL中的签名进行比对,解密消息体,非常友好的是,微信官方给出来签名生成的代码和aes解密的代码,可以下载到自己的代码中运行,我也会在下面给出我的代码。

前提条件

首先引入我们需要的jar包

<!-- beat64 -->
<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.9</version>
</dependency>

<!-- JSONObject -->
<dependency>
    <groupId>net.sf.json-lib</groupId>
    <artifactId>json-lib</artifactId>
    <version>2.4</version>
    <classifier>jdk15</classifier>
</dependency>

Coding

beat64 --> 这个jar在官方给出的demo中也同时给出了,只不过我们这里是通过maven引入项目的,下面是官方的demo代码,大家可以粘贴过去直接运行。

package com.liu.surprise.until.aes;

@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;
   }

}

package com.liu.surprise.until.aes;

import java.util.ArrayList;

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();
   }
}

package com.liu.surprise.until.aes;

import java.nio.charset.Charset;
import java.util.Arrays;

/**
 * 提供基于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;
   }

}

/**
 * 对公众平台发送给公众账号的消息加解密示例代码.
 * 
 * @copyright Copyright (c) 1998-2014 Tencent Inc.
 */

// ------------------------------------------------------------------------

package com.liu.surprise.until.aes;

import java.security.MessageDigest;
import java.util.Arrays;

/**
 * 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);
      }
   }
}
/**
 * 对公众平台发送给公众账号的消息加解密示例代码.
 * 
 * @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
 */
package com.liu.surprise.until.aes;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Random;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import com.liu.surprise.service.impl.MessageServiceImpl;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 提供接收和推送给公众平台消息的加解密接口(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>
 * @author HB_LIU
 */
public class WXBizMsgCrypt {

   private static final Logger LOGGER = LoggerFactory.getLogger(MessageServiceImpl.class);

   static Charset CHARSET = StandardCharsets.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 + appid
      byteCollector.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对加密后的字符串进行编码

         return base64.encodeToString(encrypted);
      } catch (Exception e) {
         e.printStackTrace();
         throw new AesException(AesException.EncryptAESError);
      }
   }

   /**
    * 对密文进行解密.
    * 
    * @param text 需要解密的密文
    * @return 解密得到的明文
    * @throws AesException aes解密失败
    */
   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, fromAppid;
      try {
         // 去除补位字符
         byte[] bytes = PKCS7Encoder.decode(original);

         // 分离16位随机字符串,网络字节序和AppId
         byte[] networkOrder = Arrays.copyOfRange(bytes, 16, 20);

         int xmlLength = recoverNetworkBytesOrder(networkOrder);

         xmlContent = new String(Arrays.copyOfRange(bytes, 20, 20 + xmlLength), CHARSET);
         fromAppid = new String(Arrays.copyOfRange(bytes, 20 + xmlLength, bytes.length),
               CHARSET);
      } catch (Exception e) {
         e.printStackTrace();
         throw new AesException(AesException.IllegalBuffer);
      }

      // appid不相同的情况
      if (!fromAppid.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);

      // 生成发送的xml
      return XMLParse.generate(encrypt, signature, timeStamp, nonce);    }

   /**
    * 检验消息的真实性,并且获取解密后的明文.
    * <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 {

      String signature = SHA1.getSHA1(token, timeStamp, nonce);

      // 和URL中的签名比较是否相等
      // LOGGER.info("第三方收到URL中的签名:" + msgSignature);
      // LOGGER.info("第三方校验签名:" + signature);
      if (!signature.equals(msgSignature)) {
         throw new AesException(AesException.ValidateSignatureError);
      }

      // 解密
      return decrypt(postData);
   }

   /**
    * 验证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);
      }

      return decrypt(echoStr);
   }

}

package com.liu.surprise.until.aes;

import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

/**
 * 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);

   }
}

以上就是官方给我们的demo,但是这套代码如果直接运用到我们的项目中,还是会出现问题,先留个悬念吧,不急一会再说。

到这为止我们就拥有了验证签名,解密的代码了,接下来我们要做的就是创建消息实体类,获取URL中的签名,获取加密消息体,

第一步,创建消息实体类

package com.liu.surprise.model.message;

import lombok.Data;

import java.io.Serializable;

@Data
public class BaseMessage implements Serializable {

    private static final long serialVersionUID = -4074795559908753026L;

    /**
     * 开发者微信号
     */
    private String ToUserName;

    /**
     * 发送方帐号(一个OpenID)
     */
    private String FromUserName;

    /**
     * 消息创建时间 (整型)
     */
    private long CreateTime;
    /**
     * 消息类型(text/image/location/link)
     */
    private String MsgType;

    /**
     * 消息id,64位整型
      */
    private long MsgId;
    /**
     * 位0x0001被标志时,星标刚收到的消息
     */
    private int FuncFlag;
}

package com.liu.surprise.model.message;


public class TextMessage extends BaseMessage{
   // 消息内容
    private String Content;
    
    public String getContent() {
        return Content;
    }
    public void setContent(String content) {
        Content = content;
    }
    
}

package com.liu.surprise.model.message;

import lombok.Data;
import lombok.Getter;
import lombok.Setter;

import java.io.Serializable;

/**
 * @author HB_LIU
 */
@Data
public class Article implements Serializable {

    private static final long serialVersionUID = 228150339972978127L;

    /**
     * 图文消息描述
     */
    private String Description;

    /**
     * 图片链接,支持JPG、PNG格式,<br>
     * 较好的效果为大图640*320,小图80*80
     */
    private String PicUrl;

    /**
     * 图文消息名称
     */
    private String Title;

    /**
     * 点击图文消息跳转链接
     */
    private String Url;

}

package com.liu.surprise.model.message;

import lombok.Getter;
import lombok.Setter;

import java.util.List;

@Setter
@Getter
public class NewsMessage extends BaseMessage{
    /**
     * 图文消息个数,限制为10条以内
     */
    private Integer ArticleCount;

    /**
     * 多条图文消息信息,默认第一个item为大图
     */
    private List<Article> Articles;

}

package com.liu.surprise.model.message;

import java.io.Serializable;

public class ImageMessage extends BaseMessage implements Serializable {
}

package com.liu.surprise.model.message;

import lombok.Data;
import lombok.Getter;
import lombok.Setter;

import java.io.Serializable;

/**
 * @author HB_LIU
 */
@Data
public class Music implements Serializable {
    private static final long serialVersionUID = 381822571255731959L;
    /**
     * 音乐名称
     */
    private String Title;

    /**
     * 音乐描述
     */
    private String Description;

    /**
     * 音乐链接
     */
    private String MusicUrl;

    /**
     * 高质量音乐链接,WIFI环境优先使用该链接播放音乐
     */
    private String HQMusicUrl;
}

package com.liu.surprise.model.message;

import lombok.Getter;
import lombok.Setter;

import java.io.Serializable;

@Setter
@Getter
public class MusicMessage extends BaseMessage implements Serializable {

    /**
     * 音乐
     */
    private Music Music;

}

package com.liu.surprise.model.message;


import java.io.Serializable;

public class VideoMessage extends BaseMessage implements Serializable {
}

package com.liu.surprise.model.message;


import java.io.Serializable;

public class VoiceMessage extends BaseMessage implements Serializable {
}

消息的实体类到这就创建完成了,虽然创建了这么多,只是预留一下,以防以后会用到,这里只以文字信息为例,下面需要做就是获取URL中的签名,生成我门自己的签名。先给出我的代码,边看边说吧。

package com.liu.surprise.until.aes;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import javax.servlet.http.HttpServletRequest;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import com.liu.surprise.until.aes.WXBizMsgCrypt;

/**
 * @author HB_LIU
 */
public class MessageDecrypt {
    private static String encodingAesKey = "消息加解密密钥(EncodingAESKey)";
    private static String token = "令牌(Token)";
    private static String appId = "开发者ID(AppID)";

    public static String decrypt(HttpServletRequest request) throws AesException, IOException {
        //获取请求中的时间戳和随机数,微信加密签名
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");

        Map<String, String> map = new HashMap<String, String>();
        SAXReader reader = new SAXReader();

        InputStream ins = null;
        try {
            ins = request.getInputStream();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        Document doc = null;
        try {
            doc = reader.read(ins);
            org.dom4j.Element root = doc.getRootElement();
            List<org.dom4j.Element> list = root.elements();
            for (Element e : list) {
                map.put(e.getName(), e.getText());
            }
        } catch (DocumentException e1) {
            e1.printStackTrace();
        }finally{
            ins.close();
        }

        WXBizMsgCrypt wxBizMsgCrypt = new WXBizMsgCrypt(token, encodingAesKey, appId);
        String s = wxBizMsgCrypt.decryptMsg(signature, timestamp, nonce, map.get("Encrypt"));
        return s;
    }

}

package com.liu.surprise.until;

import com.liu.surprise.model.message.*;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.core.util.QuickWriter;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.xml.PrettyPrintWriter;
import com.thoughtworks.xstream.io.xml.XppDriver;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author HB_LIU
 */
public class MessageUtil {
    /**
     * 返回消息类型:文本
     */
    public static final String RESP_MESSAGE_TYPE_TEXT = "text";

    /**
     * 返回消息类型:音乐
     */
    public static final String RESP_MESSAGE_TYPE_MUSIC = "music";

    /**
     * 返回消息类型:图文
     */
    public static final String RESP_MESSAGE_TYPE_NEWS = "news";

    /**
     * 请求消息类型:文本
     */
    public static final String REQ_MESSAGE_TYPE_TEXT = "text";

    /**
     * 请求消息类型:图片
     */
    public static final String REQ_MESSAGE_TYPE_IMAGE = "image";

    /**
     * 请求消息类型:链接
     */
    public static final String REQ_MESSAGE_TYPE_LINK = "link";

    /**
     * 请求消息类型:地理位置
     */
    public static final String REQ_MESSAGE_TYPE_LOCATION = "location";

    /**
     * 请求消息类型:音频
     */
    public static final String REQ_MESSAGE_TYPE_VOICE = "voice";

    /**
     * 请求消息类型:推送
     */
    public static final String REQ_MESSAGE_TYPE_EVENT = "event";

    /**
     * 事件类型:subscribe(订阅)
     */
    public static final String EVENT_TYPE_SUBSCRIBE = "subscribe";

    /**
     * 事件类型:unsubscribe(取消订阅)
     */
    public static final String EVENT_TYPE_UNSUBSCRIBE = "unsubscribe";

    /**
     * 事件类型:CLICK(自定义菜单点击事件)
     */
    public static final String EVENT_TYPE_CLICK = "CLICK";


    /**
     * xml转换为map
     * @param str 解密后的消息信息
     * @return
     * @throws IOException
     */
    public static Map<String, String> xmlToMap(String str) throws IOException {
        Map<String, String> map = new HashMap<String, String>();
        SAXReader reader = new SAXReader();

        InputStream ins = null;
        try {
            ins = new ByteArrayInputStream(str.getBytes("UTF-8"));
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        Document doc = null;
        try {
            doc = reader.read(ins);
            Element root = doc.getRootElement();
            List<Element> list = root.elements();
            for (Element e : list) {
                map.put(e.getName(), e.getText());
            }
            return map;
        } catch (DocumentException e1) {
            e1.printStackTrace();
        }finally{
            ins.close();
        }

        return null;
    }

    /**
     * 文本消息对象转换成xml
     *
     * @param textMessage 文本消息对象
     * @return xml
     */
    public static String textMessageToXml(TextMessage textMessage){
        xstream.alias("xml", textMessage.getClass());
        return xstream.toXML(textMessage);
    }

    /**
     * @Description: 图文消息对象转换成xml
     * @param newsMessage
     * @param @return
     * @author HB_LIU
     */
    public static String newsMessageToXml(NewsMessage newsMessage) {
        xstream.alias("xml", newsMessage.getClass());
        xstream.alias("item", new Article().getClass());
        return xstream.toXML(newsMessage);
    }

    /**
     * @Description: 图片消息对象转换成xml
     * @param imageMessage
     * @author HB_LIU
     */
    public static String imageMessageToXml(ImageMessage imageMessage) {
        xstream.alias("xml", imageMessage.getClass());
        return xstream.toXML(imageMessage);
    }

    /**
     * @Description: 语音消息对象转换成xml
     * @param voiceMessage
     * @author HB_LIU
     */
    public static String voiceMessageToXml(VoiceMessage voiceMessage) {
        xstream.alias("xml", voiceMessage.getClass());
        return xstream.toXML(voiceMessage);
    }

    /**
     * @Description: 视频消息对象转换成xml
     * @param videoMessage
     * @author HB_LIU
     */
    public static String videoMessageToXml(VideoMessage videoMessage) {
        xstream.alias("xml", videoMessage.getClass());
        return xstream.toXML(videoMessage);
    }

    /**
     * @Description: 音乐消息对象转换成xml
     * @param musicMessage
     * @author HB_LIU
     */
    public static String musicMessageToXml(MusicMessage musicMessage) {
        xstream.alias("xml", musicMessage.getClass());
        return xstream.toXML(musicMessage);
    }

    /**
     * 对象到xml的处理
     */
    private static XStream xstream = new XStream(new XppDriver() {
        @Override
        public HierarchicalStreamWriter createWriter(Writer out) {
            return new PrettyPrintWriter(out) {
                // 对所有xml节点的转换都增加CDATA标记
                boolean cdata = true;

                @Override
                public void startNode(String name, Class clazz) {
                    super.startNode(name, clazz);
                }

                @Override
                protected void writeText(QuickWriter writer, String text) {
                    if (cdata) {
                        writer.write("<![CDATA[");
                        writer.write(text);
                        writer.write("]]>");
                    } else {
                        writer.write(text);
                    }
                }
            };
        }
    });

}

package com.liu.surprise.service;

import javax.servlet.http.HttpServletRequest;

/**
 * @author HB_LIU
 */
public interface MessageService {

    /**
     * 微信公众号处理
     * @param request 请求体
     * @return        字符串
     */
    String newMessageRequest(HttpServletRequest request);
}
package com.liu.surprise.service.impl;

import com.liu.surprise.model.message.TextMessage;
import com.liu.surprise.service.MessageService;
import com.liu.surprise.until.MessageUtil;
import com.liu.surprise.until.TulingRobot;
import com.liu.surprise.until.aes.MessageDecrypt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author HB_LIU
 */
@Service
public class MessageServiceImpl implements MessageService {

    private static final Logger LOGGER = LoggerFactory.getLogger(MessageServiceImpl.class);

    @Override
    public String newMessageRequest(HttpServletRequest request) {
        String respMessage = null;
        try {
            // 第三方消息解密
            String decrypt = MessageDecrypt.decrypt(request);
            // xml请求解析
            Map<String, String> requestMap = MessageUtil.xmlToMap(decrypt);
            // 发送方帐号(open_id)
            assert requestMap != null;
            String fromUserName = requestMap.get("FromUserName");
            // 公众帐号
            String toUserName = requestMap.get("ToUserName");
            // 消息类型
            String msgType = requestMap.get("MsgType");
            // 消息内容
            String content = requestMap.get("Content");
            LOGGER.info("Content is:" + content + ",FromUserName is:" + fromUserName + ", ToUserName is:" + toUserName + ", MsgType is:" + msgType);
            // 文本消息
            if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_TEXT)) {
                // 图灵机器人接入
                // String dialogue = TulingRobot.dialogue(content);
                // 自动回复
                TextMessage text = new TextMessage();
                text.setContent(content);
                text.setToUserName(fromUserName);
                text.setFromUserName(toUserName);
                text.setCreateTime(System.currentTimeMillis());
                text.setMsgType(msgType);
                respMessage = MessageUtil.textMessageToXml(text);
            }
            // 事件推送
            else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_EVENT)) {
                String eventType = requestMap.get("Event");
                // 订阅
                if (eventType.equals(MessageUtil.EVENT_TYPE_SUBSCRIBE)) {
                    //文本消息
                    TextMessage text = new TextMessage();
                    text.setContent("老话说的好,有就享受,没有就嫖");
                    text.setToUserName(fromUserName);
                    text.setFromUserName(toUserName);
                    text.setCreateTime(System.currentTimeMillis());
                    text.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
                    respMessage = MessageUtil.textMessageToXml(text);
                }
                // 取消订阅后用户再收不到公众号发送的消息,因此不需要回复消息
                else if (eventType.equals(MessageUtil.EVENT_TYPE_UNSUBSCRIBE)) {
                    LOGGER.info("取消订阅");
                }
            }
        }
        catch (Exception e) {
            LOGGER.error("error......");
        }
        return respMessage;
    }

}

最后,在我们接入微信公众号平台的那个controller中创建一个POST方法用来调用上面的代码

package com.liu.surprise.controller;

import com.liu.surprise.service.MessageService;
import com.liu.surprise.until.WeixinCheckoutUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

/**
 * @author HB_LIU
 */
@RestController
@RequestMapping("/wxPublic")
public class WeixinCheckController {
    @Resource
    MessageService messageService;

    private static final Logger LOGGER = LoggerFactory.getLogger(WeixinCheckController.class);

    @RequestMapping(method = RequestMethod.GET)
    public String checkToken(HttpServletRequest request, HttpServletResponse response) {
        // 微信加密签名,signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
        String signature = request.getParameter("signature");
        // 时间戳
        String timestamp = request.getParameter("timestamp");
        // 随机数
        String nonce = request.getParameter("nonce");
        // 随机字符串
        String echostr = request.getParameter("echostr");

        PrintWriter out = null;
        try {
            out = response.getWriter();
            // 通过检验signature对请求进行校验,若校验成功则原样返回echostr,否则接入失败
            if (WeixinCheckoutUtil.checkSignature(signature, timestamp, nonce)) {
                LOGGER.info("微信加密签名:" + signature + ";时间戳:" + timestamp + ";随机数:" + nonce);
                out.print(echostr);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            out.close();
            out = null;
        }
        return null;
    }

    @RequestMapping(method = RequestMethod.POST)
    public void post(HttpServletRequest request, HttpServletResponse response) {
        try {
            request.setCharacterEncoding("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            LOGGER.error(e.getMessage(),e);
        }
        response.setContentType("text/xml;charset=UTF-8");

        // 调用核心业务类接收消息、处理消息
        String respMessage = messageService.newMessageRequest(request);

        // 响应消息
        PrintWriter out = null;
        try {
            out = response.getWriter();
            out.print(respMessage);
        } catch (IOException e) {
            e.printStackTrace();
            LOGGER.error(e.getMessage(),e);
        } finally {
            out.close();
            out = null;
        }
    }
}

好了,到现在为止,我们的代码就写完了(你竟然相信了,天真),编译一下项目,启动。

http://mp.weixin.qq.com/debug?token=198908656&lang=zh_CN

打开上边的页面,我们可以在这里测试我们的代码

java实现微信公众号自动回复功能 公众号自动回复开发_java_02

点击下面的“检查问题”就行了,

看看控制台,

真好,报错了

是不是在怀疑,在迷茫,在惆怅,问题不大,拿捏。

回头看看代码吧,仔细看看,注意细节,有没有发现我们忽略了官方代码中的注释信息

java实现微信公众号自动回复功能 公众号自动回复开发_i++_03

对,没错,就是这段提示,我们还没有下载JCE无限制权限策略文件,但这里官方给出的是JDK7的下载地址,而我们用的是JDK8,这不完犊子了,又被拿捏了。聪明的我想到了一个办法,把上面地址中的“7”改成“8”,回车。

牛皮,就是这个,看看,这就是大公司,我就想给他点赞。

下载到本地

按照上边的提示,操作一番,哎呦卧槽,这不是有吗,才发现,原来JDK8已经自带了JCE无限制权限策略文件,又长知识了。但还是要换成我们刚刚下载的,替换就完事了。怕啥,大点干,早点散。

替换完了,重启一下项目,请求一下。

我TM。。。怎还报错啊!

开动你那聪明的大脑,想想我们都干了什么,或者有什么地方被我们漏掉了,

比对验证签名,获取加密体,解密,说白了,我们就干了这三件事。

Debug搂一眼。

真好,第一步就错了,签名验证没通过,可是我们签名验证用的是官方代码啊,不应该啊!

不要说不应该,错了就是错了,还是回头看看文档怎么写的吧。

java实现微信公众号自动回复功能 公众号自动回复开发_i++_04


看看上边的图片,非常明确,这就是我们验证签名时调用的方法,一共四个参数,三个是从URL中获取的,还有一个是postdata(加密消息体),进到这个方法体中,我们看到这个方法做了签名的比对,如果比对成功则解密,而我们传递的参数完全是为生成签名服务的,打开log看一下,确实是因为两次签名不一致导致的异常的抛出。

想想,在生成签名时,为什么要用到加密体呢?

废话不多说,干,把getSHA1这个方法重载一下,干掉密文参数,方法调用处也把密文参数干掉。

重启一下项目,请求。看看控制台。

完美。Perfect。