public QyJsonResult Push(int appId)
        {
            var categories = CommonService.lstCategory.Where(x => x.AppId == appId && (x.CategoryCode == null || !x.CategoryCode.EndsWith(_endFix, true, CultureInfo.CurrentCulture)) && (x.IsDeleted == null || x.IsDeleted == false) && (x.IsVirtual == null || x.IsVirtual == false)).OrderBy(x => x.CategoryOrder).Select(x =>
            {
                var function = x.Function.IsNullOrEmpty() ? null : JsonHelper.FromJson <ButtonReturnType>(x.Function);
                return(new CategroyChild
                {
                    Id = x.Id,
                    key = x.CategoryCode,
                    name = function == null ? x.CategoryName : function.Button.name,
                    sub_button = new List <MenuFull_RootButton>(),
                    type = function == null ? null : function.Button.type,
                    ParentId = x.ParentCode.GetValueOrDefault(),
                    order = x.CategoryOrder.GetValueOrDefault(),
                    url = function == null ? null : function.Button.url,
                });
            }).ToList();

            var buttons = new List <MenuFull_RootButton>();

            categories.Where(x => x.ParentId == 0).ToList().ForEach(x => GenerateMenuHierarchy(categories, x, buttons));

            var menu = new GetMenuResultFull {
                menu = new MenuFull_ButtonGroup {
                    button = buttons
                }
            };
            var btnMenus = CommonApi.GetMenuFromJsonResult(menu).menu;
            var result   = CommonApi.CreateMenu(WeChatCommonService.GetWeiXinToken(appId), appId, btnMenus);

            return(result);
        }
        public JsonResult GetSubDepartment(string id, string departlist)
        {
            string accessToken = WeChatCommonService.GetWeiXinToken(AppId);
            //修改Department数据源 先根据AppId获取应用信息 allowPartys  Pending

            var config = WeChatCommonService.GetWeChatConfigByID(AppId);

            var app = AppApi.GetAppInfo(accessToken, int.Parse(config.WeixinAppId));
            GetAppInfo_AllowPartys allowPartys = app.allow_partys;

            // TODO: async/await执行较长等待的task
            var subdepartList = MailListApi.GetDepartmentList(accessToken, Int32.Parse(id)).department;//.Where(x => allowPartys.partyid.Contains(x.id)).ToList()

            var listReturn = EasyUITreeData.GetTreeData(subdepartList, "id", "name", "parentid");

            listReturn.ForEach(a =>
            {
                a.state = "closed";
            });

            if (!string.IsNullOrEmpty(departlist))
            {
                var departids = departlist.Split('|');
                EasyUITreeData.SetChecked <string>(departids.ToList(), listReturn);
            }

            return(Json(listReturn, JsonRequestBehavior.AllowGet));
        }
Exemplo n.º 3
0
        public override void PrepareEditData()
        {
            //修改tag数据源 由于是公共的发消息 没选APP之前不知道应用的allow_tags 取全部tag
            string accessToken = WeChatCommonService.GetWeiXinToken(AppId);
            var    tagList     = MailListApi.GetTagList(accessToken).taglist;

            ViewBag.taglist = tagList;
        }
        public virtual void PrepareEditData()
        {
            string accessToken = WeChatCommonService.GetWeiXinToken(AppId);
            //修改tag数据源 先根据AppId获取应用信息 allowTag Pending
            var app = AppApi.GetAppInfo(accessToken, AppId);
            GetAppInfo_AllowTags allowTags = app.allow_tags;

            var tagList = MailListApi.GetTagList(accessToken).taglist;//.Where(x=> allowTags.tagid.Contains(int.Parse(x.tagid))).ToList()

            ViewBag.taglist = tagList;
        }
Exemplo n.º 5
0
        public int UpdateEmployee(LocalSADEntity entity)
        {
            var updateEmployee = Repository.Entities.Where(t => t.LilyId.ToUpper() == entity.LillyID.ToUpper()).FirstOrDefault();

            if (updateEmployee == null)
            {
                return(0);
            }

            updateEmployee.EmployeeTime = entity.ACTL_HIRE_DT;
            updateEmployee.BaseLocation = entity.BS_LCTN_GLBL;
            updateEmployee.Tag          = CommonService.GetSysConfig("TagNameNewEmployee", "");

            //过滤条件暂时删除
            //if (updateEmployee.EmployeeTime < DateTime.Now.AddMonths(-6).Date)
            //{
            //    return 0;
            //}

            if (!string.IsNullOrEmpty(updateEmployee.Tag))
            {
                var taglist = WeChatCommonService.lstTag.Where(x => x.tagname == updateEmployee.Tag);
                int tagid   = taglist.FirstOrDefault() != null?Convert.ToInt32(taglist.FirstOrDefault().tagid) : 0;

                string[] userlist = new string[1];
                userlist[0] = entity.LillyID;
                //不超过6个月时,添加标签
                if (tagid != 0 && DateTime.Today <= (updateEmployee.EmployeeTime.AddMonths(6)))
                {
                    var tagMemberResult = MailListApi.GetTagMember(WeChatCommonService.GetWeiXinToken(0), tagid);
                    var hasTag          = tagMemberResult.userlist.Select(a => a.userid.ToUpper() == entity.LillyID.ToUpper()).FirstOrDefault();
                    if (!hasTag)
                    {
                        MailListApi.AddTagMember(WeChatCommonService.GetWeiXinToken(0), tagid, userlist);
                    }
                }

                //超过7个月时,移除标签
                if (tagid != 0 && DateTime.Today > (updateEmployee.EmployeeTime.AddMonths(7)))
                {
                    MailListApi.DelTagMember(WeChatCommonService.GetWeiXinToken(0), tagid, userlist);
                }
            }



            return(Repository.Update(updateEmployee));
        }
