public ActionResult WeChart(string id)
        {
            wx_userweixin wxuser = wx_userweixinService.instance().SingleByCompanyID(new Guid(id));

            if (wxuser == null)
            {
                wxuser = new wx_userweixin()
                {
                    CompanyID = new Guid(id)
                }
            }
            ;
            return(View(wxuser));
        }
Example #2
0
        /// <summary>
        ///【强制刷新】access_token值
        /// access_token是公众号的全局唯一票据,公众号调用各接口时都需使用access_token。正常情况下access_token有效期为7200秒,
        /// 重复获取将导致上次获取的access_token失效。
        /// 每日限额获取access_token.我们将access_token保存到数据库里,间隔时间为20分钟,从微信公众平台获得一次。
        /// </summary>
        /// <returns></returns>
        public static string FlushAccessToken(int wid, out string error)
        {
            string token = "";

            error = "";
            try
            {
                wx_property_info  pBll = new wx_property_info();
                BLL.wx_userweixin wBll = new wx_userweixin();

                Model.wx_userweixin weixininfo = wBll.GetModel(wid);
                if (weixininfo.AppId == null || weixininfo.AppSecret == null || weixininfo.AppId.Trim().Length <= 0 || weixininfo.AppSecret.Trim().Length <= 0)
                {
                    error = "appId或者AppSecret未填写完全,请在[我的公众帐号]里补全信息!";
                    return("");
                }

                var result = CommonApi.GetToken(weixininfo.AppId, weixininfo.AppSecret);
                token = result.access_token;


                //第一次插入微信属性表
                if (!pBll.ExistsWid(wid, "access_token"))
                {
                    //插入
                    pBll.AddAccess_Token(wid, token, result.expires_in);
                }
                else
                {
                    WeiXinPF.Model.wx_property_info wxProperty = new WeiXinPF.Model.wx_property_info();
                    wxProperty = pBll.GetModelList("iName='access_token' and wid=" + wid)[0];
                    //更新到数据库里
                    wxProperty.iContent   = token;
                    wxProperty.createDate = DateTime.Now;
                    wxProperty.expires_in = result.expires_in;
                    pBll.Update(wxProperty);
                }
            }
            catch (Exception ex)
            {
                error = "获得access_token出错:" + ex.Message;
                WXLogs.AddLog(wid, "access_token", "获得access_token(FlushAccessToken)", error);
            }

            return(token);
        }
