/// <summary>
        /// Event事件类型请求
        /// </summary>
        public virtual IResponseMessageBase OnEventRequest(IRequestMessageEventBase requestMessage)
        {
            var strongRequestMessage             = RequestMessage as IRequestMessageEventBase;
            IResponseMessageBase responseMessage = null;
            var weixinAppId = _postModel.AppId;

            switch (strongRequestMessage.Event)
            {
            case Event.ENTER:
                responseMessage = OnEvent_EnterRequest(RequestMessage as RequestMessageEvent_Enter);
                break;

            case Event.LOCATION:    //自动发送的用户当前位置
                responseMessage = OnEvent_LocationRequest(RequestMessage as RequestMessageEvent_Location);
                break;

            case Event.subscribe:    //订阅
                responseMessage = OnEvent_SubscribeRequest(RequestMessage as RequestMessageEvent_Subscribe);
                break;

            case Event.unsubscribe:    //退订
                responseMessage = OnEvent_UnsubscribeRequest(RequestMessage as RequestMessageEvent_Unsubscribe);
                break;

            case Event.CLICK:    //菜单点击
                responseMessage = CurrentMessageHandlerNode.Execute(RequestMessage, this, weixinAppId) ??
                                  OnEvent_ClickRequest(RequestMessage as RequestMessageEvent_Click);
                break;

            case Event.scan:    //二维码
                responseMessage = OnEvent_ScanRequest(RequestMessage as RequestMessageEvent_Scan);
                break;

            case Event.VIEW:    //URL跳转(view视图)
                responseMessage = OnEvent_ViewRequest(RequestMessage as RequestMessageEvent_View);
                break;

            case Event.MASSSENDJOBFINISH:    //群发消息成功
                responseMessage = OnEvent_MassSendJobFinishRequest(RequestMessage as RequestMessageEvent_MassSendJobFinish);
                break;

            case Event.TEMPLATESENDJOBFINISH:    //推送模板消息成功
                responseMessage = OnEvent_TemplateSendJobFinishRequest(RequestMessage as RequestMessageEvent_TemplateSendJobFinish);
                break;

            case Event.pic_photo_or_album:    //弹出拍照或者相册发图
                responseMessage = OnEvent_PicPhotoOrAlbumRequest(RequestMessage as RequestMessageEvent_Pic_Photo_Or_Album);
                break;

            case Event.scancode_push:    //扫码推事件
                responseMessage = OnEvent_ScancodePushRequest(RequestMessage as RequestMessageEvent_Scancode_Push);
                break;

            case Event.scancode_waitmsg:    //扫码推事件且弹出“消息接收中”提示框
                responseMessage = OnEvent_ScancodeWaitmsgRequest(RequestMessage as RequestMessageEvent_Scancode_Waitmsg);
                break;

            case Event.location_select:    //弹出地理位置选择器
                responseMessage = OnEvent_LocationSelectRequest(RequestMessage as RequestMessageEvent_Location_Select);
                break;

            case Event.pic_weixin:    //弹出微信相册发图器
                responseMessage = OnEvent_PicWeixinRequest(RequestMessage as RequestMessageEvent_Pic_Weixin);
                break;

            case Event.pic_sysphoto:    //弹出系统拍照发图
                responseMessage = OnEvent_PicSysphotoRequest(RequestMessage as RequestMessageEvent_Pic_Sysphoto);
                break;

            case Event.card_pass_check:    //卡券通过审核
                responseMessage = OnEvent_Card_Pass_CheckRequest(RequestMessage as RequestMessageEvent_Card_Pass_Check);
                break;

            case Event.card_not_pass_check:    //卡券未通过审核
                responseMessage = OnEvent_Card_Not_Pass_CheckRequest(RequestMessage as RequestMessageEvent_Card_Not_Pass_Check);
                break;

            case Event.user_get_card:    //领取卡券
                responseMessage = OnEvent_User_Get_CardRequest(RequestMessage as RequestMessageEvent_User_Get_Card);
                break;

            case Event.user_del_card:    //删除卡券
                responseMessage = OnEvent_User_Del_CardRequest(RequestMessage as RequestMessageEvent_User_Del_Card);
                break;

            case Event.kf_create_session:    //多客服接入会话
                responseMessage = OnEvent_Kf_Create_SessionRequest(RequestMessage as RequestMessageEvent_Kf_Create_Session);
                break;

            case Event.kf_close_session:    //多客服关闭会话
                responseMessage = OnEvent_Kf_Close_SessionRequest(RequestMessage as RequestMessageEvent_Kf_Close_Session);
                break;

            case Event.kf_switch_session:    //多客服转接会话
                responseMessage = OnEvent_Kf_Switch_SessionRequest(RequestMessage as RequestMessageEvent_Kf_Switch_Session);
                break;

            case Event.poi_check_notify:    //审核结果事件推送
                responseMessage = OnEvent_Poi_Check_NotifyRequest(RequestMessage as RequestMessageEvent_Poi_Check_Notify);
                break;

            case Event.WifiConnected:    //Wi-Fi连网成功
                responseMessage = OnEvent_WifiConnectedRequest(RequestMessage as RequestMessageEvent_WifiConnected);
                break;

            case Event.user_consume_card:    //卡券核销
                responseMessage = OnEvent_User_Consume_CardRequest(RequestMessage as RequestMessageEvent_User_Consume_Card);
                break;

            case Event.user_enter_session_from_card:    //从卡券进入公众号会话
                responseMessage = OnEvent_User_Enter_Session_From_CardRequest(RequestMessage as RequestMessageEvent_User_Enter_Session_From_Card);
                break;

            case Event.user_view_card:    //进入会员卡
                responseMessage = OnEvent_User_View_CardRequest(RequestMessage as RequestMessageEvent_User_View_Card);
                break;

            case Event.merchant_order:    //微小店订单付款通知
                responseMessage = OnEvent_Merchant_OrderRequest(RequestMessage as RequestMessageEvent_Merchant_Order);
                break;

            case Event.submit_membercard_user_info:    //接收会员信息事件通知
                responseMessage = OnEvent_Submit_Membercard_User_InfoRequest(RequestMessage as RequestMessageEvent_Submit_Membercard_User_Info);
                break;

            case Event.ShakearoundUserShake:    //摇一摇事件通知
                responseMessage = OnEvent_ShakearoundUserShakeRequest(RequestMessage as RequestMessageEvent_ShakearoundUserShake);
                break;

            case Event.user_gifting_card:    //卡券转赠事件推送
                responseMessage = OnEvent_User_Gifting_CardRequest(RequestMessage as RequestMessageEvent_User_Gifting_Card);
                break;

            case Event.user_pay_from_pay_cell:    //微信买单完成
                responseMessage = OnEvent_User_Pay_From_Pay_CellRequest(RequestMessage as RequestMessageEvent_User_Pay_From_Pay_Cell);
                break;

            case Event.update_member_card:    //会员卡内容更新事件:会员卡积分余额发生变动时
                responseMessage = OnEvent_Update_Member_CardRequest(RequestMessage as RequestMessageEvent_Update_Member_Card);
                break;

            case Event.card_sku_remind:    //卡券库存报警事件:当某个card_id的初始库存数大于200且当前库存小于等于100时
                responseMessage = OnEvent_Card_Sku_RemindRequest(RequestMessage as RequestMessageEvent_Card_Sku_Remind);
                break;

            case Event.card_pay_order:    //券点流水详情事件:当商户朋友的券券点发生变动时
                responseMessage = OnEvent_Card_Pay_OrderRequest(RequestMessage as RequestMessageEvent_Card_Pay_Order);
                break;

            case Event.apply_merchant_audit_info:    //创建门店小程序审核事件
                responseMessage = OnEvent_Apply_Merchant_Audit_InfoRequest(RequestMessage as RequestMessageEvent_ApplyMerchantAuditInfo);
                break;

            case Event.add_store_audit_info:    //门店小程序中创建门店审核事件
                responseMessage = OnEvent_Add_Store_Audit_Info(RequestMessage as RequestMessageEvent_AddStoreAuditInfo);
                break;

            case Event.create_map_poi_audit_info:    //从腾讯地图中创建门店审核事件
                responseMessage = OnEvent_Create_Map_Poi_Audit_Info(RequestMessage as RequestMessageEvent_CreateMapPoiAuditInfo);
                break;

            case Event.modify_store_audit_info:    //修改门店图片审核事件
                responseMessage = OnEvent_Modify_Store_Audit_Info(RequestMessage as RequestMessageEvent_ModifyStoreAuditInfo);
                break;

            case Event.view_miniprogram:    //点击菜单跳转小程序的事件推送
                responseMessage = OnEvent_View_Miniprogram(RequestMessage as RequestMessageEvent_View_Miniprogram);
                break;

                #region 卡券回调

            case Event.giftcard_pay_done:
                responseMessage = OnEvent_GiftCard_Pay_DoneRequest(RequestMessage as RequestMessageEvent_GiftCard_Pay_Done);
                break;

            case Event.giftcard_send_to_friend:
                responseMessage = OnEvent_GiftCard_Send_To_FriendRequest(RequestMessage as RequestMessageEvent_GiftCard_Send_To_Friend);
                break;

            case Event.giftcard_user_accept:
                responseMessage = OnEvent_GiftCard_User_AcceptRequest(RequestMessage as RequestMessageEvent_GiftCard_User_Accept);
                break;

                #endregion

                #region 微信认证事件推送

            case Event.qualification_verify_success:    //资质认证成功(此时立即获得接口权限)
                responseMessage = OnEvent_QualificationVerifySuccessRequest(RequestMessage as RequestMessageEvent_QualificationVerifySuccess);
                break;

            case Event.qualification_verify_fail:    //资质认证失败
                responseMessage = OnEvent_QualificationVerifyFailRequest(RequestMessage as RequestMessageEvent_QualificationVerifyFail);
                break;

            case Event.naming_verify_success:    //名称认证成功(即命名成功)
                responseMessage = OnEvent_NamingVerifySuccessRequest(RequestMessage as RequestMessageEvent_NamingVerifySuccess);
                break;

            case Event.naming_verify_fail:    //名称认证失败(这时虽然客户端不打勾,但仍有接口权限)
                responseMessage = OnEvent_NamingVerifyFailRequest(RequestMessage as RequestMessageEvent_NamingVerifyFail);
                break;

            case Event.annual_renew:    //年审通知
                responseMessage = OnEvent_AnnualRenewRequest(RequestMessage as RequestMessageEvent_AnnualRenew);
                break;

            case Event.verify_expired:    //认证过期失效通知
                responseMessage = OnEvent_VerifyExpiredRequest(RequestMessage as RequestMessageEvent_VerifyExpired);
                break;
                #endregion

                #region 小程序审核事件推送
                //该事件已移动到Senparc.Weixin.WxOpen
                //case Event.weapp_audit_success://
                //    responseMessage = OnEvent_WeAppAuditSuccessRequest(RequestMessage as RequestMessageEvent_WeAppAuditSuccess);
                //    break;
                //case Event.weapp_audit_fail://
                //    responseMessage = OnEvent_WeAppAuditFailRequest(RequestMessage as RequestMessageEvent_WeAppAuditFail);
                //    break;
                #endregion
            default:
                throw new UnknownRequestMsgTypeException("未知的Event下属请求信息", null);
            }
            return(responseMessage);
        }
        /// <summary>
        /// 获取响应消息
        /// </summary>
        /// <param name="requestMessage"></param>
        /// <param name="responseConfigs"></param>
        /// <param name="messageHandler"></param>
        /// <param name="accessTokenOrApi"></param>
        /// <returns></returns>
        private async Task <IResponseMessageBase> GetResponseMessage(IRequestMessageBase requestMessage, List <Response> responseConfigs, IMessageHandlerEnlightener messageHandler, string accessTokenOrApi)
        {
            IResponseMessageBase responseMessage = null;

            responseConfigs = responseConfigs ?? new List <Response>();

            if (responseConfigs.Count == 0)
            {
                return(null);
            }

            //扩展响应,会在消息回复之前发送
            var extendReponses = responseConfigs.Count > 1
                    ? responseConfigs.Take(responseConfigs.Count - 1).ToList()
                    : new List <Response>();

            //获取最后一个响应设置
            var lastResponse = responseConfigs.Last();//取最后一个

            //处理特殊情况
            if (messageHandler.MessageEntityEnlightener.PlatformType == PlatformType.WeChat_MiniProgram)
            {
                //小程序,所有的请求都使用客服消息接口,回填取出的最后一个
                extendReponses.Add(lastResponse);
                lastResponse = new Response()
                {
                    Type = ResponseMsgType.SuccessResponse
                };                                                                       //返回成功信息
                                                                                         //responseMessage = new SuccessResponseMessage();
            }

            //排序的最后一项,使用 MesageHandler 的普通消息回复
            switch (lastResponse.Type)
            {
            case ResponseMsgType.Text:
                responseMessage = RenderResponseMessageText(requestMessage, lastResponse, messageHandler.MessageEntityEnlightener);

                break;

            case ResponseMsgType.News:
            case ResponseMsgType.MultipleNews:
                responseMessage = RenderResponseMessageNews(requestMessage, lastResponse, messageHandler.MessageEntityEnlightener);
                break;

            case ResponseMsgType.Music:
                break;

            case ResponseMsgType.Image:
                responseMessage = RenderResponseMessageImage(requestMessage, lastResponse, messageHandler.MessageEntityEnlightener);
                break;

            case ResponseMsgType.Voice:
                break;

            case ResponseMsgType.Video:
                break;

            case ResponseMsgType.Transfer_Customer_Service:
                break;

            //case ResponseMsgType.MultipleNews:
            //    break;
            case ResponseMsgType.LocationMessage:
                break;

            case ResponseMsgType.NoResponse:
                responseMessage = RenderResponseMessageNoResponse(requestMessage, lastResponse, messageHandler.MessageEntityEnlightener);
                break;

            case ResponseMsgType.SuccessResponse:
                responseMessage = RenderResponseMessageSuccessResponse(requestMessage, lastResponse, messageHandler.MessageEntityEnlightener);
                break;

            case ResponseMsgType.UseApi:    //常规官方平台转发的请求不会到达这里
                break;

            default:
                break;
            }

            //使用客服接口(高级接口)发送最后一项之前的所有信息
            await ExecuteApi(extendReponses, requestMessage, messageHandler, accessTokenOrApi, requestMessage.FromUserName);

            return(responseMessage);
        }
        /// <summary>
        /// 点击事件
        /// </summary>
        /// <param name="requestMessage"></param>
        /// <returns></returns>
        public override IResponseMessageBase OnEvent_ClickRequest(RequestMessageEvent_Click requestMessage)
        {
            IResponseMessageBase reponseMessage = null;

            //菜单点击,需要跟创建菜单时的Key匹配

            switch (requestMessage.EventKey)
            {
            case "OrderClick":
            {
                // Link to a web page to sign up
            }
            break;

            case "OneClick":
            {
                //这个过程实际已经在OnTextOrEventRequest中命中“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 = "您点击了子菜单图文按钮,这是一条图文信息。这个区域是Description内容\r\n可以使用\\r\\n进行换行。",
                        PicUrl      = "https://sdk.weixin.senparc.com/Images/qrcode.jpg",
                        Url         = "https://sdk.weixin.senparc.com"
                    });

                //随机添加一条图文,或只输出一条图文信息
                if (SystemTime.Now.Second % 2 == 0)
                {
                    strongResponseMessage.Articles.Add(new Article()
                        {
                            Title       = "这是随机产生的第二条图文信息,用于测试多条图文的样式",
                            Description = "这是随机产生的第二条图文信息,用于测试多条图文的样式",
                            PicUrl      = "https://sdk.weixin.senparc.com/Images/qrcode.jpg",
                            Url         = "https://sdk.weixin.senparc.com"
                        });
                }
            }
            break;

            case "SubClickRoot_Music":
            {
                //上传缩略图

#if NET45
                var filePath = "~/Images/Logo.thumb.jpg";
#else
                var filePath = "~/wwwroot/Images/Logo.thumb.jpg";
#endif

                var uploadResult = AdvancedAPIs.MediaApi.UploadTemporaryMedia(appId, UploadMediaFileType.thumb,
                                                                              ServerUtility.ContentRootMapPath(filePath));
                //PS:缩略图官方没有特别提示文件大小限制,实际测试哪怕114K也会返回文件过大的错误,因此尽量控制在小一点(当前图片39K)

                //设置音乐信息
                var strongResponseMessage = CreateResponseMessage <ResponseMessageMusic>();
                reponseMessage = strongResponseMessage;
                strongResponseMessage.Music.Title        = "天籁之音";
                strongResponseMessage.Music.Description  = "真的是天籁之音";
                strongResponseMessage.Music.MusicUrl     = "https://sdk.weixin.senparc.com/Content/music1.mp3";
                strongResponseMessage.Music.HQMusicUrl   = "https://sdk.weixin.senparc.com/Content/music1.mp3";
                strongResponseMessage.Music.ThumbMediaId = uploadResult.thumb_media_id;
            }
            break;

            case "SubClickRoot_Image":
            {
                //上传图片
#if NET45
                var filePath = "~/Images/Logo.jpg";
#else
                var filePath = "~/wwwroot/Images/Logo.jpg";
#endif

                var uploadResult = AdvancedAPIs.MediaApi.UploadTemporaryMedia(appId, UploadMediaFileType.image,
                                                                              ServerUtility.ContentRootMapPath(filePath));
                //设置图片信息
                var strongResponseMessage = CreateResponseMessage <ResponseMessageImage>();
                reponseMessage = strongResponseMessage;
                strongResponseMessage.Image.MediaId = uploadResult.media_id;
            }
            break;

            case "SendMenu":
            {
                var menuContentList = new List <SendMenuContent>()
                {
                    new SendMenuContent("101", "满意"),
                    new SendMenuContent("102", "一般"),
                    new SendMenuContent("103", "不满意")
                };
                //使用异步接口
                CustomApi.SendMenu(appId, OpenId, "请对 Senparc.Weixin SDK 给出您的评价", menuContentList, "感谢您的参与!");

                reponseMessage = new ResponseMessageNoResponse();        //不返回任何消息
            }
            break;

            case "SubClickRoot_Agent":    //代理消息
            {
                //获取返回的XML
                var dt1 = SystemTime.Now;
                reponseMessage = MessageAgent.RequestResponseMessage(this, agentUrl, agentToken, RequestDocument.ToString());
                //上面的方法也可以使用扩展方法:this.RequestResponseMessage(this,agentUrl, agentToken, RequestDocument.ToString());

                var dt2 = SystemTime.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 = "https://sdk.weixin.senparc.com/oauth2",
                        //PicUrl = "https://sdk.weixin.senparc.com/Images/qrcode.jpg"
                    });

                strongResponseMessage.Articles.Add(new Article()
                    {
                        Title       = "OAuth2.0测试(不带returnUrl),测试环境可使用",
                        Description = "OAuth2.0测试(不带returnUrl)",
                        Url         = "https://sdk.weixin.senparc.com/oauth2",
                        PicUrl      = "https://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         = "https://sdk.weixin.senparc.com/oauth2?returnUrl=" + returnUrl.UrlEncode(),
                        PicUrl      = "https://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;

            case "GetNewMediaId":    //获取新的MediaId
            {
                var strongResponseMessage = CreateResponseMessage <ResponseMessageText>();
                try
                {
                    var result = AdvancedAPIs.MediaApi.UploadForeverMedia(appId, ServerUtility.ContentRootMapPath("~/Images/logo.jpg"));
                    strongResponseMessage.Content = result.media_id;
                }
                catch (Exception e)
                {
                    strongResponseMessage.Content = "发生错误:" + e.Message;
                    WeixinTrace.SendCustomLog("调用UploadForeverMedia()接口发生异常", e.Message);
                }
            }
            break;

            default:
            {
                var strongResponseMessage = CreateResponseMessage <ResponseMessageText>();
                strongResponseMessage.Content = "您点击了按钮,EventKey:" + requestMessage.EventKey;
                reponseMessage = strongResponseMessage;
            }
            break;
            }

            return(reponseMessage);
        }