Exemplo n.º 6
0
        //上传多媒体文件
        public JsonResult PostImage(string appid)
        {
            UploadForeverResultJson ret = new UploadForeverResultJson();

            var Config = WeChatCommonService.GetWeChatConfigByID(int.Parse(appid));

            if (Request.Files.Count > 0)
            {
                //var strToken = Rtntoken(int.Parse(appid));
                var strToken = WeChatCommonService.GetWeiXinToken(Config.Id);

                Dictionary <string, Stream> dic     = new Dictionary <string, Stream>();
                HttpPostedFileBase          objFile = Request.Files[0];
                var filename = objFile.FileName;
                var stream   = objFile.InputStream;
                dic.Add(filename, stream);
                // ret = MediaApi.UploadForeverMedia(strToken, appid, UploadMediaFileType.image, dic, "");
                // ret = MediaApi.UploadPermanent(strToken, UploadMediaFileType.image, dic, "");
                ret = MediaApi.AddMaterial(strToken, UploadMediaFileType.image, dic, "");
            }
            return(Json(ret, JsonRequestBehavior.AllowGet));
        }
Exemplo n.º 7
0
        //public List<ArticleConfig> SendArticleToNewEmployee()
        //{
        //var jsonString = CommonService.GetSysConfig("SendArticleCycle", "[]");
        //List<ArticleConfig> config = JsonConvert.DeserializeObject<List<ArticleConfig>>(jsonString);
        //foreach (var item in config)
        //{
        //    item.employeeLst = GetNewEmployee(item);
        //    foreach (var employee in item.employeeLst)
        //    {
        //        item.UserLst += employee.LilyId + "|";
        //    }
        //    item.UserLst = item.UserLst == null ? "" : item.UserLst.Substring(0, item.UserLst.Length - 1);
        //}
        //return config;
        //}


        //NewEmployee表已弃掉
        public int AddNewEmployee(LocalSADEntity entity)
        {
            NewEmployee newEmployee = new NewEmployee();

            newEmployee.Name         = entity.ChineseName;
            newEmployee.LilyId       = entity.LillyID;
            newEmployee.Email        = entity.Email;
            newEmployee.Gender       = entity.Gender;
            newEmployee.Tag          = CommonService.GetSysConfig("TagNameNewEmployee", "");
            newEmployee.EmployeeTime = entity.ACTL_HIRE_DT;
            newEmployee.BaseLocation = entity.BS_LCTN_GLBL;
            if (!string.IsNullOrEmpty(newEmployee.Tag))
            {
                //var taglist = MailListApi.GetTagList(WeChatCommonService.GetWeiXinToken(0)).taglist.Where(x => x.tagname == newEmployee.Tag);
                var taglist = WeChatCommonService.lstTag.Where(x => x.tagname == newEmployee.Tag);
                int tagid   = taglist.FirstOrDefault() != null?Convert.ToInt32(taglist.FirstOrDefault().tagid) : 0;

                string[] userlist = new string[1];
                userlist[0] = entity.LillyID;
                if (tagid != 0 && DateTime.Today <= (newEmployee.EmployeeTime.AddMonths(6)))
                {
                    MailListApi.AddTagMember(WeChatCommonService.GetWeiXinToken(0), tagid, userlist);
                }
            }
            //过滤条件暂时删除
            //if (newEmployee.EmployeeTime >= DateTime.Now.AddMonths(-6).Date)
            try
            {
                Repository.Insert(newEmployee);
            }
            //else
            catch
            {
                return(0);
            }
            return(1);
        }
 private static GetTagMemberResult GetTagMembers(int tagId, int appId)
 {
     //return _cacheManager.Get("SmartphoneMenuPermissionManager.Tagmember", () => MailListApi.GetTagMember(GetToken(), int.Parse(tagId)));
     return(MailListApi.GetTagMember(WeChatCommonService.GetWeiXinToken(appId), tagId));
 }
 private static GetTagListResult GetTagList(int appId)
 {
     return(_cacheManager.Get("SmartphoneMenuPermissionManager.tagList", () => MailListApi.GetTagList(WeChatCommonService.GetWeiXinToken(appId))));
 }
        public static List <object> CreateNewsResponseMessage(AutoReplyContentView content, int appId, bool isCorp, bool isSafe, bool isAutoReply = false)
        {
            // var photoTextMsg = this.CreateResponseMessage<ResponseMessageNews>();
            var Articles = new List <object>();

            if (content.IsNewContent.Value)
            {
                var info    = JsonConvert.DeserializeObject <List <NewsInfoView> >(content.Content);
                var configs = Infrastructure.Web.Domain.Service.CommonService.lstSysConfig;
                // var config = configs.Where(a => a.ConfigName.Equals("Content Server", StringComparison.CurrentCultureIgnoreCase)).First();
                //var contentConfig = configs.Where(a => a.ConfigName.Equals("Content Server", StringComparison.CurrentCultureIgnoreCase)).First();
                string host = Infrastructure.Web.Domain.Service.CommonService.GetSysConfig("Content Server", "").TrimEnd('/');// config.ConfigValue;
                //if (host.EndsWith("/"))
                //{
                //    host = host.Substring(0, host.Length - 1);
                //}

                int ii = 0;
                foreach (var entity in info)
                {
                    if (ii == 0) //位置不同,缩略图的比例不一样
                    {
                        entity.ImageSrc = WechatCommon.doGetFileCover(entity.ImageSrc, "_B");
                    }
                    else
                    {
                        entity.ImageSrc = WechatCommon.doGetFileCover(entity.ImageSrc, "_T");
                    }

                    ii++;

                    var picUrl = host + entity.ImageSrc;
                    //var url = host + "/News/ArticleInfo/wxdetail/" + content.AutoReplyId + "?wechatid=" + appId;// "&subId=" + item.Id;
                    var url = string.Format("{0}/{1}/Message/GetNews?id={2}&wechatid={2}&type={3}&subId={4}", host, isCorp ? "news" : "mpnews",
                                            content.AutoReplyId, appId, (int)NewsTypeEnum.AutoReply, entity.Id); //host + "/News/Message/GetNews?id=" + content.AutoReplyId + "&wechatid=" + appId + "&type=" + (int)NewsTypeEnum.AutoReply;
                    var newArticle = new Article()
                    {
                        Title       = entity.NewsTitle,
                        Url         = url,
                        PicUrl      = picUrl,
                        Description = entity.NewsComment
                    };
                    Articles.Add(newArticle);
                }
            }
            else
            {
                List <ArticleInfoView> articleList = new List <ArticleInfoView>();
                if (content.SecondaryType == (int)AutoReplyNewsEnum.MANUAL)
                {
                    List <int> articleIds = content.NewsID.Trim(',').Split(',').ToList().Select(n => int.Parse(n)).ToList();
                    if (articleIds.Count > 0)
                    {
                        log.Debug("article count :{0}.", articleIds.Count);
                        var lst = ((DbSet <ArticleInfo>)_articleInfoService.Repository.Entities).AsNoTracking()
                                  .Where(t => t.AppId == appId && articleIds.Contains(t.Id) && t.IsDeleted == false).ToList()
                                  .Select(a => (ArticleInfoView) new ArticleInfoView().ConvertAPIModelListWithContent(a)).ToList();

                        //解决顺序问题
                        foreach (var aID in articleIds)
                        {
                            var al = lst.Find(a => a.Id == aID);
                            if (al != null)
                            {
                                articleList.Add(al);
                            }
                        }
                    }
                }
                else if (content.SecondaryType == (int)AutoReplyNewsEnum.LATEST)
                {
                    articleList.AddRange(((DbSet <ArticleInfo>)_articleInfoService.Repository.Entities).AsNoTracking()
                                         .Where(t => t.AppId == appId && t.IsDeleted == false)
                                         .OrderBy("Id", System.ComponentModel.ListSortDirection.Descending)
                                         .Take(int.Parse(content.Content)).ToList()
                                         .Select(a => (ArticleInfoView) new ArticleInfoView().ConvertAPIModelListWithContent(a)).ToList());
                }
                ;

                // articleList = articleList.Distinct().OrderByDescending(t => t.PublishDate).ToList();

                var token = WeChatCommonService.GetWeiXinToken(appId);
                int ii    = 0;
                foreach (var a in articleList)
                {
                    log.Debug("Start ID:{0} ImageCoverUrl:{1} ", a.Id, a.ImageCoverUrl);

                    if (ii == 0) //位置不同,缩略图的比例不一样
                    {
                        a.ImageCoverUrl = WechatCommon.doGetFileCover(a.ImageCoverUrl, "_B");
                    }
                    else
                    {
                        a.ImageCoverUrl = WechatCommon.doGetFileCover(a.ImageCoverUrl, "_T");
                    }

                    ii++;


                    if (isSafe)
                    {
                        var newArticle = new MpNewsArticle()
                        {
                            title = a.ArticleTitle,
                            content_source_url = string.Format("{0}/{3}/ArticleInfo/wxdetail/{1}?wechatid={2}&isAutoReply={4}", _newsHost, a.Id, appId, isCorp ? "news" : "mpnews", isAutoReply ? 1 : 0),// _newsHost + "/News/ArticleInfo/wxdetail/" + a.Id + "?wechatid=" + appId,
                            //content = _newsHost + a.ImageCoverUrl,
                            digest         = a.ArticleComment,
                            content        = a.ArticleContent,// WechatCommonMP.ImageConvert(a.ArticleContent, appId),
                            author         = a.CreatedUserID,
                            show_cover_pic = "0",
                            thumb_media_id = WechatCommon.GetMediaId(a.ImageCoverUrl, token)
                        };
                        log.Debug("Creating MPNews - \r\n\tTitle: " + newArticle.title + "\r\n\tUrl: " + newArticle.content_source_url + "\r\n\tPush Image: " + newArticle.thumb_media_id);
                        Articles.Add(newArticle);
                    }
                    else
                    {
                        var newArticle = new Article()
                        {
                            Title       = a.ArticleTitle,
                            Url         = string.Format("{0}/{3}/ArticleInfo/wxdetail/{1}?wechatid={2}&isAutoReply={4}", _newsHost, a.Id, appId, isCorp ? "news" : "mpnews", isAutoReply ? 1 : 0),// _newsHost + "/News/ArticleInfo/wxdetail/" + a.Id + "?wechatid=" + appId,
                            PicUrl      = _newsHost + a.ImageCoverUrl.Replace("\\", "/").TrimStart('/'),
                            Description = a.ArticleComment
                        };
                        log.Debug("Creating News - \r\n\tTitle: " + newArticle.Title + "\r\n\tUrl: " + newArticle.Url + "\r\n\tPush Image: " + newArticle.PicUrl);
                        Articles.Add(newArticle);
                    }
                }
            }

            return(Articles);
        }
