打赏

微信公众号自动回复

先进行公众号服务器配置,不会的可参考博主上篇http://www.cnblogs.com/yanan7890/p/8629094.html

Controller:

package controller;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Map;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import util.MessageUtil;
import util.XMLUtil;

@Controller
public class PdfController {
    private static final Logger logger = LoggerFactory.getLogger(PdfController.class);

    @RequestMapping("/pdf")
    public void index(HttpServletRequest req, HttpServletResponse res) throws Exception {
        logger.info("-----------进入pdf------------");
        res.setCharacterEncoding("utf-8");
        req.setCharacterEncoding("utf-8");
        boolean isGet = req.getMethod().toLowerCase().equals("get");
        if(isGet){
            String signature = req.getParameter("signature");
            String timestamp = req.getParameter("timestamp");
            String nonce = req.getParameter("nonce");
            String echostr = req.getParameter("echostr");
            String token = "zhangyanan";
            ArrayList<String> list = new ArrayList<String>();
            list.add(nonce);
            list.add(timestamp);
            list.add(token);

            Collections.sort(list);
            String signature2 = DigestUtils.shaHex(list.get(0) + list.get(1) + list.get(2));
            if (signature.equals(signature2)) {
            res.getWriter().write(echostr);
                res.getWriter().close();
            }
        }else{
            logger.info("-----------hadreturn------------");
            ServletInputStream in = req.getInputStream();
            String params = inputStream2String(in);
            Map<String, String> mapxml = XMLUtil.XMLToMap(params);
            logger.info("params:-----------------:" + params.toString());
            in.close();
            // 消息类型
            String msgType = (String) mapxml.get("MsgType");
            String content="自动回复功能正在开发,请稍后再试";
            // 文本消息
            if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_TEXT)&&mapxml.get("Content").equals("pdf")) {
                content="pdf";    
            }
            String xmlSendUser = XMLUtil.toXmlSendUser(mapxml.get("FromUserName"), mapxml.get("ToUserName"), Integer.valueOf(mapxml.get("CreateTime")),content);
            logger.info("xmlSendUser:" + xmlSendUser);
            res.getWriter().write(xmlSendUser);
            res.getWriter().close();
        }
        
        
    }
    
    private static final String inputStream2String(InputStream in) throws UnsupportedEncodingException, IOException {
        if (in == null)
            return "";

        StringBuffer out = new StringBuffer();
        byte[] b = new byte[4096];
        for (int n; (n = in.read(b)) != -1;) {
            out.append(new String(b, 0, n, "UTF-8"));
        }
        return out.toString();
    }
}
View Code

 

 

工具类:

package util;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 
 * @todo 
 * @author zhangyanan
 * @datetime 2017年11月30日下午1:59:25
 */
public class XMLUtil {
    private static final Logger logger = LoggerFactory.getLogger(XMLUtil.class);

    /**
     * 
     * @todo xml转map
     * @author zhangyanan
     * @datetime 2017年11月30日下午1:58:49
     * @param xml
     * @return
     */
    public static Map<String,String> XMLToMap(String xml){
        Map<String, String> map = new HashMap<String, String>();
        Document document;
        try {
            document = DocumentHelper.parseText(xml);
             Element root = document.getRootElement(); // 获取XML文档的根节点对象
            @SuppressWarnings("unchecked")
            List<Element> list = root.elements(); // 获取根节点下的所有的子节点
            for (Element ele : list) { // 遍历根节点下的所有子节点并将其放入MAP对象中
                map.put(ele.getName(), ele.getText());
            }
            return map;
        } catch (DocumentException e) {
            e.printStackTrace();
        } 
        return null;
    }
    
    public static String toXmlSendUser(String OpenID,String kfwxid,int time,String Content) throws Exception {
        StringBuilder sb = new StringBuilder();
        sb.append("<xml>");
        sb.append("<ToUserName><![CDATA["+OpenID+"]]></ToUserName>");
        sb.append("<FromUserName><![CDATA["+kfwxid+"]]></FromUserName>");
        sb.append("<CreateTime><![CDATA["+time+"]]></CreateTime>");
        sb.append("<MsgType><![CDATA[text]]></MsgType>");
        sb.append("<Content><![CDATA["+Content+"]]></Content>");
        sb.append("</xml>");
        String data = sb.toString();
        logger.info("-------------------XMLPushMsg:"+data);
        return data;
    }
}
View Code

 注意:

微信官方文档提供的xml如下:

<xml> <ToUserName>< ![CDATA[toUser] ]></ToUserName> <FromUserName>< ![CDATA[fromUser] ]></FromUserName> <CreateTime>12345678</CreateTime> <MsgType>< ![CDATA[text] ]></MsgType> <Content>< ![CDATA[你好] ]></Content> </xml>
View Code

千万不要照着官网的例子来,有空格,必须删除,否则报“该公众号提供的服务出现故障,请稍后再试”

 

注意:未认证的情况下只有上述回复文本消息接口权限,如图片、视频等需要认证

posted @ 2018-03-23 18:29  每天都要学一点  阅读(332)  评论(0编辑  收藏  举报