事件之取消订阅
Inheritance: RequestMessageEventBase, IRequestMessageEventBase, IRequestMessageEventKey
 //<?xml version="1.0" encoding="utf-8"?>
 //<xml>
 //  <ToUserName><![CDATA[gh_a96a4a619366]]></ToUserName>
 //  <FromUserName><![CDATA[olPjZjsXuQPJoV0HlruZkNzKc91E]]></FromUserName>
 //  <CreateTime>1357986928</CreateTime>
 //  <MsgType><![CDATA[text]]></MsgType>
 //  <Content><![CDATA[中文]]></Content>
 //  <MsgId>5832509444155992350</MsgId>
 //</xml>
 /// <summary>
 /// 获取XDocument转换后的IRequestMessageBase实例。
 /// 如果MsgType不存在,抛出UnknownRequestMsgTypeException异常
 /// </summary>
 /// <returns></returns>
 public static IRequestMessageBase GetRequestEntity(XDocument doc)
 {
     RequestMessageBase requestMessage = null;
     RequestMsgType msgType;
     try
     {
         msgType = MsgTypeHelper.GetRequestMsgType(doc);
         switch (msgType)
         {
             case RequestMsgType.Text:
                 requestMessage = new RequestMessageText();
                 break;
             case RequestMsgType.Location:
                 requestMessage = new RequestMessageLocation();
                 break;
             case RequestMsgType.Image:
                 requestMessage = new RequestMessageImage();
                 break;
             case RequestMsgType.Voice:
                 requestMessage = new RequestMessageVoice();
                 break;
             case RequestMsgType.Link:
                 requestMessage = new RequestMessageLink();
                 break;
             case RequestMsgType.Event:
                 //判断Event类型
                 switch (doc.Root.Element("Event").Value.ToUpper())
                 {
                     case "ENTER"://进入会话
                         requestMessage = new RequestMessageEvent_Enter();
                         break;
                     case "LOCATION"://地理位置
                         requestMessage = new RequestMessageEvent_Location();
                         break;
                     case "SUBSCRIBE"://订阅(关注)
                         requestMessage = new RequestMessageEvent_Subscribe();
                         break;
                     case "UNSUBSCRIBE"://取消订阅(关注)
                         requestMessage = new RequestMessageEvent_Unsubscribe();
                         break;
                     case "CLICK"://菜单点击
                         requestMessage = new RequestMessageEvent_Click();
                         break;
                     default://其他意外类型(也可以选择抛出异常)
                         requestMessage = new RequestMessageEventBase();
                         break;
                 }
                 break;
             default:
                 throw new UnknownRequestMsgTypeException(string.Format("MsgType:{0} 在RequestMessageFactory中没有对应的处理程序!", msgType), new ArgumentOutOfRangeException());//为了能够对类型变动最大程度容错(如微信目前还可以对公众账号suscribe等未知类型,但API没有开放),建议在使用的时候catch这个异常
         }
         EntityHelper.FillEntityWithXml(requestMessage, doc);
     }
     catch (ArgumentException ex)
     {
         throw new WeixinException(string.Format("RequestMessage转换出错!可能是MsgType不存在!,XML:{0}", doc.ToString()), ex);
     }
     return requestMessage;
 }
        /// <summary>
        /// 菜单点击事件
        /// </summary>
        public override IResponseMessageBase OnEvent_ClickRequest(RequestMessageEvent_Click requestMessage)
        {
            IResponseMessageBase reponseMessage = null;
            Common.MessageFunction cmfun = new Common.MessageFunction();

            string keywords = requestMessage.EventKey; //查询关健字
            int accountId = cmfun.GetAccountId(); //公众账户ID

            string EventName = "";
            if (requestMessage.Event.ToString().Trim() != "")
            {
                EventName = requestMessage.Event.ToString();
            }
            else if (requestMessage.EventKey != null)
            {
                EventName += requestMessage.EventKey.ToString();
            }

            if (!cmfun.ExistsOriginalId(accountId, requestMessage.ToUserName))
            {  //验证接收方是否为我们系统配置的帐号,即验证微帐号与微信原始帐号id是否一致,如果不一致,说明【1】配置错误,【2】数据来源有问题
                new BLL.weixin_response_content().Add(accountId, requestMessage.FromUserName, requestMessage.MsgType.ToString(), EventName, "none", "未取到关键词对应的数据", requestMessage.ToUserName);
                return cmfun.GetResponseMessageTxtByContent(requestMessage, "验证微帐号与微信原始帐号id不一致,可能原因【1】系统配置错误,【2】非法的数据来源有问题", accountId);
            }

            int responseType = 0; //回复类型
            int ruleId = new BLL.weixin_request_rule().GetKeywordsRuleId(accountId, string.Empty, out responseType);
            if (ruleId == 0)
            {
                new BLL.weixin_response_content().Add(accountId, requestMessage.FromUserName, requestMessage.MsgType.ToString(), EventName, "none", "未取到关键词对应的数据", requestMessage.ToUserName);
                return cmfun.GetResponseMessageTxtByContent(requestMessage, "", accountId);
            }
            switch (responseType)
            {
                case 1:
                    //发送纯文字
                    reponseMessage = cmfun.GetResponseMessageTxt(requestMessage, ruleId, accountId);
                    break;
                case 2:
                    //发送多图文
                    reponseMessage = cmfun.GetResponseMessageNews(requestMessage, ruleId, accountId);
                    break;
                case 3:
                    //发送语音
                    reponseMessage = cmfun.GetResponseMessageeMusic(requestMessage, ruleId, accountId);
                    break;
                default:
                    break;
            }
            return reponseMessage;
        }
 public override IResponseMessageBase OnEvent_ClickRequest(RequestMessageEvent_Click requestMessage)
 {
     throw new Exception("Demo中还没有加入CLICK的测试!");
 }
        public override IResponseMessageBase OnEvent_ClickRequest(RequestMessageEvent_Click requestMessage)
        {
            IResponseMessageBase reponseMessage = null;
            //菜单点击,需要跟创建菜单时的Key匹配
            switch (requestMessage.EventKey)
            {
                case "OneClick":
                    {
                        var strongResponseMessage = CreateResponseMessage<ResponseMessageText>();
                        reponseMessage = strongResponseMessage;
                        strongResponseMessage.Content = "您点击了底部按钮。\r\n为了测试微信软件换行bug的应对措施,这里做了一个——\r\n换行";
                    }
                    break;
                case "SubClickRoot_Text":
                    {
                        var strongResponseMessage = CreateResponseMessage<ResponseMessageText>();
                        reponseMessage = strongResponseMessage;
                        strongResponseMessage.Content = "您点击了子菜单按钮。";
                    }
                    break;
                case "SubClickRoot_News":
                    {
                        var strongResponseMessage = CreateResponseMessage<ResponseMessageNews>();
                        reponseMessage = strongResponseMessage;
                        strongResponseMessage.Articles.Add(new Article()
                        {
                            Title = "您点击了子菜单图文按钮",
                            Description = "您点击了子菜单图文按钮,这是一条图文信息。",
                            PicUrl = "http://weixin.senparc.com/Images/qrcode.jpg",
                            Url = "http://weixin.senparc.com"
                        });
                    }
                    break;
                case "SubClickRoot_Music":
                    {
                        var strongResponseMessage = CreateResponseMessage<ResponseMessageMusic>();
                        reponseMessage = strongResponseMessage;
                        strongResponseMessage.Music.MusicUrl = "http://weixin.senparc.com/Content/music1.mp3";
                    }
                    break;
                case "SubClickRoot_Agent"://代理消息
                    {
                        //获取返回的XML
                        DateTime dt1 = DateTime.Now;
                        reponseMessage = MessageAgent.RequestResponseMessage(this, agentUrl, agentToken, RequestDocument.ToString());
                        //上面的方法也可以使用扩展方法:this.RequestResponseMessage(this,agentUrl, agentToken, RequestDocument.ToString());

                        DateTime dt2 = DateTime.Now;

                        if (reponseMessage is ResponseMessageNews)
                        {
                            (reponseMessage as ResponseMessageNews)
                                .Articles[0]
                                .Description += string.Format("\r\n\r\n代理过程总耗时:{0}毫秒", (dt2 - dt1).Milliseconds);
                        }
                    }
                    break;
                case "Member"://托管代理会员信息
                    {
                        //原始方法为:MessageAgent.RequestXml(this,agentUrl, agentToken, RequestDocument.ToString());//获取返回的XML
                        reponseMessage = this.RequestResponseMessage(agentUrl, agentToken, RequestDocument.ToString());
                    }
                    break;
                case "OAuth"://OAuth授权测试
                    {
                        var strongResponseMessage = CreateResponseMessage<ResponseMessageNews>();
                        strongResponseMessage.Articles.Add(new Article()
                        {
                            Title = "OAuth2.0测试",
                            Description = "点击【查看全文】进入授权页面。\r\n注意:此页面仅供测试,测试号随时可能过期。请将此DEMO部署到您自己的服务器上,并使用自己的appid和secret。",
                            Url = "http://weixin.senparc.com/oauth2",
                        });
                        reponseMessage = strongResponseMessage;
                    }
                    break;
            }

            return reponseMessage;
        }
        public override IResponseMessageBase OnEvent_ClickRequest(RequestMessageEvent_Click requestMessage)
        {
            IResponseMessageBase reponseMessage = null;
            //菜单点击,需要跟创建菜单时的Key匹配
            switch (requestMessage.EventKey)
            {
                case "OneClick":
                    {
                        //这个过程实际已经在OnTextOrEventRequest中完成,这里不会执行到。
                        var strongResponseMessage = CreateResponseMessage<ResponseMessageText>();
                        reponseMessage = strongResponseMessage;
                        strongResponseMessage.Content = "您点击了底部按钮。\r\n为了测试微信软件换行bug的应对措施,这里做了一个——\r\n换行";
                    }
                    break;
                case "SubClickRoot_Text":
                    {
                        var strongResponseMessage = CreateResponseMessage<ResponseMessageText>();
                        reponseMessage = strongResponseMessage;
                        strongResponseMessage.Content = "您点击了子菜单按钮。";
                    }
                    break;
                case "SubClickRoot_News":
                    {
                        var strongResponseMessage = CreateResponseMessage<ResponseMessageNews>();
                        reponseMessage = strongResponseMessage;
                        strongResponseMessage.Articles.Add(new Article()
                        {
                            Title = "您点击了子菜单图文按钮",
                            Description = "您点击了子菜单图文按钮,这是一条图文信息。",
                            PicUrl = "http://sdk.weixin.senparc.com/Images/qrcode.jpg",
                            Url = "http://sdk.weixin.senparc.com"
                        });
                    }
                    break;
                case "SubClickRoot_Music":
                    {
                        //上传缩略图
                        var accessToken = Containers.AccessTokenContainer.TryGetAccessToken(appId, appSecret);
                        var uploadResult = AdvancedAPIs.MediaApi.UploadTemporaryMedia(accessToken, UploadMediaFileType.thumb,
                                                                     Server.GetMapPath("~/Images/Logo.jpg"));
                        //设置音乐信息
                        var strongResponseMessage = CreateResponseMessage<ResponseMessageMusic>();
                        reponseMessage = strongResponseMessage;
                        strongResponseMessage.Music.Title = "天籁之音";
                        strongResponseMessage.Music.Description = "真的是天籁之音";
                        strongResponseMessage.Music.MusicUrl = "http://sdk.weixin.senparc.com/Content/music1.mp3";
                        strongResponseMessage.Music.HQMusicUrl = "http://sdk.weixin.senparc.com/Content/music1.mp3";
                        strongResponseMessage.Music.ThumbMediaId = uploadResult.thumb_media_id;
                    }
                    break;
                case "SubClickRoot_Image":
                    {
                        //上传图片
                        var accessToken = Containers.AccessTokenContainer.TryGetAccessToken(appId, appSecret);
                        var uploadResult = AdvancedAPIs.MediaApi.UploadTemporaryMedia(accessToken, UploadMediaFileType.image,
                                                                     Server.GetMapPath("~/Images/Logo.jpg"));
                        //设置图片信息
                        var strongResponseMessage = CreateResponseMessage<ResponseMessageImage>();
                        reponseMessage = strongResponseMessage;
                        strongResponseMessage.Image.MediaId = uploadResult.media_id;
                    }
                    break;
                case "SubClickRoot_Agent"://代理消息
                    {
                        //获取返回的XML
                        DateTime dt1 = DateTime.Now;
                        reponseMessage = MessageAgent.RequestResponseMessage(this, agentUrl, agentToken, RequestDocument.ToString());
                        //上面的方法也可以使用扩展方法:this.RequestResponseMessage(this,agentUrl, agentToken, RequestDocument.ToString());

                        DateTime dt2 = DateTime.Now;

                        if (reponseMessage is ResponseMessageNews)
                        {
                            (reponseMessage as ResponseMessageNews)
                                .Articles[0]
                                .Description += string.Format("\r\n\r\n代理过程总耗时:{0}毫秒", (dt2 - dt1).Milliseconds);
                        }
                    }
                    break;
                case "Member"://托管代理会员信息
                    {
                        //原始方法为:MessageAgent.RequestXml(this,agentUrl, agentToken, RequestDocument.ToString());//获取返回的XML
                        reponseMessage = this.RequestResponseMessage(agentUrl, agentToken, RequestDocument.ToString());
                    }
                    break;
                case "OAuth"://OAuth授权测试
                    {
                        var strongResponseMessage = CreateResponseMessage<ResponseMessageNews>();

                        strongResponseMessage.Articles.Add(new Article()
                        {
                            Title = "OAuth2.0测试",
                            Description = "选择下面两种不同的方式进行测试,区别在于授权成功后,最后停留的页面。",
                            //Url = "http://sdk.weixin.senparc.com/oauth2",
                            //PicUrl = "http://sdk.weixin.senparc.com/Images/qrcode.jpg"
                        });

                        strongResponseMessage.Articles.Add(new Article()
                        {
                            Title = "OAuth2.0测试(不带returnUrl),测试环境可使用",
                            Description = "OAuth2.0测试(不带returnUrl)",
                            Url = "http://sdk.weixin.senparc.com/oauth2",
                            PicUrl = "http://sdk.weixin.senparc.com/Images/qrcode.jpg"
                        });

                        var returnUrl = "/OAuth2/TestReturnUrl";
                        strongResponseMessage.Articles.Add(new Article()
                        {
                            Title = "OAuth2.0测试(带returnUrl),生产环境强烈推荐使用",
                            Description = "OAuth2.0测试(带returnUrl)",
                            Url = "http://sdk.weixin.senparc.com/oauth2?returnUrl="+ returnUrl.UrlEncode(),
                            PicUrl = "http://sdk.weixin.senparc.com/Images/qrcode.jpg"
                        });

                        reponseMessage = strongResponseMessage;

                    }
                    break;
                case "Description":
                    {
                        var strongResponseMessage = CreateResponseMessage<ResponseMessageText>();
                        strongResponseMessage.Content = GetWelcomeInfo();
                        reponseMessage = strongResponseMessage;
                    }
                    break;
                case "SubClickRoot_PicPhotoOrAlbum":
                    {
                        var strongResponseMessage = CreateResponseMessage<ResponseMessageText>();
                        reponseMessage = strongResponseMessage;
                        strongResponseMessage.Content = "您点击了【微信拍照】按钮。系统将会弹出拍照或者相册发图。";
                    }
                    break;
                case "SubClickRoot_ScancodePush":
                    {
                        var strongResponseMessage = CreateResponseMessage<ResponseMessageText>();
                        reponseMessage = strongResponseMessage;
                        strongResponseMessage.Content = "您点击了【微信扫码】按钮。";
                    }
                    break;
                case "ConditionalMenu_Male":
                    {
                        var strongResponseMessage = CreateResponseMessage<ResponseMessageText>();
                        reponseMessage = strongResponseMessage;
                        strongResponseMessage.Content = "您点击了个性化菜单按钮,您的微信性别设置为:男。";
                    }
                    break;
                case "ConditionalMenu_Femle":
                    {
                        var strongResponseMessage = CreateResponseMessage<ResponseMessageText>();
                        reponseMessage = strongResponseMessage;
                        strongResponseMessage.Content = "您点击了个性化菜单按钮,您的微信性别设置为:女。";
                    }
                    break;
                default:
                    {
                        var strongResponseMessage = CreateResponseMessage<ResponseMessageText>();
                        strongResponseMessage.Content = "您点击了按钮,EventKey:" + requestMessage.EventKey;
                        reponseMessage = strongResponseMessage;
                    }
                    break;
            }

            return reponseMessage;
        }
        public override IResponseMessageBase OnEvent_ClickRequest(RequestMessageEvent_Click requestMessage)
        {
            IResponseMessageBase reponseMessage = null;
            //菜单点击,需要跟创建菜单时的Key匹配
            switch (requestMessage.EventKey)
            {
                case "OneClick":
                    {
                        //这个过程实际已经在OnTextOrEventRequest中完成,这里不会执行到。
                        var strongResponseMessage = CreateResponseMessage<ResponseMessageText>();
                        reponseMessage = strongResponseMessage;
                        strongResponseMessage.Content = "您点击了底部按钮。\r\n为了测试微信软件换行bug的应对措施,这里做了一个——\r\n换行";
                    }
                    break;
                case "SubClickRoot_Text":
                    {
                        var strongResponseMessage = CreateResponseMessage<ResponseMessageText>();
                        reponseMessage = strongResponseMessage;
                        strongResponseMessage.Content = "您点击了子菜单按钮。";
                    }
                    break;
                case "SubClickRoot_News":
                    {
                        var strongResponseMessage = CreateResponseMessage<ResponseMessageNews>();
                        reponseMessage = strongResponseMessage;
                        strongResponseMessage.Articles.Add(new Article()
                        {
                            Title = "您点击了子菜单图文按钮",
                            Description = "您点击了子菜单图文按钮,这是一条图文信息。",
                            PicUrl = "http://weixin.senparc.com/Images/qrcode.jpg",
                            Url = "http://weixin.senparc.com"
                        });
                    }
                    break;
                case "SubClickRoot_Music":
                    {
                        //上传缩略图
                        var accessToken = CommonAPIs.AccessTokenContainer.TryGetToken(appId, appSecret);
                        var uploadResult = AdvancedAPIs.Media.MediaApi.UploadTemporaryMedia(accessToken, UploadMediaFileType.thumb,
                                                                     Server.GetMapPath("~/Images/Logo.jpg"));
                        //设置音乐信息
                        var strongResponseMessage = CreateResponseMessage<ResponseMessageMusic>();
                        reponseMessage = strongResponseMessage;
                        strongResponseMessage.Music.Title = "天籁之音";
                        strongResponseMessage.Music.Description = "真的是天籁之音";
                        strongResponseMessage.Music.MusicUrl = "http://weixin.senparc.com/Content/music1.mp3";
                        strongResponseMessage.Music.HQMusicUrl = "http://weixin.senparc.com/Content/music1.mp3";
                        strongResponseMessage.Music.ThumbMediaId = uploadResult.thumb_media_id;
                    }
                    break;
                case "SubClickRoot_Image":
                    {
                        //上传图片
                        var accessToken = CommonAPIs.AccessTokenContainer.TryGetToken(appId, appSecret);
                        var uploadResult = AdvancedAPIs.Media.MediaApi.UploadTemporaryMedia(accessToken, UploadMediaFileType.image,
                                                                     Server.GetMapPath("~/Images/Logo.jpg"));
                        //设置图片信息
                        var strongResponseMessage = CreateResponseMessage<ResponseMessageImage>();
                        reponseMessage = strongResponseMessage;
                        strongResponseMessage.Image.MediaId = uploadResult.media_id;
                    }
                    break;
                case "SubClickRoot_Agent"://代理消息
                    {
                        //获取返回的XML
                        DateTime dt1 = DateTime.Now;
                        reponseMessage = MessageAgent.RequestResponseMessage(this, agentUrl, agentToken, RequestDocument.ToString());
                        //上面的方法也可以使用扩展方法:this.RequestResponseMessage(this,agentUrl, agentToken, RequestDocument.ToString());

                        DateTime dt2 = DateTime.Now;

                        if (reponseMessage is ResponseMessageNews)
                        {
                            (reponseMessage as ResponseMessageNews)
                                .Articles[0]
                                .Description += string.Format("\r\n\r\n代理过程总耗时:{0}毫秒", (dt2 - dt1).Milliseconds);
                        }
                    }
                    break;
                case "Member"://托管代理会员信息
                    {
                        //原始方法为:MessageAgent.RequestXml(this,agentUrl, agentToken, RequestDocument.ToString());//获取返回的XML
                        reponseMessage = this.RequestResponseMessage(agentUrl, agentToken, RequestDocument.ToString());
                    }
                    break;
                case "OAuth"://OAuth授权测试
                    {
                        var strongResponseMessage = CreateResponseMessage<ResponseMessageNews>();
                        strongResponseMessage.Articles.Add(new Article()
                        {
                            Title = "OAuth2.0测试",
                            Description = "点击【查看全文】进入授权页面。\r\n注意:此页面仅供测试(是专门的一个临时测试账号的授权,并非Senparc.Weixin.MP SDK官方账号,所以如果授权后出现错误页面数正常情况),测试号随时可能过期。请将此DEMO部署到您自己的服务器上,并使用自己的appid和secret。",
                            Url = "http://weixin.senparc.com/oauth2",
                            PicUrl = "http://weixin.senparc.com/Images/qrcode.jpg"
                        });
                        reponseMessage = strongResponseMessage;
                    }
                    break;
                case "Description":
                    {
                        var strongResponseMessage = CreateResponseMessage<ResponseMessageText>();
                        strongResponseMessage.Content = GetWelcomeInfo();
                        reponseMessage = strongResponseMessage;
                    }
                    break;
                case "SubClickRoot_PicPhotoOrAlbum":
                    {
                        var strongResponseMessage = CreateResponseMessage<ResponseMessageText>();
                        reponseMessage = strongResponseMessage;
                        strongResponseMessage.Content = "您点击了【微信拍照】按钮。系统将会弹出拍照或者相册发图。";
                    }
                    break;
                case "SubClickRoot_ScancodePush":
                    {
                        var strongResponseMessage = CreateResponseMessage<ResponseMessageText>();
                        reponseMessage = strongResponseMessage;
                        strongResponseMessage.Content = "您点击了【微信扫码】按钮。";
                    }
                    break;
                default:
                    {
                        var strongResponseMessage = CreateResponseMessage<ResponseMessageText>();
                        strongResponseMessage.Content = "您点击了按钮,EventKey:" + requestMessage.EventKey;
                        reponseMessage = strongResponseMessage;
                    }
                    break;
            }

            return reponseMessage;
        }
        //<?xml version="1.0" encoding="utf-8"?>
        //<xml>
        //  <ToUserName><![CDATA[gh_a96a4a619366]]></ToUserName>
        //  <FromUserName><![CDATA[olPjZjsXuQPJoV0HlruZkNzKc91E]]></FromUserName>
        //  <CreateTime>1357986928</CreateTime>
        //  <MsgType><![CDATA[text]]></MsgType>
        //  <Content><![CDATA[中文]]></Content>
        //  <MsgId>5832509444155992350</MsgId>
        //</xml>
        /// <summary>
        /// 获取XDocument转换后的IRequestMessageBase实例。
        /// 如果MsgType不存在,抛出UnknownRequestMsgTypeException异常
        /// </summary>
        /// <returns></returns>
        public static IRequestMessageBase GetRequestEntity(XDocument doc, PostModel postModel = null)
        {
            RequestMessageBase requestMessage = null;
            RequestMsgType msgType;

            try
            {
                msgType = MsgTypeHelper.GetRequestMsgType(doc);
                switch (msgType)
                {
                    case RequestMsgType.Text:
                        requestMessage = new RequestMessageText();
                        break;
                    case RequestMsgType.Location:
                        requestMessage = new RequestMessageLocation();
                        break;
                    case RequestMsgType.Image:
                        requestMessage = new RequestMessageImage();
                        break;
                    case RequestMsgType.Voice:
                        requestMessage = new RequestMessageVoice();
                        break;
                    case RequestMsgType.Video:
                        requestMessage = new RequestMessageVideo();
                        break;
                    case RequestMsgType.Link:
                        requestMessage = new RequestMessageLink();
                        break;
                    case RequestMsgType.ShortVideo:
                        requestMessage = new RequestMessageShortVideo();
                        break;
                    case RequestMsgType.Event:
                        //判断Event类型
                        switch (doc.Root.Element("Event").Value.ToUpper())
                        {
                            case "ENTER"://进入会话
                                requestMessage = new RequestMessageEvent_Enter();
                                break;
                            case "LOCATION"://地理位置
                                requestMessage = new RequestMessageEvent_Location();
                                break;
                            case "SUBSCRIBE"://订阅(关注)
                                requestMessage = new RequestMessageEvent_Subscribe();
                                break;
                            case "UNSUBSCRIBE"://取消订阅(关注)
                                requestMessage = new RequestMessageEvent_Unsubscribe();
                                break;
                            case "CLICK"://菜单点击
                                requestMessage = new RequestMessageEvent_Click();
                                break;
                            case "SCAN"://二维码扫描
                                requestMessage = new RequestMessageEvent_Scan();
                                break;
                            case "VIEW"://URL跳转
                                requestMessage = new RequestMessageEvent_View();
                                break;
                            case "MASSSENDJOBFINISH":
                                requestMessage = new RequestMessageEvent_MassSendJobFinish();
                                break;
                            case "TEMPLATESENDJOBFINISH"://模板信息
                                requestMessage = new RequestMessageEvent_TemplateSendJobFinish();
                                break;
                            case "SCANCODE_PUSH"://扫码推事件(scancode_push)
                                requestMessage = new RequestMessageEvent_Scancode_Push();
                                break;
                            case "SCANCODE_WAITMSG"://扫码推事件且弹出“消息接收中”提示框(scancode_waitmsg)
                                requestMessage = new RequestMessageEvent_Scancode_Waitmsg();
                                break;
                            case "PIC_SYSPHOTO"://弹出系统拍照发图(pic_sysphoto)
                                requestMessage = new RequestMessageEvent_Pic_Sysphoto();
                                break;
                            case "PIC_PHOTO_OR_ALBUM"://弹出拍照或者相册发图(pic_photo_or_album)
                                requestMessage = new RequestMessageEvent_Pic_Photo_Or_Album();
                                break;
                            case "PIC_WEIXIN"://弹出微信相册发图器(pic_weixin)
                                requestMessage = new RequestMessageEvent_Pic_Weixin();
                                break;
                            case "LOCATION_SELECT"://弹出地理位置选择器(location_select)
                                requestMessage = new RequestMessageEvent_Location_Select();
                                break;
                            case "CARD_PASS_CHECK"://卡券通过审核
                                requestMessage = new RequestMessageEvent_Card_Pass_Check();
                                break;
                            case "CARD_NOT_PASS_CHECK"://卡券未通过审核
                                requestMessage = new RequestMessageEvent_Card_Not_Pass_Check();
                                break;
                            case "USER_GET_CARD"://领取卡券
                                requestMessage = new RequestMessageEvent_User_Get_Card();
                                break;
                            case "USER_DEL_CARD"://删除卡券
                                requestMessage = new RequestMessageEvent_User_Del_Card();
                                break;
                            case "KF_CREATE_SESSION"://多客服接入会话
                                requestMessage = new RequestMessageEvent_Kf_Create_Session();
                                break;
                            case "KF_CLOSE_SESSION"://多客服关闭会话
                                requestMessage = new RequestMessageEvent_Kf_Close_Session();
                                break;
                            case "KF_SWITCH_SESSION"://多客服转接会话
                                requestMessage = new RequestMessageEvent_Kf_Switch_Session();
                                break;
                            case "POI_CHECK_NOTIFY"://审核结果事件推送
                                requestMessage = new RequestMessageEvent_Poi_Check_Notify();
                                break;
                            case "WIFICONNECTED"://Wi-Fi连网成功事件
                                requestMessage = new RequestMessageEvent_WifiConnected();
                                break;
                            case "USER_CONSUME_CARD"://卡券核销
                                requestMessage = new RequestMessageEvent_User_Consume_Card();
                                break;
                            case "USER_ENTER_SESSION_FROM_CARD"://从卡券进入公众号会话
                                requestMessage = new RequestMessageEvent_User_Enter_Session_From_Card();
                                break;
                            case "USER_VIEW_CARD"://进入会员卡
                                requestMessage = new RequestMessageEvent_User_View_Card();
                                break;
                            case "MERCHANT_ORDER"://微小店订单付款通知
                                requestMessage = new RequestMessageEvent_Merchant_Order();
                                break;
                            case "SUBMIT_MEMBERCARD_USER_INFO"://接收会员信息事件通知
                                requestMessage = new RequestMessageEvent_Submit_Membercard_User_Info();
                                break;
                            default://其他意外类型(也可以选择抛出异常)
                                requestMessage = new RequestMessageEventBase();
                                break;
                        }
                        break;
                    default:
                        throw new UnknownRequestMsgTypeException(string.Format("MsgType:{0} 在RequestMessageFactory中没有对应的处理程序!", msgType), new ArgumentOutOfRangeException());//为了能够对类型变动最大程度容错(如微信目前还可以对公众账号suscribe等未知类型,但API没有开放),建议在使用的时候catch这个异常
                }
                EntityHelper.FillEntityWithXml(requestMessage, doc);
            }
            catch (ArgumentException ex)
            {
                throw new WeixinException(string.Format("RequestMessage转换出错!可能是MsgType不存在!,XML:{0}", doc.ToString()), ex);
            }
            return requestMessage;
        }
        /// <summary>
        /// 获取请求XML
        /// </summary>
        /// <returns></returns>
        private XDocument GetrequestMessaageDoc(string url, string token, RequestMsgType requestType, Event? eventType)
        {
            RequestMessageBase requestMessaage = null;
            switch (requestType)
            {
                case RequestMsgType.Text:
                    requestMessaage = new RequestMessageText()
                    {
                        Content = Request.Form["Content"],
                    };
                    break;
                case RequestMsgType.Location:
                    requestMessaage = new RequestMessageLocation()
                    {
                        Label = Request.Form["Label"],
                        Location_X = double.Parse(Request.Form["Location_X"]),
                        Location_Y = double.Parse(Request.Form["Location_Y"]),
                        Scale = int.Parse(Request.Form["Scale"])
                    };
                    break;
                case RequestMsgType.Image:
                    requestMessaage = new RequestMessageImage()
                    {
                        PicUrl = Request.Form["PicUrl"],
                    };
                    break;
                case RequestMsgType.Voice:
                    requestMessaage = new RequestMessageVoice()
                    {
                        Format = Request.Form["Format"],
                        Recognition = Request.Form["Recognition"],
                    };
                    break;
                case RequestMsgType.Video:
                    requestMessaage = new RequestMessageVideo()
                    {
                        MsgId = long.Parse(Request.Form["MsgId"]),
                        ThumbMediaId = Request.Form["ThumbMediaId"],
                    };
                    break;
                //case RequestMsgType.Link:
                //    break;
                case RequestMsgType.Event:
                    if (eventType.HasValue)
                    {
                        RequestMessageEventBase requestMessageEvent = null;
                        switch (eventType.Value)
                        {
                            //case Event.ENTER:
                            //    break;
                            case Event.LOCATION:
                                requestMessageEvent = new RequestMessageEvent_Location()
                                {
                                    Latitude = long.Parse(Request.Form["Event.Latitude"]),
                                    Longitude = long.Parse(Request.Form["Event.Longitude"]),
                                    Precision = double.Parse(Request.Form["Event.Precision"])
                                };
                                break;
                            case Event.subscribe:
                                requestMessageEvent = new RequestMessageEvent_Subscribe()
                                {
                                    EventKey = Request.Form["Event.EventKey"]
                                };
                                break;
                            case Event.unsubscribe:
                                requestMessageEvent = new RequestMessageEvent_Unsubscribe();
                                  break;
                            case Event.CLICK:
                                requestMessageEvent = new RequestMessageEvent_Click()
                                   {
                                       EventKey = Request.Form["Event.EventKey"]
                                   };
                                break;
                            case Event.scan:
                                requestMessageEvent = new RequestMessageEvent_Scan()
                                 {
                                     EventKey = Request.Form["Event.EventKey"],
                                     Ticket = Request.Form["Event.Ticket"]
                                 }; break;
                            case Event.VIEW:
                                requestMessageEvent = new RequestMessageEvent_View()
                                 {
                                     EventKey = Request.Form["Event.EventKey"]
                                 }; break;
                            case Event.MASSSENDJOBFINISH:
                                requestMessageEvent = new RequestMessageEvent_MassSendJobFinish()
                                {
                                    FromUserName = "******",//系统指定
                                    ErrorCount = int.Parse(Request.Form["Event.ErrorCount"]),
                                    FilterCount = int.Parse(Request.Form["Event.FilterCount"]),
                                    SendCount = int.Parse(Request.Form["Event.SendCount"]),
                                    Status = Request.Form["Event.Status"],
                                    TotalCount = int.Parse(Request.Form["Event.TotalCount"])
                                }; break;
                            default:
                                throw new ArgumentOutOfRangeException("eventType");
                        }
                        requestMessaage = requestMessageEvent;
                    }
                    else
                    {
                        throw new ArgumentOutOfRangeException("eventType");
                    }
                    break;
                default:
                    throw new ArgumentOutOfRangeException("requestType");
            }

            requestMessaage.CreateTime = DateTime.Now;
            requestMessaage.FromUserName = requestMessaage.FromUserName ?? "FromUserName(OpenId)";//用于区别不同的请求用户
            requestMessaage.ToUserName = "******";

            return requestMessaage.ConvertEntityToXml();
        }
        private static readonly string _urlVote = ConfigurationManager.AppSettings["UrlVote"]; //投票大赛的地址

        #endregion Fields

        #region Methods

        /// <summary>
        /// 获取XDocument转换后的IRequestMessageBase实例。
        /// 如果MsgType不存在,抛出UnknownRequestMsgTypeException异常
        /// </summary>
        /// <returns></returns>
        public static IRequestMessageBase GetRequestEntity(IWeChatManagementService service, XDocument doc,
            PostModel postModel = null)
        {
            RequestMessageBase requestMessage = null;
            RequestMsgType msgType;

            try
            {
                msgType = MsgTypeHelper.GetRequestMsgType(doc);
                switch (msgType)
                {
                    case RequestMsgType.Text:
                        requestMessage = new RequestMessageText();
                        requestMessage.FillEntityWithXml(doc);

                        /*tim update by 2016-03-31*/
                        var rMessage = (RequestMessageText) requestMessage;
                        //回复手机号重新绑定到会员
                        var b = System.Text.RegularExpressions.Regex.IsMatch(rMessage.Content.Trim(),
                            @"^1[3|4|5|8][0-9]\d{8}$");
                        if (b)
                        {
                            var customerService =
                                ServiceLocatorFactory.GetServiceLocator().GetService<ICustomerManagementService>();
                            var result = customerService.RebindFans(new CustRebindFansModel
                            {
                                Openid = rMessage.FromUserName,
                                Mobile = rMessage.Content
                            });
                            LoggerFactories.CreateLogger()
                                .Write($"rebind result:{result.errcode}", TraceEventType.Information);
                        }
                        else
                        {
                            //处理投票活动消息
                            var result = HandleVote(rMessage.Content, requestMessage.FromUserName);
                            if (result)
                            {
                                return requestMessage;
                            }
                            CustomApi.SendText(AppID, requestMessage.FromUserName, "感谢您的回复,玖伍淘车会尽快回复您。");
                        }

                        break;
                    case RequestMsgType.Location:
                        requestMessage = new RequestMessageLocation();
                        break;
                    case RequestMsgType.Image:
                        requestMessage = new RequestMessageImage();
                        break;
                    case RequestMsgType.Voice:
                        requestMessage = new RequestMessageVoice();
                        break;
                    case RequestMsgType.Video:
                        requestMessage = new RequestMessageVideo();
                        break;
                    case RequestMsgType.Link:
                        requestMessage = new RequestMessageLink();
                        break;
                    case RequestMsgType.ShortVideo:
                        requestMessage = new RequestMessageShortVideo();
                        break;
                    case RequestMsgType.Event:
                        //判断Event类型
                        switch (doc.Root.Element("Event").Value.ToUpper())
                        {
                            case "ENTER": //进入会话
                                requestMessage = new RequestMessageEvent_Enter();
                                break;
                            case "LOCATION": //地理位置
                                requestMessage = new RequestMessageEvent_Location();
                                break;
                            case "SUBSCRIBE": //订阅(关注)
                                requestMessage = new RequestMessageEvent_Subscribe();
                                EntityHelper.FillEntityWithXml(requestMessage, doc);
                                var taskSubscribe = new Task(() =>
                                {
                                    service.GenerateWechatFriend(AppID, requestMessage.FromUserName, true);
                                });
                                taskSubscribe.Start();

                                var slogan = _slogan.Replace("\\n", Environment.NewLine);

                                //"\n\n&lt;a src=''&gt;点击参加玖伍淘车首届“/强绝代车王/强”微信自拍投票大赛&lt;a/&gt;";
                                var btnContent = ConfigurationManager.AppSettings["BtnContent"];

                                var tourl = $"https://open.weixin.qq.com/connect/oauth2/authorize?appid={AppID}&redirect_uri={_urlVote}&response_type=code&scope=snsapi_base&state=vote&connect_redirect=1#wechat_redirect";

                                btnContent = $"<a href=\"{tourl}\">{btnContent}</a>";
                                slogan = string.Concat(slogan, Environment.NewLine, btnContent);

                                CustomApi.SendText(AppID, requestMessage.FromUserName, slogan);

                                //判断是否扫描场景二维码关注
                                var xElement = doc.Root.Element("EventKey");
                                if (xElement != null && xElement.Value.Contains("qrscene_"))
                                {
                                    var code = xElement.Value.Replace("qrscene_", "");
                                    service.UpdateWechatFriendQrScene(requestMessage.FromUserName, code, AppID);
                                }
                                break;
                            case "UNSUBSCRIBE": //取消订阅(关注)
                                requestMessage = new RequestMessageEvent_Unsubscribe();
                                EntityHelper.FillEntityWithXml(requestMessage, doc);
                                service.UpdateWechatFriendUnSubscribe(AppID, requestMessage.FromUserName);

                                var activityservice = ServiceLocatorFactory.GetServiceLocator().GetService<IActivityManagementService>();
                                activityservice.UnSubscribe(AppID, requestMessage.FromUserName);

                                break;
                            case "CLICK": //菜单点击
                                requestMessage = new RequestMessageEvent_Click();
                                break;
                            case "SCAN": //二维码扫描
                                requestMessage = new RequestMessageEvent_Scan();
                                break;
                            case "VIEW": //URL跳转
                                requestMessage = new RequestMessageEvent_View();
                                break;
                            case "MASSSENDJOBFINISH":
                                requestMessage = new RequestMessageEvent_MassSendJobFinish();
                                break;
                            case "TEMPLATESENDJOBFINISH": //模板信息
                                requestMessage = new RequestMessageEvent_TemplateSendJobFinish();
                                break;
                            case "SCANCODE_PUSH": //扫码推事件(scancode_push)
                                requestMessage = new RequestMessageEvent_Scancode_Push();
                                break;
                            case "SCANCODE_WAITMSG": //扫码推事件且弹出“消息接收中”提示框(scancode_waitmsg)
                                requestMessage = new RequestMessageEvent_Scancode_Waitmsg();
                                break;
                            case "PIC_SYSPHOTO": //弹出系统拍照发图(pic_sysphoto)
                                requestMessage = new RequestMessageEvent_Pic_Sysphoto();
                                break;
                            case "PIC_PHOTO_OR_ALBUM": //弹出拍照或者相册发图(pic_photo_or_album)
                                requestMessage = new RequestMessageEvent_Pic_Photo_Or_Album();
                                break;
                            case "PIC_WEIXIN": //弹出微信相册发图器(pic_weixin)
                                requestMessage = new RequestMessageEvent_Pic_Weixin();
                                break;
                            case "LOCATION_SELECT": //弹出地理位置选择器(location_select)
                                requestMessage = new RequestMessageEvent_Location_Select();
                                break;
                            case "CARD_PASS_CHECK": //卡券通过审核
                                requestMessage = new RequestMessageEvent_Card_Pass_Check();
                                break;
                            case "CARD_NOT_PASS_CHECK": //卡券未通过审核
                                requestMessage = new RequestMessageEvent_Card_Not_Pass_Check();
                                break;
                            case "USER_GET_CARD": //领取卡券
                                requestMessage = new RequestMessageEvent_User_Get_Card();
                                break;
                            case "USER_DEL_CARD": //删除卡券
                                requestMessage = new RequestMessageEvent_User_Del_Card();
                                break;
                            case "KF_CREATE_SESSION": //多客服接入会话
                                requestMessage = new RequestMessageEvent_Kf_Create_Session();
                                break;
                            case "KF_CLOSE_SESSION": //多客服关闭会话
                                requestMessage = new RequestMessageEvent_Kf_Close_Session();
                                break;
                            case "KF_SWITCH_SESSION": //多客服转接会话
                                requestMessage = new RequestMessageEvent_Kf_Switch_Session();
                                break;
                            case "POI_CHECK_NOTIFY": //审核结果事件推送
                                requestMessage = new RequestMessageEvent_Poi_Check_Notify();
                                break;
                            case "WIFICONNECTED": //Wi-Fi连网成功事件
                                requestMessage = new RequestMessageEvent_WifiConnected();
                                break;
                            case "USER_CONSUME_CARD": //卡券核销
                                requestMessage = new RequestMessageEvent_User_Consume_Card();
                                break;
                            case "USER_ENTER_SESSION_FROM_CARD": //从卡券进入公众号会话
                                requestMessage = new RequestMessageEvent_User_Enter_Session_From_Card();
                                break;
                            case "USER_VIEW_CARD": //进入会员卡
                                requestMessage = new RequestMessageEvent_User_View_Card();
                                break;
                            case "MERCHANT_ORDER": //微小店订单付款通知
                                requestMessage = new RequestMessageEvent_Merchant_Order();
                                var merchantOrderresult = (RequestMessageEvent_Merchant_Order) requestMessage;
                                EntityHelper.FillEntityWithXml(requestMessage, doc);
                                var orderresult = OrderApi.GetByIdOrder(AppID, merchantOrderresult.OrderId);
                                if (orderresult.errcode == ReturnCode.请求成功)
                                {
                                    var rewardsManagementService =
                                        ServiceLocatorFactory.GetServiceLocator()
                                            .GetService<IRewardsManagementService>();
                                    var wholesaleCouponresult =
                                        rewardsManagementService.WholesaleCoupon(new CouponBuyModel()
                                        {
                                            //ProductId = orderresult.order.product_id,
                                            //OrderId = orderresult.order.order_id,
                                            //Accountid = AppID,
                                            //Number = orderresult.order.product_count,
                                            //Openid = orderresult.order.buyer_openid
                                            Order = orderresult.order
                                        });
                                    var text = JsonConvert.SerializeObject(orderresult.order);
                                    var logresult =
                                        $"MERCHANT_ORDER:{text}    result:{JsonConvert.SerializeObject(wholesaleCouponresult)}";
                                    LoggerFactories.CreateLogger().Write(logresult, TraceEventType.Information);
                                }
                                break;
                            case "SUBMIT_MEMBERCARD_USER_INFO": //接收会员信息事件通知
                                requestMessage = new RequestMessageEvent_Submit_Membercard_User_Info();
                                break;
                            case "SHAKEAROUNDUSERSHAKE": //摇一摇事件通知
                                requestMessage = new RequestMessageEvent_ShakearoundUserShake();
                                break;
                            default: //其他意外类型(也可以选择抛出异常)
                                requestMessage = new RequestMessageEventBase();
                                break;
                        }
                        break;
                    default:
                        throw new UnknownRequestMsgTypeException(
                            $"MsgType:{msgType} 在RequestMessageFactory中没有对应的处理程序!", new ArgumentOutOfRangeException());
                    //为了能够对类型变动最大程度容错(如微信目前还可以对公众账号suscribe等未知类型,但API没有开放),建议在使用的时候catch这个异常
                }
            }
            catch (ArgumentException ex)
            {
                //throw new WeixinException(string.Format("RequestMessage转换出错!可能是MsgType不存在!,XML:{0}", doc.ToString()), ex);
                LoggerFactories.CreateLogger()
                    .Write($"RequestMessage转换出错!可能是MsgType不存在!,XML:{doc}", TraceEventType.Error, ex);
            }
            return requestMessage;
        }
        /// <summary>
        /// 获取请求XML
        /// </summary>
        /// <returns></returns>
        private XDocument GetrequestMessaageDoc(string url, string token, RequestMsgType requestType, Event? eventType)
        {
            RequestMessageBase requestMessaage = null;
            switch (requestType)
            {
                case RequestMsgType.Text:
                    requestMessaage = new RequestMessageText()
                    {
                        Content = Request.Form["Content"],
                    };
                    break;
                case RequestMsgType.Location:
                    requestMessaage = new RequestMessageLocation()
                    {
                        Label = Request.Form["Label"],
                        Location_X = double.Parse(Request.Form["Location_X"]),
                        Location_Y = double.Parse(Request.Form["Location_Y"]),
                        Scale = int.Parse(Request.Form["Scale"])
                    };
                    break;
                case RequestMsgType.Image:
                    requestMessaage = new RequestMessageImage()
                    {
                        PicUrl = Request.Form["PicUrl"],
                    };
                    break;
                case RequestMsgType.Voice:
                    requestMessaage = new RequestMessageVoice()
                    {
                        Format = Request.Form["Format"],
                        Recognition = Request.Form["Recognition"],
                    };
                    break;
                case RequestMsgType.Video:
                    requestMessaage = new RequestMessageVideo()
                    {
                        MsgId = long.Parse(Request.Form["MsgId"]),
                        ThumbMediaId = Request.Form["ThumbMediaId"],
                    };
                    break;
                //case RequestMsgType.Link:
                //    break;
                case RequestMsgType.Event:
                    if (eventType.HasValue)
                    {
                        RequestMessageEventBase requestMessageEvent = null;
                        switch (eventType.Value)
                        {
                            //case Event.ENTER:
                            //    break;
                            case Event.LOCATION:
                                requestMessageEvent = new RequestMessageEvent_Location()
                                {
                                    Latitude = long.Parse(Request.Form["Event.Latitude"]),
                                    Longitude = long.Parse(Request.Form["Event.Longitude"]),
                                    Precision = double.Parse(Request.Form["Event.Precision"])
                                };
                                break;
                            case Event.subscribe:
                                requestMessageEvent = new RequestMessageEvent_Subscribe()
                                {
                                    EventKey = Request.Form["Event.EventKey"],
                                    Ticket = Request.Form["Event.Ticket"]
                                };
                                break;
                            case Event.unsubscribe:
                                requestMessageEvent = new RequestMessageEvent_Unsubscribe();
                                break;
                            case Event.CLICK:
                                requestMessageEvent = new RequestMessageEvent_Click()
                                   {
                                       EventKey = Request.Form["Event.EventKey"]
                                   };
                                break;
                            case Event.scan:
                                requestMessageEvent = new RequestMessageEvent_Scan()
                                 {
                                     EventKey = Request.Form["Event.EventKey"],
                                     Ticket = Request.Form["Event.Ticket"]
                                 }; break;
                            case Event.VIEW:
                                requestMessageEvent = new RequestMessageEvent_View()
                                 {
                                     EventKey = Request.Form["Event.EventKey"]
                                 }; break;
                            case Event.MASSSENDJOBFINISH:
                                requestMessageEvent = new RequestMessageEvent_MassSendJobFinish()
                                {
                                    FromUserName = "******",//系统指定
                                    ErrorCount = int.Parse(Request.Form["Event.ErrorCount"]),
                                    FilterCount = int.Parse(Request.Form["Event.FilterCount"]),
                                    SentCount = int.Parse(Request.Form["Event.SentCount"]),
                                    Status = Request.Form["Event.Status"],
                                    TotalCount = int.Parse(Request.Form["Event.TotalCount"])
                                }; break;
                            case Event.TEMPLATESENDJOBFINISH:
                                requestMessageEvent = new RequestMessageEvent_TemplateSendJobFinish()
                                {
                                    FromUserName = "******",//系统指定
                                    MsgID = long.Parse(Request.Form["Event.MsgID"]),
                                    Status = Request.Form["Event.Status"],
                                }; break;
                            case Event.scancode_push:
                                requestMessageEvent = new RequestMessageEvent_Scancode_Push()
                                {
                                    FromUserName = "******",//系统指定
                                    EventKey = Request.Form["Event.EventKey"],
                                    ScanCodeInfo = new ScanCodeInfo()
                                        {
                                            ScanResult = Request.Form["Event.ScanResult"],
                                            ScanType = Request.Form["Event.ScanType"],
                                        }
                                }; break;
                            case Event.scancode_waitmsg:
                                requestMessageEvent = new RequestMessageEvent_Scancode_Waitmsg()
                                {
                                    FromUserName = "******",//系统指定
                                    EventKey = Request.Form["Event.EventKey"],
                                    ScanCodeInfo = new ScanCodeInfo()
                                    {
                                        ScanResult = Request.Form["Event.ScanResult"],
                                        ScanType = Request.Form["Event.ScanType"],
                                    }
                                }; break;
                            case Event.pic_sysphoto:
                                var sysphotoPicMd5Sum = Request.Form["Event.PicMd5Sum"];
                                PicItem sysphotoPicItem = new PicItem()
                                    {
                                        item = new Md5Sum()
                                            {
                                                PicMd5Sum = sysphotoPicMd5Sum
                                            }
                                    };
                                List<PicItem> sysphotoPicItems = new List<PicItem>();
                                sysphotoPicItems.Add(sysphotoPicItem);
                                requestMessageEvent = new RequestMessageEvent_Pic_Sysphoto()
                            {
                                FromUserName = "******",//系统指定
                                EventKey = Request.Form["Event.EventKey"],
                                SendPicsInfo = new SendPicsInfo()
                                {
                                    Count = Request.Form["Event.Count"],
                                    PicList = sysphotoPicItems
                                }
                            }; break;
                            case Event.pic_photo_or_album:
                                var photoOrAlbumPicMd5Sum = Request.Form["Event.PicMd5Sum"];
                                PicItem photoOrAlbumPicItem = new PicItem()
                                {
                                    item = new Md5Sum()
                                    {
                                        PicMd5Sum = photoOrAlbumPicMd5Sum
                                    }
                                };
                                List<PicItem> photoOrAlbumPicItems = new List<PicItem>();
                                photoOrAlbumPicItems.Add(photoOrAlbumPicItem);
                                requestMessageEvent = new RequestMessageEvent_Pic_Sysphoto()
                                {
                                    FromUserName = "******",//系统指定
                                    EventKey = Request.Form["Event.EventKey"],
                                    SendPicsInfo = new SendPicsInfo()
                                    {
                                        Count = Request.Form["Event.Count"],
                                        PicList = photoOrAlbumPicItems
                                    }
                                }; break;
                            case Event.pic_weixin:
                                var weixinPicMd5Sum = Request.Form["Event.PicMd5Sum"];
                                PicItem weixinPicItem = new PicItem()
                                {
                                    item = new Md5Sum()
                                    {
                                        PicMd5Sum = weixinPicMd5Sum
                                    }
                                };
                                List<PicItem> weixinPicItems = new List<PicItem>();
                                weixinPicItems.Add(weixinPicItem);
                                requestMessageEvent = new RequestMessageEvent_Pic_Sysphoto()
                                {
                                    FromUserName = "******",//系统指定
                                    EventKey = Request.Form["Event.EventKey"],
                                    SendPicsInfo = new SendPicsInfo()
                                    {
                                        Count = Request.Form["Event.Count"],
                                        PicList = weixinPicItems
                                    }
                                }; break;
                            case Event.location_select:
                                requestMessageEvent = new RequestMessageEvent_Location_Select()
                                {
                                    FromUserName = "******",//系统指定
                                    EventKey = Request.Form["Event.EventKey"],
                                    SendLocationInfo = new SendLocationInfo()
                                        {
                                            Label = Request.Form["Event.Label"],
                                            Location_X = Request.Form["Event.Location_X"],
                                            Location_Y = Request.Form["Event.Location_Y"],
                                            Poiname = Request.Form["Event.Poiname"],
                                            Scale = Request.Form["Event.Scale"],
                                        }
                                }; break;
                            default:
                                throw new ArgumentOutOfRangeException("eventType");
                        }
                        requestMessaage = requestMessageEvent;
                    }
                    else
                    {
                        throw new ArgumentOutOfRangeException("eventType");
                    }
                    break;
                default:
                    throw new ArgumentOutOfRangeException("requestType");
            }

            requestMessaage.MsgId = long.Parse(Request.Form["MsgId"]);
            requestMessaage.CreateTime = DateTime.Now;
            requestMessaage.FromUserName = requestMessaage.FromUserName ?? "FromUserName(OpenId)";//用于区别不同的请求用户
            requestMessaage.ToUserName = "******";

            return requestMessaage.ConvertEntityToXml();
        }
        /// <summary>
        /// 菜单点击事件
        /// </summary>
        /// <param name="requestMessage"></param>
        /// <returns></returns>
        public override IResponseMessageBase OnEvent_ClickRequest(RequestMessageEvent_Click requestMessage)
        {
            IResponseMessageBase reponseMessage = null;
            #region 注释掉
            ////菜单点击,需要跟创建菜单时的Key匹配
            //switch (requestMessage.EventKey)
            //{
            //    case "OneClick":
            //        {
            //            var strongResponseMessage = CreateResponseMessage<ResponseMessageText>();
            //            reponseMessage = strongResponseMessage;
            //            strongResponseMessage.Content = "您点击了底部按钮。\r\n为了测试微信软件换行bug的应对措施,这里做了一个——\r\n换行";
            //        }
            //        break;
            //    case "SubClickRoot_Text":
            //        {
            //            var strongResponseMessage = CreateResponseMessage<ResponseMessageText>();
            //            reponseMessage = strongResponseMessage;
            //            strongResponseMessage.Content = "您点击了子菜单按钮。";
            //        }
            //        break;
            //    case "SubClickRoot_News":
            //        {
            //            var strongResponseMessage = CreateResponseMessage<ResponseMessageNews>();
            //            reponseMessage = strongResponseMessage;
            //            strongResponseMessage.Articles.Add(new Article()
            //            {
            //                Title = "您点击了子菜单图文按钮",
            //                Description = "您点击了子菜单图文按钮,这是一条图文信息。",
            //                PicUrl = "http://weixin.senparc.com/Images/qrcode.jpg",
            //                Url = "http://weixin.senparc.com"
            //            });
            //        }
            //        break;
            //    case "SubClickRoot_Music":
            //        {
            //            var strongResponseMessage = CreateResponseMessage<ResponseMessageMusic>();
            //            reponseMessage = strongResponseMessage;
            //            strongResponseMessage.Music.MusicUrl = "http://weixin.senparc.com/Content/music1.mp3";
            //        }
            //        break;
            //    case "SubClickRoot_Agent"://代理消息
            //        {
            //            //获取返回的XML
            //            DateTime dt1 = DateTime.Now;
            //            reponseMessage = MessageAgent.RequestResponseMessage(this, agentUrl, agentToken, RequestDocument.ToString());
            //            //上面的方法也可以使用扩展方法:this.RequestResponseMessage(this,agentUrl, agentToken, RequestDocument.ToString());

            //            DateTime dt2 = DateTime.Now;

            //            if (reponseMessage is ResponseMessageNews)
            //            {
            //                (reponseMessage as ResponseMessageNews)
            //                    .Articles[0]
            //                    .Description += string.Format("\r\n\r\n代理过程总耗时:{0}毫秒", (dt2 - dt1).Milliseconds);
            //            }
            //        }
            //        break;
            //    case "Member"://托管代理会员信息
            //        {
            //            //原始方法为:MessageAgent.RequestXml(this,agentUrl, agentToken, RequestDocument.ToString());//获取返回的XML
            //            reponseMessage = this.RequestResponseMessage(agentUrl, agentToken, RequestDocument.ToString());
            //        }
            //        break;
            //    case "OAuth"://OAuth授权测试
            //        {
            //            var strongResponseMessage = CreateResponseMessage<ResponseMessageNews>();
            //            strongResponseMessage.Articles.Add(new Article()
            //            {
            //                Title = "OAuth2.0测试",
            //                Description = "点击【查看全文】进入授权页面。\r\n注意:此页面仅供测试(是专门的一个临时测试账号的授权,并非Senparc.Weixin.MP SDK官方账号,所以如果授权后出现错误页面数正常情况),测试号随时可能过期。请将此DEMO部署到您自己的服务器上,并使用自己的appid和secret。",
            //                Url = "http://weixin.senparc.com/oauth2",
            //                PicUrl = "http://weixin.senparc.com/Images/qrcode.jpg"
            //            });
            //            reponseMessage = strongResponseMessage;
            //        }
            //        break;
            //}
            #endregion
            string keywords = requestMessage.EventKey;
            int apiid = wxcomm.getApiid();

            string EventName = "";
            if (requestMessage.Event.ToString().Trim() != "")
            {
                EventName = requestMessage.Event.ToString();
            }
            else if (requestMessage.EventKey != null)
            {
                EventName += requestMessage.EventKey.ToString();
            }

            if (!wxcomm.ExistApiidAndWxId(apiid, requestMessage.ToUserName))
            {  //验证接收方是否为我们系统配置的帐号,即验证微帐号与微信原始帐号id是否一致,如果不一致,说明【1】配置错误,【2】数据来源有问题
                DAL.wxResponseBaseMgr.Add(apiid, requestMessage.FromUserName, requestMessage.MsgType.ToString(), EventName, "none", "未取到关键词对应的数据", requestMessage.ToUserName);
                return wxcomm.GetResponseMessageTxtByContent(requestMessage, "验证微帐号与微信原始帐号id不一致,可能原因【1】系统配置错误,【2】非法的数据来源有问题", apiid);
            }

            int responseType = 0;
            string modelFunctionName = "";
            int modelFunctionId = 0;
            int rid = rBll.GetRuleIdByKeyWords(apiid, keywords, out responseType, out modelFunctionName, out modelFunctionId);
            if (rid <= 0 || responseType <= 0)
            {
                // 2014-9-18 暂时性功能 针对ID为 gh_04bf23f25940的平台客户 保存发送者的ID 及 生成抽奖序号 并保存。
                if (requestMessage.ToUserName == "gh_c80ca634fa2a" && requestMessage.EventKey == "wdsluckdraw20140920")
                {
                    //发送纯文字
                    reponseMessage = wxcomm.GetResponseMessageTxt(requestMessage, apiid);
                    return reponseMessage;
                }
                else
                {
                    // 2014-9-18原功能
                    DAL.wxResponseBaseMgr.Add(apiid, requestMessage.FromUserName, requestMessage.MsgType.ToString(), EventName, "none", "未取到关键词对应的数据", requestMessage.ToUserName);
                    return wxcomm.GetResponseMessageTxtByContent(requestMessage, "", apiid);
                }
            }

            if (modelFunctionId > 0)
            {  //模块功能回复
                return wxcomm.GetModuleResponse(requestMessage, modelFunctionName, modelFunctionId, apiid);
            }

            switch (responseType)
            {
                case 1:
                    //发送纯文字
                    reponseMessage = wxcomm.GetResponseMessageTxt(requestMessage, rid, apiid);
                    break;
                case 2:
                    //发送多图文
                    reponseMessage = wxcomm.GetResponseMessageNews(requestMessage, rid, apiid);
                    break;
                case 3:
                    //发送语音
                    reponseMessage = wxcomm.GetResponseMessageeMusic(requestMessage, rid, apiid);
                    break;
                default:
                    break;
            }

            return reponseMessage;
        }
        public override IResponseMessageBase OnEvent_ClickRequest(RequestMessageEvent_Click requestMessage)
        {
            IResponseMessageBase responseMessage = null;
            var openId = requestMessage.FromUserName;
            var content = "";
            WeChatUser wechatUser = null;

            var textResponseMessage = CreateResponseMessage<ResponseMessageText>();
            var newsResponseMessage = CreateResponseMessage<ResponseMessageNews>();

            switch (requestMessage.EventKey)
            {
                #region 会员注册
                case "UserRegister":
                    {
                        content = string.Empty;

                        User user = null;

                        try
                        {
                            wechatUser = userService.GetWeChatUser(openId);

                            if (wechatUser != null)
                            {
                                if (wechatUser.UserId.HasValue)
                                {
                                    user = userService.GetUserById(wechatUser.UserId.Value);
                                }
                            }
                            else
                            {
                                content = "连接获取失败,请重新尝试。";
                            }
                        }
                        catch (Exception ex)
                        {
                            LogService.LogWexin("微信用户绑定发生错误", ex.ToString());
                            content = "连接获取失败,请重新尝试。";
                        }

                        if (string.IsNullOrEmpty(content))
                        {
                            if (user != null)
                            {
                                var userName = !string.IsNullOrEmpty(user.UserName) ? user.UserName : (!string.IsNullOrEmpty(user.Email) ? user.Email : user.Cellphone);
                                content = "您当前已绑定会员账号:" + userName + ",无需重复注册。如要重新注册新的会员账号,请点击如下链接。\r\n\r\n"
                                    + UserRegisterUrl;
                            }
                            else
                            {
                                content = "活动在线网微信服务号是活动在线网(www.huodongzaixian.com)官方开发的服务号。如需更好访问电脑、手机版及服务号,需注册账号成为会员。\r\n\r\n"
                                    + UserRegisterUrl;
                            }
                        }

                        textResponseMessage.Content = content;
                        responseMessage = textResponseMessage;
                    }
                    break;
                #endregion

                #region 账号绑定
                case "UserLogin":
                    {
                        content = string.Empty;

                        var hasUserLoggedIn = false;
                        User user = null;

                        try
                        {
                            wechatUser = userService.GetWeChatUser(openId);

                            if (wechatUser != null)
                            {
                                if (wechatUser.UserId.HasValue)
                                {
                                    user = userService.GetUserById(wechatUser.UserId.Value);

                                    if (user != null)
                                    {
                                        hasUserLoggedIn = true;
                                    }
                                }
                            }
                            else
                            {
                                content = "连接获取失败,请重新尝试。";
                            }
                        }
                        catch (Exception ex)
                        {
                            LogService.LogWexin("微信用户绑定发生错误", ex.ToString());
                            content = "连接获取失败,请重新尝试。";
                        }

                        if (string.IsNullOrEmpty(content))
                        {
                            if (hasUserLoggedIn)
                            {
                                var userName = !string.IsNullOrEmpty(user.UserName) ? user.UserName : (!string.IsNullOrEmpty(user.Email) ? user.Email : user.Cellphone);
                                content = "绑定活动在线网(www.huodongzaixian.com)会员账号,微信登录即可同步PC端会员账号数据。您当前已绑定账号为:"
                                    + userName + "。是否需要更改绑定账号?\r\n\r\n" + UserReLoginUrl;
                            }
                            else
                            {
                                content = "活动在线网微信服务号是活动在线网(www.huodongzaixian.com)官方开发的服务号。如需更好访问电脑、手机版及服务号,请立即绑定您的会员账号。\r\n\r\n"
                                       + UserLoginUrl;
                            }
                        }

                        textResponseMessage.Content = content;
                        responseMessage = textResponseMessage;
                    }

                    break;
                #endregion

                #region 会员认证
                case "UserIdentity":
                    {
                        content = string.Empty;

                        var hasUserIdentified = false;
                        User user = null;

                        try
                        {
                            wechatUser = userService.GetWeChatUser(openId);

                            if (wechatUser != null)
                            {
                                if (wechatUser.UserId.HasValue)
                                {
                                    user = userService.GetUserById(wechatUser.UserId.Value);

                                    if (user != null
                                        && user.Vip.HasValue
                                        && (user.Vip.Value == (int)VipState.Identified || user.Vip.Value == (int)VipState.VIP))
                                    {
                                        hasUserIdentified = true;
                                    }
                                }
                            }
                            else
                            {
                                content = "连接获取失败,请重新尝试。";
                            }
                        }
                        catch (Exception ex)
                        {
                            LogService.LogWexin("微信用户会员认证发生错误", ex.ToString());
                            content = "连接获取失败,请重新尝试。";
                        }

                        if (hasUserIdentified)
                        {
                            var userName = !string.IsNullOrEmpty(user.UserName) ? user.UserName : (!string.IsNullOrEmpty(user.Email) ? user.Email : user.Cellphone);

                            newsResponseMessage.Articles.Add(new Article
                            {
                                Description = "点击消息查看认证详情。",
                                PicUrl = user.IdentiyImg,
                                Title = "您的账号:" + userName + "已认证。",
                                Url = UserIdentifiedUrl
                            });

                            responseMessage = newsResponseMessage;
                        }
                        else if (string.IsNullOrEmpty(content))
                        {
                            if (user != null)
                            {
                                var userName = !string.IsNullOrEmpty(user.UserName) ? user.UserName : (!string.IsNullOrEmpty(user.Email) ? user.Email : user.Cellphone);
                                content = "活动在线认证会员可以发布资源信息、需求信息及活动在线,并且能够查看所有资源信息的联系方式。您当前认证的账号为:" + userName + "。\r\n\r\n" + UserIdentifyUrl;

                                textResponseMessage.Content = content;
                                responseMessage = textResponseMessage;
                            }
                            else
                            {
                                content = "您当前还未绑定活动在线账号, 无法完成会员认证。请先绑定活动在线会员账号。\r\n\r\n" + UserLoginUrl
                                    + "\r\n\r\n如还未注册,请点击如下链接注册成为活动在线会员。\r\n\r\n" + UserRegisterUrl;

                                textResponseMessage.Content = content;
                                responseMessage = textResponseMessage;
                            }
                        }
                        else
                        {
                            textResponseMessage.Content = content;
                            responseMessage = textResponseMessage;
                        }
                    }

                    break;
                #endregion

                #region 活动场地
                case "SpaceList":
                    {
                        content = string.Empty;

                        newsResponseMessage.Articles.Add(new Article
                        {
                            Description = "点击查看详情。",
                            PicUrl = BannerImgUrl,
                            Title = "活动场地信息",
                            Url = PlaceListUrl
                        });

                        responseMessage = newsResponseMessage;
                    }
                    break;
                #endregion

                #region 演艺人员
                case "ActorList":
                    {
                        content = string.Empty;

                        newsResponseMessage.Articles.Add(new Article
                        {
                            Description = "点击查看详情。",
                            PicUrl = BannerImgUrl,
                            Title = "演艺人员信息",
                            Url = ActorListUrl
                        });

                        responseMessage = newsResponseMessage;
                    }
                    break;
                #endregion

                #region 活动设备
                case "EquipmentList":
                    {
                        content = string.Empty;

                        newsResponseMessage.Articles.Add(new Article
                        {
                            Description = "点击查看详情。",
                            PicUrl = BannerImgUrl,
                            Title = "活动设备信息",
                            Url = EquipmentListUrl
                        });

                        responseMessage = newsResponseMessage;
                    }
                    break;
                #endregion

                #region 其他资源
                case "OtherResourceList":
                    {
                        content = string.Empty;

                        newsResponseMessage.Articles.Add(new Article
                        {
                            Description = "点击查看详情。",
                            PicUrl = BannerImgUrl,
                            Title = "其他资源信息",
                            Url = OtherResourceUrl
                        });

                        responseMessage = newsResponseMessage;
                    }
                    break;
                #endregion

                #region 需求信息
                case "DemandList":
                    {
                        content = string.Empty;

                        newsResponseMessage.Articles.Add(new Article
                        {
                            Description = "点击查看详情。",
                            PicUrl = BannerImgUrl,
                            Title = "需求信息",
                            Url = DemandListUrl
                        });

                        responseMessage = newsResponseMessage;
                    }
                    break;
                #endregion

                #region 发布需求
                case "NewDemand":
                    {
                        content = string.Empty;

                        newsResponseMessage.Articles.Add(new Article
                        {
                            Description = "点击进入发布需求页面。",
                            PicUrl = BannerImgUrl,
                            Title = "发布需求",
                            Url = DemandAddUrl
                        });

                        responseMessage = newsResponseMessage;
                    }
                    break;
                #endregion

                #region 交易中介
                case "TradeList":
                    {
                        content = string.Empty;

                        textResponseMessage.Content = "欲查看交易中介信息,请用电脑访问" + TradeListUrl;

                        responseMessage = textResponseMessage;
                    }
                    break;
                #endregion

                #region 更新交互时间
                case "UpdateRequestTime":
                    {
                        content = string.Empty;
                        textResponseMessage.Content = "更新成功。最新交互时间: " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss tt");
                        responseMessage = textResponseMessage;
                    }
                    break;
                #endregion

                #region 获取订阅内容
                case "GetSubscribedDemands":
                    Witbird.SHTS.Web.Subscription.WorkingThread.Instance.SendSubscribedDemandManually(openId);
                    break;
                #endregion

                #region 默认返回
                default:
                    {
                        textResponseMessage.Content = "暂不支持直接回复消息访问活动在线网官方微信号,请从菜单选择相应操作。";
                        responseMessage = textResponseMessage;
                    }
                    break;
                #endregion
            }

            // Update request time.
            userService.UpdateWeChatUserLastRequestTimestamp(openId);

            return responseMessage;
        }
 public override IResponseMessageBase OnEvent_ClickRequest(RequestMessageEvent_Click requestMessage)
 {
     throw new NotImplementedException();
 }
        public override IResponseMessageBase OnEvent_ClickRequest(RequestMessageEvent_Click requestMessage)
        {
            IResponseMessageBase reponseMessage = null;
            //菜单点击,需要跟创建菜单时的Key匹配
            switch (requestMessage.EventKey)
            {
                case "OneClick":
                    {
                        //这个过程实际已经在OnTextOrEventRequest中完成,这里不会执行到。
                        var strongResponseMessage = CreateResponseMessage<ResponseMessageText>();
                        reponseMessage = strongResponseMessage;
                        strongResponseMessage.Content = "您点击了底部按钮。\r\n为了测试微信软件换行bug的应对措施,这里做了一个——\r\n换行";
                    }
                    break;
                case "SubClickRoot_Text":
                    {
                        var strongResponseMessage = CreateResponseMessage<ResponseMessageText>();
                        reponseMessage = strongResponseMessage;
                        strongResponseMessage.Content = "您点击了子菜单按钮。";
                    }
                    break;
                case "SubClickRoot_News":
                    {
                        var strongResponseMessage = CreateResponseMessage<ResponseMessageNews>();
                        reponseMessage = strongResponseMessage;
                        strongResponseMessage.Articles.Add(new Article()
                        {
                            Title = "您点击了子菜单图文按钮",
                            Description = "您点击了子菜单图文按钮,这是一条图文信息。",
                            PicUrl = "http://weixin.senparc.com/Images/qrcode.jpg",
                            Url = "http://weixin.senparc.com"
                        });
                    }
                    break;
                case "SubClickRoot_Music":
                    {
                        var strongResponseMessage = CreateResponseMessage<ResponseMessageMusic>();
                        reponseMessage = strongResponseMessage;
                        strongResponseMessage.Music.MusicUrl = "http://weixin.senparc.com/Content/music1.mp3";
                    }
                    break;
                case "SubClickRoot_Image":
                    {
                        var strongResponseMessage = CreateResponseMessage<ResponseMessageImage>();
                        reponseMessage = strongResponseMessage;
                        strongResponseMessage.Image.MediaId = "Mj0WUTZeeG9yuBKhGP7iR5n1xUJO9IpTjGNC4buMuswfEOmk6QSIRb_i98do5nwo";
                    }
                    break;
                case "SubClickRoot_Agent"://代理消息
                    {
                        //获取返回的XML
                        DateTime dt1 = DateTime.Now;
                        reponseMessage = MessageAgent.RequestResponseMessage(this, agentUrl, agentToken, RequestDocument.ToString());
                        //上面的方法也可以使用扩展方法:this.RequestResponseMessage(this,agentUrl, agentToken, RequestDocument.ToString());

                        DateTime dt2 = DateTime.Now;

                        if (reponseMessage is ResponseMessageNews)
                        {
                            (reponseMessage as ResponseMessageNews)
                                .Articles[0]
                                .Description += string.Format("\r\n\r\n代理过程总耗时:{0}毫秒", (dt2 - dt1).Milliseconds);
                        }
                    }
                    break;
                case "Member"://托管代理会员信息
                    {
                        //原始方法为:MessageAgent.RequestXml(this,agentUrl, agentToken, RequestDocument.ToString());//获取返回的XML
                        reponseMessage = this.RequestResponseMessage(agentUrl, agentToken, RequestDocument.ToString());
                    }
                    break;
                case "OAuth"://OAuth授权测试
                    {
                        var strongResponseMessage = CreateResponseMessage<ResponseMessageNews>();
                        strongResponseMessage.Articles.Add(new Article()
                        {
                            Title = "OAuth2.0测试",
                            Description = "点击【查看全文】进入授权页面。\r\n注意:此页面仅供测试(是专门的一个临时测试账号的授权,并非Senparc.Weixin.MP SDK官方账号,所以如果授权后出现错误页面数正常情况),测试号随时可能过期。请将此DEMO部署到您自己的服务器上,并使用自己的appid和secret。",
                            Url = "http://weixin.senparc.com/oauth2",
                            PicUrl = "http://weixin.senparc.com/Images/qrcode.jpg"
                        });
                        reponseMessage = strongResponseMessage;
                    }
                    break;
                case "Description":
                    {
                        var strongResponseMessage = CreateResponseMessage<ResponseMessageText>();
                        strongResponseMessage.Content = GetWelcomeInfo();
                        reponseMessage = strongResponseMessage;
                    }
                    break;
            }

            return reponseMessage;
        }
        public override IResponseMessageBase OnEvent_ClickRequest(RequestMessageEvent_Click requestMessage)
        {
            IResponseMessageBase reponseMessage = null;
            //菜单点击,需要跟创建菜单时的Key匹配
            switch (requestMessage.EventKey)
            {
                case "OneClick":
                    {
                        var strongResponseMessage = CreateResponseMessage<ResponseMessageText>();
                        reponseMessage = strongResponseMessage;
                        strongResponseMessage.Content = "您点击了底部按钮。";
                    }
                    break;
                case "SubClickRoot_Text":
                    {
                        var strongResponseMessage = CreateResponseMessage<ResponseMessageText>();
                        reponseMessage = strongResponseMessage;
                        strongResponseMessage.Content = "您点击了子菜单按钮。";
                    }
                    break;
                case "SubClickRoot_News":
                    {
                        var strongResponseMessage = CreateResponseMessage<ResponseMessageNews>();
                        reponseMessage = strongResponseMessage;
                        strongResponseMessage.Articles.Add(new Article()
                        {
                            Title = "您点击了子菜单图文按钮",
                            Description = "您点击了子菜单图文按钮,这是一条图文信息。",
                            PicUrl = "http://weixin.senparc.com/Images/qrcode.jpg",
                            Url = "http://weixin.senparc.com"
                        });
                    }
                    break;
                case "SubClickRoot_Music":
                    {
                        var strongResponseMessage = CreateResponseMessage<ResponseMessageMusic>();
                        reponseMessage = strongResponseMessage;
                        strongResponseMessage.Music.MusicUrl = "http://weixin.senparc.com/Content/music1.mp3";
                    }
                    break;
                case "SubClickRoot_Agent"://代理消息
                    {
                        //获取返回的XML
                        DateTime dt1 = DateTime.Now;
                        reponseMessage = MessageAgent.RequestResponseMessage(agentUrl, agentToken, RequestDocument.ToString());
                        DateTime dt2 = DateTime.Now;

                        if (reponseMessage is ResponseMessageNews)
                        {
                            (reponseMessage as ResponseMessageNews)
                                .Articles[0]
                                .Description += string.Format("\r\n\r\n代理过程总耗时:{0}毫秒", (dt2 - dt1).Milliseconds);
                        }
                    }
                    break;
                case "Member"://托管代理会员信息
                    {
                        reponseMessage = MessageAgent.RequestResponseMessage(agentUrl, agentToken, RequestDocument.ToString());
                    }
                    break;
            }

            return reponseMessage;
        }