Exemplo n.º 11
0
        public bool SendMail(int id, string question, string jsonString, string request, string baseUrl, string title)
        {
            //获取收件人信息
            string strToken = WeChatCommonService.GetWeiXinToken(AppId);
            var    mobile   = string.Empty;

            var    obj      = MailListApi.GetMember(strToken, ViewBag.LillyId);
            string receiver = obj != null ? obj.email : "";

            var EmailReceiver  = "";
            var EmailEnableSsl = false;
            var EmailHost      = "";
            var EmailPassword  = "";
            var EmailUserName  = "";
            var EmailPort      = "";
            var EmailSender    = "";
            var EmailEnable    = true;
            var EmailTitle     = "";
            var EmailTemplate  = "";

            object jsonResult = null;

            LogManager.GetLogger(this.GetType()).Debug("request" + request);
            var js = new JavaScriptSerializer();

            jsonResult = js.Deserialize <object>(jsonString);
            var fullResult = jsonResult as Dictionary <string, object>;

            if (fullResult != null)
            {
                EmailReceiver  = fullResult["EmailReceiver"] as string;
                EmailEnableSsl = bool.Parse(fullResult["EmailEnableSsl"].ToString());
                EmailHost      = fullResult["EmailHost"] as string;
                EmailPassword  = fullResult["EmailPassword"] as string;
                EmailUserName  = fullResult["EmailUserName"] as string;
                EmailPort      = fullResult["EmailPort"] as string;
                EmailSender    = fullResult["EmailSender"] as string;
                EmailEnable    = bool.Parse(fullResult["EmailEnable"].ToString());
                EmailTitle     = fullResult["EmailTitle"] as string;
                EmailTemplate  = fullResult["EmailTemplate"] as string;
            }

            if (!string.IsNullOrEmpty(EmailTitle))
            {
                //特殊处理EmailTitle
                if (!string.IsNullOrEmpty(title))
                {
                    EmailTitle = string.Format("{0} ({1},{2})", EmailTitle, ViewBag.LillyId, DateTime.Now.ToShortDateString());
                }
                EmailTitle = EmailTitle.Replace("\r", "").Replace("\n", "");
            }

            List <QuestionImagesView> lst = _objImageService.GetListByQuestionID <QuestionImagesView>(id);
            var attachlink = "";

            if (lst != null)
            {
                attachlink = lst.Aggregate(attachlink, (current, attach) => string.Format("{0}<a href=\"{1}\">{2}</a>\n", current, string.Format("{0}Common/QuestionFile?id={1}&filename={2}", baseUrl, attach.Id, attach.ImageName), attach.ImageName));
            }

            var userModel = _objUserService.GetBylillyId(ViewBag.LillyId);

            if (userModel != null)
            {
                mobile = userModel.Tel;
            }

            var emailContent = EmailTemplate.Replace("#Url#", request).Replace("#Question#", question).
                               Replace("#LillyId#", ViewBag.LillyId).Replace("#Email#", receiver).Replace("#Contact#", mobile)
                               .Replace("#Attachment#", attachlink);

            var set = new EmailMessageSettingsRecord()
            {
                Host               = EmailHost,
                UserName           = EmailUserName,
                Password           = EmailPassword,
                Port               = int.Parse(EmailPort),
                EnableSsl          = EmailEnableSsl,
                Enable             = EmailEnable,
                DeliveryMethod     = "Network",
                Address            = EmailSender,
                RequireCredentials = true
            };

            Task.Run(() =>
            {
                var ser = new EmailMessageService(set);
                ser.SendMessage(EmailSender, EmailReceiver, EmailTitle,
                                emailContent.Replace("\r\n", "<br/>").Replace("\n", "<br/>").Replace("\r", "<br/>"));
            });

            return(true);
        }
