服务号和订阅号链接验证方式(自己根据查看资料整理)

原创 2016年12月08日 13:14:06
        //这是在struts项目写的链接和接收消息的处理方法。
        HttpServletRequest request = ServletActionContext.getRequest();
        HttpServletResponse response = ServletActionContext.getResponse();
        String method = request.getMethod();
        //链接时访问get方法进行处理。
        if(method != null && method.equals("GET"))
        {
            //微信加密签名,signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。 
            String signature = request.getParameter("signature");  
            // 时间戳  
            String timestamp = request.getParameter("timestamp");
            // 随机数  
            String nonce = request.getParameter("nonce");  
            // 随机字符串  
            String echostr = request.getParameter("echostr");  
            //获取response的writer方法,将得到的结果写回。
            PrintWriter out = response.getWriter();  

            // 通过检验signature对请求进行校验,若校验成功则原样返回echostr,表示接入成功,否则接入失败  
            //WXfInit.TOKEN链接时设置的token
            if (SignUtil.checkSignature(WXfInit.TOKEN,signature, timestamp, nonce)) {  
                out.print(echostr);  
            }  
            out.close();  
            out = null;  
        }
        //此处为处理用户发送消息POST方法。
        if(method != null && method.equals("POST"))
        {
            //设置编码
            request.setCharacterEncoding("UTF-8");  
             response.setCharacterEncoding("UTF-8");  

            // 调用核心业务类接收消息、处理消息  
            String respMessage = connectService.processRequest();  
            // 响应消息  
            PrintWriter out = response.getWriter();  
            out.print(respMessage);  
            out.close();  
        }
**请求验证工具类(查找资料得到)**
package com.cntinker.util.wx.connect;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

/** 
 * 请求校验工具类 
 *  
 */  
public class SignUtil {  

    /** 
     * 验证签名 
     *  
     * @param signature 
     * @param timestamp 
     * @param nonce 
     * @return 
     */  
    public static boolean checkSignature(String weixintoken,String signature, String timestamp, String nonce) {  
        String[] arr = new String[] { weixintoken, timestamp, nonce };  
        // 将token、timestamp、nonce三个参数进行字典序排序  
        Arrays.sort(arr);  
        StringBuilder content = new StringBuilder();  
        for (int i = 0; i < arr.length; i++) {  
            content.append(arr[i]);  
        }  
        MessageDigest md = null;  
        String tmpStr = null;  
        try {  
            md = MessageDigest.getInstance("SHA-1");  
            // 将三个参数字符串拼接成一个字符串进行sha1加密  
            byte[] digest = md.digest(content.toString().getBytes());  
            tmpStr = byteToStr(digest);  
        } catch (NoSuchAlgorithmException e) {  
            e.printStackTrace();  
        }  

        content = null;  
        // 将sha1加密后的字符串可与signature对比,标识该请求来源于微信  
        return tmpStr != null ? tmpStr.equals(signature.toUpperCase()) : false;  
    }  

    /** 
     * 将字节数组转换为十六进制字符串 
     *  
     * @param byteArray 
     * @return 
     */  
    private static String byteToStr(byte[] byteArray) {  
        String strDigest = "";  
        for (int i = 0; i < byteArray.length; i++) {  
            strDigest += byteToHexStr(byteArray[i]);  
        }  
        return strDigest;  
    }  

    /** 
     * 将字节转换为十六进制字符串 
     *  
     * @param mByte 
     * @return 
     */  
    private static String byteToHexStr(byte mByte) {  
        char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };  
        char[] tempArr = new char[2];  
        tempArr[0] = Digit[(mByte >>> 4) & 0X0F];  
        tempArr[1] = Digit[mByte & 0X0F];  