Example #3
0
        public MsgUserType GetUserType(UserManagerDto user)
        {
            MsgUserType result = MsgUserType.User;

            //酒店管理员
            var wxHotelAdmin = new BLL.wx_hotel_admin();
            int intUser      = 0;

            if (int.TryParse(user.UserId, out intUser))
            {
                var hotelAdmin = wxHotelAdmin.GetModel(intUser);
                if (hotelAdmin != null)
                {
                    result = MsgUserType.Hotel;
                    return(result);
                }

                //餐饮管理员
                var wxDiancaiAdmin = new BLL.wx_diancai_admin();
                var diancaiAdmin   = wxDiancaiAdmin.GetModel(intUser);
                if (diancaiAdmin != null)
                {
                    result = MsgUserType.Shop;
                    return(result);
                }

                //todo:是否需要判断固定的微信号?
                //景区管理员
                var count = new wx_userweixin().GetUserWxNumCount(intUser);
                if (count > 0)
                {
                    result = MsgUserType.Scenic;
                    return(result);
                }
            }
            else
            {
                //todo:判断微信是否是用户
                //如果userid不是Int型 ,默认就认为它是微信用户
                result = MsgUserType.WeChatCustomer;
                return(result);
            }


            return(result);
        }
        public JsonResult WeChart(FormCollection form)
        {
            ResultBase_form result = new ResultBase_form();
            wx_userweixin   m      = new wx_userweixin();

            TryUpdateModel <wx_userweixin>(m, form);
            if (m.ID == Guid.Empty)
            {
                result.status = wx_userweixinService.instance().Insert(m);
            }
            else
            {
                result.status = wx_userweixinService.instance().Update(m);
            }
            result.msg       = result.status == 0 ? "操作失败" : "操作成功";
            result.ResultURL = "/Company/Index";
            return(Json(result, JsonRequestBehavior.AllowGet));
        }
        /// <summary>
        /// 及时获得access_token值
        /// access_token是公众号的全局唯一票据,公众号调用各接口时都需使用access_token。正常情况下access_token有效期为7200秒,
        /// 重复获取将导致上次获取的access_token失效。
        /// 每日限额获取access_token.我们将access_token保存到数据库里,间隔时间为20分钟,从微信公众平台获得一次。
        /// </summary>
        /// <returns></returns>
        public static string getAccessToken(Guid CompanyID, out string error)
        {
            string token = "";

            error = "";
            try
            {
                wx_userweixin wx = wx_userweixinService.instance().SingleByCompanyID(CompanyID);
                //if (wx.AppId == null || wx.AppSecret == null || wx.AppId.Trim().Length <= 0 || wx.AppSecret.Trim().Length <= 0)
                //{
                //    error = "appId或者AppSecret未填写完全,请在[我的公众帐号]里补全信息!";
                //    return "";
                //}
                TimeSpan chajun = DateTime.Now - wx.ModifyTime;
                if (string.IsNullOrEmpty(wx.Access_Token) || chajun.TotalSeconds >= wx.expires_in)
                {
                    //var result = CommonApi.GetToken(wx.AppId, wx.AppSecret);
                    //wx.Access_Token = result.access_token;
                    //wx.expires_in = result.expires_in;
                    //wx.ModifyTime = DateTime.Now;
                    //if (wx_userweixinService.instance().Update(wx) == 1)
                    //{
                    //    token = result.access_token;
                    //}
                    token = ReloadToken(CompanyID);
                }
                else
                {
                    token = wx.Access_Token;
                }
            }
            catch (Exception ex)
            {
                error = "获得access_token出错:" + ex.Message;
            }
            return(token);
        }
        public static string ReloadToken(Guid CompanyID)
        {
            wx_userweixin wx = wx_userweixinService.instance().SingleByCompanyID(CompanyID);
            //if (wx.AppId == null || wx.AppSecret == null || wx.AppId.Trim().Length <= 0 || wx.AppSecret.Trim().Length <= 0)
            //{
            //    return "appId或者AppSecret未填写完全,请在[我的公众帐号]里补全信息!";
            //}
            var wx_open = wx_openInfoService.instance().Single(new Guid(System.Configuration.ConfigurationManager.AppSettings["openID"]));
            RefreshAuthorizerTokenResult result = ComponentApi.ApiAuthorizerToken(wx_open.open_access_token, wx_open.open_sAppID, wx.AppId, wx.refresh_token);

            if (result.errcode == Entity.Weixin.ReturnCode.请求成功)
            {
                wx.Access_Token  = result.authorizer_access_token;
                wx.refresh_token = result.authorizer_refresh_token;
                wx.expires_in    = result.expires_in;
                wx.ModifyTime    = DateTime.Now;
                if (wx_userweixinService.instance().Update(wx) == 1)
                {
                    return("ok");
                }
                return("更新数据库出错");
            }
            return(result.errcode.ToString());
        }
