<xml>
<ToUserName><![CDATA[toUser]]></ToUserName>
<FromUserName><![CDATA[FromUser]]></FromUserName>
<CreateTime>123456789</CreateTime>
<MsgType><![CDATA[event]]></MsgType>
<Event><![CDATA[subscribe]]></Event>
</xml>
当关注或者取消关注一个公众号时,微信平台都会给你设置的API接口提交信息,关注时,你可以活的关注着的微信号,作为资源记录,取消关注时,从数据安全角度来讲,应该从你的数据中将该用户的信息清除。
两者不同的地方就在Event值。
关注 | subscribe |
取消关注 | unsubscribe |
定义接收数据的WXMessgeBean。
import javax.xml.bind.annotation.*;
@XmlRootElement(name="xml")
@XmlAccessorType(XmlAccessType.FIELD)
public class WXMessgeBean {
private String FromUserName;
private String ToUserName;
private long CreateTime;
private String MsgType;
private String Event;
private long MsgId;
public long getMsgId() {
return MsgId;
}
public void setMsgId(long msgId) {
MsgId = msgId;
}
public String getPicUrl() {
return PicUrl;
}
public void setPicUrl(String picUrl) {
PicUrl = picUrl;
}
public String getContent() {
return Content;
}
public void setContent(String content) {
Content = content;
}
public String getFromUserName() {
return FromUserName;
}
public void setFromUserName(String fromUserName) {
FromUserName = fromUserName;
}
public String getToUserName() {
return ToUserName;
}
public void setToUserName(String toUserName) {
ToUserName = toUserName;
}
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 getEvent() {
return Event;
}
public void setEvent(String event) {
Event = event;
}
}
接收代码,可以在关注后,发送欢迎语。
@PostMapping(value = "/checktoken", produces = MediaType.APPLICATION_XML_VALUE)
public String receiveWX(HttpServletRequest request, HttpServletResponse response ){
try {
Marshaller marshaller;
Unmarshaller unmarshal;
//你要解析成哪个bean对象,newInstance的参数就是哪个对象
JAXBContext jaxbContext = JAXBContext.newInstance(WXMessgeBean.class);
unmarshal = jaxbContext.createUnmarshaller();
//xml解码成bean对象
WXMessgeBean wxMessgeBean = (WXMessgeBean) unmarshal.unmarshal(request.getInputStream());
if ("subscribe".equals(wxMessgeBean.getEvent())){
WXMessgeBean bean = new WXMessgeBean();
bean.setFromUserName(wxMessgeBean.getToUserName());
bean.setToUserName(wxMessgeBean.getFromUserName());
bean.setCreateTime(new Date().getTime());
bean.setMsgType("text");
bean.setContent("你好,欢迎浏览我的公众号");
marshaller = jaxbContext.createMarshaller();
StringWriter writer = new StringWriter();
marshaller.marshal(bean,writer);
return writer.toString();
}
else if ("unsubscribe".equals(wxMessgeBean.getEvent())){
//这里做取消关注后的处理
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}