Exemplo n.º 12
0
        public override void ExecuteResult(ControllerContext context)
        {
            if (base.Content == null)
            {
                //使用IMessageHandler输出
                if (_messageHandlerDocument == null)
                {
                    throw new Innocellence.Weixin.Exceptions.WeixinException("执行WeixinResult时提供的MessageHandler不能为Null!", null);
                }

                if (_messageHandlerDocument.ResponseMessage == null)
                {
                    //throw new Innocellence.Weixin.MP.WeixinException("ResponseMessage不能为Null!", null);
                }
                else
                {
                    context.HttpContext.Response.ClearContent();
                    context.HttpContext.Response.ContentType = "text/xml";
                    foreach (var a in _messageHandlerDocument.ResponseMessage)
                    {
                        var config   = WeChatCommonService.lstSysWeChatConfig.Find(aa => aa.WeixinCorpId == a.FromUserName);
                        var strToken = WeChatCommonService.GetWeiXinToken(config.Id);

                        if ((a as ResponseMessageBaseWechat).isSafe)
                        {
                            if (a is ResponseMessageImage)
                            {
                                var b = (ResponseMessageImage)a;
                                MassApi.SendImage(strToken, b.ToUserName, "", "", config.WeixinAppId.ToString(), b.Image.MediaId, 1);
                            }
                            else if (a is ResponseMessageVideo)
                            {
                                var b = (ResponseMessageVideo)a;
                                MassApi.SendVideo(strToken, b.ToUserName, "", "", config.WeixinAppId.ToString(), b.Video.MediaId, b.Video.Title, b.Video.Description, 1);
                            }
                            else if (a is ResponseMessageVoice)
                            {
                                var b = (ResponseMessageVoice)a;
                                MassApi.SendVoice(strToken, b.ToUserName, "", "", config.WeixinAppId.ToString(), b.Voice.MediaId, 1);
                            }
                            else if (a is ResponseMessageText)
                            {
                                var b = (ResponseMessageText)a;
                                MassApi.SendText(strToken, b.ToUserName, "", "", config.WeixinAppId.ToString(), b.Content, 1);
                            }
                            else if (a is ResponseMessageMpNews)
                            {
                                var b = (ResponseMessageMpNews)a;
                                MassApi.SendMpNews(strToken, b.ToUserName, "", "", config.WeixinAppId.ToString(), b.MpNewsArticles, 1);
                            }
                            else if (a is ResponseMessageNews)
                            {
                                log.Error("ExecuteResult ResponseMessageNews but Type is safe message!");
                                _messageHandlerDocument.FinalResponseDocument(a as ResponseMessageBaseWechat).Save(context.HttpContext.Response.OutputStream);
                            }
                        }
                        else
                        {
                            _messageHandlerDocument.FinalResponseDocument(a as ResponseMessageBaseWechat).Save(context.HttpContext.Response.OutputStream);
                        }
                    }
                }
            }

            base.ExecuteResult(context);
        }
