public ActionResult WechatServiceSendMessage(List <NewsInfoView> newsList, bool isPreview = false)
        {
            SysWechatConfig wechat = WeChatCommonService.lstSysWeChatConfig.Find(p => p.AccountManageId == AccountManageID && !p.IsCorp.Value);

            if (wechat == null)
            {
                return(Json(new { results = new { Data = 500 } }));
            }
            try
            {
                NewsInfoView news = newsList[0];
                if ("video".Equals(news.NewsCate))
                {
                    news.ImageContent = SaveBase64ImageToServer(news.ImageContent);
                }
                string           strSendType     = string.Empty;
                SearchUserMPView searchCondition = new SearchUserMPView
                {
                    Group    = news.Group,
                    Province = news.Province,
                    City     = news.City,
                    Sex      = news.Sex
                };
                using (var transactionScope = new TransactionScope(TransactionScopeOption.Suppress, new TransactionOptions {
                    IsolationLevel = IsolationLevel.RepeatableRead
                }))
                {
                    SendResult       returnResult = null;
                    List <NewsModel> articles     = new List <NewsModel>();
                    var lstArticles = GetArticleList(newsList, isPreview, strSendType, searchCondition);
                    if (!isPreview && news.PostType == (int)MessagePostTypeEnum.定时推送)
                    {
                        transactionScope.Complete();
                    }
                    else
                    {
                        string[] openids = null;

                        if (isPreview)
                        {
                            openids = news.SendToPerson;
                        }
                        //发送消息
                        returnResult = WechatCommonMP.SendMsgMP(lstArticles, searchCondition, openids);
                        if (returnResult.errcode == Weixin.ReturnCode.请求成功)
                        {
                            transactionScope.Complete();
                        }
                    }
                }
            }
            catch (Exception e)
            {
                _Logger.Error(e, "An error occurred while sending mp news.");
                // _Logger.Error(e.ToString());
                return(Json(new { results = new { Data = 500 } }));
            }
            return(Json(new { results = new { Data = 200 } }));
        }
Beispiel #2
0
        /// <summary>
        /// 发送客服消息
        /// </summary>
        /// <param name="strMsgType"></param>
        /// <param name="wechat"></param>
        /// <param name="strOpenids"></param>
        /// <param name="obj"></param>
        /// <param name="strTitle"></param>
        /// <param name="strComment"></param>
        /// <returns></returns>
        private static WxJsonResult SendMsgKF(Weixin.MP.GroupMessageType MsgType, SysWechatConfig wechat, string[] strOpenids, object obj, string strTitle = null, string strComment = null)
        {
            WxJsonResult Ret = null;

            foreach (var openId in strOpenids)
            {
                WxJsonResult returnResult = null;

                switch (MsgType)
                {
                case GroupMessageType.text:

                    returnResult = CustomApi.SendText(wechat.WeixinAppId, wechat.WeixinCorpSecret, openId, (string)obj);
                    break;
                //case GroupMessageType.mpnews:

                //    returnResult = CustomApi.SendNews(wechat.WeixinAppId, wechat.WeixinCorpSecret, openId, (List<Article>)obj);
                //    break;
                case GroupMessageType.mpnews:
                    returnResult = CustomApi.SendMpNews(wechat.WeixinAppId, wechat.WeixinCorpSecret, openId, (string)obj);
                    break;

                case GroupMessageType.image:
                    returnResult = CustomApi.SendImage(wechat.WeixinAppId, wechat.WeixinCorpSecret, openId, (string)obj);
                    break;

                case GroupMessageType.video:
                    returnResult = CustomApi.SendVideo(wechat.WeixinAppId, wechat.WeixinCorpSecret, openId, (string)obj, strTitle, strComment);
                    break;

                case GroupMessageType.voice:
                    returnResult = CustomApi.SendVoice(wechat.WeixinAppId, wechat.WeixinCorpSecret, openId, (string)obj);
                    break;
                }

                if (returnResult.errcode != ReturnCode.请求成功)
                {
                    Ret = returnResult;
                }
                else if (Ret == null)
                {
                    Ret = returnResult;
                }
            }

            return(Ret);
        }