Exemple #16
0
 /// <summary>
 /// Event事件类型请求之CLICK
 /// </summary>
 public abstract IResponseMessageBase OnEvent_ClickRequest(RequestMessageEvent_Click requestMessage);
        public override IResponseMessageBase OnEvent_ClickRequest(RequestMessageEvent_Click requestMessage)
        {
            IResponseMessageBase reponseMessage = null;
            switch (requestMessage.EventKey)
            {
                case "BeginOrderClick":
                    {
                        var strongResponseMessage = CreateResponseMessage<ResponseMessageNews>();
                        strongResponseMessage.Articles.Add(new Article
                        {
                            Title = "开始预定",
                            Description = "通过微信预订点餐",
                            PicUrl = ImgUrl + "wxbeginorder.jpg",
                            Url = string.Format(Constants.HostDomain + "/order/begin/" + Constants.CompanyId + "/{0}?type=Quick", requestMessage.FromUserName)
                        });
                        reponseMessage = strongResponseMessage;
                    }
                    break;
                case "ActivityClick":
                    {
                        var strongResponseMessage = CreateResponseMessage<ResponseMessageNews>();
                        string picUrl = Constants.HostDomain + "/NewContent/images/w.png";
                        string uid = "";

                        try
                        {
                            CrmMemberModel model = new CrmMemberModel();
                            uid = model.getCrmMemberListInfoData(requestMessage.FromUserName).FirstOrDefault().Uid;
                            var prepayAccount = model.GetPrepayAccount(uid);
                            if (prepayAccount != null && prepayAccount.AccountMoney > 0)
                            {
                                picUrl = Constants.HostDomain + "/NewContent/images/chu.png";
                            }
                        }
                        catch (Exception ex)
                        {
                            LogException(ex);
                            uid = ex.StackTrace;
                        }
                        Article article = new Article();

                        article.Title = "小场合活动·微观时代";
                        article.Description = "小场合活动·微观时代";
                        article.PicUrl = picUrl;
                        article.Url = string.Format(Constants.HostDomain + "/Jump/To?fromUserName={0}&url=/Activity/Index?activityState=1", requestMessage.FromUserName);

                        strongResponseMessage.Articles.Add(article);

                        reponseMessage = strongResponseMessage;
                    }
                    break;
                case "AccountInfoClick":
                    {
                        var strongResponseMessage = CreateResponseMessage<ResponseMessageNews>();
                        string uid = string.Empty;
                        string picUrl = Constants.HostDomain + "/NewContent/images/w.png"; ;
                        try
                        {
                            CrmMemberModel model = new CrmMemberModel();
                            uid = model.getCrmMemberListInfoData(requestMessage.FromUserName).FirstOrDefault().Uid;
                            var prepayAccount = model.GetPrepayAccount(uid);
                            if (prepayAccount != null && prepayAccount.AccountMoney > 0)
                            {
                                picUrl = Constants.HostDomain + "/NewContent/images/chu.png";
                            }
                        }
                        catch (Exception ex)
                        {
                            LogException(ex);
                            uid = ex.StackTrace;
                        }
                        strongResponseMessage.Articles.Add(new Article
                        {
                            Title = "会员信息",
                            Description = "您的会员号:" + uid,
                            PicUrl = picUrl,
                            Url = string.Format(Constants.HostDomain + "/Member/Info/" + Constants.CompanyId + "/{0}", requestMessage.FromUserName)
                        });
                        reponseMessage = strongResponseMessage;
                    }
                    break;
                case "VipPay":
                    {
                        string picUrl = Constants.HostDomain + "/NewContent/images/w.png";
                        string uid = "";

                        try
                        {
                            CrmMemberModel model = new CrmMemberModel();
                            uid = model.getCrmMemberListInfoData(requestMessage.FromUserName).FirstOrDefault().Uid;
                            var prepayAccount = model.GetPrepayAccount(uid);
                            if (prepayAccount != null && prepayAccount.AccountMoney > 0)
                            {
                                picUrl = Constants.HostDomain + "/NewContent/images/chu.png";
                            }
                        }
                        catch (Exception ex)
                        {
                            LogException(ex);
                        }
                        var strongResponseMessage = CreateResponseMessage<ResponseMessageNews>();

                        DateTime dt = DateTime.Now.AddMinutes(-15);
                        PrepayRecord rec = new PrepayRecordModel().GetUserLastUnPaidComsumingPrepayRecordWithin5Minutes(requestMessage.FromUserName);
                        string description = string.Empty;
                        string title = string.Empty;
                        string url = "";

                        if (rec != null)
                        {
                            title = "支付确认";
                            description = "您本次的消费:现金¥" + (0 - rec.PrepayMoney.Value).ToString() +
                                 "/赠送¥" + (0 - rec.PresentMoney.Value).ToString() +
                                 (rec.PayByScore > 0 ? "/积分" + rec.PayByScore.ToString() : "") +
                                 (rec.DiscountlMoeny > 0 ? ",本次优惠:" + rec.DiscountlMoeny.ToString() : "") +
                                  ",账单时间:" + rec.PrepayDate.Value.ToString("yyyy-MM-dd HH:mm:ss") + ",点击本条消息,完成支付!";
                            url = string.Format(Constants.HostDomain + "/pay/payview/?id={0}&value={1}", requestMessage.FromUserName, rec.RecordId + "|" + DateTime.Now.Ticks);

                            strongResponseMessage.Articles.Add(new Article
                            {
                                Title = title,
                                Description = description,
                                PicUrl = picUrl,
                                Url = url
                            });
                            reponseMessage = strongResponseMessage;
                        }
                        else
                        {
                            description = "未查询到未结账单,可能原因为:\n1.您没有未结账单。\n2.您的账单还未生成。\n3.为保护您账号安全,您的生成的账单已经超期!";

                            var result = CreateResponseMessage<ResponseMessageText>();
                            result.Content = description;

                            reponseMessage = result;
                        }
                    }
                    break;
                case "MyOrder"://我的订单
                    {
                        var strongResponseMessage = CreateResponseMessage<ResponseMessageNews>();
                        string picUrl = Constants.HostDomain + "/NewContent/images/w.png";
                        string uid = "";

                        try
                        {
                            CrmMemberModel model = new CrmMemberModel();
                            uid = model.getCrmMemberListInfoData(requestMessage.FromUserName).FirstOrDefault().Uid;
                            var prepayAccount = model.GetPrepayAccount(uid);
                            if (prepayAccount != null && prepayAccount.AccountMoney > 0)
                            {
                                picUrl = Constants.HostDomain + "/NewContent/images/chu.png";
                            }
                        }
                        catch (Exception ex)
                        {
                            LogException(ex);
                            uid = ex.StackTrace;
                        }

                        strongResponseMessage.Articles.Add(new Article
                        {
                            Title = "我的订单",
                            Description = "我的订单:",
                            PicUrl = picUrl,
                            Url = string.Format(Constants.HostDomain + "/NewOrder/My/" + Constants.CompanyId + "/{0}", requestMessage.FromUserName)
                        });
                        reponseMessage = strongResponseMessage;
                    }
                    break;
                case "CompanyInfo"://成都印象餐饮有限公司
                    {
                        //TODO
                    }
                    break;
                case "Xiaochanghe"://成都印象小场合
                    {
                        //TODO
                    }
                    break;
                case "Culture"://小场合文化
                    {
                        //TODO
                    }
                    break;
                default:
                    {
                        var strongResponseMessage = CreateResponseMessage<ResponseMessageText>();
                        strongResponseMessage.Content = "您点击了按钮,EventKey:" + requestMessage.EventKey;
                        reponseMessage = strongResponseMessage;
                    }
                    break;
            }

            return reponseMessage;
        }
        public override IResponseMessageBase OnEvent_ClickRequest(RequestMessageEvent_Click requestMessage)
        {
            return WeixinRender.Render(this, requestMessage.EventKey);
            #region
            IResponseMessageBase reponseMessage = null;
            //菜单点击,需要跟创建菜单时的Key匹配
            switch (requestMessage.EventKey)
            {
                case "OneClick":
                    {
                        //这个过程实际已经在OnTextOrEventRequest中完成,这里不会执行到。
                        var strongResponseMessage = CreateResponseMessage<ResponseMessageText>();
                        reponseMessage = strongResponseMessage;
                        strongResponseMessage.Content = "您点击了底部按钮。\r\n为了测试微信软件换行bug的应对措施,这里做了一个——\r\n换行";
                    }
                    break;
                case "SubClickRoot_Text":
                    {
                        var strongResponseMessage = CreateResponseMessage<ResponseMessageText>();
                        reponseMessage = strongResponseMessage;
                        strongResponseMessage.Content = "您点击了子菜单按钮。";
                    }
                    break;
                case "product_promotion":
                    {

                        var strongResponseMessage = CreateResponseMessage<ResponseMessageNews>();
                        reponseMessage = strongResponseMessage;
                        strongResponseMessage.Articles.Add(new Article()
                        {
                            Title = "您点击了子菜单图文按钮",
                            Description = "您点击了子菜单图文按钮,这是一条图文信息。",
                            PicUrl = "http://weixin.senparc.com/Images/qrcode.jpg",
                            Url = "http://weixin.senparc.com"
                        });
                    }
                    break;
                case "SubClickRoot_Music":
                    {
                        var strongResponseMessage = CreateResponseMessage<ResponseMessageMusic>();
                        reponseMessage = strongResponseMessage;
                        strongResponseMessage.Music.MusicUrl = "http://weixin.senparc.com/Content/music1.mp3";
                    }
                    break;
                case "SubClickRoot_Image":
                    {
                        var strongResponseMessage = CreateResponseMessage<ResponseMessageImage>();
                        reponseMessage = strongResponseMessage;
                        strongResponseMessage.Image.MediaId = "Mj0WUTZeeG9yuBKhGP7iR5n1xUJO9IpTjGNC4buMuswfEOmk6QSIRb_i98do5nwo";
                    }
                    break;

                case "OAuth"://OAuth授权测试
                    {
                        var strongResponseMessage = this.CreateResponseMessage<ResponseMessageNews>();
                        strongResponseMessage.Articles.Add(new Article()
                        {
                            Title = "用户登陆",
                            Description = "点击【查看全文】进入授权页面。",
                            Url = Variables.ApiDomain + "oauth2",
                            PicUrl = "http://weixin.senparc.com/Images/qrcode.jpg"
                        });
                        reponseMessage = strongResponseMessage;
                    }
                    break;
                case "Description":
                    {
                        var strongResponseMessage = CreateResponseMessage<ResponseMessageText>();
                        strongResponseMessage.Content = GetWelcomeInfo();
                        reponseMessage = strongResponseMessage;
                    }
                    break;
                default:
                    {
                        var strongResponseMessage = CreateResponseMessage<ResponseMessageText>();
                        strongResponseMessage.Content = "您点击了按钮,EventKey:" + requestMessage.EventKey;
                        reponseMessage = strongResponseMessage;
                    }
                    break;
            }

            return reponseMessage;
            #endregion
        }