        String s = new String(tempArr);  
        return s;  
    }  
}  
**解析用户消息XML**
public String processRequest() {
        HttpServletRequest request = ServletActionContext.getRequest();
        String respMessage = null;
        try {
            Map<String, String> requestMap = MessageUtil.parseXml(request); // xml请求解析
            String FromUserName = requestMap.get("FromUserName"); // 发送方帐号(open_id)
            String ToUserName = requestMap.get("ToUserName"); // 公众帐号
            String MsgType = requestMap.get("MsgType"); // 消息类型
            if (WXMsgType.REQ_MESSAGE_TYPE_TEXT.equals(MsgType))//判断用户发来的是否是文本消息
          {
            String Content = requestMap.get("Content"); // 接收用户发送的文本消息内容
            String message = null;
            //进行处理(此处写的是业务代码是:判断用户回复的文本是不是以t开头,进行照片处理。)
            if(Content.startsWith("t"))
            {
                String type=Content.substring(1, Content.length());
                Map<String, Integer> index_count = wXFarmerImageService.findImageByUserId(FromUserName, type);
                Iterator iter =index_count.entrySet().iterator(); 
                while (iter.hasNext()) { 
                    Map.Entry entry = (Map.Entry) iter.next(); 
                    String key = (String)entry.getKey(); 
                    int val = (int)entry.getValue(); 
                    if(key.equals("0"))
                    {
                        if(val!=0)
                        {
                            message = "照片分类成功,剩余"+val+"张图片未分类";
                        }else{
                            message = "照片分类成功";
                        }
                    }else if(key.equals("1"))
                    {
                        message = "照片分类失败,请按照提示回复";
                    }else if(key.equals("2"))
                    {
                        message = "您上传的照片已经全部分类,无需重复提交!";
                    }

                }
                //respfText 返回的是文本型的xml
                respMessage = respfText(FromUserName, ToUserName, message, "1234567890123456");
            }else
            {
                message = "温馨提示:\n上传图片可直接回复图片或选择菜单上传"
                        + "\n上传生产计划请选择菜单进行上传"
                        + "\n查看个人信息请选择菜单进行查看";
            }
            respMessage = respfText(FromUserName, ToUserName, message, "1234567890123456");
          }
          //判断用户时候发送的是事件,包括菜单点击,关注。取等事件
          if (WXMsgType.REQ_MESSAGE_TYPE_EVENT.equals(MsgType)) {
            String event = requestMap.get("Event");//获取事件名称
            if ("subscribe".equals(event))
            {
                String message = null;
                Farmer farmer = new Farmer();
                farmer.setUserId(FromUserName);
                String access_Token = WXFGetTokenService.accessTokenIsOvertime();
                JSONObject userInformation = WeixinUtil.httpRequest(
                        WXurl.WXF_USERNAME_URL.replace("ACCESS_TOKEN",
                                access_Token).replace("OPENID",
                                        FromUserName), "GET", null);
                farmer.setUserName(userInformation.getString("nickname"));
                farmer.setHeadPortrait(userInformation.getString("headimgurl").substring(0, userInformation.getString("headimgurl").length()-1)+"64");
                farmer.setStatus("0");
                farmerService.saveFarmer(farmer);
                message = "欢迎关注康源公社服务号\n"
                        + "温馨提示:\n上传图片可直接回复图片或选择菜单上传"
                        + "\n上传生产计划请选择菜单进行上传"
                        + "\n查看个人信息请选择菜单进行查看";
                respMessage = respfText(FromUserName, ToUserName, message, "1234567890123456");
            }
          }
          if (WXMsgType.REQ_MESSAGE_TYPE_IMAGE.equals(MsgType)) {
            String picUrl = requestMap.get(WXMessage.PICURL);
            String status = farmerService.getStatus(FromUserName);
            String message = null;
            if(status.equals("0"))
            {
                message ="点击上方文字进行填写信息";
                String access_tokenF = WXFGetTokenService.accessTokenIsOvertime();
                String messages = "<a href=\""+WXfInit.SERVICEURLW+"/xnr/page/wx/farmer/farmerExamine.action?farmerId="+FromUserName+"\">请前往页面填写审核信息。</a>";
                Text text = new Text();
                text.setContent(messages);
                TextMessageF textMessageF =new TextMessageF();
                textMessageF.setTouser(FromUserName);
                textMessageF.setMsgtype("text");
                textMessageF.setText(text);
                String outputStr = JSONObject.fromObject(textMessageF).toString();
                JSONObject jsons =  WeixinUtil.httpRequest(WXurl.WXF_MESSARW_TO_USER.replace("ACCESS_TOKEN", access_tokenF), "POST", outputStr);
            }else if(status.equals("3"))
            {
                message = "审核资料已提交,请等待审核!";
            }
            else
            {
                wXFarmerImageService.save(FromUserName, picUrl);
                String types = farmerService.getFenleiByUserId(FromUserName);
                List<BusinessGoods> list = businessGoodsService.getTypeNameById(types);
                StringBuffer me = new StringBuffer();
                for (BusinessGoods businessGoods : list) {
                    me.append("t"+businessGoods.getId()+businessGoods.getGoodsName()+"\n");
                }
                message = "请按顺序回复上传图片分类:"+me.toString();
            }
            respMessage = respfText(FromUserName, ToUserName, message, "1234567890123456");
          }
        }
        catch (Exception e) {
          e.printStackTrace();
        }
        return respMessage;
    }
