Esempio n. 1
0
        public ActionResult Post(PostModel postModel)
        {
            if (!CheckSignature.Check(postModel.Signature, postModel.Timestamp, postModel.Nonce, weixinoption.Token))
            {
                return(Content("参数错误!"));
            }


            postModel.Token          = weixinoption.Token;
            postModel.EncodingAESKey = weixinoption.WeixinAESKey; //根据自己后台的设置保持一致
            postModel.AppId          = weixinoption.AppId;        //根据自己后台的设置保持一致

            //转化steam 为memory stream
            using (MemoryStream memory = new MemoryStream())
            {
                this.Request.Body.CopyTo(memory);
                memory.Seek(0, SeekOrigin.Begin);
                var postDataDocument = XmlUtility.Convert(memory);
                var messageHandler   = new WeixinMessageHandler(postDataDocument, postModel,
                                                                ossOption, baiduapiOption, _baiyecontext, _logger); //接收消息(第一步)

                messageHandler.Execute();                                                                           //执行微信处理过程(第二步)

                return(new FixWeixinBugWeixinResult(messageHandler));                                               //返回(第三步)
            }
        }
Esempio n. 2
0
        public void ProcessRequest(HttpContext context)
        {
            string signature = HttpContext.Current.Request["signature"];
            string timestamp = HttpContext.Current.Request["timestamp"];
            string nonce = HttpContext.Current.Request["nonce"];
            string echostr = HttpContext.Current.Request["echostr"];

            if (HttpContext.Current.Request.HttpMethod == "GET")
            {
                if (CheckSignature.Check(signature, timestamp, nonce, _token))
                {
                    WriteContent(echostr); //返回随机字符串则表示验证通过
                }
                else
                {
                    WriteContent("failed:" + signature + "," + CheckSignature.GetSignature(timestamp, nonce, _token));
                }
                HttpContext.Current.Response.End();
            }
            else
            {
                //post method - 当有用户想公众账号发送消息时触发
                if (!CheckSignature.Check(signature, timestamp, nonce, _token))
                {
                    WriteContent("参数错误!");
                    return;
                }

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

                try
                {
                    //测试时可开启此记录,帮助跟踪数据
                    //_logSvc.Log(messageHandler.RequestMessage.FromUserName, messageHandler.RequestDocument.ToString(), (int)LogType.REQUEST);

                    //执行微信处理过程
                    messageHandler.Execute();


                    //测试时可开启,帮助跟踪数据
                    //_logSvc.Log(messageHandler.RequestMessage.ToUserName, messageHandler.ResponseDocument.ToString(), (int)LogType.RESPONSE);

                    WriteContent(messageHandler.ResponseDocument.ToString());
                    return;
                }
                catch (Exception)
                {
                    //_logSvc.Log(messageHandler.RequestMessage.ToUserName, ex.InnerException.Message + ex.InnerException.InnerException.StackTrace, (int)LogType.ERROR);

                    WriteContent("");
                }
                finally
                {
                    HttpContext.Current.Response.End();
                }
            }
        }