示例#4
0
        private static readonly string AppSecret      = System.Configuration.ConfigurationManager.AppSettings[CONFIG_APPSECRET];      //相当于一个秘钥 我们自己秘钥 可以配置的



        /// <summary>
        /// 点击事件
        /// </summary>
        /// <param name="requestMessage"></param>
        /// <returns></returns>
        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 = "您点击了子菜单图文按钮,这是一条图文信息。这个区域是Description内容\r\n可以使用\\r\\n进行换行。",
                //                            PicUrl = "http://sdk.weixin.senparc.com/Images/qrcode.jpg",
                //                            Url = "http://sdk.weixin.senparc.com"
                //                        });
                //
                //                        //随机添加一条图文,或只输出一条图文信息
                //                        if (DateTime.Now.Second % 2 == 0)
                //                        {
                //                            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.thumb.jpg"));
                //                        //PS:缩略图官方没有特别提示文件大小限制,实际测试哪怕114K也会返回文件过大的错误,因此尽量控制在小一点(当前图片39K)
                //
                //                        //设置音乐信息
                //                        var strongResponseMessage = CreateResponseMessage<ResponseMessageMusic>();
                //                        reponseMessage = strongResponseMessage;
                //                        strongResponseMessage.Music.Title = "天籁之音";
                //                        strongResponseMessage.Music.Description = "真的是天籁之音";
                //                        strongResponseMessage.Music.MusicUrl = "https://sdk.weixin.senparc.com/Content/music1.mp3";
                //                        strongResponseMessage.Music.HQMusicUrl = "https://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;
                //                case "GetNewMediaId"://获取新的MediaId
                //                    {
                //                        var strongResponseMessage = CreateResponseMessage<ResponseMessageText>();
                //                        try
                //                        {
                //                            var result = Senparc.Weixin.MP.AdvancedAPIs.MediaApi.UploadForeverMedia(appId, Server.GetMapPath("~/Images/logo.jpg"));
                //                            strongResponseMessage.Content = result.media_id;
                //                        }
                //                        catch (Exception e)
                //                        {
                //                            strongResponseMessage.Content = "发生错误:" + e.Message;
                //                            WeixinTrace.SendCustomLog("调用UploadForeverMedia()接口发生异常", e.Message);
                //                        }
                //                    }
                //                    break;
                //                default:
                //                    {
                //                        var strongResponseMessage = CreateResponseMessage<ResponseMessageText>();
                //                        strongResponseMessage.Content = "您点击了按钮,EventKey:" + requestMessage.EventKey;
                //                        reponseMessage = strongResponseMessage;
                //                    }
                //                    break;
            }

            return(reponseMessage);
        }
