public override bool Lock(string resourceName, int retryCount, TimeSpan retryDelay)
        {
            var key         = _mamcachedStrategy.GetFinalKey(resourceName);
            var successfull = RetryLock(key, retryCount /*暂时不限制*/, retryDelay, () =>
            {
                try
                {
                    if (_mamcachedStrategy._cache.Get(key) != null)
                    {
                        return(false);//已被别人锁住,没有取得锁
                    }
                    else
                    {
                        _mamcachedStrategy._cache.Store(StoreMode.Set, key, new object(), new TimeSpan(0, 0, 10)); //创建锁
                        return(true);                                                                              //取得锁
                    }
                }
                catch (Exception ex)
                {
                    WeixinTrace.Log("Memcached同步锁发生异常:" + ex.Message);
                    return(false);
                }
            }
                                        );

            return(successfull);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// 处理视频请求
        /// </summary>
        /// <param name="requestMessage"></param>
        /// <returns></returns>
        public override IResponseMessageBase OnVideoRequest(RequestMessageVideo requestMessage)
        {
            var responseMessage = CreateResponseMessage <ResponseMessageText>();

            responseMessage.Content = "您发送了一条视频信息,ID:" + requestMessage.MediaId;

            #region    材并推送到客户端

            Task.Factory.StartNew(async() =>
            {
                //上传素材
                var dir          = ServerUtility.ContentRootMapPath("~/App_Data/TempVideo/");
                var file         = await MediaApi.GetAsync(appId, requestMessage.MediaId, dir);
                var uploadResult = await MediaApi.UploadTemporaryMediaAsync(appId, UploadMediaFileType.video, file, 50000);
                await CustomApi.SendVideoAsync(appId, base.OpenId, uploadResult.media_id, "这是您刚才发送的视频", "这是一条视频消息");
            }).ContinueWith(async task =>
            {
                if (task.Exception != null)
                {
                    WeixinTrace.Log("OnVideoRequest()储存Video过程发生错误:", task.Exception.Message);

                    var msg = string.Format("上传素材出错:{0}\r\n{1}",
                                            task.Exception.Message,
                                            task.Exception.InnerException != null
                                    ? task.Exception.InnerException.Message
                                    : null);
                    await CustomApi.SendTextAsync(appId, base.OpenId, msg);
                }
            });

            #endregion

            return(responseMessage);
        }
Ejemplo n.º 3
0
        public void TestAll()
        {
            var mq    = new LimeMessageQueue();
            var count = mq.GetCount();
            var key   = DateTime.Now.Ticks.ToString();

            //Test Add()
            var item = mq.Add(key, () => WeixinTrace.Log("测试LimeMessageQueue写入Key=A"));

            Assert.AreEqual(count + 1, mq.GetCount());
            //var hashCode = item.GetHashCode();

            //Test GetCurrentKey()
            var currentKey = mq.GetCurrentKey();

            Assert.AreEqual(key, currentKey);

            //Test GetItem
            var currentItem = mq.GetItem(currentKey);

            Assert.AreEqual(currentItem.Key, item.Key);
            Assert.AreEqual(currentItem.AddTime, item.AddTime);

            //Test Remove
            mq.Remove(key);
            Assert.AreEqual(count, mq.GetCount());
        }
Ejemplo n.º 4
0
        public override bool Lock(string resourceName, int retryCount, TimeSpan retryDelay)
        {
            var successful = RetryLock(resourceName, retryCount, retryDelay, () =>
            {
                try
                {
                    if (LockPool.ContainsKey(resourceName))
                    {
                        return(false);//已被别人锁住,没有取得锁
                    }
                    else
                    {
                        LockPool.Add(resourceName, new object()); //创建锁
                        return(true);                             //取得锁
                    }
                }
                catch (Exception ex)
                {
                    WeixinTrace.Log("本地同步锁发生异常:" + ex.Message);
                    return(false);
                }
            }
                                       );

            return(successful);
        }
        static MemcachedObjectCacheStrategy()
        {
            // //初始化memcache服务器池
            //SockIOPool pool = SockIOPool.GetInstance();
            ////设置Memcache池连接点服务器端。
            //pool.SetServers(serverlist);
            ////其他参数根据需要进行配置

            //pool.InitConnections = 3;
            //pool.MinConnections = 3;
            //pool.MaxConnections = 5;

            //pool.SocketConnectTimeout = 1000;
            //pool.SocketTimeout = 3000;

            //pool.MaintenanceSleep = 30;
            //pool.Failover = true;

            //pool.Nagle = false;
            //pool.Initialize();

            //cache = new MemcachedClient();
            //cache.EnableCompression = false;
            try
            {
                //config.Authentication.Type = typeof(PlainTextAuthenticator);
                //config.Authentication.Parameters["userName"] = "******";
                //config.Authentication.Parameters["password"] = "******";
                //config.Authentication.Parameters["zone"] = "zone";//domain?   ——Jeffrey 2015.10.20
                DateTime dt1    = DateTime.Now;
                var      config = GetMemcachedClientConfiguration();
                //var cache = new MemcachedClient(config);'


#if NET45 || NET461
                var cache = new MemcachedClient(config);
#else
                var cache = new MemcachedClient(null, config);
#endif

                var testKey   = Guid.NewGuid().ToString();
                var testValue = Guid.NewGuid().ToString();
                cache.Store(StoreMode.Set, testKey, testValue);
                var storeValue = cache.Get(testKey);
                if (storeValue as string != testValue)
                {
                    throw new Exception("MemcachedStrategy失效,没有计入缓存!");
                }
                cache.Remove(testKey);
                DateTime dt2 = DateTime.Now;

                WeixinTrace.Log(string.Format("MemcachedStrategy正常启用,启动及测试耗时:{0}ms", (dt2 - dt1).TotalMilliseconds));
            }
            catch (Exception ex)
            {
                //TODO:记录是同日志
                WeixinTrace.Log(string.Format("MemcachedStrategy静态构造函数异常:{0}", ex.Message));
            }
        }
Ejemplo n.º 6
0
 public ActionResult Get(PostModel postModel, string echostr)
 {
     try
     {
         if (CheckSignature.Check(postModel.Signature, postModel.Timestamp, postModel.Nonce, Token))
         {
             return(Content(echostr)); //返回随机字符串则表示验证通过
         }
         else
         {
             return(Content("failed:" + postModel.Signature + "," + CheckSignature.GetSignature(postModel.Timestamp, postModel.Nonce, Token) + "。" +
                            "如果你在浏览器中看到这句话,说明此地址可以被作为微信公众账号后台的Url,请注意保持Token一致。"));
         }
     }
     catch (Exception ex)
     {
         WeixinTrace.Log(ex.Message);
         throw;
     }
 }
Ejemplo n.º 7
0
        public override bool Lock(string resourceName, int retryCount, TimeSpan retryDelay)
        {
            int currentRetry  = 0;
            int maxRetryDelay = (int)retryDelay.TotalMilliseconds;

            while (currentRetry++ < retryCount)
            {
                #region 尝试获得锁

                var getLock = false;
                try
                {
                    lock (lookPoolLock)
                    {
                        if (LockPool.ContainsKey(resourceName))
                        {
                            getLock = false;//已被别人锁住,没有取得锁
                        }
                        else
                        {
                            LockPool.Add(resourceName, new object()); //创建锁
                            getLock = true;                           //取得锁
                        }
                    }
                }
                catch (Exception ex)
                {
                    WeixinTrace.Log("本地同步锁发生异常:" + ex.Message);
                    getLock = false;
                }

                #endregion

                if (getLock)
                {
                    return(true);//取得锁
                }
                Thread.Sleep(_rnd.Next(maxRetryDelay));
            }
            return(false);
        }
Ejemplo n.º 8
0
        public ActionResult Post(PostModel postModel)
        {
            if (!CheckSignature.Check(postModel.Signature, postModel.Timestamp, postModel.Nonce, Token))
            {
                return(Content("参数错误!"));
            }

            #region 打包 PostModel 信息

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

            #endregion

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

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

            try
            {
                #region 记录 Request 日志

                var logPath = Server.MapPath(string.Format("~/App_Data/MP/{0}/", DateTime.Now.ToString("yyyy-MM-dd")));
                if (!Directory.Exists(logPath))
                {
                    Directory.CreateDirectory(logPath);
                }

                //测试时可开启此记录,帮助跟踪数据,使用前请确保App_Data文件夹存在,且有读写权限。
                messageHandler.RequestDocument.Save(Path.Combine(logPath, string.Format("{0}_Request_{1}_{2}.txt", _getRandomFileName(),
                                                                                        messageHandler.RequestMessage.FromUserName,
                                                                                        messageHandler.RequestMessage.MsgType)));
                if (messageHandler.UsingEcryptMessage)
                {
                    messageHandler.EcryptRequestDocument.Save(Path.Combine(logPath, string.Format("{0}_Request_Ecrypt_{1}_{2}.txt", _getRandomFileName(),
                                                                                                  messageHandler.RequestMessage.FromUserName,
                                                                                                  messageHandler.RequestMessage.MsgType)));
                }

                #endregion

                /* 如果需要添加消息去重功能,只需打开OmitRepeatedMessage功能,SDK会自动处理。
                 * 收到重复消息通常是因为微信服务器没有及时收到响应,会持续发送2-5条不等的相同内容的RequestMessage*/
                messageHandler.OmitRepeatedMessage = true;

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

                #region 记录 Response 日志

                //测试时可开启,帮助跟踪数据

                //if (messageHandler.ResponseDocument == null)
                //{
                //    throw new Exception(messageHandler.RequestDocument.ToString());
                //}
                if (messageHandler.ResponseDocument != null)
                {
                    messageHandler.ResponseDocument.Save(Path.Combine(logPath, string.Format("{0}_Response_{1}_{2}.txt", _getRandomFileName(),
                                                                                             messageHandler.ResponseMessage.ToUserName,
                                                                                             messageHandler.ResponseMessage.MsgType)));
                }

                if (messageHandler.UsingEcryptMessage && messageHandler.FinalResponseDocument != null)
                {
                    //记录加密后的响应信息
                    messageHandler.FinalResponseDocument.Save(Path.Combine(logPath, string.Format("{0}_Response_Final_{1}_{2}.txt", _getRandomFileName(),
                                                                                                  messageHandler.ResponseMessage.ToUserName,
                                                                                                  messageHandler.ResponseMessage.MsgType)));
                }

                #endregion `

                //return Content(messageHandler.ResponseDocument.ToString());//v0.7-
                //return new WeixinResult(messageHandler);//v0.8+
                return(new FixWeixinBugWeixinResult(messageHandler));//为了解决官方微信5.0软件换行bug暂时添加的方法,平时用下面一个方法即可
            }
            catch (Exception ex)
            {
                #region 异常处理
                WeixinTrace.Log("MessageHandler错误:{0}", ex.Message);

                using (TextWriter tw = new StreamWriter(Server.MapPath("~/App_Data/Error_" + _getRandomFileName() + ".txt")))
                {
                    tw.WriteLine("ExecptionMessage:" + ex.Message);
                    tw.WriteLine(ex.Source);
                    tw.WriteLine(ex.StackTrace);
                    //tw.WriteLine("InnerExecptionMessage:" + ex.InnerException.Message);

                    if (messageHandler.ResponseDocument != null)
                    {
                        tw.WriteLine(messageHandler.ResponseDocument.ToString());
                    }

                    if (ex.InnerException != null)
                    {
                        tw.WriteLine("========= InnerException =========");
                        tw.WriteLine(ex.InnerException.Message);
                        tw.WriteLine(ex.InnerException.Source);
                        tw.WriteLine(ex.InnerException.StackTrace);
                    }

                    tw.Flush();
                    tw.Close();
                }
                return(Content(""));

                #endregion
            }
        }
Ejemplo n.º 9
0
        public ActionResult Post(PostModel postModel)
        {
            /* 异步请求请见 WeixinAsyncController(推荐) */

            if (!CheckSignature.Check(postModel.Signature, postModel.Timestamp, postModel.Nonce, Token))
            {
                return(Content("参数错误!"));
            }

            #region 打包 PostModel 信息

            postModel.Token          = Token;          //根据自己后台的设置保持一致
            postModel.EncodingAESKey = EncodingAESKey; //根据自己后台的设置保持一致
            postModel.AppId          = AppId;          //根据自己后台的设置保持一致(必须提供)

            #endregion

            //v4.2.2之后的版本,可以设置每个人上下文消息储存的最大数量,防止内存占用过多,如果该参数小于等于0,则不限制(实际最大限制 99999)
            //注意:如果使用分布式缓存,不建议此值设置过大,如果需要储存历史信息,请使用数据库储存
            var maxRecordCount = 10;

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

            #region 设置消息去重设置

            /* 如果需要添加消息去重功能,只需打开OmitRepeatedMessage功能,SDK会自动处理。
             * 收到重复消息通常是因为微信服务器没有及时收到响应,会持续发送2-5条不等的相同内容的 RequestMessage */
            messageHandler.OmitRepeatedMessage = true;//默认已经是开启状态,此处仅作为演示,也可以设置为 false 在本次请求中停用此功能

            #endregion

            try
            {
                messageHandler.SaveRequestMessageLog();  //记录 Request 日志(可选)

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

                messageHandler.SaveResponseMessageLog(); //记录 Response 日志(可选)

                //return Content(messageHandler.ResponseDocument.ToString());//v0.7-
                //return new WeixinResult(messageHandler);//v0.8+
                return(new FixWeixinBugWeixinResult(messageHandler));//为了解决官方微信5.0软件换行bug暂时添加的方法,平时用下面一个方法即可
            }
            catch (Exception ex)
            {
                #region 异常处理
                WeixinTrace.Log("MessageHandler错误:{0}", ex.Message);

                using (TextWriter tw = new StreamWriter(ServerUtility.ContentRootMapPath("~/App_Data/Error_" + _getRandomFileName() + ".txt")))
                {
                    tw.WriteLine("ExecptionMessage:" + ex.Message);
                    tw.WriteLine(ex.Source);
                    tw.WriteLine(ex.StackTrace);
                    //tw.WriteLine("InnerExecptionMessage:" + ex.InnerException.Message);

                    if (messageHandler.ResponseDocument != null)
                    {
                        tw.WriteLine(messageHandler.ResponseDocument.ToString());
                    }

                    if (ex.InnerException != null)
                    {
                        tw.WriteLine("========= InnerException =========");
                        tw.WriteLine(ex.InnerException.Message);
                        tw.WriteLine(ex.InnerException.Source);
                        tw.WriteLine(ex.InnerException.StackTrace);
                    }

                    tw.Flush();
                    tw.Close();
                }
                return(Content(""));

                #endregion
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        /// 获取 HttpResponseMessage 对象
        /// </summary>
        /// <param name="url"></param>
        /// <param name="data">如果为 GET 请求,此参数可为 null</param>
        /// <param name="timeOut"></param>
        /// <param name="requestMethod"></param>
        /// <param name="checkDataNotNull">非 GET 请求情况下,是否强制检查 data 参数不能为 null,默认为 true</param>
        /// <returns></returns>
        public async Task <HttpResponseMessage> GetHttpResponseMessageAsync(string url, object data, int timeOut = Config.TIME_OUT, ApiRequestMethod requestMethod = ApiRequestMethod.POST, bool checkDataNotNull = true)
        {
            try
            {
                //var co2netHttpClient = CO2NET.HttpUtility.RequestUtility.HttpPost_Common_NetCore(serviceProvider, url, out var hc, contentType: "application/json");

                ////设置参数
                //var mchid = _tenpayV3Setting.TenPayV3_MchId;
                //var ser_no = _tenpayV3Setting.TenPayV3_SerialNumber;
                //var privateKey = _tenpayV3Setting.TenPayV3_PrivateKey;

                ////使用微信支付参数,配置 HttpHandler
                //TenPayHttpHandler httpHandler = new(mchid, ser_no, privateKey);

                //TODO:此处重构使用ISenparcWeixinSettingForTenpayV3
                TenPayHttpHandler httpHandler = new(_tenpayV3Setting);

                //创建 HttpClient
                HttpClient client = new HttpClient(httpHandler);
                //设置超时时间
                client.Timeout = TimeSpan.FromMilliseconds(timeOut);

                //设置 HTTP 请求头
                SetHeader(client);

                HttpResponseMessage responseMessage = null;
                switch (requestMethod)
                {
                case ApiRequestMethod.GET:
                    responseMessage = await client.GetAsync(url);

                    WeixinTrace.Log(url);     //记录Get的Json数据
                    break;

                case ApiRequestMethod.POST:
                case ApiRequestMethod.PUT:
                case ApiRequestMethod.PATCH:
                    //检查是否为空
                    if (checkDataNotNull)
                    {
                        _ = data ?? throw new ArgumentNullException($"{nameof(data)} 不能为 null!");
                    }

                    //设置请求 Json 字符串
                    //var jsonString = SerializerHelper.GetJsonString(data, new CO2NET.Helpers.Serializers.JsonSetting(true));
                    string jsonString = data != null
                            ? data.ToJson(false, new Newtonsoft.Json.JsonSerializerSettings()
                    {
                        NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore
                    })
                            : "";

                    WeixinTrace.SendApiPostDataLog(url, jsonString);     //记录Post的Json数据

                    //设置 HttpContent
                    var hc = new StringContent(jsonString, Encoding.UTF8, mediaType: "application/json");
                    //获取响应结果
                    responseMessage = requestMethod switch
                    {
                        ApiRequestMethod.POST => await client.PostAsync(url, hc),
                        ApiRequestMethod.PUT => await client.PutAsync(url, hc),
                        ApiRequestMethod.PATCH => await client.PatchAsync(url, hc),
                        _ => throw new ArgumentOutOfRangeException(nameof(requestMethod))
                    };
                    break;

                default:
                    throw new ArgumentOutOfRangeException(nameof(requestMethod));
                }

                return(responseMessage);
            }
            catch (Exception)
            {
                throw;
            }
        }
        public async Task <ActionResult> Post(PostModel postModel)
        {
            /* 异步请求请见 WeixinAsyncController(推荐) */

/*            if (!CheckSignature.Check(postModel.Signature, postModel.Timestamp, postModel.Nonce, Token))
 *          {
 *              return Content("参数错误!");
 *          }*/

            #region 打包 PostModel 信息

            postModel.Token          = Token;          //根据自己后台的设置保持一致
            postModel.EncodingAESKey = EncodingAESKey; //根据自己后台的设置保持一致
            postModel.AppId          = AppId;          //根据自己后台的设置保持一致(必须提供)

            #endregion

            //v4.2.2之后的版本,可以设置每个人上下文消息储存的最大数量,防止内存占用过多,如果该参数小于等于0,则不限制(实际最大限制 99999)
            //注意:如果使用分布式缓存,不建议此值设置过大,如果需要储存历史信息,请使用数据库储存
            var maxRecordCount = 10;

            //自定义MessageHandler,对微信请求的详细判断操作都在这里面。

            MemoryStream stream = new MemoryStream();
            await Request.Body.CopyToAsync(stream);

            //var messageHandler1 = new CustomMessageHandler(Request.Body, postModel, maxRecordCount);
            var messageHandler = new CustomMessageHandler(stream, postModel, maxRecordCount); //在这里走消息流程,断点自己看



            #region 设置消息去重设置

            /* 如果需要添加消息去重功能,只需打开OmitRepeatedMessage功能,SDK会自动处理。
             * 收到重复消息通常是因为微信服务器没有及时收到响应,会持续发送2-5条不等的相同内容的 RequestMessage */
            messageHandler.OmitRepeatedMessage = true;//默认已经是开启状态,此处仅作为演示,也可以设置为 false 在本次请求中停用此功能

            #endregion

            try
            {
                messageHandler.SaveRequestMessageLog();//记录 Request 日志(可选)

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

                //这里调用WeCHatHub类的send方法建立SignalR管道,前端-服务器-微信(CustomApi发送客服消息,白名单),微信-服务器-前端(Post)要用同个hub实例管道对象


                //拿到请求消息内容
                var textMessageFromWeixin = messageHandler.RequestMessage as RequestMessageText; //仿照写法,自己搜
                                                                                                 //把 contentFromWeixin 放到 SignalR 管道中(SingleHub),再由管道发送到前端显示
                                                                                                 //body.CustomMessageFromWeixin = contentFromWeixin;

                //赋给SingleHub管道里的字段,构建顾客消息对象
                //body.CustomMessageFromWeixin = contentFromWeixin;
                #region 该方法获得的数据

                /*
                 * 1、ToUserName     公众号AppId
                 * 2、FromUserName   发送方帐号(一个OpenID)
                 * 3、CreateTime	    消息创建时间 (整型)
                 * 4、MsgType	    消息类型,文本为text
                 * 5、Content	    文本消息内容
                 * 6、MsgId	        消息id,64位整型
                 */
                #endregion

                #region 发到前端需要的数据

                /*
                 * 由于发信息给微信不经过这里,所以只负责处理来自微信的消息
                 * 发到前端需要的数据,
                 * 1、公众号(Name) ToUserName(AppId)
                 * 2、客户信息(Name) FromUserName(OpenId) (间接获得)
                 * 3、客服信息(Name) OrchardCore.User (间接获得)
                 * 4、消息体    Content
                 * 5、创建时间  Create
                 */
                #endregion


                var contentFromWeixin = textMessageFromWeixin.Content;
                var gzhAppId          = textMessageFromWeixin.ToUserName;   //开发者微信号,这里该执行根据AppId查公众号名
                var FromUserOpenId    = textMessageFromWeixin.FromUserName; //发送发账号,OpenId,后善:这里该执行根据OpenId查询微信用户信息,存储到数据库
                var CreateTime        = textMessageFromWeixin.CreateTime;   //DateTimeOffset 类型
                var MsgType           = textMessageFromWeixin.MsgType;      //消息类型,用于判断执行的处理方法
                var MsgId             = textMessageFromWeixin.MsgId;        //消息id,64位,用于区分消息记录
                //该条信息记录对象存储到数据库

                var username = "******";
                body.ToUserName   = "******";       //1、设定发给的公众号,后善:查WeChatMP表根据AppId获取Name
                body.FromUserName = username;          //2、设定消息来自的人,即客户,后善:改根据OpenId获取客户的微信用户信息的Name,这需存储用户信息到数据库
                body.ToKefuName   = "客服1号";            //3、设定消息发给谁,即客服,后善:获取客服集合队伍,出栈,获取客服Id(OrchardUserId),根据Id获取客服Name
                body.Content      = contentFromWeixin; //4、消息体
                body.CreateTime   = CreateTime;        //5、创建时间 ,完成

                body.TextName = username;              //设定显示在前端当前发信息的人,在该方法时,为微信的客户

                //在Controller里使用管道输送
                await _hubContext.Clients.All.SendAsync("Recv", body);

                //张磊提到的使用静态类方法创建同一个实例调用
                //await Classhub.asd.All.SendAsync("Recv", body);

                //hub.Send(body);
                messageHandler.SaveResponseMessageLog();//记录 Response 日志(可选)

                //return Content(messageHandler.ResponseDocument.ToString());//v0.7-
                //return new WeixinResult(messageHandler);//v0.8+
                return(new FixWeixinBugWeixinResult(messageHandler));//为了解决官方微信5.0软件换行bug暂时添加的方法,平时用下面一个方法即可
            }
            catch (Exception ex)
            {
                #region 异常处理
                WeixinTrace.Log("MessageHandler错误:{0}", ex.Message);

                using (TextWriter tw = new StreamWriter(ServerUtility.ContentRootMapPath("~/App_Data/Error_" + _getRandomFileName() + ".txt")))
                {
                    tw.WriteLine("ExecptionMessage:" + ex.Message);
                    tw.WriteLine(ex.Source);
                    tw.WriteLine(ex.StackTrace);
                    //tw.WriteLine("InnerExecptionMessage:" + ex.InnerException.Message);

                    if (messageHandler.ResponseDocument != null)
                    {
                        tw.WriteLine(messageHandler.ResponseDocument.ToString());
                    }

                    if (ex.InnerException != null)
                    {
                        tw.WriteLine("========= InnerException =========");
                        tw.WriteLine(ex.InnerException.Message);
                        tw.WriteLine(ex.InnerException.Source);
                        tw.WriteLine(ex.InnerException.StackTrace);
                    }

                    tw.Flush();
                    tw.Close();
                }
                return(Content(""));

                #endregion
            }
        }
Ejemplo n.º 12
0
        public ActionResult Post(PostModel postModel /*,[FromBody]string requestXml*/)
        {
            if (!CheckSignature.Check(postModel.Signature, postModel.Timestamp, postModel.Nonce, token))
            {
                return(Content("参数错误!"));
            }

            #region 打包 PostModel 信息

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

            #endregion

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

            //自定义MessageHandler,对微信请求的详细判断操作都在这里面。

#if NET45
            var messageHandler = new CustomMessageHandler(Request.InputStream, postModel, maxRecordCount);
#else
            string body        = new StreamReader(Request.Body).ReadToEnd();
            byte[] requestData = Encoding.UTF8.GetBytes(body);
            Stream inputStream = new MemoryStream(requestData);

            //var inputStream = Request.Body;
            //byte[] buffer = new byte[Request.ContentLength ?? 0];
            //inputStream.Read(buffer, 0, buffer.Length);
            //var requestXmlStream = new MemoryStream(buffer);
            //var requestXml = Encoding.UTF8.GetString(buffer);


            //int bytesRead = 0;
            //while ((bytesRead = Request.Body.Read(buffer, 0, buffer.Length)) != 0)
            //{
            //    inputStream.Write(buffer, 0, bytesRead);
            //}

            //Request.Body.CopyTo(inputStream);

            var messageHandler = new CustomMessageHandler(inputStream, postModel, maxRecordCount);
#endif

            try
            {
                #region 记录 Request 日志

                var logPath = Server.GetMapPath(string.Format("~/App_Data/MP/{0}/", DateTime.Now.ToString("yyyy-MM-dd")));
                if (!Directory.Exists(logPath))
                {
                    Directory.CreateDirectory(logPath);
                }

                //测试时可开启此记录,帮助跟踪数据,使用前请确保App_Data文件夹存在,且有读写权限。

                var requestDocumentFileName       = Path.Combine(logPath, string.Format("{0}_Request_{1}.txt", _getRandomFileName(), messageHandler.RequestMessage.FromUserName));
                var ecryptRequestDocumentFileName = Path.Combine(logPath, string.Format("{0}_Request_Ecrypt_{1}.txt", _getRandomFileName(), messageHandler.RequestMessage.FromUserName));
#if NET45
                messageHandler.RequestDocument.Save(requestDocumentFileName);
                if (messageHandler.UsingEcryptMessage)
                {
                    messageHandler.EcryptRequestDocument.Save(ecryptRequestDocumentFileName);
                }
#else
                using (FileStream fs = new FileStream(requestDocumentFileName, FileMode.CreateNew, FileAccess.ReadWrite))
                {
                    messageHandler.RequestDocument.Save(fs);
                }
                if (messageHandler.UsingEcryptMessage)
                {
                    using (FileStream fs = new FileStream(ecryptRequestDocumentFileName, FileMode.CreateNew, FileAccess.ReadWrite))
                    {
                        messageHandler.EcryptRequestDocument.Save(fs);
                    }
                }
#endif


                #endregion

                /* 如果需要添加消息去重功能,只需打开OmitRepeatedMessage功能,SDK会自动处理。
                 * 收到重复消息通常是因为微信服务器没有及时收到响应,会持续发送2-5条不等的相同内容的RequestMessage*/
                messageHandler.OmitRepeatedMessage = true;

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

                #region 记录 Response 日志

                //测试时可开启,帮助跟踪数据

                //if (messageHandler.ResponseDocument == null)
                //{
                //    throw new Exception(messageHandler.RequestDocument.ToString());
                //}

                var responseDocumentFileName       = Path.Combine(logPath, string.Format("{0}_Response_{1}.txt", _getRandomFileName(), messageHandler.RequestMessage.FromUserName));
                var ecryptResponseDocumentFileName = Path.Combine(logPath, string.Format("{0}_Response_Final_{1}.txt", _getRandomFileName(), messageHandler.RequestMessage.FromUserName));

                if (messageHandler.ResponseDocument != null)
                {
                    using (FileStream fs = new FileStream(responseDocumentFileName, FileMode.CreateNew, FileAccess.ReadWrite))
                    {
                        messageHandler.ResponseDocument.Save(fs);
                    }
                }

                if (messageHandler.UsingEcryptMessage && messageHandler.FinalResponseDocument != null)
                {
                    using (FileStream fs = new FileStream(ecryptResponseDocumentFileName, FileMode.CreateNew, FileAccess.ReadWrite))
                    {
                        //记录加密后的响应信息
                        messageHandler.FinalResponseDocument.Save(fs);
                    }
                }

                #endregion `

                //return Content(messageHandler.ResponseDocument.ToString());//v0.7-
                //return new WeixinResult(messageHandler);//v0.8+
                return(new FixWeixinBugWeixinResult(messageHandler));//为了解决官方微信5.0软件换行bug暂时添加的方法,平时用下面一个方法即可
            }
            catch (Exception ex)
            {
                #region 异常处理
                WeixinTrace.Log("MessageHandler错误:{0}", ex.Message);


                using (var fs = new FileStream(Server.GetMapPath("~/App_Data/Error_" + _getRandomFileName() + ".txt"), FileMode.CreateNew, FileAccess.ReadWrite))
                {
                    using (TextWriter tw = new StreamWriter(fs))
                    {
                        tw.WriteLine("ExecptionMessage:" + ex.Message);
                        tw.WriteLine(ex.Source);
                        tw.WriteLine(ex.StackTrace);
                        //tw.WriteLine("InnerExecptionMessage:" + ex.InnerException.Message);

                        if (messageHandler.ResponseDocument != null)
                        {
                            tw.WriteLine(messageHandler.ResponseDocument.ToString());
                        }

                        if (ex.InnerException != null)
                        {
                            tw.WriteLine("========= InnerException =========");
                            tw.WriteLine(ex.InnerException.Message);
                            tw.WriteLine(ex.InnerException.Source);
                            tw.WriteLine(ex.InnerException.StackTrace);
                        }

                        tw.Flush();
                        //tw.Close();
                    }
                }
                return(Content(""));

                #endregion
            }
        }
Ejemplo n.º 13
0
        public ActionResult Post(PostModel postModel)
        {
            if (!CheckSignature.Check(postModel.Signature, postModel.Timestamp, postModel.Nonce, token))
            {
                return(Content("参数错误!"));
            }

            #region 打包 PostModel 信息

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

            #endregion

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

            //自定义MessageHandler,对微信请求的详细判断操作都在这里面。
            MessageHandler <CustomMessageContext> messageHandler;
            var messageHandlerType = WeiXinConfiguration.WeiXinMessageHandlerType;
            if (messageHandlerType != null)
            {
                messageHandler = Activator.CreateInstance(messageHandlerType, Request.GetRequestMemoryStream(), postModel, maxRecordCount) as MessageHandler <CustomMessageContext>;
            }
            else
            {
                messageHandler = new CustomMessageHandler(Request.GetRequestMemoryStream(), postModel, maxRecordCount);
            }


            #region 设置消息去重

            /* 如果需要添加消息去重功能,只需打开OmitRepeatedMessage功能,SDK会自动处理。
             * 收到重复消息通常是因为微信服务器没有及时收到响应,会持续发送2-5条不等的相同内容的RequestMessage*/
            messageHandler.OmitRepeatedMessage = true;//默认已经开启,此处仅作为演示,也可以设置为false在本次请求中停用此功能

            #endregion

            try
            {
                #region 记录 Request 日志
                //var logPath = Server.GetMapPath(string.Format("~/App_Data/MP/{0}/", DateTime.Now.ToString("yyyy-MM-dd")));
                //if (!Directory.Exists(logPath))
                //{
                //    Directory.CreateDirectory(logPath);
                //}

                ////测试时可开启此记录,帮助跟踪数据,使用前请确保App_Data文件夹存在,且有读写权限。
                //messageHandler.RequestDocument.Save(Path.Combine(logPath, string.Format("{0}_Request_{1}_{2}.txt", _getRandomFileName(),
                //    messageHandler.RequestMessage.FromUserName,
                //    messageHandler.RequestMessage.MsgType)));
                //if (messageHandler.UsingEcryptMessage)
                //{
                //    messageHandler.EcryptRequestDocument.Save(Path.Combine(logPath, string.Format("{0}_Request_Ecrypt_{1}_{2}.txt", _getRandomFileName(),
                //        messageHandler.RequestMessage.FromUserName,
                //        messageHandler.RequestMessage.MsgType)));
                //}
                Logger.Info($"WeChat Request Message:{messageHandler.RequestMessage.FromUserName},{messageHandler.RequestMessage.MsgType}");

                #endregion

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

                #region 记录 Response 日志

                //测试时可开启,帮助跟踪数据

                //if (messageHandler.ResponseDocument == null)
                //{
                //    throw new Exception(messageHandler.RequestDocument.ToString());
                //}
                //if (messageHandler.ResponseDocument != null)
                //{
                //    messageHandler.ResponseDocument.Save(Path.Combine(logPath, string.Format("{0}_Response_{1}_{2}.txt", _getRandomFileName(),
                //        messageHandler.ResponseMessage.ToUserName,
                //        messageHandler.ResponseMessage.MsgType)));
                //}

                //if (messageHandler.UsingEcryptMessage && messageHandler.FinalResponseDocument != null)
                //{
                //    记录加密后的响应信息
                //    messageHandler.FinalResponseDocument.Save(Path.Combine(logPath, string.Format("{0}_Response_Final_{1}_{2}.txt", _getRandomFileName(),
                //        messageHandler.ResponseMessage.ToUserName,
                //        messageHandler.ResponseMessage.MsgType)));
                //}
                Logger.Info($"WeChat Response Message:{messageHandler.ResponseMessage.ToUserName},{messageHandler.ResponseMessage.MsgType}");
                #endregion

                return(Content(messageHandler.ResponseDocument.ToString()));//v0.7-
                //return new WeixinResult(messageHandler);//v0.8+
                //return new FixWeixinBugWeixinResult(messageHandler);//为了解决官方微信5.0软件换行bug暂时添加的方法,平时用下面一个方法即可
            }
            catch (Exception ex)
            {
                #region 异常处理
                WeixinTrace.Log("MessageHandler错误:{0}", ex.Message);
                Logger.Error("MessageHandler错误:" + ex.Message, ex);

                return(Content(""));

                #endregion
            }
        }
Ejemplo n.º 14
0
        public ActionResult Post(PostModel postModel)
        {
            //WeixinTrace.Log("请求到达(Post),数据包:" + postModel.TryToJson());
            logHelper.Info("请求到达(Post),数据包:" + postModel.TryToJson());

            if (!CheckSignature.Check(postModel.Signature, postModel.Timestamp, postModel.Nonce, Token))
            {
                return(Content("参数错误!"));
            }

            if (_wechatConfig == null)
            {
                string orgId = ConfigHelper.GetValue("OrgId");
                _wechatConfig = wechatConfigBll.GetEntityByOrgId(orgId);

                logHelper.Info("微信配置信息:" + _wechatConfig.TryToJson());
            }

            if (_wechatConfig != null)
            {
                #region 打包 PostModel 信息

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

                #endregion

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

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

                #region 设置消息去重

                /* 如果需要添加消息去重功能,只需打开OmitRepeatedMessage功能,SDK会自动处理。
                 * 收到重复消息通常是因为微信服务器没有及时收到响应,会持续发送2-5条不等的相同内容的RequestMessage*/
                messageHandler.OmitRepeatedMessage = true; //默认已经开启,此处仅作为演示,也可以设置为false在本次请求中停用此功能

                #endregion

                try
                {
                    //messageHandler.SaveRequestMessageLog(); //记录 Request 日志(可选)
                    #region 记录 Request 日志

                    var logPath = Server.MapPath(string.Format("~/App_Data/MP/{0}/", DateTime.Now.ToString("yyyy-MM-dd")));
                    if (!Directory.Exists(logPath))
                    {
                        Directory.CreateDirectory(logPath);
                    }

                    //测试时可开启此记录,帮助跟踪数据,使用前请确保App_Data文件夹存在,且有读写权限。
                    messageHandler.RequestDocument.Save(Path.Combine(logPath, string.Format("{0}_Request_{1}_{2}.txt", _getRandomFileName(),
                                                                                            messageHandler.RequestMessage.FromUserName,
                                                                                            messageHandler.RequestMessage.MsgType)));
                    if (messageHandler.UsingEcryptMessage)
                    {
                        messageHandler.EcryptRequestDocument.Save(Path.Combine(logPath, string.Format("{0}_Request_Ecrypt_{1}_{2}.txt", _getRandomFileName(),
                                                                                                      messageHandler.RequestMessage.FromUserName,
                                                                                                      messageHandler.RequestMessage.MsgType)));
                    }

                    #endregion

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

                    //messageHandler.SaveResponseMessageLog(); //记录 Response 日志(可选)
                    #region 记录 Response 日志

                    //测试时可开启,帮助跟踪数据

                    //if (messageHandler.ResponseDocument == null)
                    //{
                    //    throw new Exception(messageHandler.RequestDocument.ToString());
                    //}
                    if (messageHandler.ResponseDocument != null)
                    {
                        messageHandler.ResponseDocument.Save(Path.Combine(logPath, string.Format("{0}_Response_{1}_{2}.txt", _getRandomFileName(),
                                                                                                 messageHandler.ResponseMessage.ToUserName,
                                                                                                 messageHandler.ResponseMessage.MsgType)));
                    }

                    if (messageHandler.UsingEcryptMessage && messageHandler.FinalResponseDocument != null)
                    {
                        //记录加密后的响应信息
                        messageHandler.FinalResponseDocument.Save(Path.Combine(logPath, string.Format("{0}_Response_Final_{1}_{2}.txt", _getRandomFileName(),
                                                                                                      messageHandler.ResponseMessage.ToUserName,
                                                                                                      messageHandler.ResponseMessage.MsgType)));
                    }

                    #endregion

                    //return Content(messageHandler.ResponseDocument.ToString());//v0.7-
                    //return new WeixinResult(messageHandler);//v0.8+
                    return(new FixWeixinBugWeixinResult(messageHandler)); //为了解决官方微信5.0软件换行bug暂时添加的方法,平时用下面一个方法即可
                }
                catch (Exception ex)
                {
                    WeixinTrace.Log(string.Format("MessageHandler错误:{0}", ex.Message));
                    return(Content(""));
                }
            }
            else
            {
                return(Content("未找到当前机构微信配置信息!"));
            }
        }