Esempio n. 3
0
        public void ExecuteTest_EncryptMessageHandle()
        {
            const string xml = @"<xml>
                                     <ToUserName><![CDATA[wx5823bf96d3bd56c7]]></ToUserName>
                                     <Encrypt><![CDATA[RypEvHKD8QQKFhvQ6QleEB4J58tiPdvo+rtK1I9qca6aM/wvqnLSV5zEPeusUiX5L5X/0lWfrf0QADHHhGd3QczcdCUpj911L3vg3W/sYYvuJTs3TUUkSUXxaccAS0qhxchrRYt66wiSpGLYL42aM6A8dTT+6k4aSknmPj48kzJs8qLjvd4Xgpue06DOdnLxAUHzM6+kDZ+HMZfJYuR+LtwGc2hgf5gsijff0ekUNXZiqATP7PF5mZxZ3Izoun1s4zG4LUMnvw2r+KqCKIw+3IQH03v+BCA9nMELNqbSf6tiWSrXJB3LAVGUcallcrw8V2t9EL4EhzJWrQUax5wLVMNS0+rUPA3k22Ncx4XXZS9o0MBH27Bo6BpNelZpS+/uh9KsNlY6bHCmJU9p8g7m3fVKn28H3KDYA5Pl/T8Z1ptDAVe0lXdQ2YoyyH2uyPIGHBZZIs2pDBS8R07+qN+E7Q==]]></Encrypt>
                                 </xml>";

            WeixinMessageContext context = new WeixinMessageContext()
            {
                HttpRequestContent = xml,
                HttpRequestParams  = new HttpRequestParams()
                {
                    Encrypt_Type  = "aes",
                    Signature     = "d2157f2f9079f4d6257b45edf665c43c62e60a0a",
                    Timestamp     = "1409659813",
                    Nonce         = "1372623149",
                    Msg_Signature = "477715d11cdb4164915debcba66cb864d751f3e6"
                }
            };

            WeixinMessageHandler handler = new WeixinMessageHandler(context);

            string content = handler.Execute();

            Assert.NotNull(content);
            Assert.True(content.Length > 0);

            //解密校验结果是否正确,
            dynamic resultXmlObj = new DynamicXml(content);

            Assert.Equal(context.HttpRequestParams.Timestamp, resultXmlObj.TimeStamp.Value);
            Assert.Equal(context.HttpRequestParams.Nonce, resultXmlObj.Nonce.Value);
            Assert.True(resultXmlObj.Encrypt.Value.Length > 0);

            //获取消息签名 后期解密字符串使用。
            string msgSignature = resultXmlObj.MsgSignature.Value;

            Assert.True(msgSignature.Length > 0);

            string          sMsg      = string.Empty;
            WeixinMsgCrypto msgCrypto = new WeixinMsgCrypto();
            int             resultXmlDecryptResult = msgCrypto.DecryptMsg(msgSignature, context.HttpRequestParams.Timestamp, context.HttpRequestParams.Nonce, content, ref sMsg);

            Assert.Equal(Convert.ToInt32(WeixinMsgCryptoErrorCode.OK), resultXmlDecryptResult);
            Assert.True(sMsg.Length > 0);

            //解密后的 xml 结果 测试。
            dynamic contentXmlObj = new DynamicXml(sMsg);

            Assert.Equal("mycreate", contentXmlObj.ToUserName.Value);
            Assert.Equal("wx5823bf96d3bd56c7", contentXmlObj.FromUserName.Value);
            Assert.True(Convert.ToInt64(contentXmlObj.CreateTime.Value) > 0);
            Assert.Equal("text", contentXmlObj.MsgType.Value);
            Assert.Equal("hello", contentXmlObj.Content.Value);
        }
Esempio n. 4
0
        public void ExecuteTest_IgnoreRepeatMessageHandle()
        {
            const string xml = @"<xml>
                                 <ToUserName><![CDATA[toUser]]></ToUserName>
                                 <FromUserName><![CDATA[fromUser]]></FromUserName> 
                                 <CreateTime>1348831860</CreateTime>
                                 <MsgType><![CDATA[text]]></MsgType>
                                 <Content><![CDATA[this is a test]]></Content>
                                 <MsgId>1234567890123456</MsgId>
                                 </xml>";

            WeixinMessageContext context = new WeixinMessageContext()
            {
                HttpRequestContent = xml,
                HttpRequestParams  = new HttpRequestParams()
                {
                    Encrypt_Type = "raw",
                    Signature    = "72e5966e52226c51c2ae8a012815cda2f1056171",
                    Timestamp    = "14433232323"
                }
            };

            WeixinMessageHandler handler = new WeixinMessageHandler(context);

            string content = handler.Execute();

            Assert.NotNull(content);
            Assert.True(content.Length > 0);

            //模拟第二次请求,如果返回空字符串则表示已经忽略消息。
            Thread.Sleep(3000);

            WeixinMessageContext context2 = new WeixinMessageContext()
            {
                HttpRequestContent = xml,
                HttpRequestParams  = new HttpRequestParams()
                {
                    Encrypt_Type = "raw",
                    Signature    = "72e5966e52226c51c2ae8a012815cda2f1056171",
                    Timestamp    = "14433232323"
                }
            };

            WeixinMessageHandler handler2 = new WeixinMessageHandler(context2);

            string content2 = handler2.Execute();

            Assert.NotNull(content2);
            Assert.Equal(string.Empty, content2);
        }