示例#5
0
        /// <summary>
        /// 执行NeuChar判断过程,获取响应消息
        /// </summary>
        /// <param name="requestMessage"></param>
        /// <param name="messageHandler"></param>
        /// <param name="accessTokenOrApi"></param>
        /// <returns></returns>
        public IResponseMessageBase Execute(IRequestMessageBase requestMessage, IMessageHandlerEnlightener messageHandler, string accessTokenOrApi)
        {
            //SenparcTrace.SendCustomLog("neuchar trace", "2");

            if (accessTokenOrApi == null)
            {
                throw new ArgumentNullException(nameof(accessTokenOrApi));
            }

            IResponseMessageBase responseMessage = null;

            //SenparcTrace.SendCustomLog("neuchar trace", "3");

            switch (requestMessage.MsgType)
            {
            case RequestMsgType.Text:
            {
                try
                {
                    //SenparcTrace.SendCustomLog("neuchar trace", "3.1");

                    var textRequestMessage = requestMessage as IRequestMessageText;
                    //遍历所有的消息设置
                    foreach (var messagePair in Config.MessagePair.Where(z => z.Request.Type == RequestMsgType.Text))
                    {
                        //遍历每一个消息设置中的关键词
                        foreach (var keyword in messagePair.Request.Keywords)
                        {
                            if (keyword.Equals(textRequestMessage.Content, StringComparison.OrdinalIgnoreCase))        //TODO:加入大小写敏感设计
                            {
                                responseMessage = GetResponseMessage(requestMessage, messagePair.Responses, messageHandler, accessTokenOrApi);
                                break;
                            }
                        }
                        if (responseMessage != null)
                        {
                            break;
                        }
                    }
                }
                catch (Exception ex)
                {
                    SenparcTrace.SendCustomLog("neuchar text error", ex.Message + "\r\n|||\r\n" + (ex.InnerException != null ? ex.InnerException.ToString() : ""));
                }
            }
            break;

            case RequestMsgType.Image:
            {
                var imageRequestMessage = requestMessage as IRequestMessageImage;
                //遍历所有的消息设置

                foreach (var messagePair in Config.MessagePair.Where(z => z.Request.Type == RequestMsgType.Image))
                {
                    responseMessage = GetResponseMessage(requestMessage, messagePair.Responses, messageHandler, accessTokenOrApi);

                    if (responseMessage != null)
                    {
                        break;
                    }
                }
            }
            break;

            default:
                //不作处理

                //throw new UnknownRequestMsgTypeException("NeuChar未支持的的MsgType请求类型:"+ requestMessage.MsgType, null);
                break;
            }
            //SenparcTrace.SendCustomLog("neuchar trace", "4");

            return(responseMessage);
        }
        /// <summary>
        /// 执行NeuChar判断过程,获取响应消息
        /// </summary>
        /// <param name="requestMessage"></param>
        /// <param name="messageHandler"></param>
        /// <param name="accessTokenOrApi"></param>
        /// <returns></returns>
        public async Task <IResponseMessageBase> ExecuteAsync <TC, TRequest, TResponse>(IRequestMessageBase requestMessage, IMessageHandlerWithContext <TC, TRequest, TResponse> messageHandler,
                                                                                        string accessTokenOrApi)
            where TC : class, IMessageContext <TRequest, TResponse>, new()
            where TRequest : class, IRequestMessageBase
            where TResponse : class, IResponseMessageBase
        {
            //SenparcTrace.SendCustomLog("neuchar trace","1");
            //if (accessTokenOrApi == null)
            //{
            //    throw new ArgumentNullException(nameof(accessTokenOrApi));
            //}

            if (messageHandler == null)
            {
                throw new ArgumentNullException(nameof(messageHandler));
            }

            var messageHandlerEnlightener = messageHandler.MessageEntityEnlightener;
            var appDataNode = messageHandler.CurrentAppDataNode;

            IResponseMessageBase responseMessage = null;

            //SenparcTrace.SendCustomLog("neuchar trace", "3");

            //进行APP特殊处理

            //判断状态
            var context = await messageHandler.GetCurrentMessageContext();

            AppDataItem currentAppDataItem = null;

            switch (context.AppStoreState)
            {
            case AppStoreState.None:    //未进入任何应用
            case AppStoreState.Exit:
                currentAppDataItem = null;
                break;

            case AppStoreState.Enter:
                //判断是否已过期
                if (context.CurrentAppDataItem != null)
                {
                    if (context.LastActiveTime.HasValue && context.LastActiveTime.Value.AddMinutes(context.CurrentAppDataItem.MessageKeepTime) < SystemTime.Now)
                    {
                        //没有上一条活动,或者对话已过期,则设置为退出状态
                        context.AppStoreState      = AppStoreState.None;
                        context.CurrentAppDataItem = null;                                            //退出清空
                        await messageHandler.GlobalMessageContext.UpdateMessageContextAsync(context); //储存到缓存
                    }
                    else
                    {
                        //继续保持应用状态
                        currentAppDataItem = context.CurrentAppDataItem;

                        if (requestMessage is IRequestMessageText || requestMessage is IRequestMessageEventKey requestClick)
                        {
                            var content = (requestMessage is IRequestMessageText requestText) ? requestText.Content : (requestMessage as IRequestMessageEventKey).EventKey;
                            if (!context.CurrentAppDataItem.MessageExitWord.IsNullOrEmpty() && context.CurrentAppDataItem.MessageExitWord.Equals(content, StringComparison.OrdinalIgnoreCase))
                            {
                                //执行退出命令
                                context.AppStoreState      = AppStoreState.None;
                                context.CurrentAppDataItem = null;                                            //退出清空
                                                                                                              //currentAppDataItem = context.CurrentAppDataItem;//当前消息仍然转发(最后一条退出消息)
                                await messageHandler.GlobalMessageContext.UpdateMessageContextAsync(context); //储存到缓存
                            }
                        }
                    }
                }
                else
                {
                    //已经进入App状态,但是没有标记退出,此处强制退出
                    context.AppStoreState = AppStoreState.None;
                    await messageHandler.GlobalMessageContext.UpdateMessageContextAsync(context);    //储存到缓存
                }
                break;

            default:
                break;
            }

            //TODO:暂时限定类型

            if (currentAppDataItem == null)
            {
                if (requestMessage is IRequestMessageText || requestMessage is IRequestMessageEventKey requestClick)
                {
                    var content = (requestMessage is IRequestMessageText requestText) ? requestText.Content : (requestMessage as IRequestMessageEventKey).EventKey;

                    currentAppDataItem = appDataNode.Config.AppDataItems
                                         .FirstOrDefault(z => z.ExpireDateTime > SystemTime.Now && !z.MessageEnterWord.IsNullOrEmpty() && z.MessageEnterWord.Equals(content, StringComparison.OrdinalIgnoreCase));

                    if (currentAppDataItem != null && currentAppDataItem.MessageKeepTime > 0)
                    {
                        //初次进入应用
                        context.AppStoreState      = AppStoreState.Enter;
                        context.CurrentAppDataItem = currentAppDataItem;
                        await messageHandler.GlobalMessageContext.UpdateMessageContextAsync(context);//储存到缓存
                    }
                }
            }

            if (currentAppDataItem != null) //已经锁定某个App
            {
                //NeuralSystem.Instance.NeuCharDomainName = "https://www.neuchar.com";

                //转发AppData消息
                var neuCharUrl = $"{NeuralSystem.Instance.NeuCharDomainName}/App/Weixin?appId={currentAppDataItem.Id}&neuralAppId={appDataNode.NeuralAppId}";
                try
                {
                    responseMessage = MessageAgent.RequestResponseMessage(messageHandler, neuCharUrl, "Senparc", requestMessage.ConvertEntityToXmlString());
                }
                catch (Exception ex)
                {
                    Senparc.CO2NET.Trace.SenparcTrace.SendCustomLog("NeuChar 远程调用 APP 失败", ex.Message);
                }
            }


            //APP特殊处理结束


            if (responseMessage != null)
            {
                if (messageHandler.MessageEntityEnlightener.PlatformType == PlatformType.WeChat_MiniProgram && responseMessage is IResponseMessageText)
                {
                    //小程序
                    messageHandler.ApiEnlightener.SendText(accessTokenOrApi, messageHandler.WeixinOpenId, (responseMessage as IResponseMessageText).Content);
                    return(new SuccessResponseMessage());
                }
                else
                {
                    return(responseMessage);
                }
            }

            //处理普通消息回复
            switch (requestMessage.MsgType)
            {
            case RequestMsgType.Text:
            {
                try
                {
                    //SenparcTrace.SendCustomLog("neuchar trace", "3.1");

                    var textRequestMessage = requestMessage as IRequestMessageText;

                    //遍历所有的消息设置
                    foreach (var messagePair in Config.MessagePair.Where(z => z.Request.Type == RequestMsgType.Text))
                    {
                        //遍历每一个消息设置中的关键词
                        var pairSuccess = messagePair.Request.Keywords.Exists(keyword => keyword.Equals(textRequestMessage.Content, StringComparison.OrdinalIgnoreCase));
                        if (pairSuccess)
                        {
                            responseMessage = await GetResponseMessage(requestMessage, messagePair.Responses, messageHandler, accessTokenOrApi);
                        }

                        if (responseMessage != null)
                        {
                            break;
                        }
                    }
                }
                catch (Exception ex)
                {
                    SenparcTrace.SendCustomLog("neuchar text error", ex.Message + "\r\n|||\r\n" + (ex.InnerException != null ? ex.InnerException.ToString() : ""));
                }
            }
            break;

            case RequestMsgType.Image:
            {
                var imageRequestMessage = requestMessage as IRequestMessageImage;
                //遍历所有的消息设置

                foreach (var messagePair in Config.MessagePair.Where(z => z.Request.Type == RequestMsgType.Image))
                {
                    responseMessage = await GetResponseMessage(requestMessage, messagePair.Responses, messageHandler, accessTokenOrApi);

                    if (responseMessage != null)
                    {
                        break;
                    }
                }
            }
            break;

            case RequestMsgType.Event:
            {
                //菜单或其他系统事件
                if (requestMessage is IRequestMessageEvent eventRequestMessage)
                {
                    var eventType = eventRequestMessage.EventName.ToUpper();

                    //构造返回结果
                    List <Response> responses = new List <Response>();


                    switch (eventType)
                    {
                    case "CLICK" when requestMessage is IRequestMessageEventKey clickRequestMessage:
                    {
                        //TODO:暂时只支持CLICK,因此在这里遍历
                        foreach (var messagePair in Config.MessagePair.Where(z => z.Request.Type == RequestMsgType.Event))
                        {
                            var pairSuccess = messagePair.Request.Keywords.Exists(keyword => keyword.Equals(clickRequestMessage.EventKey, StringComparison.OrdinalIgnoreCase));
                            if (pairSuccess)
                            {
                                try
                                {
                                    responseMessage = await GetResponseMessage(requestMessage, messagePair.Responses, messageHandler, accessTokenOrApi);
                                }
                                catch (Exception ex)
                                {
                                    SenparcTrace.SendCustomLog("CLICK 跟踪 1.1", ex.Message + "\r\n" + ex.StackTrace);
                                }
                            }

                            if (responseMessage != null)
                            {
                                break;
                            }
                        }
                    }
                    break;

                    default:
                        break;
                    }
                }
                else
                {
                    //下级模块中没有正确处理 requestMessage 类型
                }
            }
            break;

            default:
                //不作处理

                //throw new UnknownRequestMsgTypeException("NeuChar未支持的的MsgType请求类型:"+ requestMessage.MsgType, null);
                break;
            }
            //SenparcTrace.SendCustomLog("neuchar trace", "4");

            return(responseMessage);
        }
        public IResponseMessageBase ClickEventRequest(AppCtx ctx, string eventKey)
        {
            IResponseMessageBase reponseMessage = null;

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

            case "SubClickRoot_Text":
            {
                var strongResponseMessage = ctx.CreateResponseMessage <ResponseMessageText>();
                reponseMessage = strongResponseMessage;
                strongResponseMessage.Content = "您点击了子菜单按钮。";
            }
            break;

            case "product_promotion":
            {
                var strongResponseMessage = ctx.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 = ctx.CreateResponseMessage <ResponseMessageMusic>();
                reponseMessage = strongResponseMessage;
                strongResponseMessage.Music.MusicUrl = "http://weixin.senparc.com/Content/music1.mp3";
            }
            break;

            case "SubClickRoot_Image":
            {
                var strongResponseMessage = ctx.CreateResponseMessage <ResponseMessageImage>();
                reponseMessage = strongResponseMessage;
                strongResponseMessage.Image.MediaId = "Mj0WUTZeeG9yuBKhGP7iR5n1xUJO9IpTjGNC4buMuswfEOmk6QSIRb_i98do5nwo";
            }
            break;

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

            case "Description":
            {
                var strongResponseMessage = ctx.CreateResponseMessage <ResponseMessageText>();
                strongResponseMessage.Content = ctx.GetConfig().WxWelcomeMessage;
                reponseMessage = strongResponseMessage;
            }
            break;

            default:
            {
                var strongResponseMessage = ctx.CreateResponseMessage <ResponseMessageText>();
                strongResponseMessage.Content = "您点击了按钮,EventKey:" + eventKey;
                reponseMessage = strongResponseMessage;
            }
            break;
            }

            return(reponseMessage);
        }
