ASP.NET MVC5+EF6+EasyUI 后台管理系统(75)-微信公众平台开发-用户管理

最近代码出现分享问题,360云盘宣布混不下去,所有分享的连接都失效了,最近有时间会把代码转移到百度云,再把文章的代码补回去

前言

本节主要是关注者(即用户)和用户组的管理,微信公众号提供了用户和用户组的管理,我们可以在微信公众号官方里面进行操作,添加备注和标签,以及移动用户组别,同时,微信公众号也提供了相应的接口另我们本地可以操作.我们主要是同步到本地,这样我们可以自己为用户定义更多的信息,以及与本地的业务更好的对接起来.

实现

一、关注与订阅事件

看到我们之前的消息处理类 我们需要扩展一个事件类,这个类与之前消息处理类是一样的分部类,同样来自Senpars微信的SDK

  CustomMessageHandler.cs
复制代码
        /// <summary>
        /// 订阅(关注)事件
        /// </summary>
        /// <returns></returns>
        public override IResponseMessageBase OnEvent_SubscribeRequest(RequestMessageEvent_Subscribe requestMessage)
        {
            var responseMessage = base.CreateResponseMessage<ResponseMessageText>();
            responseMessage.Content = "欢迎关注";
            return responseMessage;
        }

        /// <summary>
        /// 退订
        /// 实际上用户无法收到非订阅账号的消息,所以这里可以随便写。
        /// unsubscribe事件的意义在于及时删除网站应用中已经记录的OpenID绑定,消除冗余数据。并且关注用户流失的情况。
        /// </summary>
        /// <returns></returns>
        public override IResponseMessageBase OnEvent_UnsubscribeRequest(RequestMessageEvent_Unsubscribe requestMessage)
        {
            var responseMessage = base.CreateResponseMessage<ResponseMessageText>();
            responseMessage.Content = "有空再来";
            return responseMessage;
        }
复制代码

里面有2个事件,一个用户关注时触发,一个退订时候触发,所以基本我们无需要进行什么配置,只要加入这个类就可以了

二、本地数据库表

  分组表
  用户表

表字段是根据官网,用户管理对应字段而建立,基本与官方提供的用户信息是一样的,无非是存点用户的姓名,籍贯,头像,关注事件等

三、同步数据

这时我们就可以实现OnEvent_SubscribeRequest (关注时)的代码,基本没有实现难度,步骤如下:

  1. 获得OpenID(requestMessage.FromUserName)
  2. 调用信息接口( UserInfoJson userJson = UserApi.Info(account.AccessToken, requestMessage.FromUserName);)
  3. 把信息添加到本地
  4. 启用订阅时回复的内容(回复在前面已经放出)
复制代码
    /// <summary>
        /// 订阅(关注)事件
        /// </summary>
        /// <returns></returns>
        public override IResponseMessageBase OnEvent_SubscribeRequest(RequestMessageEvent_Subscribe requestMessage)
        {
            ValidationErrors errors = new ValidationErrors();

            using (DBContainer db = new DBContainer())
            {

                IWC_OfficalAccountsBLL account_BLL = new WC_OfficalAccountsBLL()
                {
                    m_Rep = new WC_OfficalAccountsRepository(db)
                };

                //获得当前公众号
                WC_OfficalAccountsModel account = account_BLL.GetById(Id);

                //将用户提取到本地数据库
                WC_UserModel userModel = new WC_UserModel();
                IWC_UserBLL user_BLL = new WC_UserBLL()
                {
                    m_Rep = new WC_UserRepository(db)
                };
                user_BLL.Create(ref errors, userModel);
                UserInfoJson userJson = UserApi.Info(account.AccessToken, requestMessage.FromUserName);
                userModel.Id = ResultHelper.NewId;
                userModel.OpenId = userJson.openid;
                userModel.NickName = userJson.nickname;
                userModel.Sex = userJson.sex;
                userModel.Language = userJson.language;
                userModel.City = userJson.city;
                userModel.Province = userJson.province;
                userModel.Country = userJson.country;
                userModel.HeadImgUrl = userJson.headimgurl;
                userModel.SubscribeTime = ResultHelper.GetTimeByLong(userJson.subscribe_time);
                userModel.UnionId = userJson.unionid;
                userModel.Remark = userJson.remark;
                userModel.GroupId = userJson.groupid.ToString();
                userModel.TagidList = string.Join(",", userJson.tagid_list.ToArray());
                userModel.Subscribe = userJson.subscribe;
                userModel.OfficalAccountId = account.Id;
                IWC_MessageResponseRepository m_Rep = new WC_MessageResponseRepository(db);
                //订阅回复
                List<WC_MessageResponse> messageList = m_Rep.GetSubscribeResponseContent(account.Id);
                if (messageList.Count() > 0)
                {
                    if (messageList[0].Category == (int)WeChatReplyCategory.Text)
                    {
                        var responseMessage = base.CreateResponseMessage<ResponseMessageText>();
                        responseMessage.CreateTime = ResultHelper.NowTime;
                        responseMessage.ToUserName = requestMessage.FromUserName;
                        responseMessage.FromUserName = account.OfficalId;
                        responseMessage.Content = messageList[0].TextContent;
                        return responseMessage;
                    }
                    //图文方式
                    else if (messageList[0].Category == (int)WeChatReplyCategory.Image)
                    {
                        var responseMessage = CreateResponseMessage<ResponseMessageNews>();
                        foreach (var model in messageList)
                        {
                            responseMessage.Articles.Add(new Article()
                            {
                                Title = model.TextContent,
                                Description = model.ImgTextContext,
                                PicUrl = WebChatPara.SiteUrl + model.ImgTextUrl,
                                Url = model.ImgTextLink
                            });
                        }
                        return responseMessage;
                    }//一般很少用到
                    else if (messageList[0].Category == (int)WeChatReplyCategory.Voice)
                    {
                        var responseMessage = base.CreateResponseMessage<ResponseMessageMusic>();
                        responseMessage.Music.MusicUrl = WebChatPara.SiteUrl + messageList[0].MeidaUrl;
                        responseMessage.Music.Title = messageList[0].TextContent;
                        responseMessage.Music.Description = messageList[0].Remark;
                        return responseMessage;
                    }
                }
                var errorResponseMessage = requestMessage.CreateResponseMessage<ResponseMessageText>();
                return errorResponseMessage;
            }
        }