Esempio n. 5
0
        public void OnTextRequestForJingPinKeChengFailureTest()
        {
            var messageHandlers = new WeixinMessageHandler(XDocument.Parse(xmlTextForJingPinKeChengFailure));

            Assert.IsNotNull(messageHandlers.RequestDocument);
            messageHandlers.Execute();
            Assert.IsNotNull(messageHandlers.ResponseMessage);
            Assert.IsNotNull(messageHandlers.ResponseDocument);
            Console.Write(messageHandlers.ResponseDocument.ToString());

            Assert.AreEqual("gh_a96a4a619366", messageHandlers.ResponseMessage.FromUserName);

            var responseMessage = messageHandlers.ResponseMessage as ResponseMessageText;

            Assert.IsNotNull(responseMessage);
            Assert.IsTrue(responseMessage.Content.Contains("欢迎"));
        }
Esempio n. 6
0
        public void ExecuteTest_DataNativeMessageHandle()
        {
            const string xml = @"<xml>
                                 <ToUserName><![CDATA[toUser]]></ToUserName>
                                 <FromUserName><![CDATA[fromUser]]></FromUserName> 
                                 <CreateTime>1348831860</CreateTime>
                                 <MsgType><![CDATA[text]]></MsgType>
                                 <Content><![CDATA[this is a test]]></Content>
                                 <MsgId>1234567890123456</MsgId>
                                 </xml>";

            WeixinMessageContext context = new WeixinMessageContext()
            {
                HttpRequestContent = xml,
                HttpRequestParams  = new HttpRequestParams()
                {
                    Encrypt_Type = "raw",
                    Signature    = "72e5966e52226c51c2ae8a012815cda2f1056171",
                    Timestamp    = "14433232323"
                }
            };

            WeixinMessageHandler handler = new WeixinMessageHandler(context);

            string content = handler.Execute();

            Assert.NotNull(content);
            Assert.True(content.Length > 0);

            //响应 xml 结果 测试。
            dynamic contentXmlObj = new DynamicXml(content);

            Assert.Equal("fromUser", contentXmlObj.ToUserName.Value);
            Assert.Equal("toUser", contentXmlObj.FromUserName.Value);
            Assert.True(Convert.ToInt64(contentXmlObj.CreateTime.Value) > 0);
            Assert.Equal("text", contentXmlObj.MsgType.Value);
            Assert.Equal("this is a test", contentXmlObj.Content.Value);
        }
Esempio n. 7
0
        public void OnTextRequestForJingPinKeChengFailureTest()
        {
            var messageHandlers = new WeixinMessageHandler(XDocument.Parse(xmlTextForJingPinKeChengFailure));
            Assert.IsNotNull(messageHandlers.RequestDocument);
            messageHandlers.Execute();
            Assert.IsNotNull(messageHandlers.ResponseMessage);
            Assert.IsNotNull(messageHandlers.ResponseDocument);
            Console.Write(messageHandlers.ResponseDocument.ToString());

            Assert.AreEqual("gh_a96a4a619366", messageHandlers.ResponseMessage.FromUserName);

            var responseMessage = messageHandlers.ResponseMessage as ResponseMessageText;
            Assert.IsNotNull(responseMessage);
            Assert.IsTrue(responseMessage.Content.Contains("欢迎"));
        }