Example #7
0
        protected void Page_Load(object sender, EventArgs e)
        {
            string Token = "";//与微信公众账号后台的Token设置保持一致,区分大小写。
            int    wid   = 0;

            wid = MyCommFun.RequestInt("apiid");

            if (wid <= 0)
            {
                WriteContent("参数非法");
                return;
            }
            wx_userweixin wbll = new wx_userweixin();

            Token = wbll.GetWeiXinToken(wid);
            if (Token == null || string.IsNullOrEmpty(Token))
            {
                WriteContent("不存在该微信号或账号已过期或已被禁用!");
                return;
            }


            // Token = "uweixin";
            string signature = Request["signature"];
            string timestamp = Request["timestamp"];
            string nonce     = Request["nonce"];
            string echostr   = Request["echostr"];

            if (Request.HttpMethod == "GET")
            {
                //get method - 仅在微信后台填写URL验证时触发
                if (CheckSignature.Check(signature, timestamp, nonce, Token))
                {
                    WriteContent(echostr); //返回随机字符串则表示验证通过
                }
                else
                {
                    WriteContent("failed:" + signature + ",token:" + Token + " " + CheckSignature.GetSignature(timestamp, nonce, Token) + "。" +
                                 "如果你在浏览器中看到这句话,说明此地址可以被作为微信公众账号后台的Url,请注意保持Token一致。");
                }
                Response.End();
            }
            else
            {
                //本地测试的时候注释掉 ----start -----

                if (!CheckSignature.Check(signature, timestamp, nonce, Token))
                {
                    WriteContent("参数错误!");
                    return;
                }
                //本地测试的时候注释掉 ----end -----

                //post method - 当有用户想公众账号发送消息时触发
                Model.wx_userweixin uweixin = wbll.GetModel(wid);
                var postModel = new PostModel()
                {
                    Signature     = Request.QueryString["signature"],
                    Msg_Signature = Request.QueryString["msg_signature"],
                    Timestamp     = Request.QueryString["timestamp"],
                    Nonce         = Request.QueryString["nonce"],
                    //以下保密信息不会(不应该)在网络上传播,请注意
                    Token          = Token,
                    EncodingAESKey = uweixin.extStr, //根据自己后台的设置保持一致
                    AppId          = uweixin.AppId   //根据自己后台的设置保持一致
                };


                //v4.2.2之后的版本,可以设置每个人上下文消息储存的最大数量,防止内存占用过多,如果该参数小于等于0,则不限制
                var maxRecordCount = 10;

                //自定义MessageHandler,对微信请求的详细判断操作都在这里面。
                var messageHandler = new CustomMessageHandler(Request.InputStream, postModel, maxRecordCount);

                try
                {
                    //测试时可开启此记录,帮助跟踪数据,使用前请确保App_Data文件夹存在,且有读写权限。
                    messageHandler.RequestDocument.Save(
                        Server.MapPath("~/App_Data/" + DateTime.Now.Ticks + "_Request_" +
                                       messageHandler.RequestMessage.FromUserName + ".txt"));
                    //执行微信处理过程
                    messageHandler.Execute();
                    //测试时可开启,帮助跟踪数据
                    messageHandler.ResponseDocument.Save(
                        Server.MapPath("~/App_Data/" + DateTime.Now.Ticks + "_Response_" +
                                       messageHandler.ResponseMessage.ToUserName + ".txt"));


                    //为了解决官方微信5.0软件换行bug暂时添加的方法,平时用下面一个方法即可 begin
                    string lastStr = "";
                    if (messageHandler != null && messageHandler.ResponseDocument != null && messageHandler.ResponseDocument.ToString().Trim() != "")
                    {
                        lastStr = messageHandler.ResponseDocument.ToString().Replace("\r\n", "\n");
                    }
                    else
                    {
                        lastStr = messageHandler.ResponseDocument.ToString();
                    }
                    // WriteContent( messageHandler.ResponseDocument.ToString());
                    //为了解决官方微信5.0软件换行bug暂时添加的方法,平时用下面一个方法即可 end

                    //如果自动回复已经关闭,则不返回内容,start 1220

                    WeiXCommFun wxcomm = new WeiXCommFun();
                    int         apiid  = wxcomm.getApiid();
                    if (!wxcomm.wxCloseKW(apiid))
                    {
                        lastStr = "";
                    }
                    //如果自动回复已经关闭,则不返回内容,end 1220

                    WriteContent(lastStr);
                    return;
                }
                catch (Exception ex)
                {
                    using (TextWriter tw = new StreamWriter(Server.MapPath("~/App_Data/Error_" + DateTime.Now.Ticks + ".txt")))
                    {
                        tw.WriteLine(ex.Message);
                        tw.WriteLine(ex.InnerException.Message);
                        if (messageHandler.ResponseDocument != null)
                        {
                            tw.WriteLine(messageHandler.ResponseDocument.ToString());
                        }
                        tw.Flush();
                        tw.Close();
                    }
                    WriteContent("");
                }
                finally
                {
                    Response.End();
                }
            }
        }
