88 ,微信公众号开发

目录如下


image.png

1 pom




    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.2.2.RELEASE
         
    
    com.taotao
    weiixin
    0.0.1-SNAPSHOT
    weiixin
    Demo project for Spring Boot

    
        1.8
    

    
        
        
            com.github.binarywang
            weixin-java-mp
            3.4.0
        
        

        
            org.projectlombok
            lombok
            1.16.18
        
        
            org.springframework.boot
            spring-boot-starter-web
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
            
                
                    org.junit.vintage
                    junit-vintage-engine
                
            
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    



2 yml

server:
  port: 80


3,IndexController

package com.taotao.weiixin.controller;

import com.taotao.weiixin.model.TestMessage;
import com.taotao.weiixin.util.CheckUtil;
import com.taotao.weiixin.util.MessageUtil;

import org.dom4j.DocumentException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;

@RestController
public class IndexController {
    private static final String token = "helloworld"; //token
    @Autowired
    private HttpServletRequest req;
  @Autowired
  private HttpServletResponse resp;

    /**
     * get 获取token
     * @param signature
     * @param timestamp
     * @param nonce
     * @param echostr
     * @return
     */
    @RequestMapping(value = "/weChat", method = RequestMethod.GET)
    @ResponseBody
    public String validate(String signature, String timestamp, String nonce, String echostr) {
        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]);//拼接字符串
        }
        String mySignature = CheckUtil.shal(content.toString());
        if (!"".equals(signature) && !"".equals(mySignature) && signature.equals(mySignature)) {
            System.out.println("-----签名校验通过-----");
            return echostr;
        } else {
            System.out.println("-----校验签名失败-----");
            return null;
        }


    }

    /**
     * 接受消息与响应
     * @throws IOException
     * @throws DocumentException
     */
    @RequestMapping(value = "/weChat", method = RequestMethod.POST)
    @ResponseBody
    public  void xml() throws IOException, DocumentException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        Map map = MessageUtil.xmlToMap(req);
        String ToUserName = map.get("ToUserName");
        String FromUserName = map.get("FromUserName");
        String CreateTime = map.get("CreateTime");
        String MsgType = map.get("MsgType");
        String Content = map.get("Content");
        String MsgId = map.get("MsgId");
        String message=null;
        PrintWriter out=resp.getWriter();
        if (MessageUtil.MESSAGE_TEXT.equals(MsgType)) {
            if("1".equals(Content)){
                message=MessageUtil.initText(ToUserName,FromUserName,MessageUtil.firstMenu());
            }else if("2".equals(Content)){
                message=MessageUtil.initText(ToUserName,FromUserName,MessageUtil.sendMenu());
            }else if("?".equals(Content)|| "?".equals(Content)){
                message=MessageUtil.initText(ToUserName,FromUserName,MessageUtil.menuText());
            }

        }else if (MessageUtil.MESSAGE_EVENT.equals(MsgType)){
               String eventType=map.get("Event");
               if(MessageUtil.MESSAGE_SUBSCRIBE.equals(eventType)){
     message=MessageUtil.initText(ToUserName,FromUserName,MessageUtil.menuText());
               }
        }
      out.print(message);
        out.close();
    }


}




4, TestMessage

package com.taotao.weiixin.model;

import lombok.Data;

@Data
public class TestMessage {
    private String ToUserName;//开发者微信号
    private String FromUserName;//发送方账号(一个OpenID)
    private Long CreateTime;//消息创建时间(类型)
    private String MsgType;//消息类型,文本为text
    private String Content;//文本消息内容
    private String MsgId;//消息id,64位整形


}


5, CheckUtil

package com.taotao.weiixin.util;

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

/**
 * 加密校验
 */
public class CheckUtil {
    private static final String token = "helloworld"; //token

    public static boolean checkSignature(String signature, String timestamp, String nonce) throws Exception {
        String[] arr = new String[]{token, timestamp, nonce};
          //排序
        Arrays.sort(arr);
        //生成字符串
        StringBuffer content =new StringBuffer();
        for (int i = 0; i 

6,MessageUtil

package com.taotao.weiixin.util;

import com.taotao.weiixin.model.TestMessage;
import com.thoughtworks.xstream.XStream;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import sun.plugin2.message.TextEventMessage;

import javax.servlet.http.HttpServlet;
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;

public class MessageUtil {

    public static final String MESSAGE_TEXT = "text";
    public static final String MESSAGE_VOICE = "image";
    public static final String MESSAGE_T = "voice";
    public static final String MESSAGE_VIDEO = "video";
    public static final String MESSAGE_LINK = "link";
    public static final String MESSAGE_LOCATION = "location";
    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_CLICK = "CLICK";
    public static final String MESSAGE_VIEW = "VIEW";


    /*
            xml 转换map集合
             */
    public static Map xmlToMap(HttpServletRequest request) throws IOException, DocumentException {
        Map map = new HashMap();
        SAXReader reader = new SAXReader();
        InputStream ins = request.getInputStream();
        Document doc = reader.read(ins);
        Element root = doc.getRootElement();
        List list = root.elements();
        for (Element ele : list) {
            map.put(ele.getName(), ele.getText());
        }

        ins.close();
        return map;
    }


    /**
     * 将文本消息对象转换为xml
     *
     * @param textMessage
     * @return
     */
    public static String textMessageToXml(TestMessage textMessage) {

        XStream xStream = new XStream();
        xStream.alias("xml", textMessage.getClass());
        return xStream.toXML(textMessage);
    }

    //

    //ping 一个主菜单
    public static String menuText() {
        StringBuffer sb = new StringBuffer();
        sb.append("欢迎您的关注,请先按照菜单提示进行操作:\n\n");
        sb.append("1,课程介绍\n");
        sb.append("2,介绍\n");
        sb.append("3,回复 ? 调出此菜单\n");
        return sb.toString();
    }

    public static String initText(String toUserName, String fromUserName,String content) {
        TestMessage text = new TestMessage();
        text.setFromUserName(toUserName);
          text.setToUserName(fromUserName);
         text.setMsgType(MessageUtil.MESSAGE_TEXT);
       text.setCreateTime(System.currentTimeMillis());
       text.setContent(content);
   return textMessageToXml(text);
    }

    public static  String firstMenu(){
        StringBuffer sb = new StringBuffer();
        sb.append("你好,帅哥:\n\n");
        return sb.toString();
    }

    public static String sendMenu() {
        StringBuffer sb = new StringBuffer();
        sb.append("你好,美女:\n\n");
        return sb.toString();
    }
}




git地址: https://gitee.com/lttwj/wj.git

你可能感兴趣的:(88 ,微信公众号开发)