示例#8
0
        private List <IResponseMessageBase> CreateResponseMessage(string inputStr, int type)
        {
            int appId = int.Parse(_postModel.AppId);

            log.Debug("keyword :{0}, type :{1}.", inputStr, type);
            List <IResponseMessageBase> responseMsgList = new List <IResponseMessageBase>();
            var contents = autoReplyContentService.GetList <AutoReplyContentView>(appId, inputStr, type);

            if (null != contents && contents.Count > 0)
            {
                foreach (var content in contents)
                {
                    log.Debug("Response : appId:{0}, type :{1}.", appId, content.PrimaryType);

                    IResponseMessageBase responseMsg = null;
                    try
                    {
                        switch (content.PrimaryType)
                        {
                        case (int)AutoReplyContentEnum.LINK:     //被动回复不支持该类型,当成文本回复
                            responseMsg = CreateLinkeResponseMessage(content);
                            break;

                        case (int)AutoReplyContentEnum.TEXT:
                            responseMsg = CreateTextResponseMessage(content);
                            log.Debug("Response TEXT: appId:{0}, type :{1}", appId, responseMsg.MsgType.ToString());
                            break;

                        case (int)AutoReplyContentEnum.VOICE:
                            responseMsg = CreateVoiceResponseMessage(content);
                            log.Debug("Response VOICE: appId:{0}, type :{1}", appId, responseMsg.MsgType.ToString());
                            break;

                        case (int)AutoReplyContentEnum.VIDEO:
                            responseMsg = CreateVideoResponseMessage(content);
                            log.Debug("Response VIDEO: appId:{0}, type :{1}", appId, responseMsg.MsgType.ToString());
                            break;

                        case (int)AutoReplyContentEnum.NEWS:
                            responseMsg = CreateNewsResponseMessage(content, appId);
                            break;

                        case (int)AutoReplyContentEnum.IMAGE:
                            responseMsg = CreateImageResponseMessage(content);
                            break;

                        case (int)AutoReplyContentEnum.FILE:     //被动回复不支持该类型
                        default:
                            log.Warn("Some content type({0}) do not be supported in current logic.", content.PrimaryType);
                            break;
                        }
                        if (responseMsg != null)
                        {
                            log.Debug("Response responseMsg: appId:{0}, type :{1}", appId, responseMsg.MsgType.ToString());
                            (responseMsg as ResponseMessageBaseWechat).APPID = appId;
                        }
                        OtherOperationImpl(content);
                    }
                    catch (Exception e)
                    {
                        log.Error("Lost some auto reply content.");
                        log.Error(e);
                    }
                    if (responseMsg != null)
                    {
                        log.Debug("Response from :[{0}]; to :[{1}]  type:{2}", responseMsg.FromUserName, responseMsg.ToUserName, responseMsg.MsgType.ToString());
                        responseMsgList.Add(responseMsg);
                    }
                }
            }
            if (responseMsgList.Count > 0)
            {
                return(responseMsgList);
            }
            else
            {
                //  var ret = this.CreateResponseMessage<ResponseMessageText>();
                // ret.Content = "";
                //  responseMsgList.Add(ret);
                return(responseMsgList);
            }
        }
示例#9
0
        /// <summary>
        /// 执行NeuChar判断过程,获取响应消息
        /// </summary>
        /// <param name="requestMessage"></param>
        /// <param name="messageHandler"></param>
        /// <param name="accessTokenOrApi"></param>
        /// <returns></returns>
        public IResponseMessageBase Execute(IRequestMessageBase requestMessage, IMessageHandlerEnlighten messageHandler, string accessTokenOrApi)
        {
            if (accessTokenOrApi == null)
            {
                throw new ArgumentNullException(nameof(accessTokenOrApi));
            }

            IResponseMessageBase responseMessage = null;

            switch (requestMessage.MsgType)
            {
            case RequestMsgType.Text:
            {
                var textRequestMessage = requestMessage as IRequestMessageText;
                //遍历所有的消息设置
                foreach (var messagePair in Config.MessagePair.Where(z => z.Request.Type == RequestMsgType.Text))
                {
                    //遍历每一个消息设置中的关键词
                    foreach (var keyword in messagePair.Request.Keywords)
                    {
                        if (keyword.Equals(textRequestMessage.Content, StringComparison.OrdinalIgnoreCase))        //TODO:加入大小写敏感设计
                        {
                            responseMessage = GetResponseMessage(requestMessage, messagePair.Response, messageHandler.MessageEntityEnlighten);
                            ExecuteApi(messagePair, requestMessage, messageHandler.ApiEnlighten, accessTokenOrApi, requestMessage.FromUserName);
                            break;
                        }
                    }
                    if (responseMessage != null)
                    {
                        break;
                    }
                }
            }
            break;

            case RequestMsgType.Image:
            {
                var imageRequestMessage = requestMessage as IRequestMessageImage;
                //遍历所有的消息设置

                foreach (var messagePair in Config.MessagePair.Where(z => z.Request.Type == RequestMsgType.Image))
                {
                    responseMessage = GetResponseMessage(requestMessage, messagePair.Response, messageHandler.MessageEntityEnlighten);
                    ExecuteApi(messagePair, requestMessage, messageHandler.ApiEnlighten, accessTokenOrApi, requestMessage.FromUserName);

                    if (responseMessage != null)
                    {
                        break;
                    }
                }
            }
            break;

            default:
                //不作处理

                //throw new UnknownRequestMsgTypeException("NeuChar未支持的的MsgType请求类型:"+ requestMessage.MsgType, null);
                break;
            }
            return(responseMessage);
        }
示例#10
0
        /// <summary>
        ///  处理文字请求 autor:lipu
        /// </summary>
        /// <param name="requestMessage"></param>
        /// <returns></returns>
        public override IResponseMessageBase OnTextRequest(RequestMessageText requestMessage)
        {
            IResponseMessageBase IR = null;
            int apiid = 0;

            try
            {
                //  var responseMessage = base.CreateResponseMessage<ResponseMessageText>();
                string keywords = requestMessage.Content; //发送了文字信息
                apiid = wxcomm.getApiid();                //这里的appiid即为微帐号主键Id(wid)

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

                int    responseType      = 0;
                string modelFunctionName = "";
                int    modelFunctionId   = 0;
                int    ruleId            = rBll.GetRuleIdByKeyWords(apiid, keywords, out responseType, out modelFunctionName, out modelFunctionId);
                if (ruleId <= 0 || responseType <= 0)
                {
                    // 2014-9-18 暂时性功能 针对ID为 gh_04bf23f25940的平台客户 保存发送者的ID 及 生成抽奖序号 并保存。
                    //if (requestMessage.ToUserName == "gh_04bf23f25940" && requestMessage.Content = "橘州抽奖")
                    //{}
                    //else
                    //{
                    // 2014-9-18原功能
                    ///可以避掉
                    wxResponseBaseMgr.Add(apiid, requestMessage.FromUserName, requestMessage.MsgType.ToString(), requestMessage.Content, "none", "未取到关键词对应的数据", requestMessage.ToUserName, "name", "head");
                    return(wxcomm.GetResponseMessageTxtByContent(requestMessage, "未找到匹配的关键词", apiid));

                    //}
                }
                if (modelFunctionId > 0)
                {  //模块功能回复
                    return(wxcomm.GetModuleResponse(requestMessage, modelFunctionName, modelFunctionId, apiid));
                }
                //      requestMessage = ResponseMessageBase.CreateFromResponseXml("<xml><ToUserName><![CDATA[oFo2Hjq6_yMhyz6cQ2MZtmxODOVU]]></ToUserName>  <FromUserName><![CDATA[gh_2cb6c9131eb6]]></FromUserName>  <CreateTime>1469761811</CreateTime>  <MsgType><![CDATA[text]]></MsgType>  <Content><![CDATA[fffffffffffffffffff]]></Content></xml>");
                ///        RequestMessageText aa = RequestMessageText.ReferenceEquals
                //         requestMessage.ToUserName = "******";
                switch (responseType)
                {
                case 1:
                    //发送纯文字
                    //           string error = "";
                    //XCWeiXin.WeiXinComm.WeiXinCRMComm cpp = new XCWeiXin.WeiXinComm.WeiXinCRMComm();
                    //string accessToken = cpp.getAccessToken(40, out error);
                    //string openId = "oFo2HjpVWI79YLEOgGWLBvd6MPWU";
                    //string contents ="Form:"+requestMessage.FromUserName+"\ntxt:" +requestMessage.Content.ToString();
                    //string URL_FORMAT = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={0}";
                    //var data = new
                    //{
                    //    touser = openId,
                    //    msgtype = "text",
                    //    text = new
                    //    {
                    //        content = contents
                    //    }
                    //};
                    // CommonJsonSend.Send(accessToken, URL_FORMAT, data, timeOut: 1000);

                    IR = wxcomm.GetResponseMessageTxt_zhaohang(requestMessage, ruleId, apiid);

                    break;

                case 2:
                    //发送多图文
                    IR = wxcomm.GetResponseMessageNews(requestMessage, ruleId, apiid);
                    break;

                case 3:
                    //发送语音
                    IR = wxcomm.GetResponseMessageeMusic(requestMessage, ruleId, apiid);
                    break;
                //case 6:
                //    //客服接口
                //    IR = wxcomm.GetResponseMessageKefu_show(requestMessage, apiid);

                //    break;
                default:
                    break;
                }
                //  wxRequestBaseMgr.Add(apiid, requestMessage.MsgType.ToString(), requestMessage.FromUserName, requestMessage.CreateTime.ToString(), requestMessage.Content, requestMessage.ToString());
            }
            catch (Exception ex)
            {
                BLL.wx_logs logs = new BLL.wx_logs();
                logs.AddErrLog(apiid, "用户请求文字", "CustomMessageHandler.OnTextRequest", "错误:" + ex.Message);
            }

            return(IR);
        }
 public CustomRequestCountHandler(Store store, IRequestMessageBase message, IResponseMessageBase response)
 {
     this._CurrrentStore = store;
     this._message = message;
     this._response = response;
 }