Example #8
0
        /// <summary>
        /// 及时获得access_token值
        /// access_token是公众号的全局唯一票据,公众号调用各接口时都需使用access_token。正常情况下access_token有效期为7200秒,
        /// 重复获取将导致上次获取的access_token失效。
        /// 每日限额获取access_token.我们将access_token保存到数据库里,间隔时间为20分钟,从微信公众平台获得一次。
        /// </summary>
        /// <returns></returns>
        public static string getAccessToken(int wid, out string error)
        {
            string token = "";

            error = "";
            try
            {
                wx_property_info  pBll = new wx_property_info();
                BLL.wx_userweixin wBll = new wx_userweixin();

                Model.wx_userweixin weixininfo = wBll.GetModel(wid);
                if (weixininfo.AppId == null || weixininfo.AppSecret == null ||
                    weixininfo.AppId.Trim().Length <= 0 || weixininfo.AppSecret.Trim().Length <= 0)
                {
                    error = "appId或者AppSecret未填写完全,请在[我的公众帐号]里补全信息!";
                    WXLogs.AddLog(wid, "access_token", "获得access_token", error);
                    return("");
                }
                WeiXinPF.Model.wx_property_info wxProperty = new WeiXinPF.Model.wx_property_info();
                //第一次插入微信属性表
                if (!pBll.ExistsWid(wid, "access_token"))
                {
                    AccessTokenResult result = CommonApi.GetToken(weixininfo.AppId, weixininfo.AppSecret);
                    token = result.access_token;
                    pBll.AddAccess_Token(wid, token, result.expires_in);
                    return(token);

                    //WeChatAccountManager manager = WeChatAccountManager.CreateInstance(weixininfo.AppId, weixininfo.AppSecret);
                    //Credential credential = new Credential(manager);
                    //token = credential.AccessToken;
                    //pBll.AddAccess_Token(wid, token, 7000);
                    //return token;
                }

                wxProperty = pBll.GetModelList("iName='access_token' and wid=" + wid)[0];
                double chajunSecond = (DateTime.Now - wxProperty.createDate.Value).TotalSeconds;

                if (chajunSecond >= wxProperty.expires_in)
                {
                    //从微信平台重新获得access_token
                    AccessTokenResult result = CommonApi.GetToken(weixininfo.AppId, weixininfo.AppSecret);
                    token = result.access_token;
                    //更新到数据库里
                    wxProperty.iContent   = token;
                    wxProperty.createDate = DateTime.Now;
                    wxProperty.expires_in = result.expires_in;

                    //WeChatAccountManager manager = WeChatAccountManager.CreateInstance(weixininfo.AppId, weixininfo.AppSecret);
                    //Credential credential = new Credential(manager);
                    //token = credential.AccessToken;
                    ////更新到数据库里
                    //wxProperty.iContent = token;
                    //wxProperty.createDate = DateTime.Now;
                    //wxProperty.expires_in = 7000;
                    //pBll.Update(wxProperty);
                }
                else
                {
                    token = wxProperty.iContent;
                }
            }
            catch (Exception ex)
            {
                error = "获得access_token出错:" + ex.Message;
                WXLogs.AddLog(wid, "access_token", "获得access_token", error);
            }
            return(token);
        }
Example #9
0
        /// <summary>
        /// 获取jssdk 里的临时票据
        /// </summary>
        /// <param name="wid"></param>
        /// <param name="error"></param>
        /// <returns></returns>
        public static string getJsApiTicket(int wid, out string error)
        {
            string atErr       = "";
            string accessToken = getAccessToken(wid, out atErr);

            if (atErr != "")
            {
                accessToken = FlushAccessToken(wid, out atErr);
            }
            if (accessToken == "")
            {
                error = "取accessToken值出现异常";
                WXLogs.AddLog(wid, "getJsApiTicket", "获得getJsApiTicket", "WeiXinPF.WeiXinComm.getJsApiTicket" + error);
                return("");
            }

            string token = "";

            error = "";
            try
            {
                wx_property_info  pBll = new wx_property_info();
                BLL.wx_userweixin wBll = new wx_userweixin();

                Model.wx_userweixin weixininfo = wBll.GetModel(wid);
                if (weixininfo.AppId == null || weixininfo.AppSecret == null || weixininfo.AppId.Trim().Length <= 0 || weixininfo.AppSecret.Trim().Length <= 0)
                {
                    error = "appId或者AppSecret未填写完全,请在[我的公众帐号]里补全信息!";
                    return("");
                }
                WeiXinPF.Model.wx_property_info wxProperty = new WeiXinPF.Model.wx_property_info();
                //第一次插入微信属性表
                if (!pBll.ExistsWid(wid, "JsApiTicket"))
                {
                    string type = "jsapi";
                    var    url  = string.Format("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={0}&type={1}",
                                                accessToken, type);

                    JsApiTicketResult result = OneGulp.WeChat.HttpUtility.Get.GetJson <JsApiTicketResult>(url);
                    token = result.ticket;
                    //存入属性表
                    wxProperty.wid        = wid;
                    wxProperty.iName      = "JsApiTicket";
                    wxProperty.iContent   = token;
                    wxProperty.createDate = DateTime.Now;
                    wxProperty.expires_in = result.expires_in;
                    wxProperty.count      = 1;
                    pBll.Add(wxProperty);

                    return(token);
                }

                wxProperty = pBll.GetModelList("iName='JsApiTicket' and wid=" + wid)[0];
                double chajunSecond = (DateTime.Now - wxProperty.createDate.Value).TotalSeconds;

                if (chajunSecond >= wxProperty.expires_in)
                {  //从微信平台重新获得access_token
                    string type = "jsapi";
                    var    url  = string.Format("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={0}&type={1}",
                                                accessToken, type);

                    JsApiTicketResult result = OneGulp.WeChat.HttpUtility.Get.GetJson <JsApiTicketResult>(url);
                    token = result.ticket;

                    //更新到数据库里
                    wxProperty.iContent   = token;
                    wxProperty.createDate = DateTime.Now;
                    wxProperty.expires_in = result.expires_in;
                    pBll.Update(wxProperty);
                }
                else
                {
                    token = wxProperty.iContent;
                }
            }
            catch (Exception ex)
            {
                error = "获得getJsApiTicket出错:" + ex.Message;
                WXLogs.AddLog(wid, "getJsApiTicket", "获得getJsApiTicket", "WeiXinPF.WeiXinComm.getJsApiTicket" + error);
            }
            return(token);
        }
