health2.0——获取微信信息

来源:互联网 发布:以后别做朋友知乎 编辑:程序博客网 时间:2024/06/08 16:48

    背景:继health1.0 软件投入使用时候,用户反映强烈,易用性还有很多的上升空间。不得不说微信已经融入大家的生活中,为了改善health2.0的易用性和微信合作志在必行。所以在没有经过张小龙同意的情况下,偷偷的进行了health2.0微信版的开发。

    二话不说,先来张图了解宏观:


    上代码:

    接受微信发送的参数,本进行验证

    

package com.health.controller;import com.alibaba.druid.sql.visitor.functions.If;import com.health.pojo.TUserRecord;import com.health.service.UserRecordService;import com.health.util.CheckUtil;import com.health.util.MessageUtil;import com.health.util.UUIDGenerator;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;import java.io.PrintWriter;import java.util.Date;import java.util.Map;/** * 接收微信服务器发送的4个参数并返回echostr */@Controller@RequestMapping("/weixin")public class WeixinServlet extends HttpServlet {    @Autowired    TUserRecord tUserRecord;    @Autowired    UUIDGenerator uuidGenerator;    @Autowired    UserRecordService userRecordService;    @RequestMapping(value = "/index", method = {RequestMethod.GET})    public void doGet(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {        // 接收微信服务器以Get请求发送的4个参数        String signature = request.getParameter("signature");        String timestamp = request.getParameter("timestamp");        String nonce = request.getParameter("nonce");        String echostr = request.getParameter("echostr");        System.out.println(signature);        System.out.println(timestamp);        System.out.println(nonce);        System.out.println(echostr);        PrintWriter out = response.getWriter();        if (CheckUtil.checkSignature(signature, timestamp, nonce)) {            out.print(echostr);        // 校验通过,原样返回echostr参数内容        } else {            System.out.println("失败!");            out.print("shibai");        }    }    @RequestMapping(value = "/index", method = {RequestMethod.POST})    public void doPost(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {        request.setCharacterEncoding("utf-8");        response.setContentType("text/xml;charset=utf-8");        PrintWriter out = response.getWriter();        try {            Map<String, String> map = MessageUtil.xmlToMap(request);            String toUserName = map.get("ToUserName");            String fromUserName = map.get("FromUserName");            String msgType = map.get("MsgType");            String picUrl = map.get("PicUrl");            String content = map.get("Content");            String nickname = map.get("nick_name");            out.print(content);            tUserRecord.setContext(content);           if(msgType.toString() == "image" || msgType.toString().equals("image"))           {               tUserRecord.setContext(picUrl);           }            tUserRecord.setType(msgType);            tUserRecord.setOpenid(fromUserName);            tUserRecord.setCreatetime(new Date());            tUserRecord.setId(uuidGenerator.getUUID());            int num = userRecordService.insert(tUserRecord);            System.out.println("返回值:"+num);        } catch (Exception e) {            System.out.println(e.getMessage());            e.printStackTrace();        } finally {            out.close();        }    }}

工具类代码:

package com.health.util;import org.apache.commons.codec.digest.DigestUtils;import org.springframework.stereotype.Component;import java.util.Arrays;/** * 校验的工具类   微信使用 */@Componentpublic class CheckUtil {    private static final String token = "health";    public static boolean checkSignature(String signature, String timestamp, String nonce) {        String[] arr = new String[]{token, timestamp, nonce};        // 排序        Arrays.sort(arr);        // 生成字符串        StringBuilder content = new StringBuilder();        for (int i = 0; i < arr.length; i++) {            content.append(arr[i]);        }        // sha1加密        String temp = getSHA1String(content.toString());        return temp.equals(signature); // 与微信传递过来的签名进行比较    }    private static String getSHA1String(String data) {       // return DigestUtils.sha1Hex(data);    // 使用commons codec生成sha1字符串        return DigestUtils.shaHex(data);    }}

package com.health.util;import org.dom4j.Document;import org.dom4j.DocumentException;import org.dom4j.Element;import org.dom4j.io.SAXReader;import org.springframework.stereotype.Component;import javax.servlet.http.HttpServletRequest;import java.io.IOException;import java.io.InputStream;import java.util.HashMap;import java.util.List;import java.util.Map;/** * 实现消息的格式转换(Map类型和XML的互转)  微信使用 */@Componentpublic class MessageUtil {    /**     * 将XML转换成Map集合     */    public static Map<String, String>xmlToMap(HttpServletRequest request) throws IOException, DocumentException{        Map<String, String> map = new HashMap<String, String>();        SAXReader reader = new SAXReader();            // 使用dom4j解析xml        InputStream ins = request.getInputStream(); // 从request中获取输入流        Document doc = reader.read(ins);        Element root = doc.getRootElement();         // 获取根元素        List<Element> list = root.elements();        // 获取所有节点        for (Element e : list) {            map.put(e.getName(), e.getText());            System.out.println(e.getName() + "--->" + e.getText());        }        ins.close();        return map;    }   /* *//**     * 将文本消息对象转换成XML     *//*    public static String textMessageToXML(TextMeaasge textMessage){        XStream xstream = new XStream();              // 使用XStream将实体类的实例转换成xml格式        xstream.alias("xml", textMessage.getClass()); // 将xml的默认根节点替换成“xml”        return xstream.toXML(textMessage);    }*/}

学习推荐链接:http://www.cnblogs.com/liuhongfeng/p/4846260.html

    总结: 非常感谢晓如的技术支持,技术非常棒的一个大美女啊! 想什么来什么,正想着怎么优化health1.0易用性问题了,看见了晓如在做微信的开发。真是心想事成啊,我觉得前提是要去想啊!