Exemplo n.º 13
0
        public override ActionResult Edit(string id)
        {
            ViewBag.AppId = id;
            var Config = WeChatCommonService.GetWeChatConfigByID(int.Parse(id));


            //string strToken = Rtntoken(int.Parse(id));
            var strToken            = WeChatCommonService.GetWeiXinToken(Config.Id);
            GetAppInfoResult result = AppApi.GetAppInfo(strToken, int.Parse(Config.WeixinAppId));

            ViewBag.result = result;

            //部门信息
            //List<DepartmentList> subdepartList = MailListApi.GetDepartmentList(GetToken(), 0).department;
            List <DepartmentList> subdepartList = new List <DepartmentList>();

            if (WeChatCommonService.lstDepartment(AccountManageID) != null)
            {
                subdepartList = WeChatCommonService.lstDepartment(AccountManageID);
            }
            String        allowpart  = string.Join(",", result.allow_partys.partyid);
            List <string> departname = new List <string>();

            foreach (var part in allowpart.Split(','))
            {
                foreach (var allow in subdepartList)
                {
                    if (allow.id.ToString() == part)
                    {
                        departname.Add(allow.name);
                        break;
                    }
                }
            }
            ViewBag.depatlist = departname;

            //标签信息
            //var tagList = MailListApi.GetTagList(strToken).taglist;
            //ViewBag.taglist = tagList;
            List <TagItem> tagList = new List <TagItem>();

            if (WeChatCommonService.lstTag(AccountManageID) != null)
            {
                tagList = WeChatCommonService.lstTag(AccountManageID);
            }
            String        allowtag = string.Join(",", result.allow_tags.tagid);
            List <string> tagname  = new List <string>();

            foreach (var tag in allowtag.Split(','))
            {
                foreach (var tag_list in tagList)
                {
                    if (tag_list.tagid == tag)
                    {
                        tagname.Add(tag_list.tagname);
                        break;
                    }
                }
            }
            ViewBag.tagname = tagname;

            //用户信息

            List <GetMemberResult> user_List = new List <GetMemberResult>();

            if (WeChatCommonService.lstUser(AccountManageID) != null)
            {
                user_List = WeChatCommonService.lstUser(AccountManageID);
            }
            List <GetAppInfo_AllowUserInfos_User> userList = result.allow_userinfos.user;
            Dictionary <string, string>           username = new Dictionary <string, string>();

            foreach (var user in userList)
            {
                foreach (var user1 in user_List)
                {
                    if (user1.userid == user.userid)
                    {
                        username.Add(user1.name, user1.avatar);

                        break;
                    }
                }
            }
            ViewBag.userlist = username;

            //获取corpid与secret

            if (Config != null)
            {
                ViewBag.corpid         = Config.WeixinCorpId;
                ViewBag.secret         = "******";//Config.WeixinCorpSecret;
                ViewBag.welcomemessage = Config.WelcomeMessage;
                ViewBag.configid       = Config.Id;
                ViewBag.token          = "******"; // Config.WeixinToken;
                ViewBag.encodingAESKey = "******"; // Config.WeixinEncodingAESKey;
            }
            return(View("../appmanage/Edit", result));
        }