Example #10
0
        protected void Page_Load(object sender, EventArgs e)
        {
            string Token = "EtuFiNl9mTje5NTQ2LNl";//与微信公众账号后台的Token设置保持一致,区分大小写。
            int    wid   = 0;

            wid = MyCommFun.RequestInt("apiid");

            if (wid <= 0)
            {
                WriteContent("参数非法");
                return;
            }

            wx_userweixin wbll = new wx_userweixin();

            Token = wbll.GetWeiXinToken(wid);
            if (Token == null || string.IsNullOrEmpty(Token))
            {
                WriteContent("不存在该微信号!");
                return;
            }

            // Token = "uweixin";
            string signature = Request["signature"];
            string timestamp = Request["timestamp"];
            string nonce     = Request["nonce"];
            string echostr   = Request["echostr"];

            if (Request.HttpMethod == "GET")
            {
                //get method - 仅在微信后台填写URL验证时触发
                if (CheckSignature.Check(signature, timestamp, nonce, Token))
                {
                    WriteContent(echostr); //返回随机字符串则表示验证通过
                }
                else
                {
                    WriteContent("failed:" + signature + ",token:" + Token + " " + CheckSignature.GetSignature(timestamp, nonce, Token) + "。" +
                                 "如果你在浏览器中看到这句话,说明此地址可以被作为微信公众账号后台的Url,请注意保持Token一致。");
                }
                Response.End();
            }
            else
            {
                //post method - 当有用户想公众账号发送消息时触发
                //本地测试的时候注释掉 ----start -----

                if (!CheckSignature.Check(signature, timestamp, nonce, Token))
                {
                    WriteContent("参数错误!");
                    return;
                }

                //本地测试的时候注释掉 ----end -----
                //v4.2.2之后的版本,可以设置每个人上下文消息储存的最大数量,防止内存占用过多,如果该参数小于等于0,则不限制
                var maxRecordCount = 10;
                //      Senparc.Weixin.MP.Entities.Request.PostModel postModel = null;

                var postModel = new PostModel()
                {
                    Signature     = Request.QueryString["signature"],
                    Msg_Signature = Request.QueryString["msg_signature"],
                    Timestamp     = Request.QueryString["timestamp"],
                    Nonce         = Request.QueryString["nonce"],
                    //以下保密信息不会(不应该)在网络上传播,请注意
                    Token          = Token,
                    EncodingAESKey = "mgHwkbnJwqMojMcbPrFRBFjReCMSgTYtZGQkHeUduGr", //根据自己后台的设置保持一致
                    AppId          = "wx57d365e74490cf2f"                           //根据自己后台的设置保持一致
                };


                //自定义MessageHandler,对微信请求的详细判断操作都在这里面。
                var messageHandler = new CustomMessageHandler(Request.InputStream, postModel, maxRecordCount);

                try
                {
                    //测试时可开启此记录,帮助跟踪数据,使用前请确保App_Data文件夹存在,且有读写权限。
                    messageHandler.RequestDocument.Save(
                        Server.MapPath("~/App_Data/0000" + DateTime.Now.Ticks + "_Request_" +
                                       messageHandler.RequestMessage.FromUserName + ".txt"));
                    //执行微信处理过程
                    messageHandler.Execute();
                    //测试时可开启,帮助跟踪数据
                    messageHandler.ResponseDocument.Save(
                        Server.MapPath("~/App_Data/1111" + DateTime.Now.Ticks + "_Response_" +
                                       messageHandler.ResponseMessage.ToUserName + ".txt"));
                    WriteContent(messageHandler.ResponseDocument.ToString());
                    return;
                }
                catch (Exception ex)
                {
                    using (TextWriter tw = new StreamWriter(Server.MapPath("~/App_Data/Error_" + DateTime.Now.Ticks + ".txt")))
                    {
                        tw.WriteLine(ex.Message);
                        tw.WriteLine(ex.InnerException.Message);
                        if (messageHandler.ResponseDocument != null)
                        {
                            tw.WriteLine(messageHandler.ResponseDocument.ToString());
                        }
                        tw.Flush();
                        tw.Close();
                    }
                    WriteContent("");
                }
                finally
                {
                    Response.End();
                }
            }
        }