Beispiel #3
0
        public List <PersonGroup> GetAllVisibleByGroup(string appId, string groupId, int accountManageId)
        {
            var             id      = int.Parse(appId);
            SysWechatConfig appInfo = null;

            if (id == 0)
            {
                appInfo = lstSysWeChatConfig.FirstOrDefault(a => a.AccountManageId == accountManageId);
            }
            else
            {
                appInfo = lstSysWeChatConfig.SingleOrDefault(a => a.Id == id && a.AccountManageId == accountManageId);
            }

            string token       = (appInfo.IsCorp != null && !appInfo.IsCorp.Value) ? Innocellence.Weixin.MP.CommonAPIs.AccessTokenContainer.GetToken(appInfo.WeixinCorpId, appInfo.WeixinCorpSecret) : Innocellence.Weixin.QY.CommonAPIs.AccessTokenContainer.TryGetToken(appInfo.WeixinCorpId, appInfo.WeixinCorpSecret);
            var    allDeptList = MailListApi.GetDepartmentList(token).department;

            var subDepts            = allDeptList.Where(a => a.parentid == Int32.Parse(groupId));
            List <PersonGroup> list = new List <PersonGroup>();

            foreach (var dept in subDepts)
            {
                PersonGroup person = new PersonGroup();
                person.WeixinId   = dept.id.ToString();
                person.WeixinName = dept.name;
                person.Type       = "Group";
                list.Add(person);
            }


            var members = MailListApi.GetDepartmentMemberInfo(token, Int32.Parse(groupId), 0, 1);

            foreach (var member in members.userlist)
            {
                PersonGroup person = new PersonGroup();
                person.WeixinId   = member.userid;
                person.WeixinName = member.name;
                person.Avatar     = member.avatar;
                person.Type       = "Person";
                list.Add(person);
            }
            return(list);
        }
        public static string DoNewsInfo(NewsInfoView news, SysWechatConfig config, AutoReplyContentEnum type, string strFileName)
        {
            string mediaId = null;

            if (news.materialId.HasValue && news.materialId.Value > 0) //有素材
            {
                IAttachmentsItemService _attachmentsItemService = EngineContext.Current.Resolve <IAttachmentsItemService>();

                NewsInfoView news1;
                mediaId = WechatCommon.GetMediaIDByFileID(news.materialId, _attachmentsItemService, config.WeixinCorpId, out news1);
            }
            else
            {
                mediaId = WechatCommon.GetMediaInfo(type, news, news.AppId);

                NewsToAttachments(news, type.ToString().ToLower(), strFileName);
            }
            return(mediaId);
        }
Beispiel #5
0
        private int AddSysWeChatConfigNode(AccountManage model, MpAppAddView addMpAppView)
        {
            SysWechatConfig sysView = new SysWechatConfig()
            {
                AccountManageId      = model.Id,
                AppName              = model.AccountName,
                CreatedDate          = DateTime.Now,
                CreatedUserID        = User.Identity.Name,
                WeixinToken          = addMpAppView.WeixinToken,
                WeixinEncodingAESKey = addMpAppView.WeixinEncodingAESKey,
                WeixinAppId          = addMpAppView.WeixinAppId,
                WeixinCorpId         = addMpAppView.WeixinAppId,
                WeixinCorpSecret     = addMpAppView.WeixinCorpSecret,
                IsCorp = model.AccountType == 0,
            };

            _Logger.Debug("Create SysConfigView:  {0}", sysView);
            _wechatConfigService.Repository.Insert(sysView);
            int mainMenuId = sysView.Id;

            return(mainMenuId);
        }
Beispiel #6
0
        public static SysWechatConfig GetWeChatConfig(int iAppID)
        {
            var obj = new SysWechatConfig()
            {
                WeixinAppId          = ConfigurationManager.AppSettings["WeixinAppId"],
                WeixinCorpId         = ConfigurationManager.AppSettings["WeixinCorpId"],
                WeixinCorpSecret     = ConfigurationManager.AppSettings["WeixinCorpSecret"],
                WeixinEncodingAESKey = ConfigurationManager.AppSettings["WeixinEncodingAESKey"],
                WeixinToken          = ConfigurationManager.AppSettings["WeixinToken"]
            };

            //var obj = lstWeChatConfig.Find(a => a.WeixinAppId == iAppID.ToString());

            //if (obj == null)
            //{
            //    CacheManager.GetCacher("Default").Remove("SysConfig");
            //    return lstWeChatConfig.Find(a => a.WeixinAppId == iAppID.ToString());
            //}

            return(obj);

            //return obj == null || string.IsNullOrEmpty(obj.ConfigValue) ? strDefault : obj.ConfigValue;
        }
