コード例 #1
0
        public XDocument Init(IEncryptPostModel postModel)
        {
            _postModel = postModel as PostModel ?? new PostModel();

            //解密XML信息
            var postDataStr = EcryptRequestDocument.ToString();

            WXBizMsgCrypt msgCrype = new WXBizMsgCrypt(_postModel.Token, _postModel.EncodingAESKey, _postModel.AppId);
            string        msgXml   = null;
            var           result   = msgCrype.DecryptMsg(_postModel.Msg_Signature, _postModel.Timestamp, _postModel.Nonce, postDataStr, ref msgXml);

            //判断result类型
            if (result != 0)
            {
                //验证没有通过,取消执行
                CancelExecute = true;
                return(null);
            }

            RequestDocument = XDocument.Parse(msgXml);//完成解密
            RequestMessage  = RequestMessageFactory.GetRequestEntity(RequestDocument);

            //((RequestMessageBase)RequestMessage).FillEntityWithXml(RequestDocument);

            return(RequestDocument);
        }
コード例 #2
0
 public async Task <ActionResult> WXMSG(string signature, string timestamp, string nonce, string echostr)
 {
     if (!CheckSignature.Check(signature, timestamp, nonce, Commons.WXToken))
     {
         return(Content("参数错误!"));
     }
     try
     {
         XDocument requestDoc = null;
         requestDoc = XDocument.Load(Request.Body);
         var requestMessage = RequestMessageFactory.GetRequestEntity(requestDoc);
         // 关注 取消 事件
         if (requestMessage.MsgType == RequestMsgType.Event)
         {
             RequestMessageEventBase msg = (RequestMessageEventBase)requestMessage;
             if (msg.Event == Event.subscribe)
             {
                 await FocusOn(requestDoc);  //关注
             }
             if (msg.Event == Event.unsubscribe)
             {
                 await UnFocusOn(requestDoc); //取消关注
             }
         }
         else
         {
             await AcceptWechar(requestDoc);// 发送的消息
         }
         return(Content("success"));
     }
     catch (Exception ex)
     {
         return(Content(ex.ToString()));
     }
 }
コード例 #3
0
        public void ConvertEntityToXml_MusicTest()
        {
            var voiceTest     = @"<?xml version=""1.0"" encoding=""utf-8""?>
<xml>
  <ToUserName><![CDATA[gh_a96a4a619366]]></ToUserName>
  <FromUserName><![CDATA[olPjZjsXuQPJoV0HlruZkNzKc91E]]></FromUserName>
  <CreateTime>1361430302</CreateTime>
  <MsgType><![CDATA[voice]]></MsgType>
  <MediaId><![CDATA[X1yfgB2XI-faU6R2jmKz0X1JZmPCxIvM-9ktt4K92BB9577SCi41S-qMl60q5DJo]]></MediaId>
  <Format><![CDATA[amr]]></Format>
  <MsgId>5847298622973403529</MsgId>
</xml>";
            var doc           = XDocument.Parse(voiceTest);
            var requestEntity = RequestMessageFactory.GetRequestEntity(doc) as RequestMessageVoice;

            Assert.IsNotNull(requestEntity);

            var responseMusic =
                ResponseMessageBase.CreateFromRequestMessage <ResponseMessageMusic>(requestEntity);

            Assert.IsNotNull(responseMusic);

            responseMusic.Music.Title       = "测试Music";
            responseMusic.Music.Description = "测试Music的说明";
            responseMusic.Music.MusicUrl    = "http://zs.sasu.edu.cn/Content/music1.mp3";
            responseMusic.Music.HQMusicUrl  = "http://zs.sasu.edu.cn/Content/music2.mp3";

            var responseDoc = EntityHelper.ConvertEntityToXml(responseMusic);

            Console.WriteLine(responseDoc.ToString());
            Assert.AreEqual(responseMusic.Music.Title, responseDoc.Root.Element("Music").Element("Title").Value);
            Assert.AreEqual(responseMusic.Music.Description, responseDoc.Root.Element("Music").Element("Description").Value);
            Assert.AreEqual(responseMusic.Music.MusicUrl, responseDoc.Root.Element("Music").Element("MusicUrl").Value);
            Assert.AreEqual(responseMusic.Music.HQMusicUrl, responseDoc.Root.Element("Music").Element("HQMusicUrl").Value);
        }
コード例 #4
0
        public void GetRequestEntityTest()
        {
            var dt = DateTimeHelper.BaseTime.AddTicks(((long)1413192605 + 8 * 60 * 60) * 10000000);
            {
                //component_verify_ticket
                var doc    = XDocument.Parse(component_verify_ticketText);
                var result = RequestMessageFactory.GetRequestEntity(doc);
                Assert.IsInstanceOfType(result, typeof(RequestMessageComponentVerifyTicket));
                Assert.AreEqual("1", result.AppId);
                Assert.AreEqual(dt, result.CreateTime);
                Assert.AreEqual("ChainClouds", (result as RequestMessageComponentVerifyTicket).ComponentVerifyTicket);
                Console.WriteLine(doc);
            }

            {
                //unauthorized
                var doc    = XDocument.Parse(unauthorizedText);
                var result = RequestMessageFactory.GetRequestEntity(doc);
                Assert.IsInstanceOfType(result, typeof(RequestMessageUnauthorized));
                Assert.AreEqual("1", result.AppId);
                Assert.AreEqual(dt, result.CreateTime);
                Assert.AreEqual("211", (result as RequestMessageUnauthorized).AuthorizerAppid);
                Console.WriteLine(doc);
            }
        }