Exemplo n.º 14
0
        public bool SendMail(string LillyId, int AppId, string question, string jsonString, string request, string baseUrl, string title, bool sfMail = false)
        {
            //获取收件人信息
            string strToken = WeChatCommonService.GetWeiXinToken(AppId);
            var    mobile   = string.Empty;

            var    obj      = MailListApi.GetMember(strToken, LillyId);
            string receiver = obj != null ? obj.email : "";

            var EmailReceiver  = "";
            var EmailEnableSsl = false;
            var EmailHost      = "";
            var EmailPassword  = "";
            var EmailUserName  = "";
            var EmailPort      = "";
            var EmailSender    = "";
            var EmailEnable    = true;
            var EmailTitle     = "";
            var EmailTemplate  = "";

            object jsonResult = null;

            jsonResult = JsonHelper.FromJson <Dictionary <string, object> >(jsonString);
            var fullResult = jsonResult as Dictionary <string, object>;

            if (fullResult != null)
            {
                EmailReceiver  = fullResult["EmailReceiver"] as string;
                EmailEnableSsl = bool.Parse(fullResult["EmailEnableSsl"].ToString());
                EmailHost      = fullResult["EmailHost"] as string;
                EmailPassword  = fullResult["EmailPassword"] as string;
                EmailUserName  = fullResult["EmailUserName"] as string;
                EmailPort      = fullResult["EmailPort"] as string;
                EmailSender    = fullResult["EmailSender"] as string;
                EmailEnable    = bool.Parse(fullResult["EmailEnable"].ToString());
                EmailTitle     = fullResult["EmailTitle"] as string;
                EmailTemplate  = fullResult["EmailTemplate"] as string;
            }

            if (sfMail)
            {
                EmailReceiver = obj != null ? obj.email : "";
            }

            if (!string.IsNullOrEmpty(EmailTitle))
            {
                //特殊处理EmailTitle
                if (!string.IsNullOrEmpty(title))
                {
                    EmailTitle = string.Format("{0} ({1},{2})", EmailTitle, LillyId, DateTime.Now.ToShortDateString());
                }
                EmailTitle = EmailTitle.Replace("\r", "").Replace("\n", "");
            }

            var emailContent = EmailTemplate.Replace("#Url#", request).Replace("#Question#", question).
                               Replace("#LillyId#", LillyId).Replace("#Email#", receiver);

            var set = new EmailMessageSettingsRecord()
            {
                Host               = EmailHost,
                UserName           = EmailUserName,
                Password           = EmailPassword,
                Port               = int.Parse(EmailPort),
                EnableSsl          = EmailEnableSsl,
                Enable             = EmailEnable,
                DeliveryMethod     = "Network",
                Address            = EmailSender,
                RequireCredentials = true
            };

            Task.Run(() =>
            {
                var ser = new EmailMessageService(set);
                ser.SendMessage(EmailSender, EmailReceiver, EmailTitle,
                                emailContent.Replace("\r\n", "<br/>").Replace("\n", "<br/>").Replace("\r", "<br/>"));
            });

            return(true);
        }
        public QyJsonResult Push(int appId)
        {
            var categories = CommonService.lstCategory.Where(x => x.AppId == appId && (x.CategoryCode == null || !x.CategoryCode.EndsWith(_endFix, true, CultureInfo.CurrentCulture)) && (x.IsDeleted == null || x.IsDeleted == false)).OrderBy(x => x.CategoryOrder).Select(x =>
            {
                var function = x.Function.IsNullOrEmpty() ? null : JsonHelper.FromJson <ButtonReturnType>(x.Function);
                return(new CategroyChild
                {
                    Id = x.Id,
                    key = x.CategoryCode,
                    name = function == null ? x.CategoryName : function.Button.name,
                    sub_button = new List <MenuFull_RootButton>(),
                    //跳转到新闻列表本身也是view, 因此在同步时将其type改为view.
                    type = function == null ? null : "view-news-list".Equals(function.Button.type) ? "view" : function.Button.type,
                    ParentId = x.ParentCode.GetValueOrDefault(),
                    order = x.CategoryOrder.GetValueOrDefault(),
                    url = function == null ? null : function.Button.url,
                });
            }).ToList();

            foreach (var category in categories)
            {
                if ("click".Equals(category.type))
                {
                    var key   = category.key.Split(':')[0];
                    int keyId = default(int);
                    if (int.TryParse(key, out keyId))
                    {
                        var autoReply = _autoReplyService.GetDetail(keyId);
                        if (autoReply == null)
                        {
                            throw new System.Exception(string.Format("{0} 的口令不存在, 请重新选择.", category.name));
                        }
                        if ((int)AutoReplyKeywordEnum.MENU == autoReply.KeywordType &&
                            null != autoReply.Keywords && autoReply.Keywords.Count > 0)
                        {
                            if ((int)AutoReplyMenuEnum.SCAN_PUSH_EVENT == autoReply.Keywords[0].SecondaryType)
                            {
                                category.type = "scancode_push";
                            }
                            else if ((int)AutoReplyMenuEnum.SCAN_WITH_PROMPT == autoReply.Keywords[0].SecondaryType)
                            {
                                category.type = "scancode_waitmsg";
                            }
                        }
                    }
                    else
                    {
                        throw new System.Exception(string.Format("请重新选择 {0} 的口令.", category.key));
                    }
                }
            }

            var buttons = new List <MenuFull_RootButton>();

            categories.Where(x => x.ParentId == 0).ToList().ForEach(x => GenerateMenuHierarchy(categories, x, buttons));

            var config = WeChatCommonService.GetWeChatConfigByID(appId);

            //修改
            if (categories != null && categories.Count > 0)
            {
                var menu = new GetMenuResultFull {
                    menu = new MenuFull_ButtonGroup {
                        button = buttons
                    }
                };
                var btnMenus = CommonApi.GetMenuFromJsonResult(menu).menu;
                if (config.IsCorp.HasValue && !config.IsCorp.Value)
                {
                    var result = Innocellence.Weixin.MP.CommonAPIs.CommonApi.CreateMenu(config.WeixinCorpId, config.WeixinCorpSecret, btnMenus);
                    return(new QyJsonResult()
                    {
                        errcode = (ReturnCode_QY)result.errcode, errmsg = result.errmsg
                    });
                }
                else
                {
                    var result = CommonApi.CreateMenu(WeChatCommonService.GetWeiXinToken(appId), int.Parse(config.WeixinAppId), btnMenus);
                    return(result);
                }
            }
            //删除
            else
            {
                if (config.IsCorp.HasValue && !config.IsCorp.Value)
                {
                    var result = Innocellence.Weixin.MP.CommonAPIs.CommonApi.DeleteMenu(config.WeixinCorpId, config.WeixinCorpSecret);
                    return(new QyJsonResult()
                    {
                        errcode = (ReturnCode_QY)result.errcode, errmsg = result.errmsg
                    });
                }
                else
                {
                    var result = CommonApi.DeleteMenu(WeChatCommonService.GetWeiXinToken(appId), int.Parse(config.WeixinAppId));
                    return(result);
                }
            }
        }
