コード例 #1
0
        public static SendResult SendMsgMP(List <ArticleInfoView> lstContent, SearchUserMPView searchCondition, string[] PreviewOpenids /*Preview use*/, bool isKefu = false)
        {
            string strTags = ""; //ToAll

            string[] userOpenIds = null;

            if (searchCondition.Group == null)
            {
                searchCondition.Group = -2;
            }
            if (searchCondition.Sex < 0 && searchCondition.Province == "-1")
            {
                if (searchCondition.Group == -2)
                {
                    // ToAll
                    strTags = "-1";
                }
                else
                {
                    // Send By Tag
                    strTags = searchCondition.Group.ToString();
                }
            }
            else
            {
                // Send By OpenId
                IWechatMPUserService _WechatMPUserService = EngineContext.Current.Resolve <IWechatMPUserService>();
                var objConfig = WeChatCommonService.GetWeChatConfigByID(lstContent[0].AppId.Value);
                userOpenIds = _WechatMPUserService.GetUserBySearchCondition(searchCondition, objConfig.AccountManageId.Value).Select(u => u.OpenId).ToArray();
            }

            string strType = ((WechatMessageLogType)lstContent[0].ContentType).ToString();

            return(SendMsg(strType, "", lstContent, strTags, userOpenIds, PreviewOpenids, isKefu));
        }
コード例 #2
0
        ///// <summary>
        ///// 发送微信消息
        ///// </summary>
        ///// <param name="strMsgType">text,image,news</param>
        ///// <param name="strContent"></param>
        ///// <param name="lstContent"></param>
        ///// <returns></returns>
        //public static SendResult SendMsg(int iAppID, string strMsgType, string strContent, List<Article> lstContent)
        //{
        //    //MassResult objResult = null;
        //    string strDept = "", strUser = "", strTags = "";
        //    //  int IsSec = 0;

        //    GetAppInfoResult Ret = GetUserOrDept(iAppID);

        //    Ret.allow_userinfos.user.Where(a => a.status == "1").ToList().ForEach(a => { strUser += "|" + a.userid; });
        //    if (strUser.Length > 0) { strUser = strUser.Substring(1); }
        //    strDept = string.Join(",", Ret.allow_partys.partyid);
        //    strTags = string.Join(",", Ret.allow_tags.tagid);

        //    return SendMsg(iAppID, strMsgType, strUser, strDept, strTags, strContent, lstContent);

        //}

        //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
        //}

        //public static List<Article> SendNews(List<NewsInfo> lst)
        //{
        //    var lstContent = new List<Article>();
        //    Article art = new Article();
        //    NewsInfo news = lst.Find(a => a.LanguageCode == ConstData.LAN_CN);
        //    NewsInfo newsEN = lst.Find(a => a.LanguageCode == ConstData.LAN_EN);

        //    art.Title = newsEN.NewsTitle + news.NewsTitle;
        //    art.Description =newsEN.NewsContent+"\n"+news.NewsContent;
        //    art.PicUrl = string.Format("{0}Common/file?Id={1}&filename={2}&ImgType=1",
        //        WebConfigurationManager.AppSettings["WebUrl"], news.Id, news.ImageName);
        //    art.Url = string.Format("{0}NewsInfo/Detail?NewsCode={1}", WebConfigurationManager.AppSettings["WebUrl"], news.NewsCode);
        //   // art.Description = art.PicUrl;
        //    lstContent.Add(art);

        //    return lstContent;
        //}

        //public static List<Article> SendCourse(List<TrainingCourse> lst)
        //{
        //    var lstContent = new List<Article>();
        //    Article art = new Article();
        //    TrainingCourse news = lst.Find(a => a.LanguageCode == ConstData.LAN_CN);
        //    TrainingCourse newsEN = lst.Find(a => a.LanguageCode == ConstData.LAN_EN);

        //    art.Title = newsEN.CourseName + news.CourseName;
        //    art.Description = newsEN.CourseComment + "\n" + news.CourseComment;
        //    art.PicUrl = "Common/file?Id=" + news.Id + "&filename=/Content/img/Course1.png&ImgType=1";
        //    art.Url = string.Format("{0}/Course/Detail?CourseCode={1}", WebConfigurationManager.AppSettings["WebUrl"], news.CourseCode);
        //    lstContent.Add(art);

        //    return lstContent;
        //}

        /// <summary>
        /// 服务号消息内容中不能有外链的图片,需要转换
        /// </summary>
        /// <param name="strContent"></param>
        /// <param name="iAPPID"></param>
        /// <returns></returns>
        public static string ImageConvert(string strContent, int iAPPID)
        {
            List <string> lst       = new List <string>();
            string        regex     = @"(<img.*?/>)";
            Regex         listRegex = new Regex(regex, RegexOptions.Multiline | RegexOptions.IgnoreCase);
            //得到匹配的数据集合
            MatchCollection mc = listRegex.Matches(strContent);

            foreach (Match a in mc)
            {
                var href = Regex.Match(a.Value, "src=\"(.*?)\"");
                if (href == null || href.Groups.Count < 2)
                {
                    continue;
                }

                if (lst.Contains(href.Groups[1].Value))
                {
                    continue;
                }
                lst.Add(href.Groups[1].Value);
                var file = href.Groups[1].Value.Replace(CommonService.GetSysConfig("Content Server", ""), "");

                var config = WeChatCommonService.GetWeChatConfigByID(iAPPID);

                var ret = MediaApi.UploadImg(config.WeixinAppId, config.WeixinCorpSecret, (HttpContext.Current == null ? HttpRuntime.AppDomainAppPath : HttpContext.Current.Request.PhysicalApplicationPath) + file, 10000 * 60);
                strContent = strContent.Replace(href.Groups[1].Value, ret.url);
            }

            return(strContent);
        }
