微信公众平台开发教程1

工程项目图
微信公众平台开发教程1

WeixinServlet

package com.weixin.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.weixin.po.TextMessage;
import com.weixin.util.CheckUtil;
import com.weixin.util.MessageUtil;

public class WeixinServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public WeixinServlet() {
        super();

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echostr = request.getParameter("echostr");

        PrintWriter out = response.getWriter();
        if (CheckUtil.checkSignature(signature, timestamp, nonce)) {
            out.print(echostr);
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        try {
            Map<String, String> map = MessageUtil.xmlToMap(request);
            String fromUserName = map.get("FromUserName");
            String toUserName = map.get("ToUserName");
            String msgType = map.get("MsgType");
            String content = map.get("Content");
            String message = null;
            if ("text".equals(msgType)) {
                TextMessage text = new TextMessage();
                text.setFromUserName(toUserName);
                text.setToUserName(fromUserName);
                text.setMsgType("text");
                text.setCreateTime(new Date().getTime());
                text.setContent("你发送 的消息是:" + content);
                message = MessageUtil.textMessageToXml(text);
            }
            out.print(message);

        } catch (Exception e) {
            // TODO: handle exception
        } finally {
            out.close();
        }
    }
}

TextMessage

package com.weixin.po;

public class TextMessage {
private String ToUserName;
private String FromUserName;
private long CreateTime;
private String MsgType;
private String Content;
private String MsgId;
public String getToUserName() {
    return ToUserName;
}
public void setToUserName(String toUserName) {
    ToUserName = toUserName;
}
public String getFromUserName() {
    return FromUserName;
}
public void setFromUserName(String fromUserName) {
    FromUserName = fromUserName;
}
public long getCreateTime() {
    return CreateTime;
}
public void setCreateTime(long createTime) {
    CreateTime = createTime;
}
public String getMsgType() {
    return MsgType;
}
public void setMsgType(String msgType) {
    MsgType = msgType;
}
public String getContent() {
    return Content;
}
public void setContent(String content) {
    Content = content;
}
public String getMsgId() {
    return MsgId;
}
public void setMsgId(String msgId) {
    MsgId = msgId;
}

}

CheckUtil

package com.weixin.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

public class CheckUtil {
    private static final String token = "weixin";

    public static boolean checkSignature(String signature, String timestamp, String nonce) {
        String[] args = new String[] { token, timestamp, nonce };
        Arrays.sort(args);

        StringBuffer content = new StringBuffer();
        for (int i = 0; i < args.length; i++) {
            content.append(args[i]);
        }
        // 加密
        String temp = getSha1(content.toString());
        return temp.equals(signature);
    }

    public static String getSha1(String str) {
        if (str == null || str.length() == 0) {
            return null;
        }
        char hexDigits[] = { ‘0‘, ‘1‘, ‘2‘, ‘3‘, ‘4‘, ‘5‘, ‘6‘, ‘7‘, ‘8‘, ‘9‘, ‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘, ‘f‘ };
        try {
            MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
            mdTemp.update(str.getBytes("UTF-8"));
            byte[] md = mdTemp.digest();
            int j = md.length;
            char buf[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
                buf[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(buf);
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;

    }
}

MessageUtil

package com.weixin.util;

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;
import com.weixin.po.TextMessage;

public class MessageUtil {
    public static Map<String,String> xmlToMap(HttpServletRequest request){
        Map<String,String> map=new HashMap<String,String>();
        SAXReader read=new SAXReader();

        try {
            InputStream ins=request.getInputStream();
            Document doc =read.read(ins);

            Element root =doc.getRootElement();
            List<Element> list=root.elements();
            for(Element e:list){
                map.put(e.getName(),e.getText());

            }
            ins.close();
            return map;
        } catch (IOException | DocumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();

        }
        return null;

    }

    public static String textMessageToXml(TextMessage textMessage){
        XStream xStream=new XStream();
        xStream.alias("xml", textMessage.getClass());
         return xStream.toXML(textMessage);

    }
}

web.xml文件配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>weixin</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <servlet-name>weixinservlet</servlet-name>
    <servlet-class>com.weixin.servlet.WeixinServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>weixinservlet</servlet-name>
    <url-pattern>/WeixinServlet</url-pattern>
  </servlet-mapping>
</web-app>

微信公众平台的配置
微信公众平台开发教程1


课程结束

版权声明:本文为博主原创文章,未经博主允许不得转载。

微信公众平台开发教程1

上一篇:WooCommerce 微信支付插件


下一篇:MyEclipse8.0 注册码生成代码