コード例 #5
0
        public void ConvertEntityToXml_ImageTest()
        {
            {
                var imageRequestXML = @"<?xml version=""1.0"" encoding=""utf-8""?>
<xml>
  <ToUserName><![CDATA[gh_a96a4a619366]]></ToUserName>
  <FromUserName><![CDATA[olPjZjsXuQPJoV0HlruZkNzKc91E]]></FromUserName>
  <CreateTime>1357996976</CreateTime>
  <MsgType><![CDATA[image]]></MsgType>
  <PicUrl><![CDATA[http://mmsns.qpic.cn/mmsns/ZxBXNzgHyUqazGkXUvujSOOHruk6XP5P9984HOCSATlW1orZDlpdCA/0]]></PicUrl>
  <MsgId>5832552599987382826</MsgId>
  <MediaId><![CDATA[Mj0WUTZeeG9yuBKhGP7iR5n1xUJO9IpTjGNC4buMuswfEOmk6QSIRb_i98do5nwo]]></MediaId>
</xml>";
                var doc             = XDocument.Parse(imageRequestXML);
                var requestEntity   =
                    RequestMessageFactory.GetRequestEntity(new MessageContexts.DefaultMpMessageContext(), doc) as
                    RequestMessageImage;
                Assert.IsNotNull(requestEntity);

                //var responseNews =
                //        ResponseMessageBase.CreateFromRequestMessage(requestEntity, ResponseMsgType.News) as
                //        ResponseMessageNews;
                //Assert.IsNotNull(responseNews);

                //responseNews.Articles.Add(new Article()
                //{
                //    Description = "测试说明",
                //    Title = "测试标题",
                //    Url = "http://www.senparc.com",
                //    PicUrl = requestEntity.PicUrl
                //});
                //Assert.AreEqual(1, responseNews.ArticleCount);

                //var responseDoc = EntityHelper.ConvertEntityToXml(responseNews);
                //Console.WriteLine(responseDoc.ToString());
                //Assert.AreEqual(requestEntity.PicUrl, responseDoc.Root.Element("Articles").Elements("item").First().Element("PicUrl").Value);


                //返回图片信息
                var responseMessage = ResponseMessageBase.CreateFromRequestMessage <ResponseMessageImage>(requestEntity);
                responseMessage.Image.MediaId = requestEntity.MediaId;
                var responseDoc = EntityHelper.ConvertEntityToXml(responseMessage);
                Assert.IsNotNull(responseDoc);
            }

            //            {
            //                var imageResponseXML = @"<?xml version=""1.0"" encoding=""utf-8""?>
            //<xml>
            //  <ToUserName><![CDATA[gh_a96a4a619366]]></ToUserName>
            //<FromUserName><![CDATA[olPjZjsXuQPJoV0HlruZkNzKc91E]]></FromUserName>
            //<CreateTime>1392354263</CreateTime>
            //<MsgType><![CDATA[image]]></MsgType>
            //<PicUrl><![CDATA[http://mmbiz.qpic.cn/mmbiz/ZxBXNzgHyUqDOeR0nSWZ4ibeF49C2yBbUB9tltJaFLqvjvDOUkt1tgp3q2cr1KZMLRsHHA2380sAggSPRuRMjicQ/0]]></PicUrl>
            //<MsgId>5980116024231210973</MsgId>
            //<MediaId><![CDATA[Mj0WUTZeeG9yuBKhGP7iR5n1xUJO9IpTjGNC4buMuswfEOmk6QSIRb_i98do5nwo]]></MediaId>
            //</xml>";
            //            }
        }
コード例 #6
0
        public void FillEntityWithXmlTest()
        {
            var doc    = XDocument.Parse(xml);
            var entity = RequestMessageFactory.GetRequestEntity(doc);

            EntityHelper.FillEntityWithXml(entity as RequestMessageBase, doc);

            Assert.AreEqual("gh_a96a4a619366", entity.ToUserName);
            Assert.AreEqual(RequestMsgType.Text, entity.MsgType);
        }
コード例 #7
0
        public override XDocument Init(XDocument postDataDocument, object postData = null)
        {
            //进行加密判断并处理
            _postModel = postData as PostModel;
            var postDataStr = postDataDocument.ToString();

            AfterDecryptData(postDataStr, _postModel);

            XDocument decryptDoc = postDataDocument;
            XElement  AppID      = postDataDocument.Root.Element("ToUserName");

            AfterGetData(AppID == null ? "" : AppID.Value, _postModel);

            if (_postModel != null && postDataDocument.Root.Element("Encrypt") != null && !string.IsNullOrEmpty(postDataDocument.Root.Element("Encrypt").Value))
            {
                //使用了加密
                UsingEcryptMessage    = true;
                EcryptRequestDocument = postDataDocument;

                WXBizMsgCrypt msgCrype = new WXBizMsgCrypt(_postModel.Token, _postModel.EncodingAESKey, _postModel.AppId);
                string        msgXml   = null;
                var           result   = msgCrype.DecryptMsg(_postModel.Msg_Signature, _postModel.Timestamp, _postModel.Nonce, postDataStr, ref msgXml);

                //判断result类型
                if (result != 0)
                {
                    //验证没有通过,取消执行
                    CancelExcute = true;
                    return(null);
                }

                if (postDataDocument.Root.Element("FromUserName") != null && !string.IsNullOrEmpty(postDataDocument.Root.Element("FromUserName").Value))
                {
                    //TODO:使用了兼容模式,进行验证即可
                    UsingCompatibilityModelEcryptMessage = true;
                }

                decryptDoc = XDocument.Parse(msgXml);//完成解密
            }

            RequestMessage = RequestMessageFactory.GetRequestEntity(decryptDoc);
            if (UsingEcryptMessage)
            {
                RequestMessage.Encrypt = postDataDocument.Root.Element("Encrypt").Value;
            }


            //记录上下文
            if (WeixinContextGlobal.UseWeixinContext)
            {
                WeixinContext.InsertMessage(RequestMessage);
            }

            return(decryptDoc);
        }
コード例 #8
0
ファイル: MessageHandler.cs プロジェクト: CocacolaSh/temp
        private void Init(XDocument requestDocument)
        {
            RequestDocument = requestDocument;
            RequestMessage  = RequestMessageFactory.GetRequestEntity(RequestDocument);

            //记录上下文
            if (WeixinContextGlobal.UseWeixinContext)
            {
                //WeixinContext.InsertMessage(RequestMessage);
            }
        }
コード例 #9
0
        public override XDocument Init(XDocument postDataDocument, object postData = null)
        {
            RequestMessage = RequestMessageFactory.GetRequestEntity(postDataDocument);

            //记录上下文
            if (WeixinContextGlobal.UseWeixinContext)
            {
                WeixinContext.InsertMessage(RequestMessage);
            }

            return(postDataDocument);
        }
コード例 #10
0
ファイル: WechatController.cs プロジェクト: aoys4jc/blog
        public IActionResult Post([FromServices] IOptions <AppSetting> appSettings, WechatPostRequestModel model)
        {
            if (!CheckSignature.Check(model.signature, model.timestamp, model.nonce, appSettings.Value.Token))
            {
                return(Content("参数错误!"));
            }
            var doc            = XDocument.Load(Request.Body);
            var requestMessage = RequestMessageFactory.GetRequestEntity(doc);

            try
            {
                var baseMessage = ResponseMessageBase.CreateFromRequestMessage <IResponseMessageBase>(requestMessage);
                var responseDoc = Senparc.NeuChar.Helpers.EntityHelper.ConvertEntityToXml(baseMessage);
                var responseStr = responseDoc.ToString();
                switch (requestMessage.MsgType)
                {
                case RequestMsgType.Text:
                    break;

                case RequestMsgType.Location:
                    break;

                case RequestMsgType.Image:
                    break;

                case RequestMsgType.Voice:
                    break;

                case RequestMsgType.Video:
                    break;

                case RequestMsgType.Link:
                    break;

                case RequestMsgType.ShortVideo:
                    break;

                case RequestMsgType.Event:
                    //responseStr = await wechatEvent.HandleAsync(doc);
                    break;

                default:
                    break;
                }
                return(Content(responseStr));
            }
            catch (Exception ex)
            {
                ex.ToExceptionless();
                //LogManager.GetCurrentClassLogger().Error($"Exception:{ex}\n,Doc:{doc}");
                return(Content(model.echostr));
            }
        }
コード例 #11
0
        public override XDocument Init(XDocument postDataDocument, IEncryptPostModel postModel)
        {
            _postModel = postModel as PostModel ?? new PostModel();

            var postDataStr = postDataDocument.ToString();

            //Work中消息默认都是强制加密的,但通知似乎没有加密
            UsingEncryptMessage = postDataDocument.Root.Element("Encrypt") != null;

            EncryptPostData = RequestMessageFactory.GetEncryptPostData(postDataStr);

            XDocument requestDocument;

            //2、解密:获得明文字符串
            if (UsingEncryptMessage)
            {
                string msgXml = null;

                WXBizMsgCrypt msgCrype = new WXBizMsgCrypt(_postModel.Token, _postModel.EncodingAESKey, _postModel.CorpId);
                var           result   = msgCrype.DecryptMsg(_postModel.Msg_Signature, _postModel.Timestamp, _postModel.Nonce, postDataStr, ref msgXml);

                /* msgXml
                 * <xml><ToUserName><![CDATA[wx7618c0a6d9358622]]></ToUserName>
                 * <FromUserName><![CDATA[001]]></FromUserName>
                 * <CreateTime>1412585107</CreateTime>
                 * <MsgType><![CDATA[text]]></MsgType>
                 * <Content><![CDATA[你好]]></Content>
                 * <MsgId>4299263624800632834</MsgId>
                 * <AgentID>2</AgentID>
                 * </xml>
                 */

                //判断result类型
                if (result != 0)
                {
                    //验证没有通过,取消执行
                    CancelExecute = true;
                    return(null);
                }

                requestDocument = XDocument.Parse(msgXml);
            }
            else
            {
                requestDocument = postDataDocument;//TODO:深拷贝
            }

            RequestMessage = RequestMessageFactory.GetRequestEntity <TMC>(new TMC(), doc: requestDocument);

            return(requestDocument);

            //消息上下文记录将在 base.CommonInitialize() 中根据去重等条件判断后进行添加
        }
コード例 #12
0
        /// <summary>
        /// 初始化数据
        /// </summary>
        /// <param name="postDataDocument"></param>
        /// <param name="postModel"></param>
        /// <returns></returns>
        public override XDocument Init(XDocument postDataDocument, IEncryptPostModel postModel)
        {
            //进行加密判断并处理
            _postModel = postModel as PostModel ?? new PostModel();
            var postDataStr = postDataDocument.ToString();

            XDocument decryptDoc = postDataDocument;

            if (_postModel != null && !_postModel.Token.IsNullOrWhiteSpace() &&
                postDataDocument.Root.Element("Encrypt") != null && !string.IsNullOrEmpty(postDataDocument.Root.Element("Encrypt").Value))
            {
                //使用了加密
                UsingEcryptMessage    = true;
                EcryptRequestDocument = postDataDocument;

                WXBizMsgCrypt msgCrype = new WXBizMsgCrypt(_postModel.Token, _postModel.EncodingAESKey, _postModel.AppId);
                string        msgXml   = null;
                var           result   = msgCrype.DecryptMsg(_postModel.Msg_Signature, _postModel.Timestamp, _postModel.Nonce, postDataStr, ref msgXml);

                //判断result类型
                if (result != 0)
                {
                    //验证没有通过,取消执行
                    CancelExcute = true;
                    return(null);
                }

                if (postDataDocument.Root.Element("FromUserName") != null && !string.IsNullOrEmpty(postDataDocument.Root.Element("FromUserName").Value))
                {
                    //TODO:使用了兼容模式,进行验证即可
                    UsingCompatibilityModelEcryptMessage = true;
                }

                decryptDoc = XDocument.Parse(msgXml);//完成解密
            }

            RequestMessage = RequestMessageFactory.GetRequestEntity(new TMC(), decryptDoc);
            if (UsingEcryptMessage)
            {
                RequestMessage.Encrypt = postDataDocument.Root.Element("Encrypt").Value;
            }

            //记录上下文
            if (MessageContextGlobalConfig.UseMessageContext)
            {
                GlobalMessageContext.InsertMessage(RequestMessage);
            }

            return(decryptDoc);
        }
コード例 #13
0
        public override XDocument Init(XDocument postDataDocument, object postData)
        {
            _postModel = postData as PostModel;

            var postDataStr = postDataDocument.ToString();

            AfterDecryptData(postDataStr, _postModel);

            EncryptPostData = RequestMessageFactory.GetEncryptPostData(postDataStr);

            AfterGetData(EncryptPostData, _postModel);

            //解密:获得明文字符串
            WXBizMsgCrypt msgCrype = new WXBizMsgCrypt(_postModel.Token, _postModel.EncodingAESKey, _postModel.CorpId);
            string        msgXml   = null;
            var           result   = msgCrype.DecryptMsg(_postModel.Msg_Signature, _postModel.Timestamp, _postModel.Nonce, postDataStr, ref msgXml);

            /* msgXml
             *  <xml><ToUserName><![CDATA[wx7618c0a6d9358622]]></ToUserName>
             *  <FromUserName><![CDATA[001]]></FromUserName>
             *  <CreateTime>1412585107</CreateTime>
             *  <MsgType><![CDATA[text]]></MsgType>
             *  <Content><![CDATA[你好]]></Content>
             *  <MsgId>4299263624800632834</MsgId>
             *  <AgentID>2</AgentID>
             *  </xml>
             */

            //判断result类型
            if (result != 0)
            {
                //验证没有通过,取消执行
                CancelExcute = true;
                return(null);
            }

            AfterDecryptData(msgXml, _postModel);

            var requestDocument = XDocument.Parse(msgXml);

            RequestMessage = RequestMessageFactory.GetRequestEntity(requestDocument);

            //记录上下文,Chat还是不记录吧,太多了
            if (WeixinContextGlobal.UseWeixinContext && !(RequestMessage is RequestMessageChat))
            {
                WeixinContext.InsertMessage(RequestMessage);
            }

            return(requestDocument);
        }
コード例 #14
0
ファイル: HandlerBase.cs プロジェクト: gonghaimin/weixin
        protected virtual void DecryptMsg()
        {
            if (this.SignModel != null && !string.IsNullOrEmpty(this.SignModel.msg_signature))
            {
                MsgCryptUtility mc         = new MsgCryptUtility(WeiXinContext.Config.Token, WeiXinContext.Config.EncodingAESKey, WeiXinContext.Config.AppID);
                var             requestXml = this.RequestXml;

                var ret = mc.DecryptMsg(this.SignModel.msg_signature, this.SignModel.timestamp, this.SignModel.nonce, requestXml, ref requestXml);
                if (ret != 0)
                {
                    throw new Exception("消息解密失败");
                }
                this.RequestXml = requestXml;
            }
            this.RequestMessage = RequestMessageFactory.GetRequestEntity(this.RequestXml);
        }
コード例 #15
0
        public void FillEntityWithEmbedXmlTest()
        {
            var doc    = XDocument.Parse(embedXml);
            var entity = RequestMessageFactory.GetRequestEntity(doc);

            EntityHelper.FillEntityWithXml(entity as RequestMessageBase, doc);

            Assert.AreEqual("gh_4d00ed8d6399", entity.ToUserName);
            Assert.AreEqual(RequestMsgType.Event, entity.MsgType);

            var strongEntity = entity as RequestMessageEvent_MassSendJobFinish;

            Assert.IsNotNull(strongEntity);
            Assert.AreEqual(2, strongEntity.CopyrightCheckResult.Count);
            Assert.AreEqual("Url_1", strongEntity.CopyrightCheckResult.ResultList[0].item.OriginalArticleUrl);
            Assert.AreEqual("Url_2", strongEntity.CopyrightCheckResult.ResultList[1].item.OriginalArticleUrl);
        }
コード例 #16
0
        public override XDocument Init(XDocument postDataDocument, IEncryptPostModel postModel)
        {
            _postModel = postModel as PostModel ?? new PostModel();


            UsingEcryptMessage = true;//Work中消息都是强制加密的
            var postDataStr = postDataDocument.ToString();

            EncryptPostData = RequestMessageFactory.GetEncryptPostData(postDataStr);

            //2、解密:获得明文字符串
            WXBizMsgCrypt msgCrype = new WXBizMsgCrypt(_postModel.Token, _postModel.EncodingAESKey, _postModel.CorpId);
            string        msgXml   = null;
            var           result   = msgCrype.DecryptMsg(_postModel.Msg_Signature, _postModel.Timestamp, _postModel.Nonce, postDataStr, ref msgXml);

            /* msgXml
             * <xml><ToUserName><![CDATA[wx7618c0a6d9358622]]></ToUserName>
             * <FromUserName><![CDATA[001]]></FromUserName>
             * <CreateTime>1412585107</CreateTime>
             * <MsgType><![CDATA[text]]></MsgType>
             * <Content><![CDATA[你好]]></Content>
             * <MsgId>4299263624800632834</MsgId>
             * <AgentID>2</AgentID>
             * </xml>
             */

            //判断result类型
            if (result != 0)
            {
                //验证没有通过,取消执行
                CancelExcute = true;
                return(null);
            }

            var requestDocument = XDocument.Parse(msgXml);

            RequestMessage = RequestMessageFactory.GetRequestEntity(requestDocument);

            //记录上下文
            if (RequestMessage.MsgType != RequestMsgType.Unknown && MessageContextGlobalConfig.UseMessageContext)
            {
                GlobalMessageContext.InsertMessage(RequestMessage);
            }

            return(requestDocument);
        }
コード例 #17
0
        public void ConvertEntityToXml_subscribe_msg_sent_eventTest()
        {
            var xml = @"<xml>
    <ToUserName><![CDATA[gh_123456789abc]]></ToUserName>
    <FromUserName><![CDATA[otFpruAK8D-E6EfStSYonYSBZ8_4]]></FromUserName>
    <CreateTime>1610969468</CreateTime>
    <MsgType><![CDATA[event]]></MsgType>
    <Event><![CDATA[subscribe_msg_sent_event]]></Event>
    <SubscribeMsgSentEvent>
        <List>
            <TemplateId><![CDATA[VRR0UEO9VJOLs0MHlU0OilqX6MVFDwH3_3gz3Oc0NIc]]></TemplateId>
            <MsgID>1700827132819554304</MsgID>
            <ErrorCode>0</ErrorCode>
            <ErrorStatus><![CDATA[success]]></ErrorStatus>
        </List>
    </SubscribeMsgSentEvent>
</xml>";

            var doc           = XDocument.Parse(xml);
            var requestEntity =
                RequestMessageFactory.GetRequestEntity(new MessageContexts.DefaultMpMessageContext(), doc) as
                RequestMessageEvent_Subscribe_Msg_Sent;


            Assert.IsNotNull(requestEntity);


            Assert.IsTrue(requestEntity.Event.ToString() == "subscribe_msg_sent_event");

            Assert.IsTrue(requestEntity.FromUserName == "otFpruAK8D-E6EfStSYonYSBZ8_4");
            Assert.IsTrue(requestEntity.SubscribeMsgSentEvent.Count == 1);

            Assert.IsTrue(requestEntity.SubscribeMsgSentEvent[0].TemplateId ==
                          "VRR0UEO9VJOLs0MHlU0OilqX6MVFDwH3_3gz3Oc0NIc");

            Assert.IsTrue(requestEntity.SubscribeMsgSentEvent[0].MsgID ==
                          "1700827132819554304");


            Assert.IsTrue(requestEntity.SubscribeMsgSentEvent[0].ErrorCode == 0);


            Assert.IsTrue(requestEntity.SubscribeMsgSentEvent[0].ErrorStatus == "success");
        }
コード例 #18
0
        public override XDocument Init(XDocument requestDocument, IEncryptPostModel postModel)
        {
            XDocument decryptDoc     = requestDocument;
            var       messageContext = new Weixin.MP.MessageContexts.DefaultMpMessageContext();// new CustomMessageContext(); //base.GetCurrentMessageContext().GetAwaiter().GetResult();

            RequestMessage = RequestMessageFactory.GetRequestEntity(messageContext, decryptDoc) as RequestMessageBase;

            base.SpecialDeduplicationAction = (lastMessage, messageHandler) =>
            {
                //判断特殊事件
                if (!messageHandler.MessageIsRepeated &&
                    lastMessage is RequestMessageEventBase &&
                    messageHandler.RequestMessage is RequestMessageEventBase &&
                    (lastMessage as RequestMessageEventBase).Event == (messageHandler.RequestMessage as RequestMessageEventBase).Event
                    )
                {
                    var lastEventMessage    = lastMessage as RequestMessageEventBase;
                    var currentEventMessage = messageHandler.RequestMessage as RequestMessageEventBase;
                    switch (lastEventMessage.Event)
                    {
                    case Event.user_get_card:     //领取事件推送
                                                  //文档:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1451025274
                                                  //问题反馈:https://github.com/JeffreySu/WeiXinMPSDK/issues/1106
                        var lastGetUserCardMessage    = lastMessage as RequestMessageEvent_User_Get_Card;
                        var currentGetUserCardMessage = messageHandler.RequestMessage as RequestMessageEvent_User_Get_Card;
                        if (lastGetUserCardMessage.UserCardCode == currentGetUserCardMessage.UserCardCode &&
                            lastGetUserCardMessage.CardId == currentGetUserCardMessage.CardId)
                        {
                            return(true);
                        }
                        break;

                    default:
                        break;
                    }
                }
                return(false);
            };

            //消息去重的基本方法已经在基类 CommonInitialize() 中实现

            return(decryptDoc);
        }
コード例 #19
0
        /// <summary>
        /// 分析微信POST到本服务器的XML数据
        /// </summary>
        /// <param name="xmlStream"></param>
        /// <returns></returns>
        private string AnalyzeXmlFromWeiXin(HttpContext context)
        {
            try
            {
                var xmlMsg = RequestMessageFactory.GetRequestEntity(context.Request.InputStream);
                switch (xmlMsg.MsgType)
                {
                case RequestMsgType.Event:    //如果是事件
                    return(OnAttention((RequestMessageEventBase)xmlMsg));

                default:
                    return("");
                }
            }
            catch (Exception ex)
            {
                return("分析微信POST到本服务器的XML数据 出错");
            }
        }
コード例 #20
0
        public void ConvertEntityToXml_subscribe_msg_popup_eventTest()
        {
            var xml           = @"<xml>
    <ToUserName><![CDATA[gh_123456789abc]]></ToUserName>
    <FromUserName><![CDATA[otFpruAK8D-E6EfStSYonYSBZ8_4]]></FromUserName>
    <CreateTime>1610969440</CreateTime>
    <MsgType><![CDATA[event]]></MsgType>
    <Event><![CDATA[subscribe_msg_popup_event]]></Event>
    <SubscribeMsgPopupEvent>
        <List>
            <TemplateId><![CDATA[VRR0UEO9VJOLs0MHlU0OilqX6MVFDwH3_3gz3Oc0NIc]]></TemplateId>
            <SubscribeStatusString><![CDATA[accept]]></SubscribeStatusString>
            <PopupScene>2</PopupScene>
        </List>
        <List>
            <TemplateId><![CDATA[9nLIlbOQZC5Y89AZteFEux3WCXRRRG5Wfzkpssu4bLI]]></TemplateId>
            <SubscribeStatusString><![CDATA[reject]]></SubscribeStatusString>
            <PopupScene>2</PopupScene>
        </List>
    </SubscribeMsgPopupEvent>
</xml>";
            var doc           = XDocument.Parse(xml);
            var requestEntity =
                RequestMessageFactory.GetRequestEntity(new MessageContexts.DefaultMpMessageContext(), doc) as
                RequestMessageEvent_Subscribe_Msg_Popup;


            Assert.IsNotNull(requestEntity);

            Assert.IsTrue(requestEntity.Event.ToString() == "subscribe_msg_popup_event");

            Assert.IsTrue(requestEntity.FromUserName == "otFpruAK8D-E6EfStSYonYSBZ8_4");
            Assert.IsTrue(requestEntity.SubscribeMsgPopupEvent.Count == 2);

            Assert.IsTrue(requestEntity.SubscribeMsgPopupEvent[1].TemplateId ==
                          "9nLIlbOQZC5Y89AZteFEux3WCXRRRG5Wfzkpssu4bLI");

            Assert.IsTrue(requestEntity.SubscribeMsgPopupEvent[1].SubscribeStatusString ==
                          "reject");

            Assert.IsTrue(requestEntity.SubscribeMsgPopupEvent[1].PopupScene == 2);
        }
コード例 #21
0
        public void ConvertEntityToXmlTest()
        {
            var doc           = XDocument.Parse(xml);
            var requestEntity = RequestMessageFactory.GetRequestEntity(doc);

            {
                //Text
                var responseText =
                    ResponseMessageBase.CreateFromRequestMessage(requestEntity, ResponseMsgType.Text) as
                    ResponseMessageText;
                Assert.IsNotNull(responseText);
                responseText.Content = "新内容";
                var responseDoc = EntityHelper.ConvertEntityToXml(responseText);

                Console.WriteLine(responseDoc.ToString());

                Assert.AreEqual("新内容", responseDoc.Root.Element("Content").Value);
            }

            {
                //News
                var responseNews =
                    ResponseMessageBase.CreateFromRequestMessage(requestEntity, ResponseMsgType.News) as
                    ResponseMessageNews;
                Assert.IsNotNull(responseNews);

                responseNews.Articles.Add(new Article()
                {
                    Description = "测试说明",
                    Title       = "测试标题",
                    Url         = "http://www.senparc.com",
                    PicUrl      = "http://img.senparc.com/images/v2/logo.jpg'"
                });
                Assert.AreEqual(1, responseNews.ArticleCount);
                var responseDoc = EntityHelper.ConvertEntityToXml(responseNews);
                Console.WriteLine(responseDoc.ToString());
            }
        }
コード例 #22
0
        public void ConvertEntityToXml_ImageTest()
        {
            var imageXML      = @"<?xml version=""1.0"" encoding=""utf-8""?>
<xml>
  <ToUserName><![CDATA[gh_a96a4a619366]]></ToUserName>
  <FromUserName><![CDATA[olPjZjsXuQPJoV0HlruZkNzKc91E]]></FromUserName>
  <CreateTime>1357996976</CreateTime>
  <MsgType><![CDATA[image]]></MsgType>
  <PicUrl><![CDATA[http://mmsns.qpic.cn/mmsns/ZxBXNzgHyUqazGkXUvujSOOHruk6XP5P9984HOCSATlW1orZDlpdCA/0]]></PicUrl>
  <MsgId>5832552599987382826</MsgId>
</xml>";
            var doc           = XDocument.Parse(imageXML);
            var requestEntity = RequestMessageFactory.GetRequestEntity(doc) as RequestMessageImage;

            Assert.IsNotNull(requestEntity);

            var responseNews =
                ResponseMessageBase.CreateFromRequestMessage(requestEntity, ResponseMsgType.News) as
                ResponseMessageNews;

            Assert.IsNotNull(responseNews);

            responseNews.Articles.Add(new Article()
            {
                Description = "测试说明",
                Title       = "测试标题",
                Url         = "http://www.senparc.com",
                PicUrl      = requestEntity.PicUrl
            });
            Assert.AreEqual(1, responseNews.ArticleCount);

            var responseDoc = EntityHelper.ConvertEntityToXml(responseNews);

            Console.WriteLine(responseDoc.ToString());
            Assert.AreEqual(requestEntity.PicUrl, responseDoc.Root.Element("Articles").Elements("item").First().Element("PicUrl").Value);
        }
コード例 #23
0
        public void ConvertEntityToXml_subscribe_msg_change_eventTest()
        {
            var xml = @"<xml>
    <ToUserName><![CDATA[gh_123456789abc]]></ToUserName>
    <FromUserName><![CDATA[otFpruAK8D-E6EfStSYonYSBZ8_4]]></FromUserName>
    <CreateTime>1610969440</CreateTime>
    <MsgType><![CDATA[event]]></MsgType>
    <Event><![CDATA[subscribe_msg_change_event]]></Event>
    <SubscribeMsgChangeEvent>
        <List>
            <TemplateId><![CDATA[VRR0UEO9VJOLs0MHlU0OilqX6MVFDwH3_3gz3Oc0NIc]]></TemplateId>
            <SubscribeStatusString><![CDATA[reject]]></SubscribeStatusString>
        </List>
    </SubscribeMsgChangeEvent>
</xml>";

            var doc           = XDocument.Parse(xml);
            var requestEntity =
                RequestMessageFactory.GetRequestEntity(new MessageContexts.DefaultMpMessageContext(), doc) as
                RequestMessageEvent_Subscribe_Msg_Change;


            Assert.IsNotNull(requestEntity);


            Assert.IsTrue(requestEntity.Event.ToString() == "subscribe_msg_change_event");

            Assert.IsTrue(requestEntity.FromUserName == "otFpruAK8D-E6EfStSYonYSBZ8_4");
            Assert.IsTrue(requestEntity.SubscribeMsgChangeEvent.Count == 1);

            Assert.IsTrue(requestEntity.SubscribeMsgChangeEvent[0].TemplateId ==
                          "VRR0UEO9VJOLs0MHlU0OilqX6MVFDwH3_3gz3Oc0NIc");

            Assert.IsTrue(requestEntity.SubscribeMsgChangeEvent[0].SubscribeStatusString ==
                          "reject");
        }
コード例 #24
0
        public ActionResult Index(long id = 0)
        {
            Log.Info("进入微信API");

            //string token = "weixin_test";
            string token = "", signature = "", nonce = "", timestamp = "", echostr = "";
            if (id == 0)
            {
                var siteSetting = _iSiteSettingService.GetSiteSettings();
                token = siteSetting.WeixinToken;
            }
            else
            {
                var _tmp = _iVShopService.GetVShopSetting(id);
                if (_tmp == null)
                {
                    throw new HimallException("错误的商铺编号");
                }
                token = _tmp.Token;
            }
            signature = Request["signature"];
            nonce = Request["nonce"];
            timestamp = Request["timestamp"];
            echostr = Request["echostr"];
            ActionResult actionResult = Content("");

            Log.Info(string.Format("传入信息:signature = {0} , nonce = {1} , timestamp = {2} , echostr = {3} , id = {4}", signature, nonce, timestamp, echostr, id));
            if (Request.HttpMethod == "GET")
            {
                if (CheckSignature.Check(signature, timestamp, nonce, token))
                {
                    actionResult = Content(echostr);
                }
            }
            else
            {
                //TODO:[lly] 微信消息处理
                if (!CheckSignature.Check(signature, timestamp, nonce, token))
                {
                    Log.Info("验证不通过");
                }

                XDocument requestDoc = XDocument.Load(Request.InputStream);

#if DEBUG
                //调试时记录数据日志
                Core.Log.Debug(requestDoc);
#endif

                var requestBaseMsg = RequestMessageFactory.GetRequestEntity(requestDoc);
                SceneHelper helper = new SceneHelper();

                //卡券服务
                var cardser = _iWXCardService;

                switch (requestBaseMsg.MsgType)
                {
                    #region Event处理
                    case RequestMsgType.Event:
                        var requestMsg = requestBaseMsg as Senparc.Weixin.MP.Entities.RequestMessageEventBase;
                        Log.Info("进入RequestMsgType - Event:" + requestMsg.Event.ToString());
                        switch (requestMsg.Event)
                        {
                            //取消公众号订阅事件
                            case Event.unsubscribe:
                                UnSubscribe(requestMsg.FromUserName);
                                break;

                            //订阅公众号事件
                            case Event.subscribe:

                                //关注红包
                                actionResult = SendAttentionToUser(requestBaseMsg);


                                #region 关注公众号,欢迎语!
                                int nowtime = ConvertDateTimeInt(DateTime.Now);

                                string msg = "";//关注时,需要发送的内容
                                var data = WeixinAutoReplyApplication.GetAutoReplyByKey(CommonModel.ReplyType.Follow, "", false, true, true);
                                if (data != null)
                                {
                                    msg = data.TextReply;
                                }
                                else
                                    Log.Info("请设置关注后自动回复消息内容!");

                                string resxml = "<xml><ToUserName><![CDATA[" + requestBaseMsg.FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + requestBaseMsg.ToUserName + "]]></FromUserName><CreateTime>" + nowtime + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[" + msg + "]]></Content><FuncFlag>0</FuncFlag></xml>";
                                Response.Write(resxml);
                                #endregion

                                var requestSubscribe = requestMsg as Senparc.Weixin.MP.Entities.RequestMessageEvent_Subscribe;
#if DEBUG
                                Log.Debug(requestSubscribe, new Exception("进入订阅事件"));
#endif
                                bool isActivityBonus = false;
                                SceneModel sceneModel = null;
#if DEBUG
                                Log.Info("进入订阅事件requestSubscribe.EventKey =" + requestSubscribe.EventKey);
#endif
                                #region 场景二维码

                                if (requestSubscribe.EventKey != string.Empty)
                                {
                                    var scene = requestSubscribe.EventKey.Replace("qrscene_", string.Empty);
                                    sceneModel = helper.GetModel(scene);
                                    if (sceneModel != null)
                                    {
#if DEBUG
                                        Log.Info("sceneModel.Type = " + sceneModel.SceneType.ToString());
#endif
                                        if (sceneModel.SceneType == Himall.Model.QR_SCENE_Type.WithDraw)
                                        {//提现场景(未关注时)
                                            echostr = ProcessWithDrawScene(requestSubscribe, scene, sceneModel);
                                            actionResult = Content(echostr);
                                        }
                                        else if (sceneModel.SceneType == Himall.Model.QR_SCENE_Type.Bonus)
                                        {
                                            //TODO:ZJT 用户通过场景二维码扫描关注后 推送消息给用户
                                            //isActivityBonus用于判断激发关注事件的是活动红包还是其他
                                            isActivityBonus = true;
                                            actionResult = SendActivityToUser(sceneModel.Object, requestBaseMsg);
                                        }
                                        else if (sceneModel.SceneType == Himall.Model.QR_SCENE_Type.FlashSaleRemind)
                                        {
#if DEBUG
                                            Log.Info("进入限时购场景二维码事件");
#endif
                                            long flashSaleId = (long)sceneModel.Object;
                                            SendFlashSaleRemindMessage(flashSaleId, requestBaseMsg.FromUserName);
                                        }
                                        else if (sceneModel.SceneType == Himall.Model.QR_SCENE_Type.Binding)//绑定微信
                                        {
                                            echostr = Binding(requestSubscribe, scene, sceneModel);
                                            actionResult = Content(echostr);
                                        }
                                    }
                                }
                                #endregion
                                Log.Info("开始isActivityBonus=" + isActivityBonus);

                                //通过场景二维码进来,并且二维码不是活动红包,则进行关注送红包事件
                                //if (!isActivityBonus && sceneModel != null && sceneModel.SceneType == QR_SCENE_Type.Bonus)
                                //{
                                // actionResult = SendAttentionToUser(requestBaseMsg);
                                //}

#if DEBUG
                                Log.Info("开始Subscribe requestBaseMsg.FromUserName="******"进入限时购场景二维码事件");
                                            long flashSaleId = (long)sceneModel.Object;
                                            SendFlashSaleRemindMessage(flashSaleId, requestBaseMsg.FromUserName);
                                        }
                                        else if (sceneModel.SceneType == Himall.Model.QR_SCENE_Type.Binding)//绑定微信
                                        {
                                            echostr = Binding(requestScan, requestScan.EventKey, sceneModel);
                                            actionResult = Content(echostr);
                                        }
                                    }
                                }
                                break;
                            case Event.card_pass_check:
                                //TODO:DZY[150907] 卡券审核通过
                                var reqpasscard = requestMsg as Senparc.Weixin.MP.Entities.RequestMessageEvent_Card_Pass_Check;
                                if (!string.IsNullOrWhiteSpace(reqpasscard.CardId))
                                {
                                    cardser.Event_Audit(reqpasscard.CardId, WXCardLogInfo.AuditStatusEnum.Audited);
                                }
                                break;
                            case Event.card_not_pass_check:
                                //TODO:DZY[150907] 卡券审核失败
                                var reqnopasscard = requestMsg as Senparc.Weixin.MP.Entities.RequestMessageEvent_Card_Pass_Check;
                                if (!string.IsNullOrWhiteSpace(reqnopasscard.CardId))
                                {
                                    cardser.Event_Audit(reqnopasscard.CardId, WXCardLogInfo.AuditStatusEnum.AuditNot);
                                }
                                break;
                            case Event.user_del_card:
                                //TODO:DZY[150907] 删除卡包内优惠券
                                var requdelcard = requestMsg as Senparc.Weixin.MP.Entities.RequestMessageEvent_User_Del_Card;
                                if (!string.IsNullOrWhiteSpace(requdelcard.CardId) && !string.IsNullOrWhiteSpace(requdelcard.UserCardCode))
                                {
                                    cardser.Event_Unavailable(requdelcard.CardId, requdelcard.UserCardCode);
                                }
                                break;
                            case Event.user_get_card:
                                //TODO:DZY[150907] 用户获取优惠券
                                var requgetcard = requestMsg as Senparc.Weixin.MP.Entities.RequestMessageEvent_User_Get_Card;
                                Log.Debug("WXCard:" + requgetcard.CardId + "_" + requgetcard.UserCardCode);
                                if (!string.IsNullOrWhiteSpace(requgetcard.CardId) && !string.IsNullOrWhiteSpace(requgetcard.UserCardCode))
                                {
                                    cardser.Event_Send(requgetcard.CardId, requgetcard.UserCardCode, requgetcard.FromUserName, requgetcard.OuterId);
                                }
                                break;
                        }
                        break;
                    #endregion
                    case RequestMsgType.Text:
                        textCase(requestBaseMsg);
                        break;
                }
                Response.End();
            }
            return actionResult;
        }