コード例 #3
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.GetWeChatConfigByID(AccountManageID);
                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);
        }
コード例 #4
0
        ///// <summary>
        ///// 取得口令回复一览
        ///// </summary>
        ///// <param name="autoReplyView"></param>
        ///// <returns></returns>
        //private List<AutoReplyContentView> GetAutoReplyList(AutoReplyView autoReplyView)
        //{
        //    // THIS IS NOT A GOOD WAY, SHOULD TRANSFER TO JSON OBJECT IN FRONT END
        //    var list = new List<AutoReplyContentView>();
        //    var replyTypes = Request.Form.GetValues("replyType");
        //    var textReply = Request.Form.Get("saytext");
        //    var newsTitle = Request.Form.Get("msgPictitle");
        //    var newsComment = Request.Form.Get("msgtips");
        //    var newsBody = Request.Form.Get("msgbody");
        //    //var isTextEncrypts = Request.Form.GetValues("isTextEncryptReplace");
        //    var replyNewsTypes = Request.Form.GetValues("replyNewsType");
        //    var replyNewsLatestCounts = Request.Form.GetValues("replyNewsLatestCount");
        //    var replyNewsLists = Request.Form.GetValues("replyNewsList");
        //    var textReplyFiles = Request.Form.GetValues("textReplyFiles");

        //    //if (replyTypes != null)
        //    //{
        //    //    var count = replyTypes.Length;
        //    //    for (int i = 0; i < count; i++)
        //    //    {
        //            var content = new AutoReplyContentView();
        //            content.AutoReplyId = autoReplyView.Id;
        //            content.PrimaryType = 2;//int.Parse(replyTypes[i]);
        //            NewsInfoView view = new NewsInfoView();
        //            switch (content.PrimaryType)
        //            {
        //                #region text
        //                case (int)AutoReplyContentEnum.TEXT:
        //                case (int)AutoReplyContentEnum.LINK:
        //                    {
        //                        content.Content = textReply;
        //                        //if (isTextEncrypts != null)
        //                        //{
        //                        //    content.IsEncrypt = isTextEncrypts[i] == "1";
        //                        //}
        //                        break;
        //                    }
        //                #endregion

        //                #region news
        //                case (int)AutoReplyContentEnum.PHOTO_TEXT:
        //                    {
        //                        view.NewsTitle = newsTitle;
        //                        view.NewsComment = newsComment;
        //                        view.NewsContent = newsBody;
        //                        //    //ImageContent = news
        //                        content.NewsID = Guid.NewGuid().ToString();
        //                        var configs = Infrastructure.Web.Domain.Service.CommonService.lstSysConfig;
        //                        var config = configs.Where(a => a.ConfigName.Equals("Content Server", StringComparison.CurrentCultureIgnoreCase)).First();
        //                        string host = config.ConfigValue;
        //                        if (host.EndsWith("/"))
        //                        {
        //                            host = host.Substring(0, host.Length - 1);
        //                        }
        //                        //var picUrl = host + item.ImageContent;
        //                        var url = host + "WechatMain/AutoReply/GetNews?id=" + content.NewsID;
        //                        content.Content = JsonConvert.SerializeObject(view);
        //                        //if (replyNewsTypes != null)
        //                        //{
        //                        //    content.SecondaryType = int.Parse(replyNewsTypes[i]);
        //                        //    if (content.SecondaryType == (int)AutoReplyNewsEnum.LATEST)
        //                        //    {
        //                        //        if (replyNewsLatestCounts != null) content.Content = replyNewsLatestCounts[i];
        //                        //    }
        //                        //    else if (content.SecondaryType == (int)AutoReplyNewsEnum.MANUAL)
        //                        //    {
        //                        //        if (replyNewsLists != null) content.NewsID = replyNewsLists[i];
        //                        //    }
        //                        //}

        //                        break;
        //                    }
        //                #endregion

        //                case (int)AutoReplyContentEnum.VIDEO:
        //                    view.NewsTitle = newsTitle;
        //                    break;
        //                case (int)AutoReplyContentEnum.FILE:
        //                    view.NewsTitle = newsTitle;
        //                    break;
        //                case (int)AutoReplyContentEnum.IMAGE:
        //                    view.NewsTitle = newsTitle;
        //                    break;
        //                case (int)AutoReplyContentEnum.AUDIO:
        //                    view.NewsTitle = newsTitle;
        //                    break;
        //                default:
        //                    {
        //                        //if (textReplyFiles != null) content.FileID = int.Parse(textReplyFiles[i]);
        //                        break;
        //                    }
        //            }

        //            list.Add(content);
        //    //    }

        //    //}

        //    return list;
        //}
        #endregion

        private List <AutoReplyContentView> GetAutoReplyList(AutoReplyNewView model)
        {
            var list    = new List <AutoReplyContentView>();
            var content = new AutoReplyContentView();

            content.AutoReplyId = model.Main.Id;
            var news = model.Send[0]; //保存多条内容。只有新闻存在多条情况

            content.IsEncrypt = news.isSecurityPost;
            var cate = (AutoReplyContentEnum)Enum.Parse(typeof(AutoReplyContentEnum), news.NewsCate, true);

            //选择资源文件
            if (news.materialId.HasValue && news.materialId.Value > 0)
            {
                var config = WeChatCommonService.GetWeChatConfigByID(model.Main.AppId);
                content.FileID       = news.materialId;
                content.IsNewContent = false;
                //更新MediaID
                //out 之后news.isSecurityPost 被清空
                Innocellence.WeChatMain.Common.WechatCommon.GetMediaIDByFileID(news.materialId, _attachmentsItemService, config.WeixinCorpId, out news);

                content.Content = JsonConvert.SerializeObject(new List <NewsInfoView> {
                    news
                });
            }
            else if (cate == AutoReplyContentEnum.NEWS)
            {                                          //图文消息特殊处理
                if (string.IsNullOrEmpty(news.NewsID)) //如果不是选择的素材
                {
                    var listArticle = GetArticleList(model.Send);

                    content.NewsID = string.Join(",", listArticle.Select(a => a.Id).ToArray());
                }
                else
                {
                    content.NewsID = news.NewsID;
                }
                content.IsNewContent = false;
                //content.SecondaryType = model.Main.Contents[0].SecondaryType;
                content.SecondaryType = (int)AutoReplyNewsEnum.MANUAL; //此处缺少功能,临时写死。画面应该增加返回最近的几条新闻
            }
            else
            {
                if (cate != AutoReplyContentEnum.TEXT && cate != AutoReplyContentEnum.LINK) //上传文件处理
                {
                    var mediaId = WechatCommon.GetMediaInfo(cate, news, model.Main.AppId);
                    content.MediaId = mediaId;
                }


                content.IsNewContent = true;
                //content.Content = JsonConvert.SerializeObject(model.Send);  //这个地方不应该存数组,todo
                content.Content = JsonConvert.SerializeObject(new List <NewsInfoView> {
                    news
                });
            }
            content.PrimaryType = (int)cate;
            list.Add(content);
            return(list);
        }
