Ejemplo n.º 1
0
        public JsonResult GetSubDepartment(string id, string departlist)
        {
            //从缓存中读取DepartmentList
            var Id = 0;

            if (!string.IsNullOrEmpty(id))
            {
                Id = int.Parse(id);
            }
            var subdepartList = WeChatCommonService.GetSubDepartments(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));
        }
Ejemplo n.º 2
0
        public ConfigedInfo(GetAppInfoResult appInfo)
        {
            Dictionary    = new Dictionary <int, GetTagMemberResult>();
            AppInfoResult = appInfo;

            AssignedDepartmentIds = (appInfo.allow_partys == null || appInfo.allow_partys.partyid == null || !appInfo.allow_partys.partyid.Any()) ? new List <int>() : appInfo.allow_partys.partyid.ToList();

            AssignedUserIds = (appInfo.allow_userinfos == null || appInfo.allow_userinfos.user == null || !appInfo.allow_userinfos.user.Any()) ? new List <string>() : appInfo.allow_userinfos.user.Select(x => x.userid).ToList();

            //append depart and user of tag
            var tagIds = (appInfo.allow_tags == null || appInfo.allow_tags.tagid == null || !appInfo.allow_tags.tagid.Any()) ? new List <int>() : appInfo.allow_tags.tagid.ToList();

            foreach (var tagId in tagIds)
            {
                var memberResult = WeChatCommonService.GetTagMembers(tagId, int.Parse(appInfo.agentid));

                AssignedDepartmentIds.AddRange(memberResult.partylist);

                AssignedUserIds.AddRange(memberResult.userlist.Select(x => x.userid).ToList());

                Dictionary.Add(tagId, memberResult);
            }

            var subDepartments = WeChatCommonService.GetSubDepartments(AssignedDepartmentIds.Distinct().ToList()).ToList();

            AssignedUserIds.AddRange(WeChatCommonService.lstUser.Where(x => x.department.Any(y => subDepartments.Any(d => d.id == y))).Select(x => x.userid).ToList());

            AssignedUserIds = AssignedUserIds.Distinct().ToList();
        }
Ejemplo n.º 3
0
        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);
        }
Ejemplo n.º 4
0
 private void GenerateTagInfoDictionary(GetAppInfoResult appInfo)
 {
     foreach (var allowTag in appInfo.allow_tags.tagid)
     {
         tagMemberdDictionary.Add(allowTag, WeChatCommonService.GetTagMembers(allowTag, int.Parse(appInfo.agentid)));
     }
 }