Beispiel #7
0
        //public  SysWechatConfig GetAppSysWechatConfig(string appId) {
        //     return lstSysWeChatConfig.Find(a => a.WeixinAppId == appId);

        //}

        public List <PersonGroup> GetAllPersonAndGroup(string appId, int accountManageId)
        {
            var             id      = int.Parse(appId);
            SysWechatConfig appInfo = null;

            if (id == 0)
            {
                appInfo = lstSysWeChatConfig.FirstOrDefault(a => a.AccountManageId == accountManageId);
            }
            else
            {
                appInfo = lstSysWeChatConfig.SingleOrDefault(a => a.Id == id && a.AccountManageId == accountManageId);
            }
            string token   = (appInfo.IsCorp != null && !appInfo.IsCorp.Value) ? Innocellence.Weixin.MP.CommonAPIs.AccessTokenContainer.GetToken(appInfo.WeixinCorpId, appInfo.WeixinCorpSecret) : Innocellence.Weixin.QY.CommonAPIs.AccessTokenContainer.TryGetToken(appInfo.WeixinCorpId, appInfo.WeixinCorpSecret);
            var    results = AppApi.GetAppInfo(token, int.Parse(appInfo.WeixinAppId));

            List <PersonGroup> list = new List <PersonGroup>();

            if (results.allow_userinfos != null)
            {
                foreach (var person in results.allow_userinfos.user)
                {
                    PersonGroup personGroup = new PersonGroup();

                    personGroup.Type = "Person";

                    var p = MailListApi.GetMember(token, person.userid);
                    personGroup.WeixinName = p.name;
                    personGroup.WeixinId   = p.userid;
                    personGroup.Avatar     = p.avatar;
                    list.Add(personGroup);
                }
            }

            if (results.allow_partys != null)
            {
                foreach (var groupId in results.allow_partys.partyid)
                {
                    PersonGroup personGroup = new PersonGroup();

                    personGroup.Type = "Group";

                    var d = MailListApi.GetDepartmentList(token, groupId).department.FirstOrDefault();
                    if (d != null)
                    {
                        personGroup.WeixinName = d.name;
                        personGroup.WeixinId   = d.id.ToString();
                        list.Add(personGroup);
                    }
                }
            }

            if (results.allow_tags != null)
            {
                var allTagList = MailListApi.GetTagList(token).taglist;
                foreach (var groupId in results.allow_tags.tagid)
                //foreach (var tag in allTagList)
                {
                    PersonGroup personGroup = new PersonGroup();

                    personGroup.Type = "Tag";

                    var tag = allTagList.Find(a => a.tagid == groupId.ToString());
                    if (tag != null)
                    {
                        personGroup.WeixinName = tag.tagname;
                        personGroup.WeixinId   = tag.tagid;
                        list.Add(personGroup);
                    }
                }
            }
            return(list);
        }
        /// <summary>
        /// 同步企业号用户
        /// </summary>
        /// <param name="strUserID"></param>
        /// <param name="user"></param>
        /// <param name="config"></param>
        public static void SyncUserFromWechat(string strUserID, ref SysAddressBookMember user, SysWechatConfig config)
        {
            var token     = WeChatCommonService.GetWeiXinToken(config.Id);
            var apiResult = MailListApi.GetMember(token, strUserID);
            IAddressBookService _addressBookServie = EngineContext.Current.Resolve <IAddressBookService>();
            var Nowtime = System.DateTime.Now;

            //没找到用户,直接新建
            if (user == null || user.Id == 0)
            {
                user = new SysAddressBookMember()
                {
                    Avatar          = apiResult.avatar,
                    AccountManageId = config.AccountManageId,
                    // CompanyID = apiResult.
                    Gender         = apiResult.gender,
                    UserId         = apiResult.userid,
                    WeiXinId       = apiResult.weixinid,
                    UserName       = apiResult.name,
                    Status         = 1,
                    Department     = JsonConvert.SerializeObject(apiResult.department),
                    EmployeeStatus = Innocellence.WeChat.Domain.ModelsView.AddressBookMemberView.EmployeeStatusEnum.U.ToString(),
                    Mobile         = apiResult.mobile,
                    Position       = apiResult.position,
                    Email          = apiResult.email,
                    CreateTime     = DateTime.Now,
                    DeleteFlag     = 0,
                    SubscribeTime  = Nowtime
                };

                _addressBookServie.Repository.Insert(user);
            }
            else
            {
                if (apiResult.errcode == ReturnCode_QY.请求成功)
                {
                    user.Avatar = apiResult.avatar;
                }

                user.Status        = 1;
                user.SubscribeTime = Nowtime;
                _addressBookServie.UpdateMember(user);
            }
        }