コード例 #5
0
        public ActionResult Get(string msg_signature = "", string timestamp = "", string nonce = "", string echostr = "")
        {
            try
            {
                var iAppID    = int.Parse(Request["AppID"] ?? "0");
                var objConfig = WeChatCommonService.GetWeChatConfigByID(iAppID);
                //return Content(echostr); //返回随机字符串则表示验证通过
                var verifyUrl = Signature.VerifyURL(objConfig.WeixinToken, objConfig.WeixinEncodingAESKey, objConfig.WeixinCorpId, msg_signature, timestamp, nonce,
                                                    echostr);
                var logstr = string.Format("-objConfig.WeixinToken = {0}\n-objConfig.WeixinEncodingAESKey={1}\n-msg_signature={2}\n-timestamp={3}\n-nonce={4}\n-echostr={5}\n-objConfig.WeixinCorpId={6}", objConfig.WeixinToken, objConfig.WeixinEncodingAESKey, msg_signature, timestamp, nonce, echostr, objConfig.WeixinCorpId);
                log.Debug(logstr);
                if (verifyUrl != null)
                {
                    log.Debug(verifyUrl);
                    return(Content(verifyUrl)); //返回解密后的随机字符串则表示验证通过
                }
                else
                {
                    log.Debug("verifyUrl is null");
                    return(Content("如果你在浏览器中看到这句话,说明此地址可以被作为微信公众账号后台的Url,请注意保持Token一致。"));
                }
            }
            catch (Exception ex)
            {
                log.Error(ex, Request.Url.ToString());
            }

            return(Content(""));
        }