Example #11
0
        protected void Page_Load(object sender, EventArgs e)
        {
            string Token = "";//与微信公众账号后台的Token设置保持一致,区分大小写。
            int wid = 0;
            wid = MyCommFun.RequestInt("apiid");

            if (wid <= 0)
            {
                WriteContent("参数非法");
                return;
            }

            wx_userweixin wbll = new wx_userweixin();
            Token = wbll.GetWeiXinToken(wid);
            if (Token == null || string.IsNullOrEmpty(Token))
            {
                WriteContent("不存在该微信号!");
                return;
            }

               // Token = "uweixin";
            string signature = Request["signature"];
            string timestamp = Request["timestamp"];
            string nonce = Request["nonce"];
            string echostr = Request["echostr"];

            if (Request.HttpMethod == "GET")
            {
                //get method - 仅在微信后台填写URL验证时触发
                if (CheckSignature.Check(signature, timestamp, nonce, Token))
                {
                    WriteContent(echostr); //返回随机字符串则表示验证通过
                }
                else
                {
                    WriteContent("failed:" + signature + ",token:"+Token+" " + CheckSignature.GetSignature(timestamp, nonce, Token) + "。" +
                                "如果你在浏览器中看到这句话,说明此地址可以被作为微信公众账号后台的Url,请注意保持Token一致。");
                }
                Response.End();
            }
            else
            {
                //post method - 当有用户想公众账号发送消息时触发
                //本地测试的时候注释掉 ----start -----

                if (!CheckSignature.Check(signature, timestamp, nonce, Token))
                {
                    WriteContent("参数错误!");
                    return;
                }

                //本地测试的时候注释掉 ----end -----
                //v4.2.2之后的版本,可以设置每个人上下文消息储存的最大数量,防止内存占用过多,如果该参数小于等于0,则不限制
                var maxRecordCount = 10;

                //自定义MessageHandler,对微信请求的详细判断操作都在这里面。
                var messageHandler = new CustomMessageHandler(Request.InputStream, maxRecordCount);

                try
                {
                    //测试时可开启此记录,帮助跟踪数据,使用前请确保App_Data文件夹存在,且有读写权限。
                    //messageHandler.RequestDocument.Save(
                    //    Server.MapPath("~/App_Data/" + DateTime.Now.Ticks + "_Request_" +
                    //                   messageHandler.RequestMessage.FromUserName + ".txt"));
                    //执行微信处理过程
                    messageHandler.Execute();
                    //测试时可开启,帮助跟踪数据
                    //messageHandler.ResponseDocument.Save(
                    //    Server.MapPath("~/App_Data/" + DateTime.Now.Ticks + "_Response_" +
                    //                   messageHandler.ResponseMessage.ToUserName + ".txt"));
                    WriteContent(messageHandler.ResponseDocument.ToString());
                    return;
                }
                catch (Exception ex)
                {
                    using (TextWriter tw = new StreamWriter(Server.MapPath("~/App_Data/Error_" + DateTime.Now.Ticks + ".txt")))
                    {
                        tw.WriteLine(ex.Message);
                        tw.WriteLine(ex.InnerException.Message);
                        if (messageHandler.ResponseDocument != null)
                        {
                            tw.WriteLine(messageHandler.ResponseDocument.ToString());
                        }
                        tw.Flush();
                        tw.Close();
                    }
                    WriteContent("");
                }
                finally
                {
                    Response.End();
                }
            }
        }