Ejemplo n.º 5
0
        private bool CheckTag(GetAppInfoResult appInfo, IList <int> selectedTagIds, IEnumerable <string> allAssignedUsers, CheckResult checkResult)
        {
            if (!selectedTagIds.Any())
            {
                return(true);
            }

            var needTags = selectedTagIds.Select(selectedTagId => new TagEntity {
                TagId = selectedTagId, TagMember = WeChatCommonService.GetTagMembers(selectedTagId, int.Parse(appInfo.agentid))
            }).ToList();

            //needTags.Select(x => new { TagId = x.Key, TagMember = x.Value }).ToList();

            var needUsers = needTags.SelectMany(x => x.TagMember.userlist.Select(y => y.userid)).ToList();

            var needParties = WeChatCommonService.GetSubDepartments(needTags.SelectMany(x => x.TagMember.partylist).ToList()).ToList();

            needUsers.AddRange(WeChatCommonService.lstUser.Where(x => needParties.Any(y => x.department.Any(z => z == y.id))).Select(x => x.userid).ToList());

            var errorUsers = needUsers.Where(x => allAssignedUsers.Any(y => x == y)).ToList();

            var errorTags = needTags.Where(x => errorUsers.Any(y => x.TagMember.userlist.Any(z => z.userid == y))).Select(x => x.TagId).ToList();

            if (!errorTags.Any())
            {
                return(true);
            }

            checkResult.ErrorTags = GetErrorTags(errorTags);
            return(false);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// 企业号百分比统计
        /// </summary>
        /// <returns></returns>
        public async Task <ActionResult> Enterprise(string state, string date)
        {
            if (string.IsNullOrEmpty(date))
            {
            }
            else
            {
                //定义饼柱状图标的list
                List <string> xAxisList = new List <string>();
                DateTime      dt        = DateTime.Parse(date);

                // 获取token
                var objConfig = WeChatCommonService.GetWeChatConfig();
                var token     = await getToken(objConfig.WeixinCorpId, objConfig.WeixinCorpSecret);

                // 使用获取app列表的API
                var empagent = await getagentlist(token);

                foreach (var emp in empagent.agentlist)
                {
                    xAxisList.Add(emp.name);
                }
                var newObj = new
                {
                    xAxis = xAxisList,
                    //Data = seriesList,
                };
            }
            return(null);
        }
 private void ProcessPostedFile(string saveFullName, HttpPostedFileBase postedFile, string targetFilePath, string uploadFileType)
 {
     try
     {
         _Logger.Debug("begin to update file to :{0}", targetFilePath);
         string saveDir = Path.Combine(Server.MapPath("~/"), targetFilePath);
         if (Directory.Exists(saveDir) == false)//如果不存在就创建file文件夹
         {
             Directory.CreateDirectory(saveDir);
         }
         if (postedFile != null)
         {
             string strPath = Path.Combine(saveDir, saveFullName);
             if ("image".Equals(uploadFileType, StringComparison.OrdinalIgnoreCase))
             {
                 //1.压缩原图, 最大尺寸, 宽1024, 不限制高
                 ImageUtility.MakeThumbnail(null, postedFile.InputStream, strPath, 1024, 768, "W");
                 //2.生成200*200的缩略图, _T 结尾
                 ImageUtility.MakeThumbnail(null, postedFile.InputStream, strPath.Insert(strPath.LastIndexOf('.'), "_T"), 200, 200, "Cut");
                 //3.图文封面生成宽900*500的等比图, 由于900*500的容易超过64kg, 等比压缩为360*220
                 bool isNewsCover = false;
                 if (bool.TryParse(Request["isNewsCover"], out isNewsCover) && isNewsCover)
                 {
                     int appId  = -1;
                     int width  = 360;
                     int height = 220;
                     try
                     {
                         if (int.TryParse(Request["AppId"], out appId) && appId > -1)
                         {
                             var accoutManagement = WeChatCommonService.GetAccountManageByWeChatID(appId);
                             if (null != accoutManagement && null != accoutManagement.AccountType && accoutManagement.AccountType.Value == 0)
                             {
                                 width  = 900;
                                 height = 500;
                             }
                         }
                     }
                     catch (Exception ex)
                     {
                         _Logger.Error(ex);
                     }
                     _Logger.Debug("_T width:{0} height:{1}", width, height);
                     ImageUtility.MakeThumbnail(null, postedFile.InputStream, strPath.Insert(strPath.LastIndexOf('.'), "_B"), width, height, "W");
                 }
             }
             else
             {
                 postedFile.SaveAs(strPath);
             }
         }
         _Logger.Debug("success to upload file.");
     }
     catch (Exception ex)
     {
         _Logger.Error(ex, "Upload file failed");
         throw ex;
     }
 }
Ejemplo n.º 8
0
        /// <summary>
        /// tag信息列表情报获得
        /// </summary>
        /// <param name="appId">appid</param>
        /// <returns>tag列表</returns>
        private List <TagItem> PrepareEditData(int appId)
        {
            var    Config      = WeChatCommonService.GetWeChatConfig(appId);
            string accessToken = AccessTokenContainer.TryGetToken(Config.WeixinCorpId, Config.WeixinCorpSecret);
            var    tagList     = MailListApi.GetTagList(accessToken).taglist;

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

            ViewBag.taglist = tagList;
        }
Ejemplo n.º 10
0
        /// <summary>
        /// 首次关注应用事件
        /// </summary>
        /// <param name="requestMessage"></param>
        /// <returns></returns>
        public override IResponseMessageBase OnEvent_SubscribeRequest(RequestMessageEvent_Subscribe requestMessage)
        {
            var responseMessage = this.CreateResponseMessage <ResponseMessageText>();
            var objConfig       = WeChatCommonService.GetWeChatConfig(requestMessage.AgentID);

            responseMessage.Content = objConfig.WelcomeMessage;
            return(responseMessage);
        }
        public JsonResult renameTag(string Id, string tagName)
        {
            string accessToken = GetToken();

            MailListApi.UpdateTag(accessToken, Int32.Parse(Id), tagName);
            WeChatCommonService.ClearDepartmentTagMapCache(this.AccountManageID);
            return(Json(doJson(null), JsonRequestBehavior.AllowGet));
        }
 public JsonResult UpdateUserlist()
 {
     if (WeChatCommonService.lstUser(AccountManageID) != null)
     {
         cacheManager.Remove("UserItem" + AccountManageID);
     }
     return(Json(doJson(null), JsonRequestBehavior.AllowGet));
 }
Ejemplo n.º 13
0
        public string GetToken(int iAppID)
        {
            var Config = WeChatCommonService.GetWeChatConfig(iAppID);

            return(AccessTokenContainer.TryGetToken(Config.WeixinCorpId, Config.WeixinCorpSecret));

            // return resultToken.access_token;
        }
        /// <summary>
        /// 根据用户openId 创建或者更新新的二维码
        /// </summary>
        /// <param name="openId"></param>
        /// <param name="appid"></param>
        /// <param name="activityName"></param>
        /// <param name="activityid"></param>
        /// <returns></returns>
        public ActionResult CreateOrUpdateQrCodeByOpenId(string openId, string wechatappid, string activityName, string activityid, string isUpdate)
        {
            if (!VerifyParam("openId,wechatappid,activityName,activityid,isUpdate"))
            {
                return(ErrMsg());
            }
            int newAppid      = System.Convert.ToInt32(wechatappid);
            int newactivityId = System.Convert.ToInt32(activityid);

            try
            {
                var          config = WeChatCommonService.GetWeChatConfigByID(newAppid);
                var          user   = _WechatMPUserService.Repository.Entities.Where(u => u.OpenId.Equals(openId, StringComparison.CurrentCultureIgnoreCase) && u.AccountManageId == config.AccountManageId && u.IsCanceled == false).FirstOrDefault();
                var          qrcode = _QrCodeService.Repository.Entities.Where(q => q.RelatedUserId == user.Id);
                QrCodeMPItem newqr  = new QrCodeMPItem();
                if (qrcode.Any())
                {
                    newqr = qrcode.FirstOrDefault();
                    UpdateQRCode(newqr, newAppid, isUpdate);
                }
                else
                {
                    newqr.AppId         = newAppid;
                    newqr.Description   = activityName;
                    newqr.CreatedDate   = DateTime.Now;
                    newqr.Deleted       = false;
                    newqr.CreatedUserID = User.Identity.Name;
                    newqr.UpdatedDate   = DateTime.Now;
                    newqr.UpdatedUserID = User.Identity.Name;
                    newqr.RelatedUserId = user.Id;
                    _QrCodeService.Repository.Insert(newqr);
                    ///添加临时二维码时 先插入数据获取当前记录id
                    ///目前商定 所有活动用二维码 由10位数字组成 前三位代表活动id,后7位代表活动用二维码id。
                    ///
                    newqr.SceneId = newactivityId * 10000000 + newqr.Id;
                    //var config = WeChatCommonService.GetWeChatConfigByID(newAppid);
                    ///临时用二维码 过期时间为2592000秒 30天

                    ///x向腾讯申请二维码 并获取二维码url
                    var result = QrCodeApi.Create(config.WeixinAppId, config.WeixinCorpSecret, 2592000, (int)newqr.SceneId);
                    if (result.errcode == Weixin.ReturnCode.请求成功)
                    {
                        var    qrurl       = QrCodeApi.GetShowQrCodeUrl(result.ticket);
                        var    userinfo    = Innocellence.Weixin.MP.AdvancedAPIs.UserApi.Info(config.WeixinCorpId, config.WeixinCorpSecret, openId);
                        string userHeadUrl = userinfo.headimgurl;
                        newqr.Url = CombineQrCodeAndHeadImg(userHeadUrl, qrurl);
                    }
                    ///重新更新当前model
                    _QrCodeService.Repository.Update(newqr);
                }
                return(Json(new { QrcodeUrl = newqr.Url, SceneId = newqr.SceneId, Status = 200, UpdatedDate = newqr.UpdatedDate }, JsonRequestBehavior.AllowGet));
            }
            catch (Exception e)
            {
                _Logger.Error(e);
            }
            return(Json(new { Status = 400 }, JsonRequestBehavior.AllowGet));
        }
        public static GetAppInfoResult GetUserOrDept(int iAppID)
        {
            var objConfig = WeChatCommonService.GetWeChatConfigByID(iAppID);

            string strToken = AccessTokenContainer.TryGetToken(objConfig.WeixinCorpId, objConfig.WeixinCorpSecret);

            return(AppApi.GetAppInfo(strToken, int.Parse(objConfig.WeixinAppId)));
            // Ret.allow_userinfos
        }
        /// <summary>
        /// 微信认证成功
        /// </summary>
        /// <returns></returns>
        public ActionResult Subscribed(string WeChatUserID)
        {
            var objConfig = WeChatCommonService.GetWeChatConfigByID(1);
            var token     = AccessTokenContainer.TryGetToken(objConfig.WeixinCorpId, objConfig.WeixinCorpSecret);

            LogManager.GetLogger(this.GetType()).Debug("Starting ConcernApi.TwoVerification... Token=" + token + " - WeChatUserID=" + WeChatUserID);
            var result = ConcernApi.TwoVerification(token, WeChatUserID);

            return(Redirect("/subscribed.html"));
        }
        public ActionResult WechatServiceMessage()
        {
            var config = WeChatCommonService.GetWeChatConfigByID(AppId);

            if (null != config && !string.IsNullOrEmpty(config.CoverUrl))
            {
                ViewBag.AppImg = config.CoverUrl;
            }
            return(View());
        }
Ejemplo n.º 18
0
        public string GetToken(int iAppID)
        {
            LogManager.GetLogger(this.GetType()).Error("Request.Url.AbsoluteUri:" + Request.Url.AbsoluteUri);
            var Config = WeChatCommonService.GetWeChatConfig(iAppID);

            LogManager.GetLogger(this.GetType()).Debug("host:" + Request.Url.Host);
            return(AccessTokenContainer.TryGetToken(Config.WeixinCorpId, Config.WeixinCorpSecret));

            // return resultToken.access_token;
        }
        public ActionResult SendNews(List <NewsInfoView> newsList, bool isPreview = false)
        {
            int IsSec = 0;

            try
            {
                var news = newsList[0];
                if ("video".Equals(news.NewsCate))
                {
                    news.ImageContent = SaveBase64ImageToServer(news.ImageContent);
                }
                IsSec = news.isSecurityPost.HasValue && news.isSecurityPost.Value ? 1 : 0;
                var    objConfig = WeChatCommonService.GetWeChatConfigByID(news.AppId);
                string strToken  = (objConfig.IsCorp != null && !objConfig.IsCorp.Value) ? Innocellence.Weixin.MP.CommonAPIs.AccessTokenContainer.GetToken(objConfig.WeixinCorpId, objConfig.WeixinCorpSecret) : Innocellence.Weixin.QY.CommonAPIs.AccessTokenContainer.TryGetToken(objConfig.WeixinCorpId, objConfig.WeixinCorpSecret);
                string strUser   = news.SendToPerson == null ? null : string.Join("|", news.SendToPerson);
                string strDept   = news.SendToGroup == null ? null : string.Join("|", news.SendToGroup);
                string strTags   = news.SendToTag == null ? null : string.Join("|", news.SendToTag);

                // var configs = Infrastructure.Web.Domain.Service.CommonService.lstSysConfig;
                using (var transactionScope = new TransactionScope(TransactionScopeOption.Suppress,
                                                                   new TransactionOptions {
                    IsolationLevel = IsolationLevel.RepeatableRead
                }))
                {
                    MassResult result      = null;
                    var        lstArticles = GetArticleList(newsList, isPreview);
                    if (!isPreview)
                    {
                        InsertMsgLog(string.Join(",", lstArticles.Select(a => a.Id)), newsList[0]);
                    }
                    if (news.PostType == (int)MessagePostTypeEnum.定时推送)
                    {
                        transactionScope.Complete();
                    }
                    else
                    {
                        result = WechatCommon.SendMsgQY(news.AppId, news.NewsCate == "news" && IsSec == 1 ? "mpnews" : news.NewsCate, strUser, strDept, strTags, "", lstArticles, IsSec, isPreview);
                        if (result.errcode == Weixin.ReturnCode_QY.请求成功)
                        {
                            transactionScope.Complete();
                        }
                    }
                }
                //if (pp != null)
                //{
                //    _attachmentsItemService.ThumbImageAndInsertIntoDB(pp);
                //}
            }
            catch (Exception e)
            {
                _Logger.Error(e, "An error occurred while sending news.");
                return(Json(new { results = new { Data = 500 } }));
            }
            return(Json(new { results = new { Data = 200 } }));
        }
        public override ActionResult Index()
        {
            //var tagList = MailListApi.GetTagList(GetToken()).taglist;
            var tagList = WeChatCommonService.GetTagListByAccountManageID(this.AccountManageID);

            ViewBag.taglist = tagList;



            return(View());
        }
 protected bool VerifyParam(string param)
 {
     if (Request["sign"] != WeChatCommonService.GetSignature(param, Request.Params))
     {
         return(false);
     }
     else
     {
         return(true);
     }
 }
        public GetMenuResult GetMPMenu(int appId)
        {
            var config = WeChatCommonService.GetWeChatConfigByID(appId);

            if (config.IsCorp.HasValue && !config.IsCorp.Value)
            {
                var result = Innocellence.Weixin.MP.CommonAPIs.CommonApi.GetMenu(config.WeixinCorpId, config.WeixinCorpSecret);
                return(result);
            }
            return(null);
        }
        private bool CheckDepartment(GetAppInfoResult appInfo, IList <int> selectedDepartmentIds, CheckResult checkResult, int AccountMangageID)
        {
            //直接分配给应用
            var assignedDepartmentIds = appInfo.allow_partys.partyid.ToList();

            var underTagDepartmentIDs = tagMemberdDictionary.Select(x => x.Value).SelectMany(x => x.partylist).ToList();

            assignedDepartmentIds.AddRange(underTagDepartmentIDs);

            //TODO:调整
            if (!assignedDepartmentIds.Any())
            {
                if (!selectedDepartmentIds.Any())
                {
                    return(true);
                }

                checkResult.ErrorDepartments = GetErrorDepartments(selectedDepartmentIds, AccountMangageID);

                return(false);
            }

            var departments = WeChatCommonService.GetSubDepartments(assignedDepartmentIds.Distinct().ToList(), AccountMangageID).ToList();

            #region hiddlen
            //var allowUsers = WeChatCommonService.lstUser.Where(x => x.department.Any(y => departments.Any(z => z.id == y))).ToList();

            //var needUsers = WeChatCommonService.lstUser.Where(x => x.department.Any(y => selectedDepartmentIds.Any(s => s == y))).ToList();

            //var errorUsers = needUsers.Where(x => allowUsers.All(u => x.userid != u.userid)).ToList();

            //if (!errorUsers.Any())
            //{
            //    return true;
            //}

            //var errorDepartments = WeChatCommonService.lstDepartment.Where(x => errorUsers.SelectMany(y => y.department).Any(z => z == x.id)).ToList();

            //var errorDepartmentIds = selectedDepartmentIds.Where(x => WeChatCommonService.GetSubDepartments(x).Any(y => errorDepartments.Any(z => z.id == y.id))).ToList();

            //if (!errorDepartmentIds.Any()) return true;
            #endregion

            var errorDepartmentIds = selectedDepartmentIds.Where(x => departments.All(y => x != y.id)).ToList();

            if (!errorDepartmentIds.Any())
            {
                return(true);
            }

            checkResult.ErrorDepartments = GetErrorDepartments(errorDepartmentIds, AccountMangageID);

            return(false);
        }
        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;
        }