コード例 #6
0
        /// <summary>
        /// 发送微信消息.自动
        /// </summary>
        /// <param name="iAppID"></param>
        /// <param name="strMsgType"></param>
        /// <param name="strContent"></param>
        /// <param name="lstContent"></param>
        /// <returns></returns>
        public static MassResult SendMsgToUser(int iAppID, string strMsgType, string strContent, List <ArticleInfoView> lstContent)
        {
            MassResult ret;
            var        objConfig = WeChatCommonService.GetWeChatConfigByID(iAppID);

            if (objConfig.IsCorp.HasValue && objConfig.IsCorp.Value)
            {
                ret = SendMsg(iAppID, strMsgType, lstContent[0].ToUser.Replace(",", "|"), lstContent[0].ToDepartment.Replace(",", "|"), lstContent[0].ToTag.Replace(",", "|"), strContent, lstContent);
            }
            else
            {
                var retMP = WechatCommonMP.SendMsgMP(lstContent,
                                                     new WeChat.Domain.ViewModelFront.SearchUserMPView()
                {
                    Group    = lstContent[0].NewsInfo.Group,
                    City     = lstContent[0].NewsInfo.City,
                    Province = lstContent[0].NewsInfo.Province,
                    Sex      = lstContent[0].NewsInfo.Sex
                }, null);
                ret = new MassResult()
                {
                    errcode = (ReturnCode_QY)retMP.errcode, errmsg = retMP.errmsg
                };
            }

            return(ret);
        }