Exemplo n.º 16
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)));
        }
        public override void ExecuteResult(ControllerContext context)
        {
            if (base.Content == null)
            {
                //使用IMessageHandler输出
                if (_messageHandlerDocument == null)
                {
                    throw new Innocellence.Weixin.Exceptions.WeixinException("执行WeixinResult时提供的MessageHandler不能为Null!", null);
                }

                if (_messageHandlerDocument.ResponseMessage == null)
                {
                    //throw new Innocellence.Weixin.MP.WeixinException("FinalResponseDocument不能为Null!", null);
                }
                else
                {
                    context.HttpContext.Response.ClearContent();
                    context.HttpContext.Response.ContentType = "text/xml";

                    // var xml = _messageHandlerDocument.FinalResponseDocument.ToString().Replace("\r\n", "\n"); //腾
                    foreach (var a in _messageHandlerDocument.ResponseMessage)
                    {
                        if ((a as ResponseMessageBaseWechat).isSafe)
                        {
                            var appid = (a as ResponseMessageBaseWechat).APPID;

                            log.Debug("Before Send Response to wechat:{0} type:{1}", appid, a.MsgType);
                            var config = WeChatCommonService.GetWeChatConfigByID(appid);

                            var strToken = WeChatCommonService.GetWeiXinToken(config.Id);

                            if (a is ResponseMessageImage)
                            {
                                var b = (ResponseMessageImage)a;
                                MassApi.SendImage(strToken, b.ToUserName, "", "", config.WeixinAppId.ToString(), b.Image.MediaId, 1);
                            }
                            else if (a is ResponseMessageVideo)
                            {
                                var b = (ResponseMessageVideo)a;
                                MassApi.SendVideo(strToken, b.ToUserName, "", "", config.WeixinAppId.ToString(), b.Video.MediaId, b.Video.Title, b.Video.Description, 1);
                            }
                            else if (a is ResponseMessageVoice)
                            {
                                var b = (ResponseMessageVoice)a;
                                MassApi.SendVoice(strToken, b.ToUserName, "", "", config.WeixinAppId.ToString(), b.Voice.MediaId, 1);
                            }
                            else if (a is ResponseMessageText)
                            {
                                var b = (ResponseMessageText)a;
                                MassApi.SendText(strToken, b.ToUserName, "", "", config.WeixinAppId.ToString(), b.Content, 1);
                            }
                            else if (a is ResponseMessageMpNews)
                            {
                                var b = (ResponseMessageMpNews)a;
                                MassApi.SendMpNews(strToken, b.ToUserName, "", "", config.WeixinAppId.ToString(), b.MpNewsArticles, 1);
                            }
                            else if (a is ResponseMessageNews)
                            {
                                log.Error("ExecuteResult ResponseMessageNews but Type is safe message!");
                                _messageHandlerDocument.FinalResponseDocument(a as ResponseMessageBaseWechat).Save(context.HttpContext.Response.OutputStream);
                            }
                        }
                        else
                        {
                            string xml = _messageHandlerDocument.FinalResponseDocument(a as ResponseMessageBaseWechat).ToString().Replace("\r\n", "\n");


                            log.Debug("Start Send Response Message: length:{0}", xml.Length);

                            if (!string.IsNullOrEmpty(xml))
                            {
                                var bytes = Encoding.UTF8.GetBytes(xml);                                 //的
                                context.HttpContext.Response.OutputStream.Write(bytes, 0, bytes.Length); //很
                                context.HttpContext.Response.Flush();
                            }
                            log.Debug("End Response Message: length:{0}", xml.Length);
                        }
                    }
                }
            }
        }
