环境:
1、springboot后端服务
我们可以在用户关注运营的微信公众号后获取微信的用户信息,并将其存入自己的库中,以便后期使用,申请公众号的步骤这里就不涉猎了,具体操作如下:
1、在公众号页面配置服务器回调地址,只能是域名且是80或者443端口
2、在后端服务中提供这个接口,修改完成后点击下面的“提交”按钮,成功回调后后续用户关注取消关注时都会回调这个接口,本文给一个示例接口:
@RequestMapping(value = "/xxx/onWxMsg") public String checkWxToken(@RequestParam(value = "signature", required = false) String signature, @RequestParam(value = "timestamp", required = false) String timestamp, @RequestParam(value = "echostr", required = false) String echostr, @RequestBody(required = false) WxServiceMsgDto wxServiceMsgDto) { if (StringUtils.isNotEmpty(echostr)) { // 用于微信校验接口存在性,必须返回echostr return echostr; } // 只处理订阅与取消订阅消息 if (null != wxServiceMsgDto && StringUtils.isNotEmpty(wxServiceMsgDto.getMsgType()) && StringUtils.isNotEmpty(wxServiceMsgDto.getEvent())) { String msgType = wxServiceMsgDto.getMsgType(); String event = wxServiceMsgDto.getEvent(); boolean isSubcribe = WxMessageType.EVENT.getCode().equals(msgType) && (WxEeventType.SUBSCRIBE.getCode().equals(event) || WxEeventType.UNSUBSCRIBE.getCode().equals(event)); if (isSubcribe) { WxEeventType wxEeventType = WxEeventType.SUBSCRIBE.getCode().equals(event) ? WxEeventType.SUBSCRIBE : WxEeventType.UNSUBSCRIBE; wxService.onFollowCallback(wxServiceMsgDto, wxEeventType); } } 。。。。。。 }
核心类定义如下:
@XmlRootElement(name = "xml") @XmlAccessorType(XmlAccessType.FIELD) @Data public class WxServiceMsgDto { @XmlElement(name = "Event") private String event; @XmlElement(name = "Content") private String content; @XmlElement(name = "MsgType") private String msgType; @XmlElement(name = "ToUserName") private String toUserName; /** * fromUserName为关注人的openId **/ @XmlElement(name = "FromUserName") private String fromUserName; @XmlElement(name="CreateTime") private String createTime; }
@Getter public enum WxEeventType { /** * 关注公众号 */ SUBSCRIBE("subscribe"), /** * 取消关注公众号 */ UNSUBSCRIBE("unsubscribe"); private String code; WxEeventType(String code) { this.code = code; } }
@Getter public enum WxMessageType { /** * 事件类型,比如订阅与取消订阅 */ EVENT("event"), /** * 向公众号发送的文字消息 */ TEXT("text"); private String code; WxMessageType(String code) { this.code = code; } }
根据WxServiceMsgDto对象中msgType属性为event且event属性为subscribe或者unsubscribe的消息进行处理,其他类型回调都抛弃。
3、根据openId调用微信的/cgi-bin/user/info获取用户的基础信息,参考微信官网微信开放文档
————————————————
原文链接:https://blog.csdn.net/john1337/article/details/121860490
标签:code,String,微信,WxEeventType,private,公众,回调,event From: https://www.cnblogs.com/xianz666/p/18675154