示例#12
0
        /// <summary>
        /// 执行微信请求
        /// </summary>
        public void Execute()
        {
            if (CancelExcute)
            {
                return;
            }

            OnExecuting();

            if (CancelExcute)
            {
                return;
            }

            try
            {
                if (RequestMessage == null)
                {
                    return;
                }

                switch (RequestMessage.MsgType)
                {
                case RequestMsgType.Text:
                    ResponseMessage = OnTextRequest(RequestMessage as RequestMessageText);
                    break;

                case RequestMsgType.Location:
                    ResponseMessage = OnLocationRequest(RequestMessage as RequestMessageLocation);
                    break;

                case RequestMsgType.Image:
                    ResponseMessage = OnImageRequest(RequestMessage as RequestMessageImage);
                    break;

                case RequestMsgType.Voice:
                    ResponseMessage = OnVoiceRequest(RequestMessage as RequestMessageVoice);
                    break;

                case RequestMsgType.Event:
                    ResponseMessage = OnEventRequest(RequestMessage as RequestMessageEventBase);
                    break;

                default:
                    throw new UnknownRequestMsgTypeException("未知的MsgType请求类型", null);
                }

                //记录上下文
                if (WeixinContextGlobal.UseWeixinContext && ResponseMessage != null)
                {
                    WeixinContext.InsertMessage(ResponseMessage);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                OnExecuted();
            }
        }
示例#13
0
        /// <summary>
        /// 【异步方法】Event事件类型请求
        /// </summary>
        public virtual async Task <IResponseMessageBase> OnEventRequestAsync(IRequestMessageEventBase requestMessage)
        {
            var strongRequestMessage             = RequestMessage as IRequestMessageEventBase;
            IResponseMessageBase responseMessage = null;

            switch (strongRequestMessage.Event)
            {
            case Event.user_enter_tempsession:
                responseMessage = await OnEvent_UserEnterTempSessionRequestAsync(RequestMessage as RequestMessageEvent_UserEnterTempSession);

                break;

            case Event.add_nearby_poi_audit_info:
                responseMessage = await OnEvent_AddNearbyPoiAuditInfoRequestAsync(RequestMessage as RequestMessageEvent_AddNearbyPoiAuditInfo);

                break;

            case Event.nearby_category_audit_info:
                responseMessage = await OnEvent_NearbyCategoryAuditInfoRequestAsync(RequestMessage as RequestMessageEvent_NearbyCategoryAuditInfo);

                break;

            case Event.create_map_poi_audit_info:
                responseMessage = await OnEvent_CreateMapPoiAuditInfoRequestAsync(RequestMessage as RequestMessageEvent_CreateMapPoiAuditInfo);

                break;

            case Event.weapp_audit_success:    //
                responseMessage = await OnEvent_WeAppAuditSuccessRequestAsync(RequestMessage as RequestMessageEvent_WeAppAuditSuccess);

                break;

            case Event.weapp_audit_fail:    //
                responseMessage = await OnEvent_WeAppAuditFailRequestAsync(RequestMessage as RequestMessageEvent_WeAppAuditFail);

                break;

            case Event.weapp_audit_delay:    //
                responseMessage = await OnEvent_WeAppAuditDelayRequestAsync(RequestMessage as RequestMessageEvent_WeAppAuditDelay);

                break;

            case Event.wxa_nickname_audit:    //
                responseMessage = await OnEvent_NicknameAuditRequestAsync(RequestMessage as RequestMessageEvent_NicknameAudit);

                break;

            case Event.wxa_illegal_record:
                responseMessage = await OnEvent_IllegalRecordRequestAsync(RequestMessage as RequestMessageEvent_IllegalRecord);

                break;

            case Event.wxa_appeal_record:
                responseMessage = await OnEvent_AppealRecordRequestAsync(RequestMessage as RequestMessageEvent_AppealRecord);

                break;

            case Event.wxa_privacy_apply:
                responseMessage = await OnEvent_PrivacyApplyRequestAsync(RequestMessage as RequestMessageEvent_PrivacyApply);

                break;

            default:
                throw new UnknownRequestMsgTypeException("未知的Event下属请求信息", null);
            }
            return(responseMessage);
        }
示例#14
0
        /// <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);
        }
示例#15
0
        /// <summary>
        /// Event事件类型请求
        /// </summary>
        public virtual IResponseMessageBase OnEventRequest(IRequestMessageEventBase requestMessage)
        {
            var strongRequestMessage             = RequestMessage as IRequestMessageEventBase;
            IResponseMessageBase responseMessage = null;

            switch (strongRequestMessage.Event)
            {
            case Event.ENTER:
                responseMessage = OnEvent_EnterRequest(RequestMessage as RequestMessageEvent_Enter);
                break;

            case Event.LOCATION:    //自动发送的用户当前位置
                responseMessage = OnEvent_LocationRequest(RequestMessage as RequestMessageEvent_Location);
                break;

            case Event.subscribe:    //订阅
                responseMessage = OnEvent_SubscribeRequest(RequestMessage as RequestMessageEvent_Subscribe);
                break;

            case Event.unsubscribe:    //退订
                responseMessage = OnEvent_UnsubscribeRequest(RequestMessage as RequestMessageEvent_Unsubscribe);
                break;

            case Event.CLICK:    //菜单点击
                responseMessage = OnEvent_ClickRequest(RequestMessage as RequestMessageEvent_Click);
                break;

            case Event.scan:    //二维码
                responseMessage = OnEvent_ScanRequest(RequestMessage as RequestMessageEvent_Scan);
                break;

            case Event.VIEW:    //URL跳转(view视图)
                responseMessage = OnEvent_ViewRequest(RequestMessage as RequestMessageEvent_View);
                break;

            case Event.MASSSENDJOBFINISH:    //群发消息成功
                responseMessage = OnEvent_MassSendJobFinishRequest(RequestMessage as RequestMessageEvent_MassSendJobFinish);
                break;

            case Event.TEMPLATESENDJOBFINISH:    //推送模板消息成功
                responseMessage = OnEvent_TemplateSendJobFinishRequest(RequestMessage as RequestMessageEvent_TemplateSendJobFinish);
                break;

            case Event.pic_photo_or_album:    //弹出拍照或者相册发图
                responseMessage = OnEvent_PicPhotoOrAlbumRequest(RequestMessage as RequestMessageEvent_Pic_Photo_Or_Album);
                break;

            case Event.scancode_push:    //扫码推事件
                responseMessage = OnEvent_ScancodePushRequest(RequestMessage as RequestMessageEvent_Scancode_Push);
                break;

            case Event.scancode_waitmsg:    //扫码推事件且弹出“消息接收中”提示框
                responseMessage = OnEvent_ScancodeWaitmsgRequest(RequestMessage as RequestMessageEvent_Scancode_Waitmsg);
                break;

            case Event.location_select:    //弹出地理位置选择器
                responseMessage = OnEvent_LocationSelectRequest(RequestMessage as RequestMessageEvent_Location_Select);
                break;

            case Event.pic_weixin:    //弹出微信相册发图器
                responseMessage = OnEvent_PicWeixinRequest(RequestMessage as RequestMessageEvent_Pic_Weixin);
                break;

            case Event.pic_sysphoto:    //弹出系统拍照发图
                responseMessage = OnEvent_PicSysphotoRequest(RequestMessage as RequestMessageEvent_Pic_Sysphoto);
                break;

            default:
                throw new UnknownRequestMsgTypeException("未知的Event下属请求信息", null);
            }
            return(responseMessage);
        }
示例#16
0
        public override IResponseMessageBase OnEvent_ClickRequest(RequestMessageEvent_Click requestMessage)
        {
            #region
            IResponseMessageBase reponseMessage = null;

            //菜单点击,需要跟创建菜单时的Key匹配
            //switch (requestMessage.EventKey)
            //{
            //    case "Help_MenuOne":
            //        {
            //            //这个过程实际已经在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 "OAuth"://OAuth授权测试
            //    //    {
            //    //        var strongResponseMessage = CreateResponseMessage<ResponseMessageNews>();
            //    //        strongResponseMessage.Articles.Add(new Article()
            //    //        {
            //    //            Title = "OAuth2.0测试",
            //    //            Description = "点击【查看全文】进入授权页面。\r\n注意:此页面仅供测试(是专门的一个临时测试账号的授权,并非Senparc.Weixin 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 = "";
            //    //        reponseMessage = strongResponseMessage;
            //    //    }
            //    //    break;
            //}

            return(reponseMessage);

            #endregion
        }
示例#17
0
        public async Task <IResponseMessageBase> SendMessage(string appid, string openid, IResponseMessageBase responseMessage)
        {
            var messageQueue = new SenparcMessageQueue();

            if (!(responseMessage is ResponseMessageText responseMessagea))
            {
                return(responseMessage);
            }
            return(await Task.Run(() =>
            {
                {
                    var key = SenparcMessageQueue.GenerateKey("MessageHandlerSendMessageAsync", responseMessage.GetType(), Guid.NewGuid().ToString(), "SendMessage");
                    messageQueue.Add(key, () =>
                    {
                        responseMessagea.Content += "\r\n[消息超时后客服发送的消息1]";
                        // 发送客服消息 在队列里面就可以不用 async await 了
                        CustomApi.SendText(appid, openid, responseMessagea.Content);
                    });
                }

                {
                    var key = SenparcMessageQueue.GenerateKey("MessageHandlerSendMessageAsync", responseMessage.GetType(), Guid.NewGuid().ToString(), "SendMessage");
                    messageQueue.Add(key, () =>
                    {
                        responseMessagea.Content += "\r\n[消息超时后客服发送的消息2]";
                        // 发送客服消息 在队列里面就可以不用 async await 了
                        CustomApi.SendText(appid, openid, responseMessagea.Content);
                    });
                }
                return new ResponseMessageNoResponse();
            }));
        }