コード例 #25
0
 private void Init(XDocument requestDocument)
 {
     this.RequestDocument = requestDocument;
     this.RequestMessage  = RequestMessageFactory.GetRequestEntity(this.RequestDocument);
 }
コード例 #26
0
        public void GetRequestEntityTest()
        {
            var dt = DateTimeHelper.BaseTime.AddTicks(((long)1358061152 + 8 * 60 * 60) * 10000000);

            {
                //Text
                var doc    = XDocument.Parse(xmlText);
                var result = RequestMessageFactory.GetRequestEntity(doc);
                Assert.IsInstanceOfType(result, typeof(RequestMessageText));
                Assert.AreEqual("gh_a96a4a619366", result.ToUserName);
                Assert.AreEqual("TNT2", (result as RequestMessageText).Content);
            }

            {
                //Location
                var doc    = XDocument.Parse(xmlLocation);
                var result = RequestMessageFactory.GetRequestEntity(doc) as RequestMessageLocation;
                Assert.IsNotNull(result);
                Assert.AreEqual("gh_a96a4a619366", result.ToUserName);
                Assert.AreEqual(19, result.Scale);
            }

            {
                //Image
                var doc    = XDocument.Parse(xmlImage);
                var result = RequestMessageFactory.GetRequestEntity(doc) as RequestMessageImage;
                Assert.IsNotNull(result);
                Assert.AreEqual("gh_a96a4a619366", result.ToUserName);
                Assert.AreEqual("http://mmsns.qpic.cn/mmsns/ZxBXNzgHyUqazGkXUvujSPxexzynJAicf440qkyLibBd1OEO4saJiavLQ/0", result.PicUrl);
            }

            {
                //Voice
                var doc    = XDocument.Parse(xmlVoice);
                var result = RequestMessageFactory.GetRequestEntity(doc) as RequestMessageVoice;
                Assert.IsNotNull(result);
                Assert.AreEqual("gh_a96a4a619366", result.ToUserName);
                Assert.AreEqual("X1yfgB2XI-faU6R2jmKz0X1JZmPCxIvM-9ktt4K92BB9577SCi41S-qMl60q5DJo", result.MediaId);
            }

            {
                //Video
                var doc    = XDocument.Parse(xmlVideo);
                var result = RequestMessageFactory.GetRequestEntity(doc) as RequestMessageVideo;
                Assert.IsNotNull(result);
                Assert.AreEqual("gh_a96a4a619366", result.ToUserName);
                Assert.AreEqual("mediaId", result.MediaId);
                Assert.AreEqual("thumbMediaId", result.ThumbMediaId);
            }

            {
                //Link
                var doc    = XDocument.Parse(xmlLink);
                var result = RequestMessageFactory.GetRequestEntity(doc) as RequestMessageLink;
                Assert.IsNotNull(result);
                Assert.AreEqual("gh_a96a4a619366", result.ToUserName);
                Assert.AreEqual("公众平台官网链接", result.Title);
                Assert.AreEqual("Senparc.Weixin.MP SDK公众平台官网链接", result.Description);
                Assert.AreEqual("http://weixin.senparc.com", result.Url);
            }

            {
                //Event-ENTRY
                var doc    = XDocument.Parse(xmlEvent_Enter);
                var result = RequestMessageFactory.GetRequestEntity(doc) as RequestMessageEvent_Enter;
                Assert.IsNotNull(result);
                Assert.AreEqual("gh_a96a4a619366", result.ToUserName);
                Assert.AreEqual(Event.ENTER, result.Event);
            }

            {
                //Event-Location
                var doc    = XDocument.Parse(xmlEvent_Location);
                var result = RequestMessageFactory.GetRequestEntity(doc) as RequestMessageEvent_Location;
                Assert.IsNotNull(result);
                Assert.AreEqual("gh_a96a4a619366", result.ToUserName);
                Assert.AreEqual(Event.LOCATION, result.Event);
                Assert.AreEqual(23.137466, result.Latitude);
                Assert.AreEqual(113.352425, result.Longitude);
                Assert.AreEqual(119.385040, result.Precision);
            }

            {
                //Event-Subscribe
                var doc    = XDocument.Parse(xmlEvent_Subscribe);
                var result = RequestMessageFactory.GetRequestEntity(doc) as RequestMessageEvent_Subscribe;
                Assert.IsNotNull(result);
                Assert.AreEqual("gh_a96a4a619366", result.ToUserName);
                Assert.AreEqual(Event.subscribe, result.Event);
            }

            {
                //Event-Unsubscribe
                var doc    = XDocument.Parse(xmlEvent_Unsubscribe);
                var result = RequestMessageFactory.GetRequestEntity(doc) as RequestMessageEvent_Unsubscribe;
                Assert.IsNotNull(result);
                Assert.AreEqual("gh_a96a4a619366", result.ToUserName);
                Assert.AreEqual(Event.unsubscribe, result.Event);
                Assert.AreEqual(new DateTime(2013, 3, 28), result.CreateTime.Date);
            }

            {
                //Event-CLICK
                var doc    = XDocument.Parse(xmlEvent_Click);
                var result = RequestMessageFactory.GetRequestEntity(doc) as RequestMessageEvent_Click;
                Assert.IsNotNull(result);
                Assert.AreEqual("gh_a96a4a619366", result.ToUserName);
                Assert.AreEqual(Event.CLICK, result.Event);
                Assert.AreEqual(new DateTime(2013, 3, 28), result.CreateTime.Date);

                Assert.AreEqual("SubClickRoot_Agent", result.EventKey);
            }

            {
                //Event-scan
                var doc    = XDocument.Parse(xmlEvent_Scan);
                var result = RequestMessageFactory.GetRequestEntity(doc) as RequestMessageEvent_Scan;
                Assert.IsNotNull(result);
                Assert.AreEqual("gh_a96a4a619366", result.ToUserName);
                Assert.AreEqual(Event.scan, result.Event);
                Assert.AreEqual(new DateTime(2013, 3, 28), result.CreateTime.Date);

                Assert.AreEqual("SCENE_VALUE", result.EventKey);
                Assert.AreEqual("TICKET", result.Ticket);
            }

            {
                //Event-VIEW
                var doc    = XDocument.Parse(xmlEvent_View);
                var result = RequestMessageFactory.GetRequestEntity(doc) as RequestMessageEvent_View;
                Assert.IsNotNull(result);
                Assert.AreEqual("gh_a96a4a619366", result.ToUserName);
                Assert.AreEqual(Event.scan, result.Event);
                Assert.AreEqual(new DateTime(2014, 3, 14), result.CreateTime.Date);
                Assert.AreEqual("http://weixin.senparc.com", result.EventKey);
            }
        }