コード例 #7
0
        public ActionResult AddQrCode(QrCodeView model)
        {
            var config  = WeChatCommonService.GetWeChatConfigByID(model.AppId);
            var sceneId = ((IQrCodeService)_BaseService).GenerateSceneId();
            var result  = QrCodeApi.Create(config.WeixinAppId, config.WeixinCorpSecret, 0, sceneId);

            if (result.errcode == Weixin.ReturnCode.请求成功)
            {
                var    url      = QrCodeApi.GetShowQrCodeUrl(result.ticket);
                string ourPath  = "/content/OrCodeMP" + result.url.Substring(result.url.IndexOf("/q/")) + ".jpg";
                string savePath = Server.MapPath(ourPath);
                if (!System.IO.File.Exists(savePath))//判断文件是否存在
                {
                    string saveFolderPath = savePath.Replace(savePath.Split('\\').Last(), "");

                    if (!Directory.Exists(saveFolderPath))         //判断文件夹是否存在
                    {
                        Directory.CreateDirectory(saveFolderPath); //不存在则创建文件夹
                    }
                    var mClient = new WebClient();
                    mClient.DownloadFile(url, savePath);
                }
                model.Url     = ourPath;
                model.SceneId = sceneId;
                ((IQrCodeService)_BaseService).AddOrCode(model, User.Identity.Name);
            }

            return(Json(new { result = 200 }));
        }
コード例 #8
0
        public static MassResult SendMsg(int iAppID, string strMsgType, string strUser, string strDept, string strTags, string strContent, List <ArticleInfoView> lstContent, bool isPreview = false)
        {
            var objConfig = WeChatCommonService.GetWeChatConfigByID(iAppID);

            if (objConfig.IsCorp.HasValue && !objConfig.IsCorp.Value)
            {
                var ret = WechatCommonMP.SendMsg(strMsgType, strContent, lstContent, strTags, strUser.Split(','), null);

                return(new MassResult()
                {
                    errmsg = ret.errmsg, errcode = (ReturnCode_QY)ret.errcode
                });
            }
            else
            {
                int isSafe = 0;
                if (lstContent != null && lstContent.Count > 0)
                {
                    if (lstContent[0].NewsInfo != null && lstContent[0].NewsInfo.isSecurityPost.HasValue && lstContent[0].NewsInfo.isSecurityPost.Value)
                    {
                        isSafe = 1;
                    }
                }
                return(SendMsgQY(iAppID, strMsgType, strUser, strDept, strTags, strContent, lstContent, isSafe, isPreview));
            }
        }
コード例 #9
0
        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));
        }
コード例 #10
0
        public string GetToken(int iWeChatID)
        {
            var Config = WeChatCommonService.GetWeChatConfigByID(iWeChatID);

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

            // return resultToken.access_token;
        }
コード例 #11
0
        /// <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));
        }
コード例 #12
0
        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
        }
コード例 #13
0
        /// <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"));
        }
コード例 #14
0
        public ActionResult WechatServiceMessage()
        {
            var config = WeChatCommonService.GetWeChatConfigByID(AppId);

            if (null != config && !string.IsNullOrEmpty(config.CoverUrl))
            {
                ViewBag.AppImg = config.CoverUrl;
            }
            return(View());
        }
コード例 #15
0
        public string GetTokenByID(int iWeChatID)
        {
            LogManager.GetLogger(this.GetType()).Debug("Request.Url.AbsoluteUri:" + Request.Url.AbsoluteUri);
            var Config = WeChatCommonService.GetWeChatConfigByID(iWeChatID);

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

            // return resultToken.access_token;
        }
コード例 #16
0
        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 } }));
        }
コード例 #17
0
        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);
        }
コード例 #18
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);
        }
コード例 #19
0
        // 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);
        }