示例#18
0
 /// <summary>
 /// 将ResponseMessage实体转为XML
 /// </summary>
 /// <param name="entity">ResponseMessage实体</param>
 /// <returns></returns>
 public static XDocument ConvertEntityToXml(IResponseMessageBase entity)
 {
     return(EntityHelper.ConvertEntityToXml <IResponseMessageBase>(entity));
 }
示例#19
0
        /// <summary>
        /// Event事件类型请求
        /// </summary>
        public virtual IResponseMessageBase OnEventRequest(IRequestMessageEventBase requestMessage)
        {
            var strongRequestMessage             = RequestMessage as IRequestMessageEventBase;
            IResponseMessageBase responseMessage = null;

            switch (strongRequestMessage.Event)
            {
            case Event.CLICK:    //菜单点击
                responseMessage = OnEvent_ClickRequest(RequestMessage as RequestMessageEvent_Click);
                break;

            case Event.VIEW:    //URL跳转(view视图)
                responseMessage = OnEvent_ViewRequest(RequestMessage as RequestMessageEvent_View);
                break;

            case Event.PIC_PHOTO_OR_ALBUM:    //弹出拍照或者相册发图
                responseMessage = OnEvent_PicPhotoOrAlbumRequest(RequestMessage as RequestMessageEvent_Pic_Photo_Or_Album);
                break;

            case Event.SCANCODE_PUSH:    //扫码推事件
                responseMessage = OnEvent_ScancodePushRequest(RequestMessage as RequestMessageEvent_Scancode_Push);
                break;

            case Event.SCANCODE_WAITMSG:    //扫码推事件且弹出“消息接收中”提示框
                responseMessage = OnEvent_ScancodeWaitmsgRequest(RequestMessage as RequestMessageEvent_Scancode_Waitmsg);
                break;

            case Event.LOCATION_SELECT:    //弹出地理位置选择器
                responseMessage = OnEvent_LocationSelectRequest(RequestMessage as RequestMessageEvent_Location_Select);
                break;

            case Event.PIC_WEIXIN:    //弹出微信相册发图器
                responseMessage = OnEvent_PicWeixinRequest(RequestMessage as RequestMessageEvent_Pic_Weixin);
                break;

            case Event.PIC_SYSPHOTO:    //弹出系统拍照发图
                responseMessage = OnEvent_PicSysphotoRequest(RequestMessage as RequestMessageEvent_Pic_Sysphoto);
                break;

            case Event.subscribe:    //订阅
                responseMessage = OnEvent_SubscribeRequest(RequestMessage as RequestMessageEvent_Subscribe);
                break;

            case Event.unsubscribe:    //取消订阅
                responseMessage = OnEvent_UnSubscribeRequest(RequestMessage as RequestMessageEvent_UnSubscribe);
                break;

            case Event.LOCATION:    //上报地理位置事件
                responseMessage = OnEvent_LocationRequest(RequestMessage as RequestMessageEvent_Location);
                break;

            case Event.ENTER_AGENT:    //用户进入应用的事件推送(enter_agent)
                responseMessage = OnEvent_EnterAgentRequest(RequestMessage as RequestMessageEvent_Enter_Agent);
                break;

            case Event.BATCH_JOB_RESULT:    //异步任务完成事件推送(batch_job_result)
                responseMessage = OnEvent_BatchJobResultRequest(RequestMessage as RequestMessageEvent_Batch_Job_Result);
                break;

            default:
                throw new UnknownRequestMsgTypeException("未知的Event下属请求信息", null);
            }
            return(responseMessage);
        }
示例#20
0
 public static string ConvertEntityToXmlStr(IResponseMessageBase entity)
 {
     return(EntityHelper.ConvertEntityToXml <IResponseMessageBase>(entity).ToString());
 }
示例#21
0
        public override void Execute()
        {
            if (CancelExcute)
            {
                return;
            }

            OnExecuting();

            if (CancelExcute)
            {
                return;
            }

            try
            {
                if (RequestMessage == null)
                {
                    return;
                }

                switch (RequestMessage.MsgType)
                {
                case RequestMsgType.Text:
                {
                    var requestMessage = RequestMessage as RequestMessageText;
                    ResponseMessage = OnTextOrEventRequest(requestMessage) ?? OnTextRequest(requestMessage);
                }
                break;

                case RequestMsgType.Location:
                    ResponseMessage = OnLocationRequest(RequestMessage as RequestMessageLocation);
                    break;

                case RequestMsgType.Image:
                    ResponseMessage = OnImageRequest(RequestMessage as RequestMessageImage);
                    break;

                case RequestMsgType.Voice:
                    ResponseMessage = OnVoiceRequest(RequestMessage as RequestMessageVoice);
                    break;

                case RequestMsgType.Video:
                    ResponseMessage = OnVideoRequest(RequestMessage as RequestMessageVideo);
                    break;

                case RequestMsgType.Event:
                {
                    var requestMessageText = (RequestMessage as IRequestMessageEventBase).ConvertToRequestMessageText();
                    ResponseMessage = OnTextOrEventRequest(requestMessageText) ?? OnEventRequest(RequestMessage as IRequestMessageEventBase);
                }
                break;

                default:
                    throw new UnknownRequestMsgTypeException("未知的MsgType请求类型", null);
                }

                //记录上下文
                if (WeixinContextGlobal.UseWeixinContext && ResponseMessage != null)
                {
                    WeixinContext.InsertMessage(ResponseMessage);
                }
            }
            catch (Exception ex)
            {
                throw new MessageHandlerException("MessageHandler中Execute()过程发生错误:" + ex.Message, ex);
            }
            finally
            {
                OnExecuted();
            }
        }
示例#22
0
        /// <summary>
        /// 定阅事件的统一处理
        /// </summary>
        public IResponseMessageBase EventSubscribe(int type, RequestMessageEventBase requestMessage)
        {
            int    accountId = GetAccountId(); //取得公众账户ID
            string EventName = "";

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


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


                return(GetResponseMessageTxtByContent(requestMessage, "验证微帐号与微信原始帐号id不一致,可能原因【1】系统配置错误,【2】非法的数据来源", accountId));
            }


            int responseType = 0, ruleId = 0;
            //int ruleId = new BLL.weixin_request_rule().GetRuleIdAndResponseType(accountId, "request_type=" + type, out responseType);
            WeixinRequestRule rule = WeixinRequestRule.Find(WeixinRequestRule._.RequestType == type);

            if (rule != null)
            {
                responseType = rule.ResponseType;
                ruleId       = rule.Id;
            }

            if (ruleId <= 0)
            {
                //new BLL.weixin_response_content().Add(accountId, requestMessage.FromUserName, requestMessage.MsgType.ToString(), EventName, "none", "未取到关键词对应的数据", requestMessage.ToUserName);
                WeixinResponseContent entity = new WeixinResponseContent()
                {
                    OpenId         = requestMessage.FromUserName,
                    RequestType    = requestMessage.MsgType.ToString(),
                    RequestContent = EventName,
                    ResponseType   = "none",
                    ReponseContent = "未取到关键词对应的数据",
                    XmlContent     = requestMessage.ToUserName
                };
                entity.Insert();
                return(null);
            }

            IResponseMessageBase reponseMessage = null;

            switch (responseType)
            {
            case (int)WeixinRequestRule.XResponseType.Text:
                //发送纯文字
                reponseMessage = GetResponseMessageTxt(requestMessage, rule.Id, accountId);
                break;

            case (int)WeixinRequestRule.XResponseType.Image:
                //发送多图文
                reponseMessage = GetResponseMessageNews(requestMessage, rule.Id, accountId);
                break;

            case (int)WeixinRequestRule.XResponseType.Voice:
                //发送语音
                reponseMessage = GetResponseMessageeMusic(requestMessage, rule.Id, accountId);
                break;

            case (int)WeixinRequestRule.XResponseType.SingleImage:
                reponseMessage = GetResponseMessageSingleImage(requestMessage, rule.Id, accountId);
                break;

            default:
                break;
            }
            return(reponseMessage);
        }