Example #12
0
        public List <ShortMsgWithCountDto> GetAllLastNewMsg(UserManagerDto toUserDto)
        {
            List <ShortMsgWithCountDto> result = new List <ShortMsgWithCountDto>();

            if (toUserDto != null)
            {
                var userType = _userService.GetUserType(toUserDto);
                Expression <Func <ShortMsg, bool> > func;
                if (userType != MsgUserType.User)
                {
                    var userids    = new List <string>();
                    var hotelBll   = new BLL.wx_hotel_admin();
                    var diancaiBll = new BLL.wx_diancai_admin();
                    switch (userType)
                    {
                    case MsgUserType.Hotel:
                        var listU = hotelBll.GetModelList(String.Format(
                                                              "HotelId=(SELECT HotelId FROM dbo.wx_hotel_admin WHERE ManagerId={0})"
                                                              , toUserDto.UserId));
                        if (listU != null && listU.Any())
                        {
                            userids = listU.Select(i => i.ManagerId.ToString()).ToList();
                        }
                        break;

                    case MsgUserType.Shop:
                        var listD = diancaiBll.GetModelList(String.Format(
                                                                "ShopId=(SELECT ShopId FROM dbo.wx_diancai_admin WHERE ManagerId={0})"
                                                                , toUserDto.UserId));
                        if (listD != null && listD.Any())
                        {
                            userids = listD.Select(i => i.ManagerId.ToString()).ToList();
                        }
                        break;

                    case MsgUserType.Scenic:
                    default:
                        //景区管理员
                        var count = new wx_userweixin().GetUserWxNumCount(toUserDto.UserId.ToInt());
                        if (count > 0)
                        {
                            userids.Add(toUserDto.UserId);
                        }

                        break;
                    }


                    func = c =>
                           c.MsgToUserType == (int)userType &&
                           userids.Contains(c.ToUserId) &&
                           c.IsRead == false;
                }
                else
                {
                    func = c =>
                           c.ToUserId == toUserDto.UserId && c.IsRead == false;
                }
                var msgList = _msgRepository.GetAllList(func);
                //todo:判断组合方法
                //现在是如果不是微信用户发的,就按发送人分组
                //是微信用户发的直接分组
                var list = msgList.Where(c => (MsgUserType)c.MsgFromUserType
                                         != MsgUserType.WeChatCustomer).GroupBy(c =>
                                                                                new { FromUserId = c.FromUserId, Type = c.Type, DetailType = c.DetailType })
                           .Select(c =>
                                   new
                {
                    Count = c.Count(),
                    Key   = c.Key
                }).ToList();

                if (list.Any())
                {
                    var listReslut = list.Select(c => new ShortMsgWithCountDto
                    {
                        Count = c.Count,
                        Msg   = GetLastNewMsg(toUserDto, c.Key.FromUserId, c.Key.Type, c.Key.DetailType)
                    }).ToList();

                    //多个商品在商品描述上加上xx等5件商品
                    listReslut.ForEach(c =>
                    {
                        if (c.Count > 1)
                        {
                            var index = c.Msg.Content.LastIndexOf(']');

                            c.Msg.Content = c.Msg.Content.Insert(index + 1,
                                                                 String.Format("等{0}件商品", c.Count));
                        }
                    });
                    result.AddRange(listReslut);
                }

                //添加是微信用户发的直接分组的
                if (msgList.Any(c => (MsgUserType)c.MsgFromUserType == MsgUserType.WeChatCustomer))
                {
                    var wxlist = msgList.Where(c => (MsgUserType)c.MsgFromUserType
                                               == MsgUserType.WeChatCustomer).GroupBy(c => c.MsgFromUserType)
                                 .Select(c =>
                                         new
                    {
                        Count = c.Count(),
                        Key   = c.Max(u => u.Id)
                    }).ToList();

                    if (wxlist.Any())
                    {
                        var listReslut = wxlist.Select(c => new ShortMsgWithCountDto
                        {
                            Count = c.Count,
                            Msg   = GetMsg(c.Key)
                        }).ToList();

                        //多个订单在商品描述上加上xx等5件订单
                        listReslut.ForEach(c =>
                        {
                            if (c.Count > 1)
                            {
                                var index      = c.Msg.Content.LastIndexOf("的订单");
                                var msgContent = c.Msg.Content.Substring(0, index);
                                var msgHz      = c.Msg.Content.Substring(c.Msg.Content.LastIndexOf(","));
                                //todo:写死的判断多个时后缀
                                var hz        = c.Msg.Type.ToLower().Contains("order") ? "订单" : "";
                                c.Msg.Content = String.Format("{2}等{0}个{1}{3}", c.Count, hz, msgContent, msgHz);
                            }
                        });
                        result.AddRange(listReslut);
                    }
                }
            }

            return(result);
        }
