微信消息回调处理

引入依赖 处理xml格式数据

            <dependency>
                <groupId>com.thoughtworks.xstream</groupId>
                <artifactId>xstream</artifactId>
                <xstream.version>1.4.11.1</xstream.version>
            </dependency>

回调入口

@Api(tags = "微信API")
@RestController
@RequestMapping("/api/weChat/v1")
@Slf4j
public class WeChatController {
    @PostMapping(value = "/checkSignature/nL",produces = "text/html; charset=utf-8")
    public void weChatMsgHandle(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse) {
        WeChatMsgXmlRequest weChatMsgXmlRequest = resolveXmlData(httpServletRequest);
        if (weChatMsgXmlRequest != null){
            weChatService.weChatMsgHandle(weChatMsgXmlRequest,httpServletResponse);
        }
    }

/**
     * 数据转换
     * @return
     */
    public WeChatMsgXmlRequest resolveXmlData(HttpServletRequest httpServletRequest){
        WeChatMsgXmlRequest weChatMsgXmlRequest = null;
        try {
            String xmlData = new String(IoUtils.toByteArray(httpServletRequest.getInputStream()));
            XStream xstream = new XStream();
            xstream.setClassLoader(WeChatMsgXmlRequest.class.getClassLoader());
            xstream.processAnnotations(WeChatMsgXmlRequest.class);
            xstream.alias("xml", WeChatMsgXmlRequest.class);
            xstream.ignoreUnknownElements();
            weChatMsgXmlRequest = (WeChatMsgXmlRequest) xstream.fromXML(xmlData);
            log.info("【weChatMsgXmlRequest: {}】 ", JsonUtil.object2String(weChatMsgXmlRequest));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("【error】{}", e.getMessage());
        }
        return weChatMsgXmlRequest;
    }
}

接受xml格式实体

@Data
@XStreamAlias("xml")
public class WeChatMsgXmlRequest{

    /**
     * 开发者微信号
     */
    @XStreamAlias("ToUserName")
    private String toUserName;
    /**
     * 发送方帐号(一个OpenID)
     */
    @XStreamAlias("FromUserName")
    private String fromUserName;
    /**
     * 消息创建时间 (整型)
     */
    @XStreamAlias("CreateTime")
    private Long createTime;
    /**
     * 消息类型,文本为text
     */
    @XStreamAlias("MsgType")
    private String msgType;
    /**
     * 文本消息内容
     */
    @XStreamAlias("Content")
    private String content;
    /**
     * 消息id
     */
    @XStreamAlias("MsgId")
    private String msgId;

    /**
     * 事件类型,subscribe(订阅)、unsubscribe(取消订阅)
     */
    @XStreamAlias("Event")
    private String event;
    @XStreamAlias("EventKey")
    private String eventkey;
}

接口定义

@Component
public interface WeChatMsgTypeAbstractHandle{

    /**
     * 如需回复返回xml格式的字符串
     * @param weChatMsgXmlRequest
     * @return
     */
    public abstract String msgHandle(WeChatMsgXmlRequest weChatMsgXmlRequest);

    public abstract WeChatMsgTypeEnum msgType();
}

定义处理器枚举类型

@Getter
public enum WeChatMsgTypeEnum {

    DEFAULT("默认处理器,处理没有配置的消息类型","default"),
    TEXT("文本类型","text"),
    EVENT("事件类型,关注与取消关注","event");

    private String describe;

    private String msgType;

    WeChatMsgTypeEnum(String describe, String msgType) {
        this.describe = describe;
        this.msgType = msgType;
    }

    public static boolean checkMsgType(String msgType){
        for (WeChatMsgTypeEnum index: WeChatMsgTypeEnum.values()) {
            if(index.getMsgType().equals(msgType) ){
                return true;
            }
        }
        return false;
    }
}

定义处理器

import com.ijiaolian.generic.controller.request.WeChatMsgXmlRequest;
import com.ijiaolian.generic.enums.WeChatMsgTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @ Author:
 * @ Date:2022/5/18
 * @ Description:微信文本消息处理
 * @author: 
 */
@Component
@Slf4j
public class WeChatTextHandle implements WeChatMsgTypeAbstractHandle {

    @Override
    public String msgHandle(WeChatMsgXmlRequest weChatMsgXmlRequest) {
        log.info("start Handle WeChatText");

        return "";
    }

    @Override
    public WeChatMsgTypeEnum msgType(){
        return WeChatMsgTypeEnum.TEXT;
    }
}

通过Spting启动监听器 初始化处理事件工厂对象

import com.ijiaolian.generic.enums.WeChatMsgTypeEnum;
import com.ijiaolian.generic.service.wechat.impl.handle.WeChatMsgTypeAbstractHandle;
import com.ijiaolian.spring.SpringUtil;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

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

@Component
public class WeChatMsgTypeFactory implements ApplicationListener<ContextRefreshedEvent> {
    private static Map<String, WeChatMsgTypeAbstractHandle> msgTypeMap = new HashMap<>();

    public static WeChatMsgTypeAbstractHandle getHandle(String msgType){
        if (WeChatMsgTypeEnum.checkMsgType(msgType) && msgTypeMap.containsKey(msgType)){
            return msgTypeMap.get(msgType);
        }

        //没有返回默认的处理器
        return msgTypeMap.get(WeChatMsgTypeEnum.DEFAULT.getMsgType());
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        Map<String, WeChatMsgTypeAbstractHandle> sockets = SpringUtil.getApplicationContext().getBeansOfType(WeChatMsgTypeAbstractHandle.class);
        sockets.forEach((k,v) -> msgTypeMap.put(v.msgType().getMsgType(),v));
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 本文是我自己在秋招复习时的读书笔记,整理的知识点,也是为了防止忘记,尊重劳动成果,转载注明出处哦!如果你也喜欢,那...
    波波波先森阅读 14,206评论 6 86
  • 1.Spring整体架构 1)核心容器(Core Container) Core模块,主要包含了Spring框架基...
    Sponge1128阅读 4,799评论 0 1
  • 欢迎关注公众号“Tim在路上” 1.听说你对JVM有点研究,讲一讲JVM的内存模型吧(我说虚拟机栈,本地方法栈,程...
    Tim在路上阅读 8,977评论 4 91
  • 目录 1 数据交换格式 2 Java反射 3 Spring简介 4 Spring IOC 5 代理 6...
    小小千千阅读 2,990评论 1 0
  • Spring容器高层视图 Spring 启动时读取应用程序提供的Bean配置信息,并在Spring容器中生成一份相...
    Theriseof阅读 7,804评论 1 24