コード例 #27
0
        public void GetRequestEntityTest()
        {
            {
                //Text
                var doc    = XDocument.Parse(xml_Text);
                var result = RequestMessageFactory.GetRequestEntity(doc) as RequestMessageText;
                Assert.IsNotNull(result);
                Assert.AreEqual("toUser", result.ToUserName);
                Assert.AreEqual("this is a test", result.Content);
                Assert.AreEqual(1, result.AgentID);
            }

            {
                //Image
                var doc    = XDocument.Parse(xml_Image);
                var result = RequestMessageFactory.GetRequestEntity(doc) as RequestMessageImage;
                Assert.IsNotNull(result);
                Assert.AreEqual("toUser", result.ToUserName);
                Assert.AreEqual("this is a url", result.PicUrl);
                Assert.AreEqual(1, result.AgentID);
            }

            {
                //Voice
                var doc    = XDocument.Parse(xml_Voice);
                var result = RequestMessageFactory.GetRequestEntity(doc) as RequestMessageVoice;
                Assert.IsNotNull(result);
                Assert.AreEqual("toUser", result.ToUserName);
                Assert.AreEqual("media_id", result.MediaId);
                Assert.AreEqual(1, result.AgentID);
            }

            {
                //Video
                var doc    = XDocument.Parse(xml_Video);
                var result = RequestMessageFactory.GetRequestEntity(doc) as RequestMessageVideo;
                Assert.IsNotNull(result);
                Assert.AreEqual("toUser", result.ToUserName);
                Assert.AreEqual("media_id", result.MediaId);
                Assert.AreEqual(1, result.AgentID);
            }

            {
                //Location
                var doc    = XDocument.Parse(xml_Location);
                var result = RequestMessageFactory.GetRequestEntity(doc) as RequestMessageLocation;
                Assert.IsNotNull(result);
                Assert.AreEqual("toUser", result.ToUserName);
                Assert.AreEqual(113.358803, result.Location_Y);
                Assert.AreEqual(1, result.AgentID);
            }

            {
                //ShortVideo
                var doc    = XDocument.Parse(xmlEvent_ShortVideo);
                var result = RequestMessageFactory.GetRequestEntity(doc) as RequestMessageShortVideo;
                Assert.IsNotNull(result);
                Assert.AreEqual("toUser", result.ToUserName);
                Assert.AreEqual("media_id", result.MediaId);
                Assert.AreEqual(1, result.AgentID);
            }

            {
                //Event_Location
                var doc    = XDocument.Parse(xmlEvent_Location);
                var result = RequestMessageFactory.GetRequestEntity(doc) as RequestMessageEvent_Location;
                Assert.IsNotNull(result);
                Assert.AreEqual("toUser", result.ToUserName);
                Assert.AreEqual(113.320107, result.Longitude);
                Assert.AreEqual(1, result.AgentID);
            }

            {
                //Event_Click
                var doc    = XDocument.Parse(xmlEvent_Click);
                var result = RequestMessageFactory.GetRequestEntity(doc) as RequestMessageEvent_Click;
                Assert.IsNotNull(result);
                Assert.AreEqual("toUser", result.ToUserName);
                Assert.AreEqual("EVENTKEY", result.EventKey);
                Assert.AreEqual(1, result.AgentID);
            }

            {
                //Event_View
                var doc    = XDocument.Parse(xmlEvent_View);
                var result = RequestMessageFactory.GetRequestEntity(doc) as RequestMessageEvent_View;
                Assert.IsNotNull(result);
                Assert.AreEqual("toUser", result.ToUserName);
                Assert.AreEqual("www.qq.com", result.EventKey);
                Assert.AreEqual(1, result.AgentID);
            }

            {
                //Event_Scancode_Push
                var doc    = XDocument.Parse(xmlEvent_Scancode_Push);
                var result = RequestMessageFactory.GetRequestEntity(doc) as RequestMessageEvent_Scancode_Push;
                Assert.IsNotNull(result);
                Assert.AreEqual("toUser", result.ToUserName);
                Assert.AreEqual("qrcode", result.ScanCodeInfo.ScanType);
                Assert.AreEqual(1, result.AgentID);
            }

            {
                //Event_Scancode_Waitmsg
                var doc    = XDocument.Parse(xmlEvent_Scancode_Waitmsg);
                var result = RequestMessageFactory.GetRequestEntity(doc) as RequestMessageEvent_Scancode_Waitmsg;
                Assert.IsNotNull(result);
                Assert.AreEqual("toUser", result.ToUserName);
                Assert.AreEqual("qrcode", result.ScanCodeInfo.ScanType);
                Assert.AreEqual(1, result.AgentID);
            }

            {
                //Event_Pic_Sysphoto
                var doc    = XDocument.Parse(xmlEvent_Pic_Sysphoto);
                var result = RequestMessageFactory.GetRequestEntity(doc) as RequestMessageEvent_Pic_Sysphoto;
                Assert.IsNotNull(result);
                Assert.AreEqual("toUser", result.ToUserName);
                Assert.AreEqual("1", result.SendPicsInfo.Count);
                Assert.AreEqual(1, result.AgentID);
            }

            {
                //Event_Pic_Photo_Or_Album
                var doc    = XDocument.Parse(xmlEvent_Pic_Photo_Or_Album);
                var result = RequestMessageFactory.GetRequestEntity(doc) as RequestMessageEvent_Pic_Photo_Or_Album;
                Assert.IsNotNull(result);
                Assert.AreEqual("toUser", result.ToUserName);
                Assert.AreEqual("5a75aaca956d97be686719218f275c6b", result.SendPicsInfo.PicList[0].item.PicMd5Sum);
                Assert.AreEqual(1, result.AgentID);
            }

            {
                //Event_Pic_Weixin
                var doc    = XDocument.Parse(xmlEvent_Pic_Weixin);
                var result = RequestMessageFactory.GetRequestEntity(doc) as RequestMessageEvent_Pic_Weixin;
                Assert.IsNotNull(result);
                Assert.AreEqual("toUser", result.ToUserName);
                Assert.AreEqual("5a75aaca956d97be686719218f275c6b", result.SendPicsInfo.PicList[0].item.PicMd5Sum);
                Assert.AreEqual(1, result.AgentID);
            }

            {
                //Event_Location_Select
                var doc    = XDocument.Parse(xmlEvent_Location_Select);
                var result = RequestMessageFactory.GetRequestEntity(doc) as RequestMessageEvent_Location_Select;
                Assert.IsNotNull(result);
                Assert.AreEqual("toUser", result.ToUserName);
                Assert.AreEqual(" 广州市海珠区客村艺苑路 106号", result.SendLocationInfo.Label);
                Assert.AreEqual(1, result.AgentID);
            }

            {
                //Event_Enter_Agent
                var doc    = XDocument.Parse(xmlEvent_Enter_Agent);
                var result = RequestMessageFactory.GetRequestEntity(doc) as RequestMessageEvent_Enter_Agent;
                Assert.IsNotNull(result);
                Assert.AreEqual("toUser", result.ToUserName);
                Assert.AreEqual(1, result.AgentID);
            }

            {
                //Suite_Ticket
                var doc    = XDocument.Parse(xml_Suite_Ticket);
                var result = RequestMessageFactory.GetRequestEntity(doc) as RequestMessageInfo_Suite_Ticket;
                Assert.IsNotNull(result);
                Assert.AreEqual("wxfc918a2d200c9a4c", result.SuiteId);
                Assert.AreEqual("asdfasfdasdfasdf", result.SuiteTicket);
            }

            {
                //Change_Auth
                var doc    = XDocument.Parse(xml_Change_Auth);
                var result = RequestMessageFactory.GetRequestEntity(doc) as RequestMessageInfo_Change_Auth;
                Assert.IsNotNull(result);
                Assert.AreEqual("wxfc918a2d200c9a4c", result.SuiteId);
                Assert.AreEqual("wxf8b4f85f3a794e77", result.AuthCorpId);
            }

            {
                //Cancel_Auth
                var doc    = XDocument.Parse(xml_Cancel_Auth);
                var result = RequestMessageFactory.GetRequestEntity(doc) as RequestMessageInfo_Cancel_Auth;
                Assert.IsNotNull(result);
                Assert.AreEqual("wxfc918a2d200c9a4c", result.SuiteId);
                Assert.AreEqual("wxf8b4f85f3a794e77", result.AuthCorpId);
            }

            {
                //Batch_Job_Result
                var doc    = XDocument.Parse(xml_Batch_Job_Result);
                var result = RequestMessageFactory.GetRequestEntity(doc) as RequestMessageEvent_Batch_Job_Result;
                Assert.IsNotNull(result);
                Assert.AreEqual("wx28dbb14e37208abe", result.ToUserName);
                Assert.AreEqual("ok", result.BatchJob.ErrMsg);
                Assert.AreEqual(0, result.BatchJob.ErrCode);
            }
        }