コード例 #20
0
        /// <summary>
        /// {"appid":"wx41a2bf0afed3b33d","noncestr":"USUtYzXJw4wELBKX","sign":"ed18cbd26d2f82b44dd2fb70743b484e68e68d3c","timestamp":"1438746212"}
        /// </summary>
        /// <returns></returns>
        public ActionResult sign(int appId, string url)
        {
            var config = WeChatCommonService.GetWeChatConfigByID(appId);
            var ret    = JSSDKHelper.GetJsSdkUiPackage(config.WeixinCorpId, config.WeixinCorpSecret, url);

            return(Json(new
            {
                appid = ret.AppId,
                noncestr = ret.NonceStr,
                sign = ret.Signature,
                timestamp = ret.Timestamp
            }, JsonRequestBehavior.AllowGet));
        }
コード例 #21
0
        public ActionResult Agree()
        {
            if (string.IsNullOrEmpty(ViewBag.WeChatUserID))
            {
                return(Redirect("/notauthed.html"));
            }
            var config = WeChatCommonService.GetWeChatConfigByID(AppId);
            var Token  = AccessTokenContainer.TryGetToken(config.WeixinCorpId, config.WeixinCorpSecret);

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

            return(Redirect("~/subscribed.html"));
        }
コード例 #22
0
        /// <summary>
        /// 取得List数据
        /// </summary>
        /// <param name="predicate"></param>
        /// <param name="ConPage"></param>
        /// <returns></returns>
        public override List <AutoReplyView> GetListEx(Expression <Func <AutoReply, bool> > predicate, PageCondition ConPage)
        {
            // TODO: NEED CHECK APP ID
            int    appId    = int.Parse(Request["appid"]);
            string type     = Request["type"];
            string name     = Request["name"];
            bool   queryAll = false;

            if (bool.TryParse(Request["queryAll"], out queryAll))
            {
                if (queryAll)
                {
                    ConPage.PageSize = int.MaxValue;
                }
            }

            if (!string.IsNullOrEmpty(type))
            {
                int primaryType = int.Parse(type);
                predicate = predicate.AndAlso(x => x.PrimaryType == primaryType);
            }

            if (!string.IsNullOrEmpty(name))
            {
                name      = name.Trim().ToLower();
                predicate = predicate.AndAlso(x => x.Name.ToLower().Contains(name));
            }

            predicate = predicate.AndAlso(x => x.AppId == appId && x.IsDeleted == false);

            var list = _objService.GetList <AutoReplyView>(predicate, ConPage);

            // get type name;
            var wechatConfig = WeChatCommonService.GetWeChatConfigByID(appId);

            if (wechatConfig.IsCorp.Value)
            {
                ViewBag.IsCorp = 1;
                list.ForEach(x => x.KeywordTypeName = ((AutoReplyKeywordEnum)x.KeywordType).GetDescriptionByName());
            }
            else
            {
                list.ForEach(x => x.KeywordTypeName = ((AutoReplyMPKeywordEnum)x.KeywordType).GetDescriptionByName());
            }

            return(list);
        }
コード例 #23
0
        /// <summary>
        /// {"appid":"wx41a2bf0afed3b33d","noncestr":"USUtYzXJw4wELBKX","sign":"ed18cbd26d2f82b44dd2fb70743b484e68e68d3c","timestamp":"1438746212"}
        /// </summary>
        /// <returns></returns>
        public ActionResult GetJsSDK(int appId, string url)
        {
            //if (!VerifyParam("url"))
            //{
            //    return ErrMsg();
            //}
            var config = WeChatCommonService.GetWeChatConfigByID(appId);
            var ret    = Weixin.MP.Helpers.JSSDKHelper.GetJsSdkUiPackage(config.WeixinCorpId, config.WeixinCorpSecret, url);

            return(Json(new
            {
                appid = ret.AppId,
                noncestr = ret.NonceStr,
                sign = ret.Signature,
                timestamp = ret.Timestamp
            }, JsonRequestBehavior.AllowGet));
        }
