微信公众号关注回调
环境:
1、springboot后端服务
我们可以在用户关注运营的微信公众号后获取微信的用户信息,并将其存入自己的库中,以便后期使用,申请公众号的步骤这里就不涉猎了,具体操作如下:
1、在公众号页面配置服务器回调地址,只能是域名且是80或者443端口
2、在后端服务中提供这个接口,修改完成后点击下面的“提交”按钮,成功回调后后续用户关注取消关注时都会回调这个接口,本文给一个示例接口:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | @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); } } 。。。。。。 } |
核心类定义如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | @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; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | @Getter public enum WxEeventType { /** * 关注公众号 */ SUBSCRIBE( "subscribe" ), /** * 取消关注公众号 */ UNSUBSCRIBE( "unsubscribe" ); private String code; WxEeventType(String code) { this .code = code; } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | @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
分类:
微信小程序和微信公众号
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!