Esempio n. 8
0
        protected void Page_Load(object sender, EventArgs e)
        {
            //取传入参数
            string signature = Request["signature"];
            string timestamp = Request["timestamp"];
            string nonce = Request["nonce"];
            string echostr = Request["echostr"];

            //记录传入参数
            SaveParameters(signature, timestamp, nonce, echostr);

            //标准回应
            if (Request.HttpMethod == "GET")
            {
                //get method - 仅在微信后台填写URL验证时触发
                if (CheckSignature.Check(signature, timestamp, nonce, Token))
                {
                    WriteContent(echostr); //返回随机字符串则表示验证通过
                }
                else
                {
                    WriteContent(String.Format("failed:{0},{1}", signature, CheckSignature.GetSignature(timestamp, nonce, Token)));
                }
                Response.End();
            }
            else
            {
                //post method - 当有用户想公众账号发送消息时触发
                if (!CheckSignature.Check(signature, timestamp, nonce, Token))
                {
                    WriteContent("参数错误!");
                }
                //自定义MessageHandler,对微信请求的详细判断操作都在这里面。
                var messageHandler = new WeixinMessageHandler(Request.InputStream);

                //var inputStream = Request.InputStream;
                //var pos = inputStream.Position;
                //var reader = new StreamReader(inputStream);
                //inputStream.Position = 0;
                //var text = reader.ReadToEnd();
                //inputStream.Position = pos;

                //var xml = XDocument.Parse(text);

                //var messageHandler = new WeixinMessageHandler(xml);
                try
                {
                    //测试时可开启此记录,帮助跟踪数据
                    SaveRequest(messageHandler);
                    //执行微信处理过程
                    messageHandler.Execute();
                    //测试时可开启,帮助跟踪数据
                    SaveResponse(messageHandler);
                    WriteContent(messageHandler.ResponseDocument.ToString());
                    return;
                }
                catch (Exception ex)
                {
                    //记录错误
                    SaveError(messageHandler, ex);
                    WriteContent("");
                }
                finally
                {
                    Response.End();
                }

                ////执行微信处理过程
                //messageHandler.Execute();
                ////输出结果
                //WriteContent(messageHandler.ResponseDocument.ToString());
            }
            //Response.End();
        }
Esempio n. 9
0
        protected void Page_Load(object sender, EventArgs e)
        {
            //取传入参数
            string signature = Request["signature"];
            string timestamp = Request["timestamp"];
            string nonce     = Request["nonce"];
            string echostr   = Request["echostr"];

            //记录传入参数
            SaveParameters(signature, timestamp, nonce, echostr);

            //标准回应
            if (Request.HttpMethod == "GET")
            {
                //get method - 仅在微信后台填写URL验证时触发
                if (CheckSignature.Check(signature, timestamp, nonce, Token))
                {
                    WriteContent(echostr); //返回随机字符串则表示验证通过
                }
                else
                {
                    WriteContent(String.Format("failed:{0},{1}", signature, CheckSignature.GetSignature(timestamp, nonce, Token)));
                }
                Response.End();
            }
            else
            {
                //post method - 当有用户想公众账号发送消息时触发
                if (!CheckSignature.Check(signature, timestamp, nonce, Token))
                {
                    WriteContent("参数错误!");
                }
                //自定义MessageHandler,对微信请求的详细判断操作都在这里面。
                var messageHandler = new WeixinMessageHandler(Request.InputStream);

                //var inputStream = Request.InputStream;
                //var pos = inputStream.Position;
                //var reader = new StreamReader(inputStream);
                //inputStream.Position = 0;
                //var text = reader.ReadToEnd();
                //inputStream.Position = pos;

                //var xml = XDocument.Parse(text);

                //var messageHandler = new WeixinMessageHandler(xml);
                try
                {
                    //测试时可开启此记录,帮助跟踪数据
                    SaveRequest(messageHandler);
                    //执行微信处理过程
                    messageHandler.Execute();
                    //测试时可开启,帮助跟踪数据
                    SaveResponse(messageHandler);
                    WriteContent(messageHandler.ResponseDocument.ToString());
                    return;
                }
                catch (Exception ex)
                {
                    //记录错误
                    SaveError(messageHandler, ex);
                    WriteContent("");
                }
                finally
                {
                    Response.End();
                }

                ////执行微信处理过程
                //messageHandler.Execute();
                ////输出结果
                //WriteContent(messageHandler.ResponseDocument.ToString());
            }
            //Response.End();
        }