Beispiel #9
0
        private static SendResult MPSendMessage(SysWechatConfig wechat, string value,
                                                Weixin.MP.GroupMessageType type, string strTags, string[] strOpenids, string[] PreviewOpenids, string VideoTitle, string VideoContent, bool isKefu)
        {
            SendResult returnResult = null;

            //客服消息
            if (isKefu)
            {
                WxJsonResult retCustom = SendMsgKF(type, wechat, strOpenids, value, VideoTitle, VideoContent);

                return(new SendResult()
                {
                    errcode = retCustom.errcode, errmsg = retCustom.errmsg
                });
            }

            //预览消息
            if (PreviewOpenids != null)
            {
                foreach (var openid in PreviewOpenids)
                {
                    returnResult = Innocellence.Weixin.MP.AdvancedAPIs.GroupMessageApi.SendGroupMessagePreview(wechat.WeixinAppId, wechat.WeixinCorpSecret, type, value, openid);
                }
                return(returnResult);
            }


            //其他正常消息
            if (strTags == "-1" || (null != strOpenids && strOpenids.Length == 1 && "@all".Equals(strOpenids[0]))) //ToAll
            {
                returnResult = Innocellence.Weixin.MP.AdvancedAPIs.GroupMessageApi.SendGroupMessageByGroupId(wechat.WeixinAppId, wechat.WeixinCorpSecret, "", value, type, true, false, 10000);
            }
            else if (!string.IsNullOrEmpty(strTags)) //To Tags
            {
                returnResult = Innocellence.Weixin.MP.AdvancedAPIs.GroupMessageApi.SendGroupMessageByGroupId(wechat.WeixinAppId, wechat.WeixinCorpSecret, strTags, value, type, false, false, 10000);
            }
            else if (strOpenids.Length > 0) //To openids
            {
                //一次最多1W人,超过1W,分批发
                int      iOpenidCount = strOpenids.Length;
                string[] TempOpenids;

                for (int i = 0; i < Math.Ceiling(iOpenidCount / 5000d); i++)
                {
                    int iTo = 5000 * (i + 1) > iOpenidCount ? (iOpenidCount - 5000 * i) : 5000;
                    TempOpenids = new string[iTo];

                    Array.Copy(strOpenids, 5000 * i, TempOpenids, 0, iTo);

                    if (type == GroupMessageType.video) //腾讯接口视频单独处理
                    {
                        returnResult = Innocellence.Weixin.MP.AdvancedAPIs.GroupMessageApi.SendVideoGroupMessageByOpenId(wechat.WeixinAppId, wechat.WeixinCorpSecret, VideoTitle, VideoContent, value, 10000, TempOpenids);
                    }
                    else
                    {
                        returnResult = Innocellence.Weixin.MP.AdvancedAPIs.GroupMessageApi.SendGroupMessageByOpenId(wechat.WeixinAppId, wechat.WeixinCorpSecret, type, value, 10000, TempOpenids);
                    }
                }
            }

            return(returnResult);
        }
        public ActionResult PostQuickResponse(string openId, List <NewsInfoView> newsList)
        {
            try
            {
                var news = newsList[0];
                if ("video".Equals(news.NewsCate))
                {
                    news.ImageContent = SaveBase64ImageToServer(news.ImageContent);
                }
                SysWechatConfig wechat = WeChatCommonService.lstSysWeChatConfig.Find(p => p.Id == news.AppId && !p.IsCorp.Value);
                if (wechat == null)
                {
                    return(Json(new { results = new { Data = 500 } }));
                }
                ResponseMessageBase response = null;

                var lstArticles = GetArticleList(newsList, false, news.NewsCate, null, false);

                //发送消息
                WechatCommonMP.SendMsg(news.NewsCate, "", lstArticles, "", new string[] { openId }, null, true);

                switch (news.NewsCate)
                {
                case "text":
                    response = new ResponseMessageText()
                    {
                        Content = news.NewsContent
                    };
                    //returnResult = CustomApi.SendText(wechat.WeixinAppId, wechat.WeixinCorpSecret, openId, news.NewsContent);
                    break;

                case "news":
                    //var lstArticles = GetArticleList(newsList, false);
                    //List<NewsModel> articles = new List<NewsModel>();
                    //string host = CommonService.GetSysConfig("Content Server", "");
                    //if (host.EndsWith("/"))
                    //{
                    //    host = host.Substring(0, host.Length - 1);
                    //}
                    //for (int i = 0; i < lstArticles.Count; i++)
                    //{
                    //    var item = lstArticles[i];
                    //    var filePath = Server.MapPath("~/") + item.ImageCoverUrl.Insert(item.ImageCoverUrl.LastIndexOf('.'), "_T");
                    //    if (0 == i)
                    //    {
                    //        filePath = filePath.Replace("_T", "_B");
                    //    }
                    //    var ret0 = Innocellence.Weixin.MP.AdvancedAPIs.MediaApi.UploadTemporaryMedia(wechat.WeixinAppId, wechat.WeixinCorpSecret, Weixin.MP.UploadMediaFileType.thumb, filePath);
                    //    var picUrl = (host + item.ImageCoverUrl).Replace("\\", "/");
                    //    var url = string.Format("{0}/MPNews/ArticleInfo/WxDetail/{1}?wechatid={2}&isPreview={3}", host, item.Id, item.AppId, false);

                    //    articles.Add(new NewsModel() { title = item.ArticleTitle, content = WechatCommonMP.ImageConvert(item.ArticleContent, wechat.Id), thumb_url = picUrl, thumb_media_id = ret0.thumb_media_id, content_source_url = url });
                    //}
                    //var ret = Innocellence.Weixin.MP.AdvancedAPIs.MediaApi.UploadTemporaryNews(wechat.WeixinAppId, wechat.WeixinCorpSecret, 10000, articles.ToArray());
                    //returnResult = CustomApi.SendMpNews(wechat.WeixinAppId, wechat.WeixinCorpSecret, openId, ret.media_id);
                    string _newsHost = Infrastructure.Web.Domain.Service.CommonService.GetSysConfig("WeChatUrl", "");
                    response = new ResponseMessageNews()
                    {
                        Articles = lstArticles.Select(a => new Article()
                        {
                            Title       = a.ArticleTitle,
                            Url         = string.Format("{0}/{3}/ArticleInfo/wxdetail/{1}?wechatid={2}&isAutoReply={4}", _newsHost, a.Id, news.AppId, "mpnews", 0),// _newsHost + "/News/ArticleInfo/wxdetail/" + a.Id + "?wechatid=" + appId,
                            PicUrl      = _newsHost + a.ImageCoverUrl,
                            Description = a.ArticleComment
                        }).ToList()
                    };
                    break;

                case "image":
                    //WechatCommon.GetMediaInfo(AutoReplyContentEnum.IMAGE, news, news.AppId);
                    //returnResult = CustomApi.SendImage(wechat.WeixinAppId, wechat.WeixinCorpSecret, openId, news.MediaId);
                    response = new ResponseMessageImage()
                    {
                        Image = new Weixin.Entities.Image()
                        {
                            MediaId = news.MediaId
                        }
                    };
                    break;

                case "video":
                    //WechatCommon.GetMediaInfo(AutoReplyContentEnum.VIDEO, news, news.AppId);
                    ////var ret1 = Innocellence.Weixin.MP.AdvancedAPIs.GroupMessageApi.GetOpenIdVideoMediaIdResult(wechat.WeixinAppId, wechat.WeixinCorpSecret, news.MediaId, news.NewsTitle, news.NewsComment);
                    ////news.MediaId = ret1.media_id;
                    ////news.MediaCreateTime = ret1.created_at;
                    //returnResult = CustomApi.SendVideo(wechat.WeixinAppId, wechat.WeixinCorpSecret, openId, news.MediaId, news.NewsTitle, news.NewsComment);
                    response = new ResponseMessageVideo()
                    {
                        Video = new Video()
                        {
                            MediaId = news.MediaId
                        }
                    };
                    break;

                case "voice":
                    //WechatCommon.GetMediaInfo(AutoReplyContentEnum.VOICE, news, news.AppId);
                    //returnResult = CustomApi.SendVoice(wechat.WeixinAppId, wechat.WeixinCorpSecret, openId, news.MediaId);
                    response = new ResponseMessageVoice()
                    {
                        Voice = new Voice()
                        {
                            MediaId = news.MediaId
                        }
                    };
                    break;

                default:
                    throw new Exception("Invalid media type.");
                }
                //var user = _WechatMPUserService.GetUserByOpenId(openId);
                response.ToUserName = openId;
                var task = _WeChatUserRequestMessageLogHandler.WriteResponseLogMP(new List <Innocellence.Weixin.Entities.IResponseMessageBase> {
                    response
                }, news.AppId.ToString(), false);
                return(Json(new { results = new { Data = 200, Object = task.Result } }));
            }
            catch (Exception e)
            {
                _Logger.Error(e, "An error occurred while PostQuickResponse.");
                return(Json(new { results = new { Data = 500, Message = e.Message } }));
            }
        }
        /// <summary>
        /// 同步微信用户
        /// </summary>
        /// <param name="WeixinOpenId"></param>
        /// <param name="userInfo"></param>
        /// <param name="config"></param>
        public static void SycUserFromWeixinMP(string WeixinOpenId, ref WechatMPUser userInfo, SysWechatConfig config)
        {
            Logger.Debug("SycUserFromWeixin");
            Innocellence.Weixin.MP.AdvancedAPIs.User.BatchGetUserInfoData user = new Innocellence.Weixin.MP.AdvancedAPIs.User.BatchGetUserInfoData
            {
                openid = WeixinOpenId,
                lang   = Language.zh_CN.ToString()
            };
            var result = Innocellence.Weixin.MP.AdvancedAPIs.UserApi.BatchGetUserInfo(config.WeixinAppId,
                                                                                      config.WeixinCorpSecret,
                                                                                      new List <Innocellence.Weixin.MP.AdvancedAPIs.User.BatchGetUserInfoData> {
                user
            });

            Logger.Debug("SycUserFromWeixin result");
            if (result != null && result.user_info_list != null)
            {
                Logger.Debug("result count :{0}", result.user_info_list.Count);
                var objuserInfo = result.user_info_list.Select(a => WechatMPUserView.ConvertWeChatUserToMpUser(a, config.AccountManageId.Value, config.Id)).ToList().FirstOrDefault();
                if (userInfo == null)
                {
                    userInfo = objuserInfo;
                }
                if (objuserInfo != null)
                {
                    Logger.Debug("SycUserFromWeixin userInfo: " + userInfo.OpenId + userInfo.NickName);
                    objuserInfo.AccountManageId = config.AccountManageId;
                    if (objuserInfo.SubScribe == 0) //未关注
                    {
                        objuserInfo.Id         = userInfo.Id;
                        objuserInfo.IsCanceled = true;
                        userInfo = objuserInfo;
                    }
                    else
                    {
                        objuserInfo.Id = userInfo.Id;
                    }
                    Logger.Debug("SycUserFromWeixin userInfo id: {0}, SubScribe: {1}", objuserInfo.Id, objuserInfo.SubScribe);
                    IWechatMPUserService wechatMPUserService = EngineContext.Current.Resolve <IWechatMPUserService>();
                    wechatMPUserService.RegistToWeiXin(objuserInfo);
                    Logger.Debug("SycUserFromWeixin userInfo updated.");
                }
                else
                {
                    Logger.Debug("SycUserFromWeixin Error objuserInfo=null.{0}", WeixinOpenId);
                }
            }
        }
