• 微信公众号的开发教程Java版本


    1、首先,去官网注册一个微信公众号

    2、点击开发者中心,填写服务器配置信息

    3、通过ngrok来映射本地的请求到服务器端

    4、通过代码来验证请求,并给出相应的回复,不多说,贴代码

    package com.weixin.action;
    
    import java.io.IOException;
    /*
     * 第一次请求的时候是get请求,用户验证
     * 第二次请求就是Post请求,传递消息和返回消息
     */
    import java.io.PrintWriter;
    import java.util.Map;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    public class WeixinServlet extends HttpServlet{
    
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {
            /*
             * 获取参数,然后验证是否是正确的连接应用
             */
            String signature = req.getParameter("signature");
            String timestamp = req.getParameter("timestamp");
            String nonce = req.getParameter("nonce");
            String echostr = req.getParameter("echostr");
            PrintWriter out = resp.getWriter();
            if(CheckUtil.checkSignature(signature, timestamp, nonce)){
                out.print(echostr);
            }
        }
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {
            // TODO Auto-generated method stub
            req.setCharacterEncoding("UTF-8");
            resp.setCharacterEncoding("UTF-8");
            Map<String,String> map = MessageUtil.readStringXmlOut(req, null);
            String ToUserName = map.get("ToUserName");
            String FromUserName = map.get("FromUserName");
        //    String CreateTime = map.get("CreateTime");
            String Content = map.get("Content");
        //    String MsgId = map.get("MsgId");
            String MsgType = map.get("MsgType");
            PrintWriter writer = resp.getWriter();
            String msg = null;
            if(MessageUtil.MESSAGE_TEXT.equals(MsgType)){
                if("1".equals(Content)){
                    Content = "你好";
                }else if("2".equals(Content)){
                    Content = "暂时";
                }
                msg = MessageUtil.initText(ToUserName, FromUserName, Content);
            }else if(MessageUtil.MESSAGE_EVENT.equals(MsgType)){
                String event = map.get("event");
                if(MessageUtil.MESSAGE_SUBSCRIBE.equals(event)){
                    msg = MessageUtil.initText(ToUserName, FromUserName, MessageUtil.menuText());
                }
            }
            writer.print(msg);
            writer.close();
            
        }
        
        
    
    }
    View Code

    5、验证请求是否合法sha1验证

    package com.weixin.action;
    
    import java.util.Arrays;
    
    public class CheckUtil {
        
        private static final String token = "imooc";
        
        public static boolean checkSignature(String signature,String timestamp,String nonce){
            String[] arr = new String[]{token,timestamp,nonce};
            Arrays.sort(arr);
            //生成字符串
            StringBuffer content = new StringBuffer();
            for(int i = 0; i< arr.length;i++){
                content.append(arr[i]);
            }
            //sha1加密
            //String temp = new SHA1().getDigestOfString(content.toString().getBytes()).toLowerCase();
            String temp = Util.sha1(content.toString()).toLowerCase();
            return temp.equals(signature);
        }
    }
    View Code
    package com.weixin.action;
    
    import java.security.MessageDigest;
    import java.security.NoSuchAlgorithmException;
    
    public class Util {
    
        /**
         * sha1加密
         * 
         * @author qincd
         * @date Nov 3, 2014 4:16:39 PM
         */
        public static String sha1(String str) {
            if (str == null || str.length() == 0)
                return "";
            try {
                MessageDigest md = MessageDigest.getInstance("SHA1");
                byte[] bytes = md.digest(str.getBytes());
                return byte2Hex(bytes);
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
                throw new RuntimeException("SHA1加密出错");
            }
        }
    
        public static String byte2Hex(byte[] data) {
            if (data == null || data.length == 0)
                return "";
            StringBuilder sbu = new StringBuilder();
            for (int i = 0; i < data.length; i++) {
                if ((data[i] & 0xff) < 0x10) {
                    sbu.append("0");
                }
                sbu.append(Integer.toHexString(data[i] & 0xff));
            }
            return sbu.toString();
        }
    }
    View Code

    6、处理请求

    package com.weixin.action;
    
    public class MessageText {
        
        private String Content;
        private String CreateTime;
        private String FromUserName;
        private String MsgID;
        private String MsgType;
        private String ToUserName;
        
        public MessageText() {
            // TODO Auto-generated constructor stub
        }
    
        public MessageText(String toUserName, String fromUserName,
                String createTime, String msgType, String content, String msgID) {
            ToUserName = toUserName;
            FromUserName = fromUserName;
            CreateTime = createTime;
            MsgType = msgType;
            Content = content;
            MsgID = msgID;
        }
    
        public String getContent() {
            return Content;
        }
    
        public void setContent(String content) {
            Content = content;
        }
    
        public String getCreateTime() {
            return CreateTime;
        }
    
        public void setCreateTime(String createTime) {
            CreateTime = createTime;
        }
    
        public String getFromUserName() {
            return FromUserName;
        }
    
        public void setFromUserName(String fromUserName) {
            FromUserName = fromUserName;
        }
    
        public String getMsgID() {
            return MsgID;
        }
    
        public void setMsgID(String msgID) {
            MsgID = msgID;
        }
    
        public String getMsgType() {
            return MsgType;
        }
    
        public void setMsgType(String msgType) {
            MsgType = msgType;
        }
    
        public String getToUserName() {
            return ToUserName;
        }
    
        public void setToUserName(String toUserName) {
            ToUserName = toUserName;
        }
    
    }
    View Code

    7、协助处理请求的工具类

    package com.weixin.action;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    import javax.servlet.http.HttpServletRequest;
    
    import org.dom4j.Document;
    import org.dom4j.DocumentException;
    import org.dom4j.Element;
    import org.dom4j.io.SAXReader;
    
    import com.thoughtworks.xstream.XStream;
    
    public class MessageUtil {
        
        public static final String  MESSAGE_TEXT = "text";
        public static final String  MESSAGE_IMAGE = "image";
        public static final String  MESSAGE_VOICE = "voice";
        public static final String  MESSAGE_VIDEO = "video";
        public static final String  MESSAGE_SHORTVIDEO = "shortvideo";    
        public static final String  MESSAGE_LOCATION = "location";
        public static final String  MESSAGE_LINK = "link";
        public static final String  MESSAGE_EVENT = "event";
        public static final String  MESSAGE_SUBSCRIBE = "subscribe";
        public static final String  MESSAGE_UNSUBSCRIBE = "unsubscribe";
        public static final String  MESSAGE_SCAN = "SCAN";
        public static final String  MESSAGE_LOCATIONs = "LOCATION";
        public static final String  MESSAGE_CLICK = "CLICK";
        public static final String  MESSAGE_VIEW = "VIEW";
        
        
        public static Map readStringXmlOut(HttpServletRequest req,String xml) {
             Map map = new HashMap();
             Document doc = null;
             InputStream stream = null;
             // 将字符串转为XML
            try {
                SAXReader reader = new SAXReader();
                stream = req.getInputStream();
                doc = reader.read(stream);
                Element rootElt = doc.getRootElement();
                List<Element> es = rootElt.elements();
                for(Element e:es){
                    map.put(e.getName(), e.getText());
                }
            } catch (DocumentException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }finally{
                try {
                    if(stream!=null){
                        stream.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            // 获取根节点
             return map;
        }
        
        public static String objToXml(MessageText text){
            XStream xml = new XStream();
            xml.alias("xml", text.getClass());
            return xml.toXML(text);
        }
        
        /*
         * 主菜单
         */
        public static String menuText(){
            StringBuffer sb = new StringBuffer();
            sb.append("欢迎您的关注,请按照才对提示进行操作
    
    ");
            sb.append("1、小村长介绍。");
            sb.append("2、小村庄介绍");
            sb.append("回复?调出主菜单");
            return sb.toString();
        }
        
        /*
         * 拼接文本消息
         */
        public static String initText(String ToUserName,String FromUserName,String Content){
            MessageText text = new MessageText();
            text.setFromUserName(ToUserName);
            text.setToUserName(FromUserName);
            text.setMsgType("text");
            text.setCreateTime(System.currentTimeMillis()+"");
            text.setContent(Content);
            return MessageUtil.objToXml(text);
        }
    }
    View Code
  • 相关阅读:
    第二十一章 PHP编译安装(centos7)
    第二十章 nginx常见问题
    第十九章 keepalived高可用
    dijkstra
    求逆序对
    A
    P2014 [CTSC1997]选课
    樱花 混合背包
    1401D
    CF1343D
  • 原文地址:https://www.cnblogs.com/hiter-java/p/4508128.html
Copyright © 2020-2023  润新知