コード例 #24
0
        public virtual ActionResult Index(int appId)
        {
            ViewBag.AppId = appId;
            var wechatConfig = WeChatCommonService.GetWeChatConfigByID(appId);

            if (wechatConfig.IsCorp.Value)
            {
                ViewBag.IsCorp       = 1;
                ViewBag.KeywordTypes = typeof(AutoReplyKeywordEnum).GetAllItems();
            }
            else
            {
                ViewBag.IsCorp = 0;
                var mpList = typeof(AutoReplyMPKeywordEnum).GetAllItems();
                //mpList.RemoveAll(e => e.Value == (int)AutoReplyMPKeywordEnum.EnterEvent);
                ViewBag.KeywordTypes = mpList;
            }
            return(base.Index());
        }
コード例 #25
0
        /// <summary>
        /// {"appid":"wx41a2bf0afed3b33d","noncestr":"USUtYzXJw4wELBKX","sign":"ed18cbd26d2f82b44dd2fb70743b484e68e68d3c","timestamp":"1438746212"}
        /// </summary>
        /// <returns></returns>
        public ActionResult sign(int appId, string url)
        {
            log.Debug("web API sign Start  appId:{0} Uri:{1} Request URL:{2}", appId, url, Request.Url);

            var config = WeChatCommonService.GetWeChatConfigByID(appId);

            var ret = JSSDKHelper.GetJsSdkUiPackage(config.WeixinCorpId, config.WeixinCorpSecret, url);


            log.Debug("web API sign End  UserID:{0} noncestr:{1} Signature:{2} Timestamp:{3}", config.WeixinAppId, ret.NonceStr, ret.Signature, ret.Timestamp);

            return(Json(new
            {
                appid = ret.AppId,
                noncestr = ret.NonceStr,
                sign = ret.Signature,
                timestamp = ret.Timestamp
            }, JsonRequestBehavior.AllowGet));
        }
コード例 #26
0
        public CreateMenuConditionalResult CreateConditionalMenu(int appId, string menuJsonStr, Weixin.MP.Entities.Menu.MenuMatchRule menuMatchRule)
        {
            var config = WeChatCommonService.GetWeChatConfigByID(appId);

            if (config != null && config.IsCorp.HasValue && !config.IsCorp.Value)
            {
                var menu = Innocellence.Weixin.MP.CommonAPIs.CommonApi.GetMenuFromJson(menuJsonStr);
                if (menu != null)
                {
                    Weixin.MP.Entities.Menu.ConditionalButtonGroup conditonalBtnGroup = new Weixin.MP.Entities.Menu.ConditionalButtonGroup()
                    {
                        button    = menu.menu.button,
                        matchrule = menuMatchRule,
                    };
                    var result = Innocellence.Weixin.MP.CommonAPIs.CommonApi.CreateMenuConditional(config.WeixinCorpId, config.WeixinCorpSecret, conditonalBtnGroup);
                    return(result);
                }
            }
            throw new Exception(string.Format("{0} 的配置错误, 请联系管理员.", appId));
        }
コード例 #27
0
        public ActionResult EditNews(string id, int appId)
        {
            var config = WeChatCommonService.GetWeChatConfigByID(appId);

            if (null != config && !string.IsNullOrEmpty(config.CoverUrl))
            {
                ViewBag.AppImg = config.CoverUrl;
            }
            else
            {
                ViewBag.AppImg = "/Content/picture/AccountLogo0.jpg";
                int AccountManageId = 0;
                if (int.TryParse(Request.Cookies["AccountManageId"].Value, out AccountManageId))
                {
                    ViewBag.AppImg = _accountManageService.Repository.GetByKey(AccountManageId).AccountLogo;
                }
                ViewBag.AppImg = _accountManageService.Repository.GetByKey(AccountManageId).AccountLogo;
            }
            return(View("../Message/EditNews"));
        }