コード例 #28
0
        public ActionResult OldPost(string signature, string timestamp, string nonce, string echostr)
        {
            LocationService locationService = new LocationService();
            EventService    eventService    = new EventService();

            if (!CheckSignature.Check(signature, timestamp, nonce, Token))
            {
                return(Content("参数错误!"));
            }
            XDocument requestDoc = null;

            try
            {
                requestDoc = XDocument.Load(Request.InputStream);

                var requestMessage = RequestMessageFactory.GetRequestEntity(requestDoc);
                //如果不需要记录requestDoc,只需要:
                //var requestMessage = RequestMessageFactory.GetRequestEntity(Request.InputStream);

                requestDoc.Save(Server.MapPath("~/App_Data/" + DateTime.Now.Ticks + "_Request_" + requestMessage.FromUserName + ".txt"));//测试时可开启,帮助跟踪数据
                ResponseMessageBase responseMessage = null;
                switch (requestMessage.MsgType)
                {
                case RequestMsgType.Text:    //文字
                {
                    //TODO:交给Service处理具体信息,参考/Service/EventSercice.cs 及 /Service/LocationSercice.cs
                    var strongRequestMessage  = requestMessage as RequestMessageText;
                    var strongresponseMessage =
                        ResponseMessageBase.CreateFromRequestMessage(requestMessage, ResponseMsgType.Text) as
                        ResponseMessageText;
                    strongresponseMessage.Content =
                        string.Format(
                            "您刚才发送了文字信息:{0}\r\n您还可以发送【位置】【图片】【语音】等类型的信息,查看不同格式的回复。\r\nSDK官方地址:http://weixin.senparc.com",
                            strongRequestMessage.Content);
                    responseMessage = strongresponseMessage;
                    break;
                }

                case RequestMsgType.Location:    //位置
                {
                    responseMessage = locationService.GetResponseMessage(requestMessage as RequestMessageLocation);
                    break;
                }

                case RequestMsgType.Image:    //图片
                {
                    //TODO:交给Service处理具体信息
                    var strongRequestMessage  = requestMessage as RequestMessageImage;
                    var strongresponseMessage =
                        ResponseMessageBase.CreateFromRequestMessage(requestMessage, ResponseMsgType.News) as
                        ResponseMessageNews;
                    strongresponseMessage.Articles.Add(new Article()
                        {
                            Title       = "您刚才发送了图片信息",
                            Description = "您发送的图片将会显示在边上",
                            PicUrl      = strongRequestMessage.PicUrl,
                            Url         = "http://weixin.senparc.com"
                        });
                    strongresponseMessage.Articles.Add(new Article()
                        {
                            Title       = "第二条",
                            Description = "第二条带连接的内容",
                            PicUrl      = strongRequestMessage.PicUrl,
                            Url         = "http://weixin.senparc.com"
                        });
                    responseMessage = strongresponseMessage;
                    break;
                }

                case RequestMsgType.Voice:    //语音
                {
                    //TODO:交给Service处理具体信息
                    var strongRequestMessage  = requestMessage as RequestMessageVoice;
                    var strongresponseMessage =
                        ResponseMessageBase.CreateFromRequestMessage(requestMessage, ResponseMsgType.Music) as
                        ResponseMessageMusic;
                    strongresponseMessage.Music.MusicUrl = "http://weixin.senparc.com/Content/music1.mp3";
                    responseMessage = strongresponseMessage;
                    break;
                }

                case RequestMsgType.Event:    //事件
                {
                    responseMessage = eventService.GetResponseMessage(requestMessage as RequestMessageEventBase);
                    break;
                }

                default:
                    throw new ArgumentOutOfRangeException();
                }
                var responseDoc = MP.Helpers.EntityHelper.ConvertEntityToXml(responseMessage);
                responseDoc.Save(Server.MapPath("~/App_Data/" + DateTime.Now.Ticks + "_Response_" + responseMessage.ToUserName + ".txt"));//测试时可开启,帮助跟踪数据

                return(Content(responseDoc.ToString()));
                //如果不需要记录responseDoc,只需要:
                //return Content(responseMessage.ConvertEntityToXmlString());
            }
            catch (Exception ex)
            {
                using (
                    TextWriter tw = new StreamWriter(Server.MapPath("~/App_Data/Error_" + DateTime.Now.Ticks + ".txt")))
                {
                    tw.WriteLine(ex.Message);
                    tw.WriteLine(ex.InnerException.Message);
                    if (requestDoc != null)
                    {
                        tw.WriteLine(requestDoc.ToString());
                    }
                    tw.Flush();
                    tw.Close();
                }
                return(Content(""));
            }
        }