示例#23
0
        /// <summary>
        /// Event事件类型请求
        /// </summary>
        public virtual IResponseMessageBase OnEventRequest(IRequestMessageEventBase requestMessage)
        {
            var strongRequestMessage             = RequestMessage as IRequestMessageEventBase;
            IResponseMessageBase responseMessage = null;

            switch (strongRequestMessage.Event)
            {
            case Event.ENTER:
                responseMessage = OnEvent_EnterRequest(RequestMessage as RequestMessageEvent_Enter);
                break;

            case Event.LOCATION:    //自动发送的用户当前位置
                responseMessage = OnEvent_LocationRequest(RequestMessage as RequestMessageEvent_Location);
                break;

            case Event.subscribe:    //订阅
                responseMessage = OnEvent_SubscribeRequest(RequestMessage as RequestMessageEvent_Subscribe);
                break;

            case Event.unsubscribe:    //退订
                responseMessage = OnEvent_UnsubscribeRequest(RequestMessage as RequestMessageEvent_Unsubscribe);
                break;

            case Event.CLICK:    //菜单点击
                responseMessage = OnEvent_ClickRequest(RequestMessage as RequestMessageEvent_Click);
                break;

            case Event.scan:    //二维码
                responseMessage = OnEvent_ScanRequest(RequestMessage as RequestMessageEvent_Scan);
                break;

            case Event.VIEW:    //URL跳转(view视图)
                responseMessage = OnEvent_ViewRequest(RequestMessage as RequestMessageEvent_View);
                break;

            case Event.MASSSENDJOBFINISH:    //群发消息成功
                responseMessage = OnEvent_MassSendJobFinishRequest(RequestMessage as RequestMessageEvent_MassSendJobFinish);
                break;

            case Event.TEMPLATESENDJOBFINISH:    //推送模板消息成功
                responseMessage = OnEvent_TemplateSendJobFinishRequest(RequestMessage as RequestMessageEvent_TemplateSendJobFinish);
                break;

            case Event.pic_photo_or_album:    //弹出拍照或者相册发图
                responseMessage = OnEvent_PicPhotoOrAlbumRequest(RequestMessage as RequestMessageEvent_Pic_Photo_Or_Album);
                break;

            case Event.scancode_push:    //扫码推事件
                responseMessage = OnEvent_ScancodePushRequest(RequestMessage as RequestMessageEvent_Scancode_Push);
                break;

            case Event.scancode_waitmsg:    //扫码推事件且弹出“消息接收中”提示框
                responseMessage = OnEvent_ScancodeWaitmsgRequest(RequestMessage as RequestMessageEvent_Scancode_Waitmsg);
                break;

            case Event.location_select:    //弹出地理位置选择器
                responseMessage = OnEvent_LocationSelectRequest(RequestMessage as RequestMessageEvent_Location_Select);
                break;

            case Event.pic_weixin:    //弹出微信相册发图器
                responseMessage = OnEvent_PicWeixinRequest(RequestMessage as RequestMessageEvent_Pic_Weixin);
                break;

            case Event.pic_sysphoto:    //弹出系统拍照发图
                responseMessage = OnEvent_PicSysphotoRequest(RequestMessage as RequestMessageEvent_Pic_Sysphoto);
                break;

            case Event.card_pass_check:    //卡券通过审核
                responseMessage = OnEvent_Card_Pass_CheckRequest(RequestMessage as RequestMessageEvent_Card_Pass_Check);
                break;

            case Event.card_not_pass_check:    //卡券未通过审核
                responseMessage = OnEvent_Card_Not_Pass_CheckRequest(RequestMessage as RequestMessageEvent_Card_Not_Pass_Check);
                break;

            case Event.user_get_card:    //领取卡券
                responseMessage = OnEvent_User_Get_CardRequest(RequestMessage as RequestMessageEvent_User_Get_Card);
                break;

            case Event.user_del_card:    //删除卡券
                responseMessage = OnEvent_User_Del_CardRequest(RequestMessage as RequestMessageEvent_User_Del_Card);
                break;

            case Event.kf_create_session:    //多客服接入会话
                responseMessage = OnEvent_Kf_Create_SessionRequest(RequestMessage as RequestMessageEvent_Kf_Create_Session);
                break;

            case Event.kf_close_session:    //多客服关闭会话
                responseMessage = OnEvent_Kf_Close_SessionRequest(RequestMessage as RequestMessageEvent_Kf_Close_Session);
                break;

            case Event.kf_switch_session:    //多客服转接会话
                responseMessage = OnEvent_Kf_Switch_SessionRequest(RequestMessage as RequestMessageEvent_Kf_Switch_Session);
                break;

            case Event.poi_check_notify:    //审核结果事件推送
                responseMessage = OnEvent_Poi_Check_NotifyRequest(RequestMessage as RequestMessageEvent_Poi_Check_Notify);
                break;

            case Event.WifiConnected:    //Wi-Fi连网成功
                responseMessage = OnEvent_WifiConnected(RequestMessage as RequestMessageEvent_WifiConnected);
                break;

            case Event.user_consume_card:    //卡券核销
                responseMessage = OnEvent_User_Consume_Card(RequestMessage as RequestMessageEvent_User_Consume_Card);
                break;

            case Event.user_enter_session_from_card:    //从卡券进入公众号会话
                responseMessage = OnEvent_User_Enter_Session_From_Card(RequestMessage as RequestMessageEvent_User_Enter_Session_From_Card);
                break;

            case Event.user_view_card:    //进入会员卡
                responseMessage = OnEvent_User_View_Card(RequestMessage as RequestMessageEvent_User_View_Card);
                break;

            case Event.merchant_order:    //微小店订单付款通知
                responseMessage = OnEvent_Merchant_Order(RequestMessage as RequestMessageEvent_Merchant_Order);
                break;

            case Event.submit_membercard_user_info:    //接收会员信息事件通知
                responseMessage = OnEvent_Submit_Membercard_User_Info(RequestMessage as RequestMessageEvent_Submit_Membercard_User_Info);
                break;

            case Event.ShakearoundUserShake:    //摇一摇事件通知
                responseMessage = OnEvent_ShakearoundUserShake(RequestMessage as RequestMessageEvent_ShakearoundUserShake);
                break;

            default:
                throw new UnknownRequestMsgTypeException("未知的Event下属请求信息", null);
            }
            return(responseMessage);
        }
        /// <summary>
        /// Event事件类型请求
        /// </summary>
        public virtual IResponseMessageBase OnEventRequest(IRequestMessageEventBase requestMessage)
        {
            var strongRequestMessage             = RequestMessage as IRequestMessageEventBase;
            IResponseMessageBase responseMessage = null;

            switch (strongRequestMessage.Event)
            {
            case Event.ENTER:    //
                responseMessage = OnEvent_EnterRequest(RequestMessage as RequestMessageEvent_Enter);
                break;

            case Event.LOCATION:    //自动发送的用户当前位置
                responseMessage = OnEvent_LocationRequest(RequestMessage as RequestMessageEvent_Location);
                break;

            case Event.SUBSCRIBE:    //订阅
                responseMessage = OnEvent_SubscribeRequest(RequestMessage as RequestMessageEvent_Subscribe);
                break;

            case Event.UNSUBSCRIBE:    //退订
                responseMessage = OnEvent_UnsubscribeRequest(RequestMessage as RequestMessageEvent_Unsubscribe);
                break;

            case Event.CLICK:    //菜单点击
                responseMessage = OnEvent_ClickRequest(RequestMessage as RequestMessageEvent_Click);
                break;

            case Event.SCAN:    //二维码
                responseMessage = OnEvent_ScanRequest(RequestMessage as RequestMessageEvent_Scan);
                break;

            case Event.VIEW:    //URL跳转(view视图)
                responseMessage = OnEvent_ViewRequest(RequestMessage as RequestMessageEvent_View);
                break;

            case Event.MASSSENDJOBFINISH:    //群发消息成功
                responseMessage = OnEvent_MassSendJobFinishRequest(RequestMessage as RequestMessageEvent_MassSendJobFinish);
                break;

            case Event.TEMPLATESENDJOBFINISH:    //推送模板消息成功
                responseMessage = OnEvent_TemplateSendJobFinishRequest(RequestMessage as RequestMessageEvent_TemplateSendJobFinish);
                break;

            case Event.PIC_PHOTO_OR_ALBUM:    //弹出拍照或者相册发图
                responseMessage = OnEvent_PicPhotoOrAlbumRequest(RequestMessage as RequestMessageEvent_Pic_Photo_Or_Album);
                break;

            case Event.SCANCODE_PUSH:    //扫码推事件
                responseMessage = OnEvent_ScancodePushRequest(RequestMessage as RequestMessageEvent_Scancode_Push);
                break;

            case Event.SCANCODE_WAITMSG:    //扫码推事件且弹出“消息接收中”提示框
                responseMessage = OnEvent_ScancodeWaitmsgRequest(RequestMessage as RequestMessageEvent_Scancode_Waitmsg);
                break;

            case Event.LOCATION_SELECT:    //弹出地理位置选择器
                responseMessage = OnEvent_LocationSelectRequest(RequestMessage as RequestMessageEvent_Location_Select);
                break;

            case Event.PIC_WEIXIN:    //弹出微信相册发图器
                responseMessage = OnEvent_PicWeixinRequest(RequestMessage as RequestMessageEvent_Pic_Weixin);
                break;

            case Event.PIC_SYSPHOTO:    //弹出系统拍照发图
                responseMessage = OnEvent_PicSysphotoRequest(RequestMessage as RequestMessageEvent_Pic_Sysphoto);
                break;

            case Event.CARD_PASS_CHECK:    //卡券通过审核
                responseMessage = OnEvent_Card_Pass_CheckRequest(RequestMessage as RequestMessageEvent_Card_Pass_Check);
                break;

            case Event.CARD_NOT_PASS_CHECK:    //卡券未通过审核
                responseMessage = OnEvent_Card_Not_Pass_CheckRequest(RequestMessage as RequestMessageEvent_Card_Not_Pass_Check);
                break;

            case Event.USER_GET_CARD:    //领取卡券
                responseMessage = OnEvent_User_Get_CardRequest(RequestMessage as RequestMessageEvent_User_Get_Card);
                break;

            case Event.USER_DEL_CARD:    //删除卡券
                responseMessage = OnEvent_User_Del_CardRequest(RequestMessage as RequestMessageEvent_User_Del_Card);
                break;

            case Event.KF_CREATE_SESSION:    //多客服接入会话
                responseMessage = OnEvent_Kf_Create_SessionRequest(RequestMessage as RequestMessageEvent_Kf_Create_Session);
                break;

            case Event.KF_CLOSE_SESSION:    //多客服关闭会话
                responseMessage = OnEvent_Kf_Close_SessionRequest(RequestMessage as RequestMessageEvent_Kf_Close_Session);
                break;

            case Event.KF_SWITCH_SESSION:    //多客服转接会话
                responseMessage = OnEvent_Kf_Switch_SessionRequest(RequestMessage as RequestMessageEvent_Kf_Switch_Session);
                break;

            case Event.POI_CHECK_NOTIFY:    //审核结果事件推送
                responseMessage = OnEvent_Poi_Check_NotifyRequest(RequestMessage as RequestMessageEvent_Poi_Check_Notify);
                break;

            case Event.WIFICONNECTED:    //Wi-Fi连网成功
                responseMessage = OnEvent_WifiConnected(RequestMessage as RequestMessageEvent_WifiConnected);
                break;

            case Event.USER_CONSUME_CARD:    //卡券核销
                responseMessage = OnEvent_User_Consume_Card(RequestMessage as RequestMessageEvent_User_Consume_Card);
                break;

            case Event.USER_ENTER_SESSION_FROM_CARD:    //从卡券进入公众号会话
                responseMessage = OnEvent_User_Enter_Session_From_Card(RequestMessage as RequestMessageEvent_User_Enter_Session_From_Card);
                break;

            case Event.USER_VIEW_CARD:    //进入会员卡
                responseMessage = OnEvent_User_View_Card(RequestMessage as RequestMessageEvent_User_View_Card);
                break;

            case Event.MERCHANT_ORDER:    //微小店订单付款通知
                responseMessage = OnEvent_Merchant_Order(RequestMessage as RequestMessageEvent_Merchant_Order);
                break;

            case Event.SUBMIT_MEMBERCARD_USER_INFO:    //接收会员信息事件通知
                responseMessage = OnEvent_Submit_Membercard_User_Info(RequestMessage as RequestMessageEvent_Submit_Membercard_User_Info);
                break;

            case Event.SHAKEAROUNDUSERSHAKE:    //摇一摇事件通知
                responseMessage = OnEvent_ShakearoundUserShake(RequestMessage as RequestMessageEvent_ShakearoundUserShake);
                break;

            default:
                throw new UnknownRequestMsgTypeException("未知的Event下属请求信息", null);
            }
            return(responseMessage);
        }
        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 = "点击【查看全文】进入授权页面。\r\n注意:此页面仅供测试(是专门的一个临时测试账号的授权,并非Senparc.Weixin.MP SDK官方账号,所以如果授权后出现错误页面数正常情况),测试号随时可能过期。请将此DEMO部署到您自己的服务器上,并使用自己的appid和secret。",
                        Url         = "http://sdk.weixin.senparc.com/oauth2",
                        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://sdk.weixin.senparc.com/Images/qrcode.jpg",
                        Url         = "http://sdk.weixin.senparc.com"
                    });
            }
            break;

            case "SubClickRoot_Music":
            {
                //上传缩略图
                var accessToken  = Senparc.Weixin.MP.Containers.AccessTokenContainer.TryGetAccessToken(appId, appSecret);
                var uploadResult = Senparc.Weixin.MP.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  = Senparc.Weixin.MP.Containers.AccessTokenContainer.TryGetAccessToken(appId, appSecret);
                var uploadResult = Senparc.Weixin.MP.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_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);
        }
