微信接受消息

通过微信的聊天小窗口或者自定义菜单将消息推送到后台接口,后台获取信息并返回。
public void weiXinMsgReceive(String signature, String timestamp, String nonce, String echostr, HttpServletResponse response, HttpServletRequest request) {
  response.setCharacterEncoding("UTF-8");
  response.setContentType("text/xml");
  PrintWriter out = null;
  try {
   out = response.getWriter();
   boolean isGet = request.getMethod().toLowerCase().equals("get");
   System.out.println("weiXinMsgReceive 获得微信请求:" + request.getMethod() + " 方式");
   System.out.println("weiXinMsgReceive 微信请求URL:" + request.getServletPath());
   // 消息来源可靠性验证
   String token = "weixin4j";
   if (isGet) {
    // 1.验证消息真实性
    // http://mp.weixin.qq.com/wiki/index.php?title=验证消息真实性
    // URL为http://www.weixin4j.org/api/公众号
    // 成为开发者验证
    // 确认此次GET请求来自微信服务器,原样返回echostr参数内容,则接入生效,成为开发者成功,否则接入失败
    if (WeiXinPushAuth.checkSignature(token, signature, timestamp, nonce)) {
     out.write(echostr);
    }
   } else {
    // 确认此次GET请求来自微信服务器,原样返回echostr参数内容,则接入生效,成为开发者成功,否则接入失败
    if (!WeiXinPushAuth.checkSignature(token, signature, timestamp, nonce)) {
     out.write("");
     return;
    }
    // 用户每次向公众号发送消息、或者产生自定义菜单点击事件时,响应URL将得到推送
    try {
     // 获取POST流
     InputStream is = request.getInputStream();
     // 已HTTP请求输入流建立一个BufferedReader对象
     BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
     // 读取HTTP请求内容
     String buffer = null;
     StringBuffer sb = new StringBuffer();
     while ((buffer = br.readLine()) != null) {
      // 在页面中显示读取到的请求参数
      sb.append(buffer);
     }
     // 处理输入消息,返回结果
     String xml = sb.toString();
     log.info("weiXinMsgReceive Param xml=" + xml);
     //实现操作
     // 返回结果
     out.write("接受成功");
    } catch (Exception ex) {
     ex.printStackTrace();
     log.info("weiXinMsgReceive Exception ex="+ex.getMessage());
     out.write("");
    }
   }
  } catch (Exception e) {
   e.printStackTrace();
   log.info("weiXinMsgReceive Exception e="+e.getMessage());
   out.write("");
  } finally {
   if (out != null) {
    out.close();
   }
  }
 }

校验类:
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class WeiXinPushAuth {
 private static final char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
 
 public static boolean checkSignature(String token, String signature,
   String timestamp, String nonce) {
  List params = new ArrayList();
  params.add(token);
  params.add(timestamp);
  params.add(nonce);
  Collections.sort(params, new Comparator() {
   @Override
   public int compare(Object o1, Object o2) {
    // TODO Auto-generated method stub
    return ((String) o1).compareTo((String) o2);
   }
  });
  String temp = encode(((String) params.get(0))
    + ((String) params.get(1)) + ((String) params.get(2)));
  return temp.equals(signature);
 }
 public static String encode(String str) {
  if (str == null)
   return null;
  try {
   MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
   messageDigest.update(str.getBytes());
   return getFormattedText(messageDigest.digest());
  } catch (Exception e) {
   throw new RuntimeException(e);
  }
 }
 private static String getFormattedText(byte[] bytes) {
  int len = bytes.length;
  StringBuilder buf = new StringBuilder(len * 2);
  for (int j = 0; j < len; ++j) {
   buf.append(HEX_DIGITS[(bytes[j] >> 4 & 0xF)]);
   buf.append(HEX_DIGITS[(bytes[j] & 0xF)]);
  }
  return buf.toString();
 }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值