public void ProcessRequest(HttpContext context) { string signature = context.Request["signature"]; string nonce = context.Request["nonce"]; string timestamp = context.Request["timestamp"]; string echostr = context.Request["echostr"]; if (context.Request.HttpMethod == "GET") { if (CheckSignature.Check(signature, timestamp, nonce)) { context.Response.Write(echostr); } } else { //if (!CheckSignature.Check(signature, timestamp, nonce)) //{ // context.Response.Write("参数错误"); // context.Response.End(); //} var maxRecordCount = 10; var messageHandler = new CustomMessageHandler(context.Request.InputStream, maxRecordCount); try { messageHandler.RequestDocument.Save(context.Server.MapPath("~/" + DateTime.Now.Ticks + "-" + messageHandler.RequestMessage.MsgType + ".txt")); messageHandler.Execute(); messageHandler.ResponseDocument.Save(context.Server.MapPath("~/" + DateTime.Now.Ticks + "-" + messageHandler.ResponseMessage.ToUserName + ".txt")); context.Response.Write(messageHandler.ResponseDocument.ToString().Replace("<?xml version=\"1.0\" encoding=\"utf - 8\"?>", "")); } catch (Exception ex) { using (TextWriter tw = new StreamWriter(context.Server.MapPath("~/" + DateTime.Now.Ticks + ".txt"))) { tw.WriteLine(ex.Message); tw.WriteLine(ex.InnerException.Message); if (messageHandler.ResponseDocument != null) { tw.WriteLine(messageHandler.ResponseDocument.ToString()); } tw.Flush(); tw.Close(); } } finally { context.Response.End(); } } }
protected void Page_Load(object sender, EventArgs e) { string signature = Request.Form["signature"].IsNullOrEmpty() ? Request["signature"] : Request.Form["signature"]; string timestamp = Request.Form["timestamp"].IsNullOrEmpty() ? Request["timestamp"] : Request.Form["timestamp"]; string nonce = Request.Form["nonce"].IsNullOrEmpty() ? Request["nonce"] : Request.Form["nonce"]; string echostr = Request.Form["echostr"].IsNullOrEmpty() ? Request["echostr"] : Request.Form["echostr"]; //Log.Default.Debug(Request.ServerVariables["REQUEST_METHOD"]); //Log.Default.Debug("========api-begin======"); //Log.Default.Debug("signature:" + signature); //Log.Default.Debug("timestamp:" + timestamp); //Log.Default.Debug("nonce:" + nonce); //Log.Default.Debug("echostr:" + echostr); //Log.Default.Debug("========api-end========"); if (Request.ServerVariables["REQUEST_METHOD"] == "POST") { if (!CheckSignature.Check(signature, timestamp, nonce, ConfigurationManager.AppSettings["BindToken"])) { Response.Write("参数错误!"); } //自定义MessageHandler,对微信请求的详细判断操作都在这里面。 var messageHandler = new CustomMessageHandler(Request.InputStream); try { messageHandler.Execute(); messageHandler.ResponseDocument.Save(Response.OutputStream); } catch (Exception ex) { Log.Default.Error(ex); } finally { Response.End(); } } else { string res = ""; if (CheckSignature.Check(signature, timestamp, nonce, ConfigurationManager.AppSettings["BindToken"])) { res = echostr; } else { //Response.Write("failed:" + signature + "," + CheckSignature.GetSignature(timestamp, nonce, ConfigurationManager.AppSettings["OAuthAppSercet"]) + "。如果您在浏览器中看到这条信息,表明此Url可以填入微信后台。"); res = "failed:" + signature + "," + CheckSignature.GetSignature(timestamp, nonce, ConfigurationManager.AppSettings["BindToken"]) + "。如果您在浏览器中看到这条信息,表明此Url可以填入微信后台。"; } //Log.Default.Debug("CheckSignature.Check:" + res); Response.Write(res); Response.End(); } }
public IResponseMessageBase GetPromotion(CustomMessageHandler handler) { var rsp = handler.CreateResponseMessage<ResponseMessageNews>(); rsp.Articles.Add(new Article() { Title = "您点击了子菜单图文按钮", Description = "您点击了子菜单图文按钮,这是一条图文信息。", PicUrl = "http://weixin.senparc.com/Images/qrcode.jpg", Url = "http://weixin.senparc.com" }); return rsp; }
public IResponseMessageBase GetCoIntro(CustomMessageHandler handler) { var rsp = handler.CreateResponseMessage<ResponseMessageNews>(); rsp.Articles.Add(new Article() { Title = "公司介绍", Description = "中国人民人寿保险股份有限公司和路华救援(北京)有限公司合作进行旅行保险的服务...", PicUrl = "http://www.epicc.com.cn/ymdblm/db_gyrb/201205/W020120710544945374543.jpg", Url = "http://travel.e-picclife.com/m/aboutus.aspx" }); return rsp; // }
public ActionResult Post(PostModel postModel) { if (!CheckSignature.Check(postModel.Signature, postModel.Timestamp, postModel.Nonce, Token)) { return Content("参数错误!"); } postModel.Token = Token; postModel.EncodingAESKey = EncodingAESKey; postModel.AppId = AppId; var messageHandler = new CustomMessageHandler(Request.InputStream, postModel); messageHandler.Execute(); return new WeixinResult(messageHandler); }
public IResponseMessageBase GetClalmProfile(CustomMessageHandler handler) { var rsp = handler.CreateResponseMessage<ResponseMessageNews>(); rsp.Articles.Add(new Article() { Title = "理赔资料", Description = "如果您有任何的疑问和意见,欢迎和我们联系!", PicUrl = "http://travel.e-picclife.com/m/_imgs_v2/paris/banner_contactus.jpg", Url = "http://travel.e-picclife.com/m/contactus.aspx" }); rsp.Articles.Add(new Article() { Title = "理赔资料-理赔资料A", Description = "如果您有任何的疑问和意见,欢迎和我们联系!", PicUrl = "http://travel.e-picclife.com/m/_imgs_v2/paris/banner_contactus.jpg", Url = "http://travel.e-picclife.com/m/contactus.aspx" }); rsp.Articles.Add(new Article() { Title = "理赔资料-理赔资料B", Description = "如果您有任何的疑问和意见,欢迎和我们联系!", PicUrl = "http://travel.e-picclife.com/m/_imgs_v2/paris/banner_contactus.jpg", Url = "http://travel.e-picclife.com/m/contactus.aspx" }); rsp.Articles.Add(new Article() { Title = "理赔资料-理赔资料C", Description = "如果您有任何的疑问和意见,欢迎和我们联系!", PicUrl = "http://travel.e-picclife.com/m/_imgs_v2/paris/banner_contactus.jpg", Url = "http://travel.e-picclife.com/m/contactus.aspx" }); rsp.Articles.Add(new Article() { Title = "理赔资料-理赔资料D", Description = "如果您有任何的疑问和意见,欢迎和我们联系!", PicUrl = "http://travel.e-picclife.com/m/_imgs_v2/paris/banner_contactus.jpg", Url = "http://travel.e-picclife.com/m/contactus.aspx" }); return rsp; }
public async Task should_not_be_able_to_pick_invalid_node(ClusterMessages.VNodeState invalidState) { var gossip = new ClusterMessages.ClusterInfo { Members = new[] { new ClusterMessages.MemberInfo { State = invalidState, InstanceId = Guid.NewGuid(), HttpEndPointAddress = IPAddress.Any.ToString(), HttpEndPointPort = 4444, IsAlive = true, }, } }; var handler = new CustomMessageHandler(req => { _fixture.CurrentClusterInfo.Members = gossip.Members; }); var sut = new ClusterEndpointDiscoverer(1, new[] { new DnsEndPoint(_fixture.Host, _fixture.Port), }, Timeout.InfiniteTimeSpan, TimeSpan.Zero, NodePreference.Leader, handler); await Assert.ThrowsAsync <DiscoveryException>(() => sut.DiscoverAsync()); }
public ActionResult Post(PostModel postModel) { if (!CheckSignature.Check(postModel.Signature, postModel.Timestamp, postModel.Nonce, Token)) { return(Content("参数错误!")); } postModel.Token = Token; //根据自己后台的设置保持一致 postModel.EncodingAESKey = EncodingAESKey; //根据自己后台的设置保持一致 postModel.AppId = AppId; //根据自己后台的设置保持一致 //自定义MessageHandler,对微信请求的详细判断操作都在这里面。 //获取request的响应 var memoryStream = new MemoryStream(); Request.Body.CopyTo(memoryStream); var messageHandler = new CustomMessageHandler(memoryStream, postModel); //接收消息 messageHandler.Execute(); //执行微信处理过程 return(new FixWeixinBugWeixinResult(messageHandler)); }
public ActionResult Post(string signature, string timestamp, string nonce, string echostr) { if (!CheckSignature.Check(signature, timestamp, nonce, Token)) { return(Content("参数错误!")); } //自定义MessageHandler,对微信请求的详细判断操作都在这里面。 var messageHandler = new CustomMessageHandler(Request.InputStream); try { //测试时可开启此记录,帮助跟踪数据 messageHandler.RequestDocument.Save(Server.MapPath("~/App_Data/" + DateTime.Now.Ticks + "_Request_" + messageHandler.RequestMessage.FromUserName + ".txt")); //执行微信处理过程 messageHandler.Execute(); //测试时可开启,帮助跟踪数据 messageHandler.ResponseDocument.Save(Server.MapPath("~/App_Data/" + DateTime.Now.Ticks + "_Response_" + messageHandler.ResponseMessage.ToUserName + ".txt")); return(Content(messageHandler.ResponseDocument.ToString())); } catch (Exception ex) { using (TextWriter tw = new StreamWriter(Server.MapPath("~/App_Data/Error_" + DateTime.Now.Ticks + ".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()); } tw.Flush(); tw.Close(); } return(Content("")); } }
public ActionResult Index(PostModel pmodel) { Log.Info("≤============", null, null); Log.Info("服务器", "POST握手一次", null); if (!CheckSignature.Check(pmodel.Signature, pmodel.Timestamp, pmodel.Nonce, Token)) { Log.Info("服务器", "参数错误!", null); return(Content("参数错误!")); } pmodel.Token = Token; pmodel.EncodingAESKey = EncodingAesKey; //根据自己后台的设置保持一致 pmodel.AppId = AppId; //根据自己后台的设置保持一致 var messageHandler = new CustomMessageHandler(Request.InputStream, pmodel); //接收消息(第一步) try { messageHandler.Execute(); //执行微信处理过程(第二步) if (messageHandler.ResponseMessage != null) { Log.Info("Execute:执行微信处理过程", "\r\n" + messageHandler.ResponseDocument.ToString(), "running..."); return(Content(messageHandler.ResponseDocument.ToString())); return(new FixWeixinBugWeixinResult(messageHandler)); //返回(第三步) } } catch (Exception e) { Log.Info("Execute:执行微信处理过程", e.Message, "Exception"); throw; } finally { Log.Info("============≥", null, null); } return(new FixWeixinBugWeixinResult(messageHandler));//返回(第三步) }
public ActionResult Index(PostModel postModel) { if (!CheckSignature.Check(postModel.Signature, postModel.Timestamp, postModel.Nonce, Senparc.Weixin.Config.DefaultSenparcWeixinSetting.Token)) { return(Content("参数错误!")); } postModel.Token = Senparc.Weixin.Config.DefaultSenparcWeixinSetting.Token; //根据自己后台的设置保持一致 postModel.EncodingAESKey = Senparc.Weixin.Config.DefaultSenparcWeixinSetting.EncodingAESKey; //根据自己后台的设置保持一致 postModel.AppId = Senparc.Weixin.Config.DefaultSenparcWeixinSetting.WeixinAppId; //根据自己后台的设置保持一致 //自定义MessageHandler,对微信请求的详细判断操作都在这里面。 //获取request的响应 var memoryStream = new MemoryStream(); Request.Body.CopyTo(memoryStream); var messageHandler = new CustomMessageHandler(memoryStream, postModel, _hostingEnvironment.WebRootPath); //接收消息 messageHandler.Execute(); //执行微信处理过程 //return new WeixinResult(messageHandler); return(new FixWeixinBugWeixinResult(messageHandler)); //返回结果 }
public ActionResult MiniPost(PostModel postModel) { if (!CheckSignature.Check(postModel.Signature, postModel.Timestamp, postModel.Nonce, Token)) { //return Content("参数错误!");//v0.7- return(new WeixinResult("参数错误!"));//v0.8+ } postModel.Token = Token; postModel.EncodingAESKey = EncodingAESKey; //根据自己后台的设置保持一致 postModel.AppId = AppId; //根据自己后台的设置保持一致 var stream = this.HttpContext.Request.Body; XDocument doc = XDocument.Load(stream); var messageHandler = new CustomMessageHandler(doc, postModel, 10); messageHandler.Execute();//执行微信处理过程 //return Content(messageHandler.ResponseDocument.ToString());//v0.7- return(new FixWeixinBugWeixinResult(messageHandler));//v0.8+ //return new WeixinResult(messageHandler);//v0.8+ }
public ActionResult MiniPost(PostModel postModel) { var weixinInfo = GetWeixinApp(postModel.Signature, postModel.Timestamp, postModel.Nonce); if (weixinInfo == null) { //return Content("参数错误!");//v0.7- return(new WeixinResult("参数错误!"));//v0.8+ } postModel.Token = weixinInfo.AppToken; postModel.EncodingAESKey = weixinInfo.AppEncodingAESKey; //根据自己后台的设置保持一致 postModel.AppId = weixinInfo.AppId; //根据自己后台的设置保持一致 var messageHandler = new CustomMessageHandler(Request.InputStream, postModel, 10); messageHandler.Execute();//执行微信处理过程 //return Content(messageHandler.ResponseDocument.ToString());//v0.7- //return new WeixinResult(messageHandler);//v0.8+ return(new FixWeixinBugWeixinResult(messageHandler));//v0.8+ }
public ActionResult MiniPost(PostModel postModel) { if (!CheckSignature.Check(postModel.Signature, postModel.Timestamp, postModel.Nonce, Token)) { //return Content("参数错误!");//v0.7- return(new WeixinResult("参数错误!"));//v0.8+ } postModel.Token = Token; postModel.EncodingAESKey = EncodingAESKey; //根据自己后台的设置保持一致 postModel.AppId = AppId; //根据自己后台的设置保持一致 var messageHandler = new CustomMessageHandler(Request.InputStream, postModel, 10); messageHandler.Execute();//执行微信处理过程 //return Content(messageHandler.ResponseDocument.ToString());//v0.7- //return new WeixinResult(messageHandler);//v0.8+ var result = new FixWeixinBugWeixinResult(messageHandler);//v0.8+ return(result); }
public async Task DocumentClient_BuildHttpClientFactory_WithHandler() { HttpMessageHandler messageHandler = new CustomMessageHandler(); ConnectionPolicy connectionPolicy = new ConnectionPolicy() { HttpClientFactory = () => new HttpClient(messageHandler) }; CosmosHttpClient httpClient = CosmosHttpClientCore.CreateWithConnectionPolicy( apiType: ApiType.None, eventSource: DocumentClientEventSource.Instance, connectionPolicy: connectionPolicy, httpMessageHandler: null, sendingRequestEventArgs: null, receivedResponseEventArgs: null); Assert.IsNotNull(httpClient); HttpResponseMessage response = await httpClient.GetAsync( uri : new Uri("https://localhost"), additionalHeaders : new DictionaryNameValueCollection(), resourceType : ResourceType.Document, diagnosticsContext : null, cancellationToken : default);
string WeixinEncodingAESKey = ConfigurationManager.AppSettings["WeixinEncodingAESKey"];//消息加密密锁 protected void Page_Load(object sender, EventArgs e) { //post method - 当有用户想公众账号发送消息时触发 var postModel = new PostModel() { Signature = Request.QueryString["signature"], Msg_Signature = Request.QueryString["msg_signature"], Timestamp = Request.QueryString["timestamp"], Nonce = Request.QueryString["nonce"], //以下保密信息不会(不应该)在网络上传播,请注意 Token = Token, EncodingAESKey = WeixinEncodingAESKey, // "mNnY5GekpChwqhy2c4NBH90g3hND6GeI4gii2YCvKLY",//根据自己后台的设置保持一致 AppId = WeixinAppId // "wx669ef95216eef885"//根据自己后台的设置保持一致 }; var maxRecordCount = 10; var messageHandler = new CustomMessageHandler(Request.InputStream, postModel, maxRecordCount); //string access_token = Senparc.Weixin.MP.Containers.AccessTokenContainer.TryGetAccessToken(WeixinAppId, WeixinAppSecret); //LogTextHelper_x.Info("特别的你access_token是:" + access_token); messageHandler.RequestDocument.Save( Server.MapPath("~/App_Data/" + DateTime.Now.Ticks + "_Request_" + messageHandler.RequestMessage.FromUserName + ".txt")); //string wxAppid = ConfigurationManager.AppSettings["WeixinAppid"];// //Response.Write("<br/>应该跳转才对"); //string temp1 = OAuthApi.GetAuthorizeUrl(wxAppid, "http://www.dq006.com/sq_add.aspx", "a_z", Senparc.Weixin.MP.OAuthScope.snsapi_userinfo); ////Response.Write("<br/>地址为:"+temp1); ////HttpContext.Current.Response.Redirect(temp1); //Response.Redirect(temp1); }
public void DoResponse(HttpRequest request, HttpResponse response) { string token = ConfigHelper.AppConfig["token"]; string signature = request.Params["signature"]; string nonce = request.Params["nonce"]; string timestamp = request.Params["timestamp"]; string echostr = request.Params["echostr"]; response.ContentType = "text/html;charset=utf-8"; //返回随机字符串则表示验证通过 var checkResult = CheckSignature.Check(signature, timestamp, nonce, token); if (checkResult == false) { response.Write("如果你在浏览器中看到这句话,说明此地址可以被作为微信公众账号后台的Url,请注意保持Token一致。"); response.End(); } else if (!string.IsNullOrEmpty(echostr)) { response.Write(echostr); //返回解密后的随机字符串则表示验证通过 response.End(); } var messageHandler = new CustomMessageHandler(request.InputStream, new PostModel() { Token = token, EncodingAESKey = null, AppId = ConfigHelper.AppConfig["appId"] }); //接收消息 messageHandler.Execute(); //执行微信处理过程 response.ClearContent(); response.ContentType = "text/xml"; messageHandler.FinalResponseDocument.Save(response.OutputStream); //return new WeixinResult(messageHandler);//返回结果 }
public ActionResult Post(PostModel postModel) { ////首先进行校验 if (!CheckSignature.Check(postModel.Signature, postModel.Timestamp, postModel.Nonce, Token)) { return(Content("参数错误!")); } postModel.Token = Token; postModel.EncodingAESKey = EncodingAESKey; postModel.AppId = AppId; //v4.2.2之后的版本,可以设置每个人上下文消息储存的最大数量,防止内存占用过多,如果该参数小于等于0,则不限制 var maxRecordCount = 10; //自定义MessageHandler,对微信请求的详细判断操作都在这里面。 var messageHandler = new CustomMessageHandler(Request.InputStream, postModel, maxRecordCount); //执行微信处理过程 messageHandler.Execute(); //返回结果 return(new WeixinResult(messageHandler)); }
public async Task <ActionResult> Post(PostModel postModel) { if (!CheckSignature.Check(postModel.Signature, postModel.Timestamp, postModel.Nonce, Token)) { return(new WeixinResult("参数错误!")); } postModel.Token = Token; postModel.EncodingAESKey = EncodingAESKey; //根据自己后台的设置保持一致 postModel.AppId = AppId; //根据自己后台的设置保持一致 var cancellationToken = new CancellationToken(); //给异步方法使用 var messageHandler = new CustomMessageHandler(Request.GetRequestMemoryStream(), postModel, 10) { DefaultMessageHandlerAsyncEvent = DefaultMessageHandlerAsyncEvent.SelfSynicMethod//没有重写的异步方法将默认尝试调用同步方法中的代码(为了偷懒) }; #region 设置消息去重 /* 如果需要添加消息去重功能,只需打开OmitRepeatedMessage功能,SDK会自动处理。 * 收到重复消息通常是因为微信服务器没有及时收到响应,会持续发送2-5条不等的相同内容的RequestMessage*/ messageHandler.OmitRepeatedMessage = true;//默认已经开启,此处仅作为演示,也可以设置为false在本次请求中停用此功能 #endregion messageHandler.SaveRequestMessageLog(); //记录 Request 日志(可选) await messageHandler.ExecuteAsync(cancellationToken); //执行微信处理过程(关键) messageHandler.SaveResponseMessageLog(); //记录 Response 日志(可选) MessageHandler = messageHandler; //开放出MessageHandler是为了做单元测试,实际使用过程中这一行不需要 return(new FixWeixinBugWeixinResult(messageHandler)); }
public ActionResult Post(PostModel postModel) { string weixin = ""; //获取xml数据 weixin = PostInput(); //自定义方法,获取xml数据 LogUtil.WebLog("用户发送消息:" + weixin); if (!CheckSignature.Check(postModel.Signature, postModel.Timestamp, postModel.Nonce, sToken)) { LogUtil.WebLog("参数错误!"); return(Content("参数错误!")); } postModel.Token = sToken; //根据自己后台的设置保持一致 postModel.EncodingAESKey = sEncodingAESKey; //根据自己后台的设置保持一致 postModel.AppId = sAppID; //根据自己后台的设置保持一致 //自定义MessageHandler,对微信请求的详细判断操作都在这里面。 var messageHandler = new CustomMessageHandler(Request.InputStream, postModel); //接收消息 messageHandler.Execute(); //执行微信处理过程 return(new FixWeixinBugWeixinResult(messageHandler)); //返回结果 }
public async Task <IMessageHandlerDocument> GetMessageHandlerAsync(Stream inputStream, PostModel postModel, int maxRecordCount = 0) { CustomMessageHandler messageHandler = new CustomMessageHandler(inputStream, postModel, maxRecordCount); messageHandler.Messages = await GetCustomMessagesAsync(); messageHandler.OnSubscribe += MessageHandler_OnSubscribe; messageHandler.OnUnsubscribe += MessageHandler_OnUnsubscribe; messageHandler.DefaultMessageHandlerAsyncEvent = DefaultMessageHandlerAsyncEvent.SelfSynicMethod; //没有重写的异步方法将默认尝试调用同步方法中的代码 messageHandler.Logger = Logger; var cancellationToken = new CancellationToken();//给异步方法使用 #region 设置消息去重 //默认已经开启 //messageHandler.OmitRepeatedMessage = true; #endregion messageHandler.SaveRequestMessageLog(); //记录 Request 日志(可选) await messageHandler.ExecuteAsync(cancellationToken); //执行微信处理过程(关键) messageHandler.SaveResponseMessageLog(); //记录 Response 日志(可选) return(messageHandler); }
public ActionResult Post(string signature, string timestamp, string nonce, string echostr) { if (!CheckSignature.Check(signature, timestamp, nonce, token)) { return(Content("参数错误")); } var logPath = Server.MapPath(string.Format("~/log/MP/{0}/", DateTime.Now.ToString("yyyy-MM-dd"))); try { var messageHandler = new CustomMessageHandler(Request.InputStream); messageHandler.RequestDocument.Save(Path.Combine(logPath, string.Format("{0}_Request_{1}.txt", _getRandomFileName(), messageHandler.RequestMessage.FromUserName))); messageHandler.Execute(); return(Content(messageHandler.ResponseDocument.ToString())); } catch (Exception ex) { return(Content("err:")); } }
/// <summary> /// 最简单的Page_Load写法(本方法仅用于演示过程,针对未加密消息,未实际在DEMO演示中使用到) /// </summary> private void MiniProcess() { string signature = Request["signature"]; string timestamp = Request["timestamp"]; string nonce = Request["nonce"]; string echostr = Request["echostr"]; if (Request.HttpMethod == "GET") { //get method - 仅在微信后台填写URL验证时触发 if (CheckSignature.Check(signature, timestamp, nonce, Token)) { WriteContent(echostr); //返回随机字符串则表示验证通过 } else { WriteContent("failed:" + signature + "," + CheckSignature.GetSignature(timestamp, nonce, Token)); } } else { //post method - 当有用户想公众账号发送消息时触发 if (!CheckSignature.Check(signature, timestamp, nonce, Token)) { WriteContent("参数错误!"); } //自定义MessageHandler,对微信请求的详细判断操作都在这里面。 var messageHandler = new CustomMessageHandler(Request.InputStream, null); //执行微信处理过程 messageHandler.Execute(); //输出结果 WriteContent(messageHandler.ResponseDocument.ToString()); } Response.End(); }
public async Task <IActionResult> Post(string appId, PostModel postModel) { try { string token = GlobalContext.Configuration.GetSection("WxConfig:Token").Value; string encodingAESKey = GlobalContext.Configuration.GetSection("WxConfig:EncodingAESKey").Value; if (!CheckSignature.Check(postModel.Signature, postModel.Timestamp, postModel.Nonce, token)) { return(new WeixinResult("")); } // 打包 PostModel 信息,根据自己后台的设置保持一致 postModel.Token = token; postModel.EncodingAESKey = encodingAESKey; postModel.AppId = appId; //v4.2.2之后的版本,可以设置每个人上下文消息储存的最大数量,防止内存占用过多,如果该参数小于等于0,则不限制 int maxRecordCount = 2; //自定义MessageHandler,对微信请求的详细判断操作都在这里面。 CustomMessageHandler messageHandler = new CustomMessageHandler(Request.GetRequestMemoryStream(), postModel, maxRecordCount); // messageHandler.SaveRequestMessageLog();//记录 Request 日志(可选) var cancellationToken = new CancellationToken(); // 给异步方法使用 _ = messageHandler.ExecuteAsync(cancellationToken); // 执行微信处理过程(关键) await Task.Delay(1); // messageHandler.SaveResponseMessageLog();//记录 Response 日志(可选) return(new WeixinResult("")); } catch (Exception) { //NLogger.Current.Error(ex); return(new WeixinResult("")); } }
public ActionResult Post(PostModel postModel) { if (!CheckSignature.Check(postModel.Signature, postModel.Timestamp, postModel.Nonce, Token)) { return Content("参数错误!"); } postModel.Token = Token; postModel.EncodingAESKey = EncodingAESKey; postModel.AppId = AppId; //v4.2.2之后的版本,可以设置每个人上下文消息储存的最大数量,防止内存占用过多,如果该参数小于等于0,则不限制 var maxRecordCount = 10; var logPath = Server.MapPath(string.Format("~/App_Data/MP/{0}/", DateTime.Now.ToString("yyyy-MM-dd"))); if (!Directory.Exists(logPath)) { Directory.CreateDirectory(logPath); } //自定义MessageHandler,对微信请求的详细判断操作都在这里面。 var messageHandler = new CustomMessageHandler(Request.InputStream, postModel, maxRecordCount); try { //测试时可开启此记录,帮助跟踪数据,使用前请确保App_Data文件夹存在,且有读写权限。 messageHandler.RequestDocument.Save(Path.Combine(logPath, string.Format("{0}_Request_{1}.txt", DateTime.Now.Ticks, messageHandler.RequestMessage.FromUserName))); if (messageHandler.UsingEcryptMessage) { messageHandler.EcryptRequestDocument.Save(Path.Combine(logPath, string.Format("{0}_Request_Ecrypt_{1}.txt", DateTime.Now.Ticks, messageHandler.RequestMessage.FromUserName))); } /* 如果需要添加消息去重功能,只需打开OmitRepeatedMessage功能,SDK会自动处理。 * 收到重复消息通常是因为微信服务器没有及时收到响应,会持续发送2-5条不等的相同内容的RequestMessage*/ messageHandler.OmitRepeatedMessage = true; //执行微信处理过程 messageHandler.Execute(); //测试时可开启,帮助跟踪数据 //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}.txt", DateTime.Now.Ticks, messageHandler.RequestMessage.FromUserName))); } if (messageHandler.UsingEcryptMessage) { //记录加密后的响应信息 messageHandler.FinalResponseDocument.Save(Path.Combine(logPath, string.Format("{0}_Response_Final_{1}.txt", DateTime.Now.Ticks, messageHandler.RequestMessage.FromUserName))); } //return new FixWeixinBugWeixinResult(messageHandler);//为了解决官方微信5.0软件换行bug暂时添加的方法,平时用下面一个方法即可 return new WeixinResult(messageHandler);//v0.8+ } catch (Exception ex) { logger.Error(ex); return Content(""); } }
/// <summary> /// 处理微信消息 /// </summary> /// <param name="channelId"></param> /// <param name="msg_signature"></param> /// <param name="timestamp"></param> /// <param name="nonce"></param> /// <param name="msg"></param> /// <returns></returns> public async Task <ExecuteResult <string> > HandleInputWeixinQyMessageAsync(int channelId, string msg_signature, string timestamp, string nonce, string msg) { var result = new ExecuteResult <string> { Success = false, ErrorMsg = "", ErrorCode = ExecuteResult.ErrorCodeEnum.Fail, }; try { var configDto = await ChannelHelper.GetAgentConfigDTOByChannelIdAsync(channelId); Senparc.Weixin.Work.Tencent.WXBizMsgCrypt crypt = new Senparc.Weixin.Work.Tencent.WXBizMsgCrypt(configDto.Token, configDto.EncodingAESKey, configDto.CorpId); var info = string.Empty; var r1 = crypt.DecryptMsg(msg_signature, timestamp, nonce, msg, ref info); var replyMsg = string.Empty; var reply = info.Replace("<ToUserName><![CDATA[wx9a80f6e6ed2a89e6]]></ToUserName><FromUserName><![CDATA[Yan-Xia]]></FromUserName>", "<ToUserName><![CDATA[Yan-Xia]]></ToUserName><FromUserName><![CDATA[wx9a80f6e6ed2a89e6]]></FromUserName>"); crypt.EncryptMsg(reply, timestamp, nonce, ref replyMsg); result.Data = replyMsg; var signHelper = new SignatureHelper(configDto); //signHelper.d string testXml = @"<xml><ToUserName><![CDATA[wx7618c0a6d9358622]]></ToUserName> <Encrypt><![CDATA[h3z+AK9zKP4dYs8j1FmthAILbJghEmdo2Y1U9Pdghzann6H2KJOpepaDT1zcp09/1/e/6ta48aUXebkHlu0rhzk4GW+cvVUHzbEiQVFlIvD+q4T/NLIm8E8BM+gO+DHslM7aXmYjvgMw6AYiBx80D+nZKNyJD3I8lRT3aHCq/hez0c+HTAnZyuCi5TfUAw0c6jWSfAq61VesRw4lhV925vJUOBXT/zOw760CEsYXSr2IAr/n4aPfDgRs2Ww2h/HPiVOQ2Ms1f/BOtFiKVWMqZCxbmJ7cyPHH7+uOSAS6DtXiQAdwpEZwHz+A5QTsmK6V0C6Ifgr7zrStb7ygM7kmcrAJctPhCfG7WlfrWrFNLdtx9Q2F7d6/soinswdoYF8g56s8UWguOVkM7UFGr8H2QqrUJm5S5iFP/XNcBwvPWYA=]]></Encrypt> <AgentID><![CDATA[2]]></AgentID> </xml>"; var postModel = new Senparc.Weixin.Work.Entities.PostModel() { Msg_Signature = "845997ceb6e4fd73edd9a377be227848ce20d34f", Timestamp = "1412587525", Nonce = "1501543730", Token = "fzBsmSaI8XE1OwBh", EncodingAESKey = "9J8CQ7iF9mLtQDZrUM1loOVQ6oNDxVtBi1DBU2oaewl", CorpId = "wx7618c0a6d9358622" }; var messageHandler = new CustomMessageHandlers(XDocument.Parse(testXml), postModel, 10); var xmlInfo = XDocument.Parse(msg); var postModel1 = new Senparc.Weixin.Work.Entities.PostModel { CorpId = configDto.CorpId, EncodingAESKey = configDto.EncodingAESKey, Msg_Signature = msg_signature, Nonce = nonce, Timestamp = timestamp, Token = configDto.Token, //Msg_Signature = "845997ceb6e4fd73edd9a377be227848ce20d34f", //Timestamp = "1412587525", //Nonce = "1501543730", //Token = "fzBsmSaI8XE1OwBh", //EncodingAESKey = "9J8CQ7iF9mLtQDZrUM1loOVQ6oNDxVtBi1DBU2oaewl", //CorpId = "wx7618c0a6d9358622" }; var handler = new CustomMessageHandler(xmlInfo, postModel1, 10); return(result); } catch (Exception ex) { ex.WriteExceptionLog(""); } return(result); }
private readonly string Token = "weixin";//与微信公众账号后台的Token设置保持一致,区分大小写。 protected void Page_Load(object sender, EventArgs e) { string signature = Request["signature"]; string timestamp = Request["timestamp"]; string nonce = Request["nonce"]; string echostr = Request["echostr"]; if (Request.HttpMethod == "GET") { //get method - 仅在微信后台填写URL验证时触发 if (CheckSignature.Check(signature, timestamp, nonce, Token)) { WriteContent(echostr); //返回随机字符串则表示验证通过 } else { WriteContent("failed:" + signature + "," + CheckSignature.GetSignature(timestamp, nonce, Token)); } Response.End(); } else { //post method - 当有用户想公众账号发送消息时触发 if (!CheckSignature.Check(signature, timestamp, nonce, Token)) { WriteContent("参数错误!"); return; } //自定义MessageHandler,对微信请求的详细判断操作都在这里面。 var messageHandler = new CustomMessageHandler(Request.InputStream); try { //测试时可开启此记录,帮助跟踪数据 messageHandler.RequestDocument.Save( Server.MapPath("~/App_Data/" + DateTime.Now.Ticks + "_Request_" + messageHandler.RequestMessage.FromUserName + ".txt")); //执行微信处理过程 messageHandler.Execute(); //测试时可开启,帮助跟踪数据 messageHandler.ResponseDocument.Save( Server.MapPath("~/App_Data/" + DateTime.Now.Ticks + "_Response_" + messageHandler.ResponseMessage.ToUserName + ".txt")); WriteContent(messageHandler.ResponseDocument.ToString()); return; } 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 (messageHandler.ResponseDocument != null) { tw.WriteLine(messageHandler.ResponseDocument.ToString()); } tw.Flush(); tw.Close(); } WriteContent(""); } finally { Response.End(); } } }
public ActionResult Post(PostModel postModel) { if (!CheckSignature.Check(postModel.Signature, postModel.Timestamp, postModel.Nonce, Token)) { return Content("参数错误!"); } postModel.Token = Token; postModel.AppId = AppId; postModel.EncodingAESKey = EncodingAESKey; int maxRecordContent = 20;//每个人上下文消息存储的最大数量。 string logPath = Server.MapPath(string.Format("~App_Data/MP/{0}/", DateTime.Now.ToString("yyyy-MM-dd"))); if (!Directory.Exists(logPath)) { Directory.CreateDirectory(logPath); } var messageHandler = new CustomMessageHandler(Request.InputStream, postModel, maxRecordContent); try { messageHandler.RequestDocument.Save(Path.Combine(logPath, string.Format("{0}_Request_{1}.txt", _getRandomFileName(), messageHandler.RequestMessage.FromUserName))); /* 如果需要添加消息去重功能,只需打开OmitRepeatedMessage功能,SDK会自动处理。 * 收到重复消息通常是因为微信服务器没有及时收到响应,会持续发送2-5条不等的相同内容的RequestMessage*/ messageHandler.OmitRepeatedMessage = false; messageHandler.Execute();//执行微信处理过程 //测试时可开启,帮助跟踪数据 //if (messageHandler.ResponseDocument == null) //{ // throw new Exception(messageHandler.RequestDocument.ToString()); //} if (messageHandler.ResponseMessage != null) { messageHandler.ResponseDocument.Save(Path.Combine(logPath, string.Format("{0}_Response_{1}.txt", _getRandomFileName(), messageHandler.RequestMessage.FromUserName))); } if (messageHandler.UsingEcryptMessage) { //记录加密后的响应信息 messageHandler.FinalResponseDocument.Save(Path.Combine(logPath, string.Format("{0}_Response_Final_{1}.txt", _getRandomFileName(), messageHandler.RequestMessage.FromUserName))); } return new FixWeixinBugWeixinResult(messageHandler); } catch (Exception ex) { 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(""); } }
private async Task SendQueueAsync(int millisecondsWait = 0) { if (_sendQueue.Count == 0) { return; } // Extremely important that this will not allow more than one thread at a time. // This methods handle ordering and potential encryption, hence order matters. if (!(await _syncHack.WaitAsync(millisecondsWait))) { return; } try { var sendList = new List <Packet>(); //Queue<Packet> queue = _sendQueueNotConcurrent; int length = _sendQueue.Count; for (int i = 0; i < length; i++) { Packet packet; if (!_sendQueue.TryDequeue(out packet)) { break; } if (packet == null) { continue; } if (State == ConnectionState.Unconnected) { packet.PutPool(); continue; } sendList.Add(packet); } if (sendList.Count == 0) { return; } List <Packet> prepareSend = CustomMessageHandler.PrepareSend(sendList); var preppedSendList = new List <Packet>(); foreach (Packet packet in prepareSend) { Packet message = packet; if (CustomMessageHandler != null) { message = CustomMessageHandler.HandleOrderedSend(message); } Reliability reliability = message.ReliabilityHeader.Reliability; if (reliability == Reliability.Undefined) { reliability = Reliability.Reliable; // Questionable practice } if (reliability == Reliability.ReliableOrdered) { message.ReliabilityHeader.OrderingIndex = Interlocked.Increment(ref OrderingIndex); } preppedSendList.Add(message); //await _packetSender.SendPacketAsync(this, message); } await _packetSender.SendPacketAsync(this, preppedSendList); } catch (Exception e) { Log.Error(e); } finally { _syncHack.Release(); } }
private void HandlePacket(Packet message) { if (message == null) { return; } /*if ((message.ReliabilityHeader.Reliability == Reliability.ReliableSequenced || message.ReliabilityHeader.Reliability == Reliability.UnreliableSequenced) || && message.ReliabilityHeader.SequencingIndex < Interlocked.Read(ref _lastSequencingIndex)) || { || return; || } */ try { // RakOfflineHandler.TraceReceive(Log, message); if (message.Id < (int)DefaultMessageIdTypes.ID_USER_PACKET_ENUM) { // Standard RakNet online message handlers switch (message) { case ConnectedPing connectedPing: HandleConnectedPing(connectedPing); break; case ConnectedPong connectedPong: HandleConnectedPong(connectedPong); break; case DetectLostConnections _: break; case ConnectionRequest connectionRequest: HandleConnectionRequest(connectionRequest); break; case ConnectionRequestAccepted connectionRequestAccepted: HandleConnectionRequestAccepted(connectionRequestAccepted); break; case NewIncomingConnection newIncomingConnection: HandleNewIncomingConnection(newIncomingConnection); break; case DisconnectionNotification _: HandleDisconnectionNotification(); break; default: Log.Error($"Unhandled packet: {message.GetType().Name} 0x{message.Id:X2} for user: {Username}, IP {EndPoint.Address}"); if (Log.IsDebugEnabled) { Log.Warn($"Unknown packet 0x{message.Id:X2}\n{Packet.HexDump(message.Bytes)}"); } break; } } else { try { CustomMessageHandler.HandlePacket(message); } catch (Exception e) { // ignore Log.Warn(e, $"Custom message handler error"); } } if (message.Timer.IsRunning) { long elapsedMilliseconds = message.Timer.ElapsedMilliseconds; if (elapsedMilliseconds > 1000) { Log.Warn($"Packet (0x{message.Id:x2}) handling too long {elapsedMilliseconds}ms ({message.ToString()})"); } } else { Log.Warn("Packet (0x{0:x2}) timer not started for {1}.", message.Id, Username); } } catch (Exception e) { Log.Error(e, "Packet handling"); throw; } finally { message?.PutPool(); } }
public static IResponseMessageBase Render(CustomMessageHandler handler, string eventKey) { //IResponseMessageBase rsp = null; if (eventKey.StartsWith("res:")) { return generator.GetResponseByResKey(handler,eventKey.Substring(eventKey.IndexOf(":") + 1)); } switch (eventKey) { case "product_promotion": return generator.GetPromotion(handler); case "co_intro": return generator.GetCoIntro(handler); case "clalm_profile": return generator.GetClalmProfile(handler); case "co_contact": return generator.GetCoContact(handler); } if (Variables.DebugMode) { var strongResponseMessage = handler.CreateResponseMessage<ResponseMessageText>(); strongResponseMessage.Content = "您点击了按钮,EventKey:" + eventKey; return strongResponseMessage; } return null; }
internal IResponseMessageBase GetCoContact(CustomMessageHandler handler) { var rsp = handler.CreateResponseMessage<ResponseMessageNews>(); rsp.Articles.Add(new Article() { Title = "公司介绍", Description = "如果您有任何的疑问和意见,欢迎和我们联系!", PicUrl = "http://travel.e-picclife.com/m/_imgs_v2/paris/banner_contactus.jpg", Url = "http://travel.e-picclife.com/m/contactus.aspx" }); return rsp; }
public HttpResponseMessage Post(string id, string signature, string timestamp, string nonce, string echostr) { try { LogHelper.WriteLog(string.Format(@"进入Post: signature: {0} timestamp: {1} nonce: {2} echostr: {3}", signature, timestamp, nonce, echostr)); lock (_postingLock) { if (!_postingFlag) { _postingFlag = true; //LogHelper.WriteLog(string.Format("{0}\n{1}\n{2}\n{3}\n{4}", id, signature, timestamp, nonce, echostr), "MiniPost"); UserProfile userProfile = _userProfileRepository.Find(Specification<UserProfile>.Eval(e => e.UserCode == id)); if (userProfile != null) { if (!CheckSignature.Check(signature, timestamp, nonce, userProfile.WeixinToken)) { return new HttpResponseMessage { Content = new StringContent("参数错误!") }; } } else { return new HttpResponseMessage { Content = new StringContent("参数错误!") }; } var logfilename = userProfile.UserName + "," + nonce; try { var stream = HttpContext.Current.Request.InputStream; if (stream == null) { throw new NullReferenceException("HttpContext.Current.Request.InputStream 是获取不到stream的"); } var messageHandler = new CustomMessageHandler(stream, userProfile, signature, timestamp, nonce, _qrCodeRepository); LogHelper.WriteLog(string.Format(@" signature: {0} timestamp: {1} nonce: {2} echostr: {3} requestdocument: {4}", signature, timestamp, nonce, echostr, messageHandler.RequestDocument.ToString(), userProfile.UserName), logfilename + "debug接收微信xml"); messageHandler.Execute(); if (messageHandler.ResponseDocument != null) LogHelper.WriteLog(messageHandler.ResponseDocument.ToString(), logfilename + "debug返回微信xml"); _postingFlag = false; if (!CheckContent(messageHandler)) { return new HttpResponseMessage { Content = new StringContent("") }; } //return new WeixinResult(messageHandler);//v0.8+ return new HttpResponseMessage { Content = new StringContent(messageHandler.ResponseDocument.ToString()) };//v0.7- } catch (Exception ex) { LogHelper.WriteException(ex, logfilename); return new HttpResponseMessage { Content = new StringContent("") }; } } else { return new HttpResponseMessage { Content = new StringContent("") }; } } } catch (Exception ex) { LogHelper.WriteException(ex, "错误"); return new HttpResponseMessage { Content = new StringContent("...") }; } }
public void ProcessRequest(HttpContext context) { Request = context.Request; Response = context.Response; string signature = Request["signature"]; string timestamp = Request["timestamp"]; string nonce = Request["nonce"]; string echostr = Request["echostr"]; if (Request.HttpMethod == "GET") { //get method_仅在微信后台填写URL验证时触发 if (CheckSignature.Check(signature, timestamp, nonce, Token)) { //返回随机字符串则表示验证通过 WriteContent(echostr); } else { WriteContent("failed:" + signature + "," + CheckSignature.GetSignature(timestamp, nonce, Token) + "。" + "如果你在浏览器中看到这句话,说明此地址可以被作为微信公众账号后台的Url,请注意保持Token一致。"); } Response.End(); } else { //post method_当有用户想公众账号发送消息时触发 if (!CheckSignature.Check(signature, timestamp, nonce, Token)) { WriteContent("参数错误!"); return; } //v4.2.2之后的版本,可以设置每个人上下文消息储存的最大数量,防止内存占用过多,如果该参数小于等于0,则不限制 const int maxRecordCount = 10; var url = context.Server.MapPath("/"); //自定义MessageHandler,对微信请求的详细判断操作都在这里面。 var messageHandler = new CustomMessageHandler(Request.InputStream, maxRecordCount, url); try { //用户请求内容 Logger.Write(new LogEntity { Title = "用户" + messageHandler.RequestMessage.FromUserName + "查询公告", Content = messageHandler.RequestDocument.ToString() ,Sevenrity = Sevenrity.Info}); messageHandler.Execute(); WriteContent(messageHandler.ResponseDocument.ToString()); //服务器向用户发送内容 Logger.Write(new LogEntity { Title = "服务器向用户" + messageHandler.ResponseMessage.ToUserName + "返回公告", Content = messageHandler.ResponseDocument.ToString(), Sevenrity = Sevenrity.Info }); Logger.ShutDown(); } catch (Exception ex) { using (TextWriter tw = new StreamWriter(context.Server.MapPath("~/App_Data/Error_" + DateTime.Now.Ticks + ".txt"))) { tw.WriteLine(ex.Message); tw.WriteLine(ex.InnerException.Message); if (messageHandler.ResponseDocument != null) { tw.WriteLine(messageHandler.ResponseDocument.ToString()); } tw.Flush(); tw.Close(); } WriteContent(""); } finally { Response.End(); } } }
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 } }
/// <summary> /// 之判断返回文字的时候的Content属性,因为Content如果为"",则会提示该公众号已停止服务 /// </summary> /// <param name="messageHandler"></param> /// <returns></returns> private bool CheckContent(CustomMessageHandler messageHandler) { if (messageHandler.ResponseDocument != null) { var xDocument = messageHandler.ResponseDocument; var element = xDocument.Descendants("Content").FirstOrDefault(); if (element != null) { if (!string.IsNullOrEmpty(element.Value)) { return true; } } else { return true; } } return false; }
public IResponseMessageBase GetResponseByResKey(CustomMessageHandler handler,string resKey) { IWxRes res = IocObject.WeixinRes.GetResByKey(resKey); if (res == null) { Config.Logln("素材"+resKey+"不存在"); } TextRes trs; if ((trs = res as TextRes) != null) { var strongResponseMessage = handler.CreateResponseMessage<ResponseMessageText>(); strongResponseMessage.Content =trs.Content; Config.Logln("素材" + resKey + "/文本"); return strongResponseMessage; } else { var rsp = handler.CreateResponseMessage<ResponseMessageNews>(); ArticleRes ares = res as ArticleRes; var items = ares.Items; string domain = WebCtx.Domain; foreach (var item in items) { if (item.Enabled) { rsp.Articles.Add(new Article() { Title = item.Title, Description = item.Description??"", PicUrl = domain + "/"+item.Pic, Url =item.Url.StartsWith("http://")?item.Url:domain+ item.Url }); } } Config.Logln("素材"+resKey+"/图文"); return rsp; } }
public virtual void Disconnect(string reason, bool sendDisconnect = true) { CustomMessageHandler?.Disconnect(reason, sendDisconnect); Close(); }
protected void Page_Load(object sender, EventArgs e) { string Token = "";//与微信公众账号后台的Token设置保持一致,区分大小写。 int wid = 0; wid = MyCommFun.RequestInt("apiid"); if (wid <= 0) { WriteContent("参数非法"); return; } wx_userweixin wbll = new wx_userweixin(); Token = wbll.GetWeiXinToken(wid); if (Token == null || string.IsNullOrEmpty(Token)) { WriteContent("不存在该微信号或账号已过期或已被禁用!"); return; } // Token = "uweixin"; string signature = Request["signature"]; string timestamp = Request["timestamp"]; string nonce = Request["nonce"]; string echostr = Request["echostr"]; if (Request.HttpMethod == "GET") { //get method - 仅在微信后台填写URL验证时触发 if (CheckSignature.Check(signature, timestamp, nonce, Token)) { WriteContent(echostr); //返回随机字符串则表示验证通过 } else { WriteContent("failed:" + signature + ",token:" + Token + " " + CheckSignature.GetSignature(timestamp, nonce, Token) + "。" + "如果你在浏览器中看到这句话,说明此地址可以被作为微信公众账号后台的Url,请注意保持Token一致。"); } Response.End(); } else { //本地测试的时候注释掉 ----start ----- if (!CheckSignature.Check(signature, timestamp, nonce, Token)) { WriteContent("参数错误!"); return; } //本地测试的时候注释掉 ----end ----- //post method - 当有用户想公众账号发送消息时触发 Model.wx_userweixin uweixin = wbll.GetModel(wid); var postModel = new PostModel() { Signature = Request.QueryString["signature"], Msg_Signature = Request.QueryString["msg_signature"], Timestamp = Request.QueryString["timestamp"], Nonce = Request.QueryString["nonce"], //以下保密信息不会(不应该)在网络上传播,请注意 Token = Token, EncodingAESKey = uweixin.extStr, //根据自己后台的设置保持一致 AppId = uweixin.AppId //根据自己后台的设置保持一致 }; //v4.2.2之后的版本,可以设置每个人上下文消息储存的最大数量,防止内存占用过多,如果该参数小于等于0,则不限制 var maxRecordCount = 10; //自定义MessageHandler,对微信请求的详细判断操作都在这里面。 var messageHandler = new CustomMessageHandler(Request.InputStream, postModel, maxRecordCount); try { //测试时可开启此记录,帮助跟踪数据,使用前请确保App_Data文件夹存在,且有读写权限。 messageHandler.RequestDocument.Save( Server.MapPath("~/App_Data/" + DateTime.Now.Ticks + "_Request_" + messageHandler.RequestMessage.FromUserName + ".txt")); //执行微信处理过程 messageHandler.Execute(); //测试时可开启,帮助跟踪数据 messageHandler.ResponseDocument.Save( Server.MapPath("~/App_Data/" + DateTime.Now.Ticks + "_Response_" + messageHandler.ResponseMessage.ToUserName + ".txt")); //为了解决官方微信5.0软件换行bug暂时添加的方法,平时用下面一个方法即可 begin string lastStr = ""; if (messageHandler != null && messageHandler.ResponseDocument != null && messageHandler.ResponseDocument.ToString().Trim() != "") { lastStr = messageHandler.ResponseDocument.ToString().Replace("\r\n", "\n"); } else { lastStr = messageHandler.ResponseDocument.ToString(); } // WriteContent( messageHandler.ResponseDocument.ToString()); //为了解决官方微信5.0软件换行bug暂时添加的方法,平时用下面一个方法即可 end //如果自动回复已经关闭,则不返回内容,start 1220 WeiXCommFun wxcomm = new WeiXCommFun(); int apiid = wxcomm.getApiid(); if (!wxcomm.wxCloseKW(apiid)) { lastStr = ""; } //如果自动回复已经关闭,则不返回内容,end 1220 WriteContent(lastStr); return; } 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 (messageHandler.ResponseDocument != null) { tw.WriteLine(messageHandler.ResponseDocument.ToString()); } tw.Flush(); tw.Close(); } WriteContent(""); } finally { Response.End(); } } }
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 } }
private readonly string Token = "weixin"; //与微信公众账号后台的Token设置保持一致,区分大小写。 #endregion Fields #region Methods protected void Page_Load(object sender, EventArgs e) { string signature = Request["signature"]; string timestamp = Request["timestamp"]; string nonce = Request["nonce"]; string echostr = Request["echostr"]; if (Request.HttpMethod == "GET") { //get method - 仅在微信后台填写URL验证时触发 if (CheckSignature.Check(signature, timestamp, nonce, Token)) { WriteContent(echostr); //返回随机字符串则表示验证通过 } else { WriteContent("failed:" + signature + "," + CheckSignature.GetSignature(timestamp, nonce, Token) + "。" + "如果你在浏览器中看到这句话,说明此地址可以被作为微信公众账号后台的Url,请注意保持Token一致。"); } Response.End(); } else { //post method - 当有用户想公众账号发送消息时触发 if (!CheckSignature.Check(signature, timestamp, nonce, Token)) { WriteContent("参数错误!"); return; } //设置每个人上下文消息储存的最大数量,防止内存占用过多,如果该参数小于等于0,则不限制 var maxRecordCount = 10; //自定义MessageHandler,对微信请求的详细判断操作都在这里面。 var messageHandler = new CustomMessageHandler(Request.InputStream, maxRecordCount); try { //测试时可开启此记录,帮助跟踪数据,使用前请确保App_Data文件夹存在,且有读写权限。 messageHandler.RequestDocument.Save( Server.MapPath("~/App_Data/" + DateTime.Now.Ticks + "_Request_" + messageHandler.RequestMessage.FromUserName + ".txt")); //执行微信处理过程 messageHandler.Execute(); //测试时可开启,帮助跟踪数据 messageHandler.ResponseDocument.Save( Server.MapPath("~/App_Data/" + DateTime.Now.Ticks + "_Response_" + messageHandler.ResponseMessage.ToUserName + ".txt")); WriteContent(messageHandler.ResponseDocument.ToString()); return; } catch (Exception ex) { //将程序运行中发生的错误记录到App_Data文件夹 using (TextWriter tw = new StreamWriter(Server.MapPath("~/App_Data/Error_" + DateTime.Now.Ticks + ".txt"))) { tw.WriteLine(ex.Message); tw.WriteLine(ex.InnerException.Message); if (messageHandler.ResponseDocument != null) { tw.WriteLine(messageHandler.ResponseDocument.ToString()); } tw.Flush(); tw.Close(); } WriteContent(""); } finally { Response.End(); } } }
private readonly string Token = "weixin";//与微信公众账号后台的Token设置保持一致,区分大小写。 protected void Page_Load(object sender, EventArgs e) { string signature = Request["signature"]; string timestamp = Request["timestamp"]; string nonce = Request["nonce"]; string echostr = Request["echostr"]; if (Request.HttpMethod == "GET") { //get method - 仅在微信后台填写URL验证时触发 if (CheckSignature.Check(signature, timestamp, nonce, Token)) { WriteContent(echostr); //返回随机字符串则表示验证通过 } else { WriteContent("failed:" + signature + "," + CheckSignature.GetSignature(timestamp, nonce, Token) + "。" + "如果你在浏览器中看到这句话,说明此地址可以被作为微信公众账号后台的Url,请注意保持Token一致。"); } Response.End(); } else { //post method - 当有用户想公众账号发送消息时触发 if (!CheckSignature.Check(signature, timestamp, nonce, Token)) { WriteContent("参数错误!"); return; } //post method - 当有用户想公众账号发送消息时触发 var postModel = new PostModel() { Signature = Request.QueryString["signature"], Msg_Signature = Request.QueryString["msg_signature"], Timestamp = Request.QueryString["timestamp"], Nonce = Request.QueryString["nonce"], //以下保密信息不会(不应该)在网络上传播,请注意 Token = Token, EncodingAESKey = "mNnY5GekpChwqhy2c4NBH90g3hND6GeI4gii2YCvKLY", //根据自己后台的设置保持一致 AppId = "wx669ef95216eef885" //根据自己后台的设置保持一致 }; //v4.2.2之后的版本,可以设置每个人上下文消息储存的最大数量,防止内存占用过多,如果该参数小于等于0,则不限制 var maxRecordCount = 10; //自定义MessageHandler,对微信请求的详细判断操作都在这里面。 var messageHandler = new CustomMessageHandler(Request.InputStream, postModel, maxRecordCount); try { //测试时可开启此记录,帮助跟踪数据,使用前请确保App_Data文件夹存在,且有读写权限。 messageHandler.RequestDocument.Save( Server.MapPath("~/App_Data/" + DateTime.Now.Ticks + "_Request_" + messageHandler.RequestMessage.FromUserName + ".txt")); //执行微信处理过程 messageHandler.Execute(); //测试时可开启,帮助跟踪数据 messageHandler.ResponseDocument.Save( Server.MapPath("~/App_Data/" + DateTime.Now.Ticks + "_Response_" + messageHandler.ResponseMessage.ToUserName + ".txt")); WriteContent(messageHandler.ResponseDocument.ToString()); return; } 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 (messageHandler.ResponseDocument != null) { tw.WriteLine(messageHandler.ResponseDocument.ToString()); } tw.Flush(); tw.Close(); } } finally { Response.End(); } } }
public ActionResult Callback(Senparc.Weixin.MP.Entities.Request.PostModel postModel) { //此处的URL格式类型为:http://sdk.weixin.senparc.com/Open/Callback/$APPID$, 在RouteConfig中进行了配置,你也可以用自己的格式,只要和开放平台设置的一致。 //处理微信普通消息,可以直接使用公众号的MessageHandler。此处的URL也可以直接填写公众号普通的URL,如本Demo中的/Weixin访问地址。 var logPath = ServerUtility.ContentRootMapPath(string.Format("~/App_Data/Open/{0}/", SystemTime.Now.ToString("yyyy-MM-dd"))); if (!Directory.Exists(logPath)) { Directory.CreateDirectory(logPath); } postModel.Token = component_Token; postModel.EncodingAESKey = component_EncodingAESKey; //根据自己后台的设置保持一致 postModel.AppId = component_AppId; //根据自己后台的设置保持一致 var maxRecordCount = 10; MessageHandler <CustomMessageContext> messageHandler = null; try { var checkPublish = false; //是否在“全网发布”阶段 if (checkPublish) { messageHandler = new OpenCheckMessageHandler(Request.GetRequestMemoryStream(), postModel, 10); } else { messageHandler = new CustomMessageHandler(Request.GetRequestMemoryStream(), postModel, maxRecordCount); } messageHandler.SaveRequestMessageLog(); //记录 Request 日志(可选) messageHandler.Execute(); //执行微信处理过程(关键) messageHandler.SaveResponseMessageLog(); //记录 Response 日志(可选) return(new FixWeixinBugWeixinResult(messageHandler)); } catch (Exception ex) { using ( TextWriter tw = new StreamWriter(ServerUtility.ContentRootMapPath("~/App_Data/Open/Error_" + SystemTime.Now.Ticks + ".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("")); } } }
public async Task <ActionResult> Post(PostModel postModel) { var token = config.GetValue <string>("weixinChannel:token"); if (!CheckSignature.Check(postModel.Signature, postModel.Timestamp, postModel.Nonce, token)) { return(new WeixinResult("参数错误!")); } postModel.Token = token; postModel.EncodingAESKey = config.GetValue <string>("weixinChannel:encodingAESKey"); postModel.AppId = config.GetValue <string>("weixinChannel:appId"); var messageHandler = new CustomMessageHandler(builder, config, Request.GetRequestMemoryStream(), postModel, 10); messageHandler.DefaultMessageHandlerAsyncEvent = Senparc.NeuChar.MessageHandlers.DefaultMessageHandlerAsyncEvent.SelfSynicMethod;//没有重写的异步方法将默认尝试调用同步方法中的代码(为了偷懒) #region 设置消息去重 /* 如果需要添加消息去重功能,只需打开OmitRepeatedMessage功能,SDK会自动处理。 * 收到重复消息通常是因为微信服务器没有及时收到响应,会持续发送2-5条不等的相同内容的RequestMessage*/ messageHandler.OmitRepeatedMessage = true;//默认已经开启,此处仅作为演示,也可以设置为false在本次请求中停用此功能 #endregion #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))); } #endregion await messageHandler.ExecuteAsync(); //执行微信处理过程 #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 MessageHandler = messageHandler;//开放出MessageHandler是为了做单元测试,实际使用过程中不需要 return(new FixWeixinBugWeixinResult(messageHandler)); }
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 } }