コード例 #28
0
        public JsonResult EditPost(AutoReplyNewView model)
        {
            var wechatConfig = WeChatCommonService.GetWeChatConfigByID(model.Main.AppId);

            if (string.IsNullOrWhiteSpace(model.Main.Description))
            {
                model.Main.Description = string.Empty;
            }

            // 口令类型
            model.Main.Keywords = GetAutoReplySubTypes(model);

            // 口令回复
            model.Main.Contents = GetAutoReplyList(model);

            //if (!wechatConfig.IsCorp.Value)
            //{
            model.SetExtraContent(model.Main.Contents);
            //}

            // 输入校验
            //if (!BeforeAddOrUpdate(model) || !ModelState.IsValid)
            //{
            //    return Json(GetErrorJson(), JsonRequestBehavior.AllowGet);
            //}

            // add
            if (model.Main.Id == 0)
            {
                _autoReplyService.Add(model.Main);
            }
            // Edit
            else
            {
                _autoReplyService.Update(model.Main);
            }

            //return RedirectToAction("Index", new RouteValueDictionary { {"appId", appId} });
            return(Json(doJson(null), JsonRequestBehavior.AllowGet));
        }
コード例 #29
0
        private dynamic GetCurrentSupportMsgTypes(bool isHasReaded = false)
        {
            List <dynamic> msgTypes = new List <dynamic>();

            msgTypes = typeof(WechatUserMessageLogContentType).GetAllItems();
            if (isHasReaded)
            {
                List <int> hasReadedDisplayMsgTypes = new List <int>()
                {
                    (int)WechatUserMessageLogContentType.Request_Text,
                    (int)WechatUserMessageLogContentType.Request_Voice,
                    (int)WechatUserMessageLogContentType.Request_Video,
                    (int)WechatUserMessageLogContentType.Request_Image,
                    (int)WechatUserMessageLogContentType.Request_Link,
                    (int)WechatUserMessageLogContentType.Response_Empty
                };
                msgTypes.RemoveAll(obj => !hasReadedDisplayMsgTypes.Contains(obj.Value));
            }
            else
            {
                List <int> notDisplayMsgTypes = new List <int>()
                {
                    (int)WechatUserMessageLogContentType.DEFAULT,
                    (int)WechatUserMessageLogContentType.Request_Event,
                    (int)WechatUserMessageLogContentType.Request_Chat,
                };
                msgTypes.RemoveAll(obj => notDisplayMsgTypes.Contains(obj.Value) || obj.Value > (int)WechatUserMessageLogContentType.Response_Empty);
            }
            msgTypes.RemoveAll(obj => obj.Value == (int)WechatUserMessageLogContentType.Request_ShortVideo);
            if (AppId > 0)
            {
                var accountManage = WeChatCommonService.GetWeChatConfigByID(AppId);
                if (null != accountManage && accountManage.IsCorp.HasValue && accountManage.IsCorp.Value)
                {
                    msgTypes.RemoveAll(obj => obj.Value == (int)WechatUserMessageLogContentType.Request_Link);
                }
            }
            return(msgTypes);
        }
コード例 #30
0
 public void UpdateQRCode(QrCodeMPItem thisqr, int newappid, string isUpdate)
 {
     if (thisqr.UpdatedDate.Value.AddMonths(1) < DateTime.Now || isUpdate.Equals("true"))
     {
         var config = WeChatCommonService.GetWeChatConfigByID(newappid);
         var result = QrCodeApi.Create(config.WeixinAppId, config.WeixinCorpSecret, 2592000, (int)thisqr.SceneId);
         if (result.errcode == Weixin.ReturnCode.请求成功)
         {
             var user = _WechatMPUserService.Repository.Entities.Where(u => u.Id == thisqr.RelatedUserId);
             if (user.Any())
             {
                 var    userinfo    = Innocellence.Weixin.MP.AdvancedAPIs.UserApi.Info(config.WeixinCorpId, config.WeixinCorpSecret, user.FirstOrDefault().OpenId);
                 string userHeadUrl = userinfo.headimgurl;
                 var    qrurl       = QrCodeApi.GetShowQrCodeUrl(result.ticket);
                 thisqr.Url         = CombineQrCodeAndHeadImg(userHeadUrl, qrurl);
                 thisqr.UpdatedDate = DateTime.Now;
             }
         }
         ///重新更新当前model
         _QrCodeService.Repository.Update(thisqr);
     }
 }