示例#27
0
        /// <summary>
        /// Event事件类型请求
        /// </summary>
        public virtual IResponseMessageBase OnEventRequest(IRequestMessageEventBase requestMessage)
        {
            var strongRequestMessage             = RequestMessage as IRequestMessageEventBase;
            IResponseMessageBase responseMessage = null;

            switch (strongRequestMessage.Event)
            {
            case Event.LOCATION:    //自动发送的用户当前位置
                responseMessage = OnEvent_LocationRequest(RequestMessage as RequestMessageEvent_Location);
                break;

            case Event.subscribe:    //订阅
                responseMessage = OnEvent_SubscribeRequest(RequestMessage as RequestMessageEvent_Subscribe);
                break;

            case Event.unsubscribe:    //退订
                responseMessage = OnEvent_UnsubscribeRequest(RequestMessage as RequestMessageEvent_Unsubscribe);
                break;

            case Event.CLICK:    //菜单点击
                responseMessage = OnEvent_ClickRequest(RequestMessage as RequestMessageEvent_Click);
                break;

            case Event.scan:    //二维码
                responseMessage = OnEvent_ScanRequest(RequestMessage as RequestMessageEvent_Scan);
                break;

            case Event.VIEW:    //URL跳转(view视图)
                responseMessage = OnEvent_ViewRequest(RequestMessage as RequestMessageEvent_View);
                break;

            case Event.MASSSENDJOBFINISH:    //群发消息成功
                responseMessage = OnEvent_MassSendJobFinishRequest(RequestMessage as RequestMessageEvent_MassSendJobFinish);
                break;

            case Event.TEMPLATESENDJOBFINISH:    //推送模板消息成功
                responseMessage = OnEvent_TemplateSendJobFinishRequest(RequestMessage as RequestMessageEvent_TemplateSendJobFinish);
                break;

            case Event.pic_photo_or_album:    //弹出拍照或者相册发图
                responseMessage = OnEvent_PicPhotoOrAlbumRequest(RequestMessage as RequestMessageEvent_Pic_Photo_Or_Album);
                break;

            case Event.scancode_push:    //扫码推事件
                responseMessage = OnEvent_ScancodePushRequest(RequestMessage as RequestMessageEvent_Scancode_Push);
                break;

            case Event.scancode_waitmsg:    //扫码推事件且弹出“消息接收中”提示框
                responseMessage = OnEvent_ScancodeWaitmsgRequest(RequestMessage as RequestMessageEvent_Scancode_Waitmsg);
                break;

            case Event.location_select:    //弹出地理位置选择器
                responseMessage = OnEvent_LocationSelectRequest(RequestMessage as RequestMessageEvent_Location_Select);
                break;

            case Event.pic_weixin:    //弹出微信相册发图器
                responseMessage = OnEvent_PicWeixinRequest(RequestMessage as RequestMessageEvent_Pic_Weixin);
                break;

            case Event.pic_sysphoto:    //弹出系统拍照发图
                responseMessage = OnEvent_PicSysphotoRequest(RequestMessage as RequestMessageEvent_Pic_Sysphoto);
                break;

            case Event.card_pass_check:    //卡券通过审核
                responseMessage = OnEvent_Card_Pass_CheckRequest(RequestMessage as RequestMessageEvent_Card_Pass_Check);
                break;

            case Event.card_not_pass_check:    //卡券未通过审核
                responseMessage = OnEvent_Card_Not_Pass_CheckRequest(RequestMessage as RequestMessageEvent_Card_Not_Pass_Check);
                break;

            case Event.user_get_card:    //领取卡券
                responseMessage = OnEvent_User_Get_CardRequest(RequestMessage as RequestMessageEvent_User_Get_Card);
                break;

            case Event.user_del_card:    //删除卡券
                responseMessage = OnEvent_User_Del_CardRequest(RequestMessage as RequestMessageEvent_User_Del_Card);
                break;

            case Event.kf_create_session:    //多客服接入会话
                responseMessage = OnEvent_Kf_Create_SessionRequest(RequestMessage as RequestMessageEvent_Kf_Create_Session);
                break;

            case Event.kf_close_session:    //多客服关闭会话
                responseMessage = OnEvent_Kf_Close_SessionRequest(RequestMessage as RequestMessageEvent_Kf_Close_Session);
                break;

            case Event.kf_switch_session:    //多客服转接会话
                responseMessage = OnEvent_Kf_Switch_SessionRequest(RequestMessage as RequestMessageEvent_Kf_Switch_Session);
                break;

            case Event.poi_check_notify:    //审核结果事件推送
                responseMessage = OnEvent_Poi_Check_NotifyRequest(RequestMessage as RequestMessageEvent_Poi_Check_Notify);
                break;

            default:
                throw new UnknownRequestMsgTypeException("未知的Event下属请求信息", null);
            }
            return(responseMessage);
        }
        /// <summary>
        /// 点击事件
        /// </summary>
        /// <param name="requestMessage"></param>
        /// <returns></returns>
        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 = "您点击了子菜单图文按钮,这是一条图文信息。这个区域是Description内容\r\n可以使用\\r\\n进行换行。",
                        PicUrl      = "http://sdk.weixin.senparc.com/Images/qrcode.jpg",
                        Url         = "http://sdk.weixin.senparc.com"
                    });

                //随机添加一条图文,或只输出一条图文信息
                if (DateTime.Now.Second % 2 == 0)
                {
                    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);
        }
示例#29
0
        public override void Execute()
        {
            if (CancelExcute)
            {
                return;
            }

            OnExecuting();

            if (CancelExcute)
            {
                return;
            }

            try
            {
                if (RequestMessage == null)
                {
                    return;
                }

                switch (RequestMessage.MsgType)
                {
                case RequestMsgType.DEFAULT:    //第三方回调
                {
                    if (RequestMessage is IThirdPartyInfoBase)
                    {
                        var thirdPartyInfo = RequestMessage as IThirdPartyInfoBase;
                        switch (thirdPartyInfo.InfoType)
                        {
                        case ThirdPartyInfo.SUITE_TICKET:
                            break;

                        case ThirdPartyInfo.CHANGE_AUTH:
                            break;

                        case ThirdPartyInfo.CANCEL_AUTH:
                            break;

                        default:
                            throw new UnknownRequestMsgTypeException("未知的InfoType请求类型", null);
                        }
                        TextResponseMessage = "success";        //设置文字类型返回
                    }
                    else
                    {
                        throw new WeixinException("没有找到合适的消息类型。");
                    }
                }
                break;

                //以下是普通信息
                case RequestMsgType.Text:
                {
                    var requestMessage = RequestMessage as RequestMessageText;
                    ResponseMessage = OnTextOrEventRequest(requestMessage) ?? OnTextRequest(requestMessage);
                }
                break;

                case RequestMsgType.Location:
                    ResponseMessage = OnLocationRequest(RequestMessage as RequestMessageLocation);
                    break;

                case RequestMsgType.Image:
                    ResponseMessage = OnImageRequest(RequestMessage as RequestMessageImage);
                    break;

                case RequestMsgType.Voice:
                    ResponseMessage = OnVoiceRequest(RequestMessage as RequestMessageVoice);
                    break;

                case RequestMsgType.Video:
                    ResponseMessage = OnVideoRequest(RequestMessage as RequestMessageVideo);
                    break;

                case RequestMsgType.Event:
                {
                    var requestMessageText = (RequestMessage as IRequestMessageEventBase).ConvertToRequestMessageText();
                    ResponseMessage = OnTextOrEventRequest(requestMessageText) ?? OnEventRequest(RequestMessage as IRequestMessageEventBase);
                }
                break;

                default:
                    throw new UnknownRequestMsgTypeException("未知的MsgType请求类型", null);
                }

                //记录上下文
                if (WeixinContextGlobal.UseWeixinContext && ResponseMessage != null)
                {
                    WeixinContext.InsertMessage(ResponseMessage);
                }
            }
            catch (Exception ex)
            {
                throw new MessageHandlerException("MessageHandler中Execute()过程发生错误:" + ex.Message, ex);
            }
            finally
            {
                OnExecuted();
            }
        }
示例#30
0
        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 = "hello world!!!!您点击了底部按钮。\r\n为了测试微信软件换行bug的应对措施,这里做了一个——\r\n换行";
            }
            break;

            case "SubClickRoot_Text":
            {
                var strongResponseMessage = CreateResponseMessage <ResponseMessageText>();
                reponseMessage = strongResponseMessage;
                strongResponseMessage.Content = "hello祖爷 你好啊!!!!您点击了子菜单按钮。";
            }
            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"
                    });
                strongResponseMessage.Articles.Add(new Article()
                    {
                        Title       = "2祖爷 你好啊!!!!您点击了子菜单图文按钮",
                        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;

            default:
            {
                var strongResponseMessage = CreateResponseMessage <ResponseMessageText>();
                strongResponseMessage.Content = "您点击了按钮,EventKey:" + requestMessage.EventKey;
                reponseMessage = strongResponseMessage;
            }
            break;
            }

            return(reponseMessage);
        }
示例#31
0
        /// <summary>
        /// 执行微信请求
        /// </summary>
        public void Execute()
        {
            if (RequestMessage == null)
            {
                return;
            }

            switch (RequestMessage.MsgType)
            {
                case RequestMsgType.Text:
                    ResponseMessage = OnTextRequest(RequestMessage as RequestMessageText);
                    break;
                case RequestMsgType.Location:
                    ResponseMessage = OnLocationRequest(RequestMessage as RequestMessageLocation);
                    break;
                case RequestMsgType.Image:
                    ResponseMessage = OnImageRequest(RequestMessage as RequestMessageImage);
                    break;
                case RequestMsgType.Voice:
                    ResponseMessage = OnVoiceRequest(RequestMessage as RequestMessageVoice);
                    break;
                case RequestMsgType.Event:
                    ResponseMessage = OnEventRequest(RequestMessage as RequestMessageEventBase);
                    break;
                default:
                    throw new UnknownRequestMsgTypeException("未知的MsgType请求类型", null);
            }
        }
示例#32
0
        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_Image":
            {
                var strongResponseMessage = CreateResponseMessage <ResponseMessageImage>();
                reponseMessage = strongResponseMessage;
                strongResponseMessage.Image.MediaId = "Mj0WUTZeeG9yuBKhGP7iR5n1xUJO9IpTjGNC4buMuswfEOmk6QSIRb_i98do5nwo";
            }
            break;

            case "Description":
            {
                var strongResponseMessage = CreateResponseMessage <ResponseMessageText>();
                strongResponseMessage.Content = "欢迎关注,此项目正处于测试状态,开发者官网:http://www.fliujun.com";
                reponseMessage = strongResponseMessage;
            }
            break;
            }

            return(reponseMessage);
        }