コード例 #29
0
        public void GetRequestEntityTest()
        {
            var dt = DateTimeHelper.BaseTime.AddTicks(((long)1358061152 + 8 * 60 * 60) * 10000000);

            {
                //Text
                var doc    = XDocument.Parse(xmlText);
                var result = RequestMessageFactory.GetRequestEntity(new MessageContexts.DefaultMpMessageContext(), doc);
                Assert.IsInstanceOfType(result, typeof(RequestMessageText));
                Assert.AreEqual("gh_a96a4a619366", result.ToUserName);
                Assert.AreEqual("TNT2", (result as RequestMessageText).Content);
            }

            {
                //Location
                var doc    = XDocument.Parse(xmlLocation);
                var result = RequestMessageFactory.GetRequestEntity(new MessageContexts.DefaultMpMessageContext(), doc) as RequestMessageLocation;
                Assert.IsNotNull(result);
                Assert.AreEqual("gh_a96a4a619366", result.ToUserName);
                Assert.AreEqual(19, result.Scale);
            }

            {
                //Image
                var doc    = XDocument.Parse(xmlImage);
                var result = RequestMessageFactory.GetRequestEntity(new MessageContexts.DefaultMpMessageContext(), doc) as RequestMessageImage;
                Assert.IsNotNull(result);
                Assert.AreEqual("gh_a96a4a619366", result.ToUserName);
                Assert.AreEqual("http://mmsns.qpic.cn/mmsns/ZxBXNzgHyUqazGkXUvujSPxexzynJAicf440qkyLibBd1OEO4saJiavLQ/0", result.PicUrl);
            }

            {
                //Voice
                var doc    = XDocument.Parse(xmlVoice);
                var result = RequestMessageFactory.GetRequestEntity(new MessageContexts.DefaultMpMessageContext(), doc) as RequestMessageVoice;
                Assert.IsNotNull(result);
                Assert.AreEqual("gh_a96a4a619366", result.ToUserName);
                Assert.AreEqual("X1yfgB2XI-faU6R2jmKz0X1JZmPCxIvM-9ktt4K92BB9577SCi41S-qMl60q5DJo", result.MediaId);
            }

            {
                //Video
                var doc    = XDocument.Parse(xmlVideo);
                var result = RequestMessageFactory.GetRequestEntity(new MessageContexts.DefaultMpMessageContext(), doc) as RequestMessageVideo;
                Assert.IsNotNull(result);
                Assert.AreEqual("gh_a96a4a619366", result.ToUserName);
                Assert.AreEqual("mediaId", result.MediaId);
                Assert.AreEqual("thumbMediaId", result.ThumbMediaId);
            }

            {
                //ShortVideo
                var doc    = XDocument.Parse(xmlShortVideo);
                var result = RequestMessageFactory.GetRequestEntity(new MessageContexts.DefaultMpMessageContext(), doc) as RequestMessageShortVideo;
                Assert.IsNotNull(result);
                Assert.AreEqual("toUser", result.ToUserName);
                Assert.AreEqual("media_id", result.MediaId);
                Assert.AreEqual("thumb_media_id", result.ThumbMediaId);
            }

            {
                //Link
                var doc    = XDocument.Parse(xmlLink);
                var result = RequestMessageFactory.GetRequestEntity(new MessageContexts.DefaultMpMessageContext(), doc) as RequestMessageLink;
                Assert.IsNotNull(result);
                Assert.AreEqual("gh_a96a4a619366", result.ToUserName);
                Assert.AreEqual("公众平台官网链接", result.Title);
                Assert.AreEqual("Senparc.Weixin.MP SDK公众平台官网链接", result.Description);
                Assert.AreEqual("https://sdk.weixin.senparc.com", result.Url);
            }

            {
                //Event-ENTRY
                var doc    = XDocument.Parse(xmlEvent_Enter);
                var result = RequestMessageFactory.GetRequestEntity(new MessageContexts.DefaultMpMessageContext(), doc) as RequestMessageEvent_Enter;
                Assert.IsNotNull(result);
                Assert.AreEqual("gh_a96a4a619366", result.ToUserName);
                Assert.AreEqual(Event.ENTER, result.Event);
            }

            {
                //Event-Location
                var doc    = XDocument.Parse(xmlEvent_Location);
                var result = RequestMessageFactory.GetRequestEntity(new MessageContexts.DefaultMpMessageContext(), doc) as RequestMessageEvent_Location;
                Assert.IsNotNull(result);
                Assert.AreEqual("gh_a96a4a619366", result.ToUserName);
                Assert.AreEqual(Event.LOCATION, result.Event);
                Assert.AreEqual(23.137466, result.Latitude);
                Assert.AreEqual(113.352425, result.Longitude);
                Assert.AreEqual(119.385040, result.Precision);
            }

            {
                //Event-Subscribe
                var doc    = XDocument.Parse(xmlEvent_Subscribe);
                var result = RequestMessageFactory.GetRequestEntity(new MessageContexts.DefaultMpMessageContext(), doc) as RequestMessageEvent_Subscribe;
                Assert.IsNotNull(result);
                Assert.AreEqual("gh_a96a4a619366", result.ToUserName);
                Assert.AreEqual(Event.subscribe, result.Event);
            }

            {
                //Event-Unsubscribe
                var doc    = XDocument.Parse(xmlEvent_Unsubscribe);
                var result = RequestMessageFactory.GetRequestEntity(new MessageContexts.DefaultMpMessageContext(), doc) as RequestMessageEvent_Unsubscribe;
                Assert.IsNotNull(result);
                Assert.AreEqual("gh_a96a4a619366", result.ToUserName);
                Assert.AreEqual(Event.unsubscribe, result.Event);
                Assert.AreEqual(new DateTime(2013, 3, 28), result.CreateTime.Date);
            }

            {
                //Event-CLICK
                var doc    = XDocument.Parse(xmlEvent_Click);
                var result = RequestMessageFactory.GetRequestEntity(new MessageContexts.DefaultMpMessageContext(), doc) as RequestMessageEvent_Click;
                Assert.IsNotNull(result);
                Assert.AreEqual("gh_a96a4a619366", result.ToUserName);
                Assert.AreEqual(Event.CLICK, result.Event);
                Assert.AreEqual(new DateTime(2013, 3, 28), result.CreateTime.Date);

                Assert.AreEqual("SubClickRoot_Agent", result.EventKey);
            }

            {
                //Event-scan
                var doc    = XDocument.Parse(xmlEvent_Scan);
                var result = RequestMessageFactory.GetRequestEntity(new MessageContexts.DefaultMpMessageContext(), doc) as RequestMessageEvent_Scan;
                Assert.IsNotNull(result);
                Assert.AreEqual("gh_a96a4a619366", result.ToUserName);
                Assert.AreEqual(Event.scan, result.Event);
                Assert.AreEqual(new DateTime(2013, 3, 28), result.CreateTime.Date);

                Assert.AreEqual("SCENE_VALUE", result.EventKey);
                Assert.AreEqual("TICKET", result.Ticket);
            }

            {
                //Event-VIEW
                var doc    = XDocument.Parse(xmlEvent_View);
                var result = RequestMessageFactory.GetRequestEntity(new MessageContexts.DefaultMpMessageContext(), doc) as RequestMessageEvent_View;
                Assert.IsNotNull(result);
                Assert.AreEqual("gh_a96a4a619366", result.ToUserName);
                Assert.AreEqual(Event.VIEW, result.Event);
                Assert.AreEqual(new DateTime(2014, 3, 14), result.CreateTime.Date);
                Assert.AreEqual("https://sdk.weixin.senparc.com", result.EventKey);
            }

            {
                //Event-Scancode_Push
                var doc    = XDocument.Parse(xmlEvent_Scancode_Push);
                var result = RequestMessageFactory.GetRequestEntity(new MessageContexts.DefaultMpMessageContext(), doc) as RequestMessageEvent_Scancode_Push;
                Assert.IsNotNull(result);
                Assert.AreEqual("gh_a96a4a619366", result.ToUserName);
                Assert.AreEqual(Event.scancode_push, result.Event);
                Assert.IsNotNull(result.ScanCodeInfo.ScanResult);
            }

            {
                //Event-Scancode_Scancode_Waitmsg
                var doc    = XDocument.Parse(xmlEvent_Scancode_Waitmsg);
                var result = RequestMessageFactory.GetRequestEntity(new MessageContexts.DefaultMpMessageContext(), doc) as RequestMessageEvent_Scancode_Waitmsg;
                Assert.IsNotNull(result);
                Assert.AreEqual("gh_a96a4a619366", result.ToUserName);
                Assert.AreEqual(Event.scancode_waitmsg, result.Event);
                Assert.IsNotNull(result.ScanCodeInfo.ScanResult);
            }

            {
                //Event-Scancode_Pic_Sysphoto
                var doc    = XDocument.Parse(xmlEvent_Pic_Sysphoto);
                var result = RequestMessageFactory.GetRequestEntity(new MessageContexts.DefaultMpMessageContext(), doc) as RequestMessageEvent_Pic_Sysphoto;
                Assert.IsNotNull(result);
                Assert.AreEqual("gh_a96a4a619366", result.ToUserName);
                Assert.AreEqual(Event.pic_sysphoto, result.Event);
                Assert.IsNotNull(result.SendPicsInfo.PicList);
            }

            {
                //Event-Scancode_Pic_Photo_Or_Album
                var doc    = XDocument.Parse(xmlEvent_Pic_Photo_Or_Album);
                var result = RequestMessageFactory.GetRequestEntity(new MessageContexts.DefaultMpMessageContext(), doc) as RequestMessageEvent_Pic_Photo_Or_Album;
                Assert.IsNotNull(result);
                Assert.AreEqual("gh_a96a4a619366", result.ToUserName);
                Assert.AreEqual(Event.pic_photo_or_album, result.Event);
                Assert.IsNotNull(result.SendPicsInfo.PicList);
            }

            {
                //Event-Scancode_Pic_Weixin
                var doc    = XDocument.Parse(xmlEvent_Pic_Weixin);
                var result = RequestMessageFactory.GetRequestEntity(new MessageContexts.DefaultMpMessageContext(), doc) as RequestMessageEvent_Pic_Weixin;
                Assert.IsNotNull(result);
                Assert.AreEqual("gh_a96a4a619366", result.ToUserName);
                Assert.AreEqual(Event.pic_weixin, result.Event);
                Assert.IsNotNull(result.SendPicsInfo.PicList);
            }

            {
                //Event-Location_Select
                var doc    = XDocument.Parse(xmlEvent_Location_Select);
                var result = RequestMessageFactory.GetRequestEntity(new MessageContexts.DefaultMpMessageContext(), doc) as RequestMessageEvent_Location_Select;
                Assert.IsNotNull(result);
                Assert.AreEqual("gh_a96a4a619366", result.ToUserName);
                Assert.AreEqual(Event.location_select, result.Event);
                Assert.IsNotNull(result.SendLocationInfo.Location_X);
            }

            {
                //Event-MassSendJobFinish
                var doc    = XDocument.Parse(xmlEvent_MassSendJobFinish);
                var result = RequestMessageFactory.GetRequestEntity(new MessageContexts.DefaultMpMessageContext(), doc) as RequestMessageEvent_MassSendJobFinish;
                Assert.IsNotNull(result);
                Assert.AreEqual("gh_a96a4a619366", result.ToUserName);
                Assert.AreEqual(Event.MASSSENDJOBFINISH, result.Event);
                Assert.AreEqual(result.SentCount, 75);
                Assert.AreEqual(result.ErrorCount, 5);
                Assert.IsNotNull(result.MsgID);
                Assert.AreEqual(1988, result.MsgID);
            }

            {
                //Event-Card_Pass_Check
                var doc    = XDocument.Parse(xmlEvent_Card_Pass_Check);
                var result = RequestMessageFactory.GetRequestEntity(new MessageContexts.DefaultMpMessageContext(), doc) as RequestMessageEvent_Card_Pass_Check;
                Assert.IsNotNull(result);
                Assert.AreEqual("toUser", result.ToUserName);
                Assert.AreEqual(Event.card_pass_check, result.Event);
                Assert.IsNotNull(result.CardId);
                Assert.AreEqual("cardid", result.CardId);
            }

            {
                //Event-Card_Not_Pass_Check
                var doc    = XDocument.Parse(xmlEvent_Card_Not_Pass_Check);
                var result = RequestMessageFactory.GetRequestEntity(new MessageContexts.DefaultMpMessageContext(), doc) as RequestMessageEvent_Card_Not_Pass_Check;
                Assert.IsNotNull(result);
                Assert.AreEqual("toUser", result.ToUserName);
                Assert.AreEqual(Event.card_not_pass_check, result.Event);
                Assert.IsNotNull(result.CardId);
                Assert.AreEqual("cardid", result.CardId);
            }

            {
                //Event-User_Get_Card
                var doc    = XDocument.Parse(xmlEvent_User_Get_Card);
                var result = RequestMessageFactory.GetRequestEntity(new MessageContexts.DefaultMpMessageContext(), doc) as RequestMessageEvent_User_Get_Card;
                Assert.IsNotNull(result);
                Assert.AreEqual("toUser", result.ToUserName);
                Assert.AreEqual(Event.user_get_card, result.Event);
                Assert.IsNotNull(result.CardId);
                Assert.AreEqual(1, result.IsGiveByFriend);
            }

            {
                //Event-User_Del_Card
                var doc    = XDocument.Parse(xmlEvent_User_Del_Card);
                var result = RequestMessageFactory.GetRequestEntity(new MessageContexts.DefaultMpMessageContext(), doc) as RequestMessageEvent_User_Del_Card;
                Assert.IsNotNull(result);
                Assert.AreEqual("toUser", result.ToUserName);
                Assert.AreEqual(Event.user_del_card, result.Event);
                Assert.IsNotNull(result.CardId);
                Assert.AreEqual("12312312", result.UserCardCode);
            }

            {
                //Event-Kf_Create_Session
                var doc    = XDocument.Parse(xmlEvent_Kf_Create_Session);
                var result = RequestMessageFactory.GetRequestEntity(new MessageContexts.DefaultMpMessageContext(), doc) as RequestMessageEvent_Kf_Create_Session;
                Assert.IsNotNull(result);
                Assert.AreEqual("touser", result.ToUserName);
                Assert.AreEqual(Event.kf_create_session, result.Event);
                Assert.AreEqual("test1@test", result.KfAccount);
            }

            {
                //Event-Kf_Close_Session
                var doc    = XDocument.Parse(xmlEvent_Kf_Close_Session);
                var result = RequestMessageFactory.GetRequestEntity(new MessageContexts.DefaultMpMessageContext(), doc) as RequestMessageEvent_Kf_Close_Session;
                Assert.IsNotNull(result);
                Assert.AreEqual("touser", result.ToUserName);
                Assert.AreEqual(Event.kf_close_session, result.Event);
                Assert.AreEqual("test1@test", result.KfAccount);
            }

            {
                //Event-Kf_Switch_Session
                var doc    = XDocument.Parse(xmlEvent_Kf_Switch_Session);
                var result = RequestMessageFactory.GetRequestEntity(new MessageContexts.DefaultMpMessageContext(), doc) as RequestMessageEvent_Kf_Switch_Session;
                Assert.IsNotNull(result);
                Assert.AreEqual("touser", result.ToUserName);
                Assert.AreEqual(Event.kf_switch_session, result.Event);
                Assert.AreEqual("test1@test", result.FromKfAccount);
                Assert.AreEqual("test2@test", result.ToKfAccount);
            }

            {
                //Event-Poi_Check_Notify
                var doc    = XDocument.Parse(xmlEvent_Poi_Check_Notify);
                var result = RequestMessageFactory.GetRequestEntity(new MessageContexts.DefaultMpMessageContext(), doc) as RequestMessageEvent_Poi_Check_Notify;
                Assert.IsNotNull(result);
                Assert.AreEqual("toUser", result.ToUserName);
                Assert.AreEqual(Event.poi_check_notify, result.Event);
                Assert.AreEqual("123adb", result.UniqId);
                Assert.AreEqual("fail", result.Result);
            }

            {
                //Event-WifiConnected
                var doc    = XDocument.Parse(xmlEvent_WifiConnected);
                var result = RequestMessageFactory.GetRequestEntity(new MessageContexts.DefaultMpMessageContext(), doc) as RequestMessageEvent_WifiConnected;
                Assert.IsNotNull(result);
                Assert.AreEqual("toUser", result.ToUserName);
                Assert.AreEqual(Event.WifiConnected, result.Event);
                Assert.AreEqual("PlaceId", result.PlaceId);
                Assert.AreEqual("3001224419", result.VendorId);
            }

            {
                //Event-User_Consume_Card
                var doc    = XDocument.Parse(xmlEvent_User_Consume_Card);
                var result = RequestMessageFactory.GetRequestEntity(new MessageContexts.DefaultMpMessageContext(), doc) as RequestMessageEvent_User_Consume_Card;
                Assert.IsNotNull(result);
                Assert.AreEqual("toUser", result.ToUserName);
                Assert.AreEqual(Event.user_consume_card, result.Event);
                Assert.AreEqual("cardid", result.CardId);
            }

            {
                //Event-User_Enter_Session_From_Card
                var doc    = XDocument.Parse(xmlEvent_User_Enter_Session_From_Card);
                var result = RequestMessageFactory.GetRequestEntity(new MessageContexts.DefaultMpMessageContext(), doc) as RequestMessageEvent_User_Enter_Session_From_Card;
                Assert.IsNotNull(result);
                Assert.AreEqual("toUser", result.ToUserName);
                Assert.AreEqual(Event.user_enter_session_from_card, result.Event);
                Assert.AreEqual("cardid", result.CardId);
            }

            {
                //Event-User_View_Card
                var doc    = XDocument.Parse(xmlEvent_User_View_Card);
                var result = RequestMessageFactory.GetRequestEntity(new MessageContexts.DefaultMpMessageContext(), doc) as RequestMessageEvent_User_View_Card;
                Assert.IsNotNull(result);
                Assert.AreEqual("toUser", result.ToUserName);
                Assert.AreEqual(Event.user_view_card, result.Event);
                Assert.AreEqual("cardid", result.CardId);
            }

            {
                //Event-Merchant_Order
                var doc    = XDocument.Parse(xmlEvent_Merchant_Order);
                var result = RequestMessageFactory.GetRequestEntity(new MessageContexts.DefaultMpMessageContext(), doc) as RequestMessageEvent_Merchant_Order;
                Assert.IsNotNull(result);
                Assert.AreEqual("weixin_media1", result.ToUserName);
                Assert.AreEqual(Event.merchant_order, result.Event);
                Assert.AreEqual("test_product_id", result.ProductId);
            }

            {
                //Event-Submit_Membercard_User_Info
                var doc    = XDocument.Parse(xmlEvent_Submit_Membercard_User_Info);
                var result = RequestMessageFactory.GetRequestEntity(new MessageContexts.DefaultMpMessageContext(), doc) as RequestMessageEvent_Submit_Membercard_User_Info;
                Assert.IsNotNull(result);
                Assert.AreEqual("gh_3fcea188bf78", result.ToUserName);
                Assert.AreEqual(Event.submit_membercard_user_info, result.Event);
                Assert.AreEqual("pbLatjtZ7v1BG_ZnTjbW85GYc_E8", result.CardId);
            }

            {
                //Event-ShakearoundUserShake
                var doc    = XDocument.Parse(xmlEvent_ShakearoundUserShake);
                var result = RequestMessageFactory.GetRequestEntity(new MessageContexts.DefaultMpMessageContext(), doc) as RequestMessageEvent_ShakearoundUserShake;
                Assert.IsNotNull(result);
                Assert.AreEqual("toUser", result.ToUserName);
                Assert.AreEqual(Event.ShakearoundUserShake, result.Event);
                Assert.AreEqual(12345, result.ChosenBeacon.Major);
                Assert.AreEqual(54321, result.ChosenBeacon.Minor);
                Assert.AreEqual(2, result.AroundBeacons.Count);
                Assert.AreEqual(15.013, result.AroundBeacons.ElementAt(1).Distance);
            }

            {
                //Event-Apply_Merchant_Audit_InfoRequest
                var doc    = XDocument.Parse(xmlEvent_Apply_Merchant_Audit_InfoRequest);
                var result = RequestMessageFactory.GetRequestEntity(new MessageContexts.DefaultMpMessageContext(), doc) as RequestMessageEvent_ApplyMerchantAuditInfo;
                Assert.IsNotNull(result);
                Assert.AreEqual("gh_4346ac1514d8", result.ToUserName);
                Assert.AreEqual(Event.apply_merchant_audit_info, result.Event);
                Assert.AreEqual(11111, result.audit_id);
                Assert.AreEqual(3, result.status);
                Assert.AreEqual("xxx", result.reason);
            }

            {
                //Event-Apply_CreateMapPoiAuditInfo
                var doc    = XDocument.Parse(xmlEvent_Create_Map_Poi_Audit_Info);
                var result = RequestMessageFactory.GetRequestEntity(new MessageContexts.DefaultMpMessageContext(), doc) as RequestMessageEvent_CreateMapPoiAuditInfo;
                Assert.IsNotNull(result);
                Assert.AreEqual("gh_4346ac1514d8", result.ToUserName);
                Assert.AreEqual(Event.create_map_poi_audit_info, result.Event);
                Assert.AreEqual(11111, result.audit_id);
                Assert.AreEqual(1, result.status);
                Assert.AreEqual("xxx", result.map_poi_id);
                Assert.AreEqual("xxx", result.name);
                Assert.AreEqual("xxx", result.address);
                Assert.AreEqual(134, result.latitude);
                Assert.AreEqual(30, result.longitude);
                Assert.AreEqual("xxx", result.sh_remark);
            }

            {
                //Event-Apply_AddStoreAuditInfo
                var doc    = XDocument.Parse(xmlEvent_Add_Store_Audit_Info);
                var result = RequestMessageFactory.GetRequestEntity(new MessageContexts.DefaultMpMessageContext(), doc) as RequestMessageEvent_AddStoreAuditInfo;
                Assert.IsNotNull(result);
                Assert.AreEqual("gh_4346ac1514d8", result.ToUserName);
                Assert.AreEqual(Event.add_store_audit_info, result.Event);
                Assert.AreEqual(11111, result.audit_id);
                Assert.AreEqual(3, result.is_upgrade);
                Assert.AreEqual("12344", result.poiid);
                Assert.AreEqual(3, result.status);
                Assert.AreEqual("xxx", result.reason);
            }

            {
                //Event-Apply_AddStoreAuditInfo
                var doc    = XDocument.Parse(xmlEvent_Modify_Store_Audit_Info);
                var result = RequestMessageFactory.GetRequestEntity(new MessageContexts.DefaultMpMessageContext(), doc) as RequestMessageEvent_ModifyStoreAuditInfo;
                Assert.IsNotNull(result);
                Assert.AreEqual("gh_4346ac1514d8", result.ToUserName);
                Assert.AreEqual(Event.modify_store_audit_info, result.Event);
                Assert.AreEqual(11111, result.audit_id);
                Assert.AreEqual(3, result.status);
                Assert.AreEqual("xxx", result.reason);
            }
        }