Beispiel #12
0
        /// <summary>
        /// 设置企业号应用
        /// </summary>
        /// <param name="data"></param>
        //[AllowAnonymous]
        //[HttpPost]
        public ActionResult SetAppInfo(SetAppPostData data, string Id)
        {
            //更新SysWechatConfig数据库
            //验证错误
            if (!BeforeAddOrUpdate(data, Id) || !ModelState.IsValid)
            {
                return(Json(GetErrorJson(), JsonRequestBehavior.AllowGet));
            }
            #region 更新菜单
            var loginUser = (SysUser)Session["UserInfo"];
            var objModel  = sys.Repository.GetByKey(int.Parse(Request["ConfigID"]));
            var menuModel = _sysMenuService.GetMenusByUserID(loginUser, null).Where(a => a.AppId == int.Parse(Request["ConfigID"]) && a.NavigateUrl.Equals("/")).FirstOrDefault();
            if (menuModel != null)
            {
                menuModel.MenuName  = data.name;
                menuModel.MenuTitle = data.name;
                _sysMenuService.Repository.Update(menuModel);
            }
            #endregion

            var Config = WeChatCommonService.GetWeChatConfigByID(int.Parse(Request["ConfigID"]));

            #region  步到微信
            //var strToken = Rtntoken(int.Parse(data.agentid));
            var strToken = WeChatCommonService.GetWeiXinToken(Config.Id);
            if (!string.IsNullOrEmpty(Request["MediaID"]))
            {
                data.logo_mediaid = Request["MediaID"];
            }
            if (string.IsNullOrEmpty(data.redirect_domain))
            {
                data.redirect_domain = string.Empty;
            }

            AppApi.SetApp(strToken, data);
            #endregion

            #region 存DB
            var objNewModel = new SysWechatConfig();
            #region 从微信获取App logo, 存入objNewModel
            try
            {
                GetAppInfoResult result = AppApi.GetAppInfo(strToken, int.Parse(Config.WeixinAppId));
                objNewModel.CoverUrl = result.square_logo_url;
            }
            catch (Exception ex)
            {
                _Logger.Error("an error occurd when get app logo :{0}", ex);
            }
            #endregion
            var lst = new List <string>();
            objNewModel.Id      = objModel.Id;
            objNewModel.AppName = data.name;

            if (Request["CorpID"] != objModel.WeixinCorpId && !string.IsNullOrEmpty(Request["Secret"]))
            {
                objNewModel.WeixinCorpId = Request["CorpID"];
            }
            if (Request["Secret"] != objModel.WeixinCorpSecret && Request["Secret"] != "******" && !string.IsNullOrEmpty(Request["Secret"]))
            {
                objNewModel.WeixinCorpSecret = Request["Secret"];
            }
            if (Request["Welcome"] != objModel.WelcomeMessage)
            {
                objNewModel.WelcomeMessage = Request["Welcome"];
            }
            if (Request["Token"] != objModel.WeixinToken && Request["Token"] != "******" && !string.IsNullOrEmpty(Request["Token"]))
            {
                objNewModel.WeixinToken = Request["Token"];
            }
            if (Request["EncodingAESKey"] != objModel.WeixinEncodingAESKey && Request["EncodingAESKey"] != "******" && !string.IsNullOrEmpty(Request["EncodingAESKey"]))
            {
                objNewModel.WeixinEncodingAESKey = Request["EncodingAESKey"];
            }

            sys.Repository.Update(objNewModel);
            #endregion

            #region 清理缓存
            //清理缓存
            if (WeChatCommonService.lstDepartment(AccountManageID) != null)
            {
                cacheManager.Remove("DepartmentList");
            }
            if (WeChatCommonService.lstTag(AccountManageID) != null)
            {
                cacheManager.Remove("TagItem");
            }

            if (WeChatCommonService.lstUser(AccountManageID) != null)
            {
                cacheManager.Remove("UserItem" + AccountManageID);
            }
            if (WeChatCommonService.lstSysWeChatConfig != null)
            {
                cacheManager.Remove("SysWeChatConfig");
            }

            var newMenus = _sysMenuService.GetMenusByUserID(loginUser, null);
            loginUser.Menus     = newMenus;
            Session["UserInfo"] = loginUser;
            #endregion

            return(Json(doJson(null)));
        }