复制代码

退订事件:OnEvent_UnsubscribeRequest(退订没有什么代码,只是标记这个openID已经取消关注)

复制代码
 /// <summary>
        /// 订阅(关注)事件
        /// </summary>
        /// <returns></returns>
        public override IResponseMessageBase OnEvent_SubscribeRequest(RequestMessageEvent_Subscribe requestMessage)
        {
            ValidationErrors errors = new ValidationErrors();

            using (DBContainer db = new DBContainer())
            {

                IWC_OfficalAccountsBLL account_BLL = new WC_OfficalAccountsBLL()
                {
                    m_Rep = new WC_OfficalAccountsRepository(db)
                };
                //获得当前公众号
                WC_OfficalAccountsModel account = account_BLL.GetById(Id);
                //将用户提取到本地数据库
                IWC_UserBLL user_BLL = new WC_UserBLL()
                {
                    m_Rep = new WC_UserRepository(db)
                };
                WC_UserModel userModel = user_BLL.GetById(Id);
                //标记为取消关注
                userModel.Subscribe = 0;
                user_BLL.Edit(ref errors, userModel);
                var errorResponseMessage = requestMessage.CreateResponseMessage<ResponseMessageText>();
                return errorResponseMessage;
            }
        }
复制代码

后台管理

后台管理最直接的效益是分析统计用户的数据状况,这里只演示从服务器同步用户信息,其他都是以前写得发愁的,增删改查了

 前端JS

复制代码
 $("#btnSync").click(function () {
            var rows = $('#List').datagrid('getSelections');
            if (rows.length > 0) {
                var ids = rows.join(",");
                $.each(rows, function (index, row) {
                    ids = ids + row.value + ",";
                });
                $.post("@Url.Action("SyncUser")?ids=" + ids, function (data) {
                    if (data.type == 1)
                        $("#List").datagrid('load');
                        $.messageBox5s('@Resource.Tip', data.message);
                }, "json");
            } else { $.messageBox5s('@Resource.Tip', '@Resource.PlaseChooseToOperatingRecords'); }
        });
复制代码

后端控制器代码

复制代码
 public JsonResult SyncUser(string ids,string officeId)
        {
            if (!string.IsNullOrWhiteSpace(ids))
            {
                //填充数据
                string[] arrs = ids.Split(',');
                List<BatchGetUserInfoData> list = new List<BatchGetUserInfoData>();
                foreach (var m in arrs)
                {
                    list.Add(new BatchGetUserInfoData() {
                        openid = m
                    });
                }

                //批量同步数据
                WC_OfficalAccountsModel accountModel =  account_BLL.GetById(officeId);
                var batchList =  Senparc.Weixin.MP.AdvancedAPIs.UserApi.BatchGetUserInfo(accountModel.AccessToken, list);
                foreach (var info in batchList.user_info_list)
                {
                    WC_UserModel userModel = m_BLL.GetById(info.openid);
                    if (userModel != null)
                    {
                        userModel.City = info.city;
                        userModel.OpenId = info.openid;
                        userModel.Id = info.openid;
                        userModel.HeadImgUrl = info.headimgurl;
                        userModel.Language = info.language;
                        userModel.NickName = info.nickname;
                        userModel.Province = info.province;
                        userModel.Sex = info.sex;
                        m_BLL.Edit(ref errors, userModel);
                    }
                }

                LogHandler.WriteServiceLog(GetUserId(), "Ids:" + ids, "成功", "删除", "WC_User");
                return Json(JsonHandler.CreateMessage(1, Resource.SaveSucceed));
            }
            else
            {
                return Json(JsonHandler.CreateMessage(0, Resource.SaveFail));
            }


        }
复制代码

代码简单易懂:通过OpenID到公众号同步到数据,再将本地数据修改

同步接口在Senparc WX SDK下的Senparc.Weixin.MP.AdvancedAPIs  UserApi

同时这个类也提供了:获取用户信息,获取关注者OpenId信息,修改关注者备注信息,批量获取用户基本信息

示例代码下载:https://yunpan.cn/cM9ffkutawueD  访问密码 2f0d

 

作者: YmNets
出处: http://ymnets.cnblogs.com/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

 

 
 

转载于:https://www.cnblogs.com/zhangxiaolei521/p/6012658.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值