コード例 #30
0
        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="postDataDocument"></param>
        /// <param name="postData"></param>
        /// <returns></returns>
        public override XDocument Init(XDocument postDataDocument, object postData = null)
        {
            //进行加密判断并处理
            _postModel = postData as PostModel;
            var postDataStr = postDataDocument.ToString();

            XDocument decryptDoc = postDataDocument;

            if (_postModel != null && postDataDocument.Root.Element("Encrypt") != null && !string.IsNullOrEmpty(postDataDocument.Root.Element("Encrypt").Value))
            {
                //使用了加密
                UsingEcryptMessage    = true;
                EcryptRequestDocument = postDataDocument;

                WXBizMsgCrypt msgCrype = new WXBizMsgCrypt(_postModel.Token, _postModel.EncodingAESKey, _postModel.AppId);
                string        msgXml   = null;
                var           result   = msgCrype.DecryptMsg(_postModel.Msg_Signature, _postModel.Timestamp, _postModel.Nonce, postDataStr, ref msgXml);

                //判断result类型
                if (result != 0)
                {
                    //验证没有通过,取消执行
                    CancelExcute = true;
                    return(null);
                }

                if (postDataDocument.Root.Element("FromUserName") != null && !string.IsNullOrEmpty(postDataDocument.Root.Element("FromUserName").Value))
                {
                    //TODO:使用了兼容模式,进行验证即可
                    UsingCompatibilityModelEcryptMessage = true;
                }

                decryptDoc = XDocument.Parse(msgXml);//完成解密
            }

            RequestMessage = RequestMessageFactory.GetRequestEntity(decryptDoc);
            if (UsingEcryptMessage)
            {
                RequestMessage.Encrypt = postDataDocument.Root.Element("Encrypt").Value;
            }


            //TODO:分布式系统中本地的上下文会有同步问题,需要同步使用远程的储存
            if (MessageContextGlobalConfig.UseMessageContext)
            {
                var omit = OmitRepeatedMessageFunc == null || OmitRepeatedMessageFunc(RequestMessage);

                lock (MessageContextGlobalConfig.OmitRepeatLock)//TODO:使用分布式锁
                {
                    #region 消息去重

                    if (omit &&
                        OmitRepeatedMessage &&
                        CurrentMessageContext.RequestMessages.Count > 0
                        //&& !(RequestMessage is RequestMessageEvent_Merchant_Order)批量订单的MsgId可能会相同
                        )
                    {
                        //lastMessage必定有值(除非极端小的过期时间条件下,几乎不可能发生)
                        var lastMessage = CurrentMessageContext.RequestMessages[CurrentMessageContext.RequestMessages.Count - 1];

                        if (
                            //使用MsgId去重
                            (lastMessage.MsgId != 0 && lastMessage.MsgId == RequestMessage.MsgId) ||
                            //使用CreateTime去重(OpenId对象已经是同一个)
                            (lastMessage.MsgId == RequestMessage.MsgId &&
                             lastMessage.CreateTime == RequestMessage.CreateTime &&
                             lastMessage.MsgType == RequestMessage.MsgType)
                            )
                        {
                            MarkRepeatedMessage();//标记为已重复
                        }

                        //判断特殊事件
                        if (!MessageIsRepeated &&
                            lastMessage is RequestMessageEventBase &&
                            RequestMessage is RequestMessageEventBase &&
                            (lastMessage as RequestMessageEventBase).Event == (RequestMessage as RequestMessageEventBase).Event
                            )
                        {
                            var lastEventMessage    = lastMessage as RequestMessageEventBase;
                            var currentEventMessage = RequestMessage as RequestMessageEventBase;
                            switch (lastEventMessage.Event)
                            {
                            case Event.user_get_card:    //领取事件推送
                                //文档:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1451025274
                                //问题反馈:https://github.com/JeffreySu/WeiXinMPSDK/issues/1106
                                var lastGetUserCardMessage    = lastMessage as RequestMessageEvent_User_Get_Card;
                                var currentGetUserCardMessage = RequestMessage as RequestMessageEvent_User_Get_Card;
                                if (lastGetUserCardMessage.UserCardCode == currentGetUserCardMessage.UserCardCode &&
                                    lastGetUserCardMessage.CardId == currentGetUserCardMessage.CardId)
                                {
                                    MarkRepeatedMessage();    //标记为已重复
                                }
                                break;

                            default:
                                break;
                            }
                        }
                    }

                    #endregion

                    //在消息没有被去重的情况下记录上下文
                    if (!MessageIsRepeated)
                    {
                        GlobalMessageContext.InsertMessage(RequestMessage);
                    }
                }
            }


            return(decryptDoc);
        }