Ejemplo n.º 25
0
        public string rtntoken(int agentid = 0)
        {
            var Config   = WeChatCommonService.GetWeChatConfig(agentid);
            var strToken = AccessTokenContainer.TryGetToken(Config.WeixinCorpId, Config.WeixinCorpSecret);

            if (!string.IsNullOrEmpty(strToken))
            {
                return(strToken);
            }

            return(null);
        }
Ejemplo n.º 26
0
        /// <summary>
        /// 取得token
        /// </summary>
        /// <param name="appId">这个appId不是微信的agengId,而是DB中的appId,也就是表SysWechatConfig的Id</param>
        /// <returns></returns>
        public string Rtntoken(int appId = 0)
        {
            var config   = WeChatCommonService.GetWeChatConfigByID(appId);
            var strToken = AccessTokenContainer.TryGetToken(config.WeixinCorpId, config.WeixinCorpSecret);

            if (!string.IsNullOrEmpty(strToken))
            {
                return(strToken);
            }

            return(null);
        }
        /// <summary>
        /// 过滤成员
        /// </summary>
        /// <returns></returns>
        public JsonResult GetListByCondation()
        {
            string          condation = Request["txtSearch"].ToUpper();
            GetMemberResult member    = new GetMemberResult();

            if (WeChatCommonService.lstUser(AccountManageID) != null)
            {
                member = WeChatCommonService.lstUser(AccountManageID).Find(a => a.userid.Equals(condation, StringComparison.InvariantCultureIgnoreCase));
            }

            return(Json(new { data = member }, JsonRequestBehavior.AllowGet));
        }
 /// <summary>
 /// 通过API获取APP的可见范围, 判断该User是否在其中
 /// </summary>
 /// <param name="appId"></param>
 /// <returns></returns>
 private bool ValidateUserInApp(int?appId)
 {
     if (null != appId)
     {
         SysAddressBookMember user = GetCropUser();
         if (null != user && null != user.AccountManageId)
         {
             return(WeChatCommonService.IsValidateUser((int)appId, user, (int)user.AccountManageId));
         }
     }
     return(false);
 }
        // THIS METHOD SHOULD BE MOVED TO COMMON SERVICE. ACTUALLY, WinxinBaseController HAS THIS METHOD
        private string getWxToken(int agentid = 0)
        {
            var config   = WeChatCommonService.GetWeChatConfigByID(agentid);
            var strToken = AccessTokenContainer.TryGetToken(config.WeixinCorpId, config.WeixinCorpSecret);

            if (!string.IsNullOrEmpty(strToken))
            {
                return(strToken);
            }

            return(null);
        }