Example #13
0
        protected void Page_Load(object sender, EventArgs e)
        {
            string Token = "";//与微信公众账号后台的Token设置保持一致,区分大小写。
            int    wid   = 0;

            wid = MyCommFun.RequestInt("apiid");

            if (wid <= 0)
            {
                WriteContent("参数非法");
                return;
            }

            wx_userweixin wbll = new wx_userweixin();

            Token = wbll.GetWeiXinToken(wid);
            if (Token == null || string.IsNullOrEmpty(Token))
            {
                WriteContent("不存在该微信号!");
                return;
            }

            // Token = "uweixin";
            string signature = Request["signature"];
            string timestamp = Request["timestamp"];
            string nonce     = Request["nonce"];
            string echostr   = Request["echostr"];

            if (Request.HttpMethod == "GET")
            {
                //get method - 仅在微信后台填写URL验证时触发
                if (CheckSignature.Check(signature, timestamp, nonce, Token))
                {
                    WriteContent(echostr); //返回随机字符串则表示验证通过
                }
                else
                {
                    WriteContent("failed:" + signature + ",token:" + Token + " " + CheckSignature.GetSignature(timestamp, nonce, Token) + "。" +
                                 "如果你在浏览器中看到这句话,说明此地址可以被作为微信公众账号后台的Url,请注意保持Token一致。");
                }
                Response.End();
            }
            else
            {
                //post method - 当有用户想公众账号发送消息时触发
                //本地测试的时候注释掉 ----start -----

                if (!CheckSignature.Check(signature, timestamp, nonce, Token))
                {
                    WriteContent("参数错误!");
                    return;
                }

                //本地测试的时候注释掉 ----end -----
                //v4.2.2之后的版本,可以设置每个人上下文消息储存的最大数量,防止内存占用过多,如果该参数小于等于0,则不限制
                var maxRecordCount = 10;

                //自定义MessageHandler,对微信请求的详细判断操作都在这里面。
                var messageHandler = new CustomMessageHandler(Request.InputStream, maxRecordCount);

                try
                {
                    //测试时可开启此记录,帮助跟踪数据,使用前请确保App_Data文件夹存在,且有读写权限。
                    //messageHandler.RequestDocument.Save(
                    //    Server.MapPath("~/App_Data/" + DateTime.Now.Ticks + "_Request_" +
                    //                   messageHandler.RequestMessage.FromUserName + ".txt"));
                    //执行微信处理过程
                    messageHandler.Execute();
                    //测试时可开启,帮助跟踪数据
                    //messageHandler.ResponseDocument.Save(
                    //    Server.MapPath("~/App_Data/" + DateTime.Now.Ticks + "_Response_" +
                    //                   messageHandler.ResponseMessage.ToUserName + ".txt"));
                    WriteContent(messageHandler.ResponseDocument.ToString());
                    return;
                }
                catch (Exception ex)
                {
                    using (TextWriter tw = new StreamWriter(Server.MapPath("~/App_Data/Error_" + DateTime.Now.Ticks + ".txt")))
                    {
                        tw.WriteLine(ex.Message);
                        tw.WriteLine(ex.InnerException.Message);
                        if (messageHandler.ResponseDocument != null)
                        {
                            tw.WriteLine(messageHandler.ResponseDocument.ToString());
                        }
                        tw.Flush();
                        tw.Close();
                    }
                    WriteContent("");
                }
                finally
                {
                    Response.End();
                }
            }
        }