Exemplo n.º 18
0
        ///// <summary>
        ///// 获取所有App信息
        ///// </summary>
        ///// <param name="appid"></param>
        ///// <returns></returns>

        /// <summary>
        /// 取得并同步一个微信号(企业号)下所有App信息
        /// </summary>
        /// <param name="accountManageId"></param>
        /// <returns></returns>
        public List <GetAppInfoResult> GetAndSyncApps(int accountManageId, bool?isSyncMenu)
        {
            var result      = new List <GetAppInfoResult>();
            var appSelected = Request["APPList"];

            // ------------从微信服务器获取所有的App,以此为基础同步我们的App管理表

            // 取得accessToken

            var config = WeChatCommonService.lstSysWeChatConfig.FirstOrDefault(a => a.AccountManageId == accountManageId);

            var accessToken = WeChatCommonService.GetWeiXinToken(config.Id);

            // 如果是搜索App
            if (!string.IsNullOrEmpty(appSelected))
            {
                var app = WeChatCommonService.lstSysWeChatConfig.FirstOrDefault(a => a.AccountManageId == accountManageId && a.WeixinAppId == appSelected);


                var appInfo = AppApi.GetAppInfo(accessToken, int.Parse(appSelected));
                // 取得平台内AppId

                appInfo.agentid = app.Id.ToString();
                result.Add(appInfo);

                return(result);
            }
            var wxApps  = AppApi.GetAppList(accessToken);
            var applist = WeChatCommonService.lstSysWeChatConfig.Where(a => a.AccountManageId == accountManageId).ToList();

            // 同步App
            // TODO:目前的效率不高,在每次刷新页面或者翻页时都会重新去同步App
            _sysWechatConfigService.SyncWechatApps(accountManageId, accessToken, wxApps.agentlist, applist, isSyncMenu ?? true);

            // 将Session中的Menu更新
            var loginUser = (SysUser)Session["UserInfo"];
            var newMenus  = _sysMenuService.GetMenusByUserID(loginUser, null);

            loginUser.Menus     = newMenus;
            Session["UserInfo"] = loginUser;

            // 返回List
            var newAppList = WeChatCommonService.lstSysWeChatConfig.Where(a => a.AccountManageId == accountManageId).ToList();

            //这段代码完全没必要了
            //foreach (var newApp in newAppList)
            //{
            //    try
            //    {
            //        var appInfo = AppApi.GetAppInfo(accessToken, int.Parse(newApp.WeixinAppId));
            //        // 前台需要的是平台的AppID,而不是微信的agentId
            //        // 所以此处借用agentid字段来存储appId(因为类GetAppInfoResult已经打包为dll作为底层了,修改的话势必可能会影响到别的地方)
            //        appInfo.agentid = newApp.Id.ToString();
            //        result.Add(appInfo);
            //    }
            //    catch
            //    {
            //    }
            //}

            return(result);
        }