Ejemplo n.º 30
0
        /// <summary>
        /// 微信图文推送。该函数不建议使用,建议使用PublishMessage函数代替。
        /// </summary>
        /// <param name="iAppID"></param>
        /// <param name="strMsgType"></param>
        /// <param name="strUser"></param>
        /// <param name="strDept"></param>
        /// <param name="strTags"></param>
        /// <param name="strContent"></param>
        /// <param name="lstContent"></param>
        /// <returns></returns>
        public static MassResult SendMsg(int iAppID, string strMsgType, string strUser, string strDept, string strTags, string strContent, List <Article> lstContent)
        {
            MassResult objResult = null;

            int IsSec = 0;

            var objConfig = WeChatCommonService.GetWeChatConfig(iAppID);

            LogManager.GetLogger(typeof(WechatCommon)).Debug("strUser:{0} strDept:{1} strTags:{2} Msg:{3}", strUser, strDept, strTags, strContent);

            string strToken = AccessTokenContainer.TryGetToken(objConfig.WeixinCorpId, objConfig.WeixinCorpSecret);

            switch (strMsgType)
            {
            case "text":
                objResult = MassApi.SendText(strToken, strUser, strDept, strTags, iAppID.ToString(), strContent, IsSec);
                break;

            case "image":

                Dictionary <string, Stream> dic = new Dictionary <string, Stream>();

                // for (int i = 0; i < Request.Files.Count; i++)
                {
                    var stream = System.IO.File.OpenRead(HttpContext.Current.Server.MapPath("~/") + "/style/images/meteorshower.jpg");
                    dic.Add("meteorshower.jpg", stream);
                }
                var ret = MediaApi.Upload(strToken, UploadMediaFileType.file, dic, "");

                objResult = MassApi.SendImage(strToken, strUser, strDept, strTags, iAppID.ToString(), ret.media_id, IsSec);
                break;

            case "news":
                objResult = MassApi.SendNews(strToken, strUser, strDept, strTags, iAppID.ToString(), lstContent, IsSec);
                break;

            case "file":

                Dictionary <string, Stream> dic1 = new Dictionary <string, Stream>();

                for (int i = 0; i < HttpContext.Current.Request.Files.Count; i++)
                {
                    var stream = System.IO.File.OpenRead(HttpContext.Current.Server.MapPath("~/") + "/style/images/meteorshower.jpg");
                    dic1.Add("meteorshower.jpg", stream);
                }
                var ret1 = MediaApi.Upload(strToken, UploadMediaFileType.file, dic1, "");

                objResult = MassApi.SendFile(strToken, strUser, strDept, strTags, iAppID.ToString(), ret1.media_id, IsSec);
                break;
            }

            return(objResult);
        }