**对用户的xml解析和返回和转义成xml形式工具类(查找资料获取)**
package com.xnradmin.client.service.wx;

import java.io.InputStream;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

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 com.xnradmin.client.messag.resp.Article;
import com.xnradmin.client.messag.resp.MusicMessage;
import com.xnradmin.client.messag.resp.NewsMessage;
import com.xnradmin.client.messag.resp.TextMessage;
import com.xnradmin.client.messag.resp.Voice;
import com.xnradmin.client.messag.resp.VoiceMessage;

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";
  public static final String EVENT_TYPE_SUBSCRIBE = "subscribe";
  public static final String EVENT_TYPE_UNSUBSCRIBE = "unsubscribe";
  public static final String EVENT_TYPE_CLICK = "click";

  private static XStream xstream = new XStream(new XppDriver() {
    public HierarchicalStreamWriter createWriter(Writer out) {
      return new PrettyPrintWriter(out)
      {
        boolean cdata;

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

        protected void writeText(QuickWriter writer, String text) {
          if (this.cdata) {
            writer.write("<![CDATA[");
            writer.write(text);
            writer.write("]]>");
          } else {
            writer.write(text);
          }
        }
      };
    }
  });
//将xml转存到map数组中
  public static Map<String, String> parseXml(HttpServletRequest request)
    throws Exception
  {
    Map map = new HashMap();

    InputStream inputStream = request.getInputStream();

    SAXReader reader = new SAXReader();
    Document document = reader.read(inputStream);

    Element root = document.getRootElement();

    List<Element> elementList = root.elements();

    for (Element e : elementList)
    {
      map.put(e.getName(), e.getText());
    }

    inputStream.close();

    return map;
  }
//将文本实体转换成xml格式
  public static String textMessageToXml(TextMessage textMessage)
  {
    xstream.alias("xml", textMessage.getClass());
    return xstream.toXML(textMessage);
  }
//将音乐实体转换成xml格式
  public static String musicMessageToXml(MusicMessage musicMessage)
  {
    xstream.alias("xml", musicMessage.getClass());
    return xstream.toXML(musicMessage);
  }
//将图文实体转换成xml格式
  public static String newsMessageToXml(NewsMessage newsMessage)
  {
    xstream.alias("xml", newsMessage.getClass());
    xstream.alias("item", new Article().getClass());
    return xstream.toXML(newsMessage); }
//将音频实体转换成xml格式
  public static String voiceMessageToXml(VoiceMessage voiceMessage) {
    xstream.alias("xml", voiceMessage.getClass());
    xstream.alias("mediaId", new Voice().getClass());
    return xstream.toXML(voiceMessage);
  }
}
**返回文本型XML**
/**
*接收者openid
*发送者openid
*文本消息
*随机串
*/
private String respfText(String FromUserName, String ToUserName, String text, String MsgId) {
        TextMessage textMessage = new TextMessage();
        textMessage.setToUserName(FromUserName);
        textMessage.setFromUserName(ToUserName);
        textMessage.setCreateTime(new Date().getTime());
        textMessage.setMsgType("text");
        textMessage.setMsgId(MsgId);
        textMessage.setContent(text);
        return MessageUtil.textMessageToXml(textMessage);
      }
版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

微信服务号与订阅号

  • 2013-12-14 16:46
  • 414KB
  • 下载

微信公众平台开发教程(十) 订阅号与服务号的区别

原文地址:http://www.cnblogs.com/yank/p/3651592.html 为了消除大家对订阅号与服务号的疑问,特总结如下:   功能点 介绍 订阅号 服...

微信服务号与订阅号区别

  • 2014-04-21 20:15
  • 224KB
  • 下载

微信公众平台服务号、订阅号的相关说明

一、服务号、订阅号的介绍(区别)  微信公众平台现在已分成订阅公众号和服务公众号两种类型。 公众平台服务号,是公众平台的一种帐号类型,旨在为用户提供服务。 特点:每月可群发一条信息给...

教你3分钟快速开发微信公众号[订阅号][服务号]

java微信公众号开发框架 微信开发框架 快速开发
  • antgan
  • antgan
  • 2016-06-20 00:48
  • 8154
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)