微信小程序 登录 服务器 c#,微信小程序【消息推送服务器认证C# WebAPI】

public classwxapi : IHttpHandler

{//public static readonly string Token = Config.SenparcWeixinSetting.Token;//与微信公众帐号后台的Token设置保持一致,区分大小写。//public static readonly string EncodingAESKey = Config.SenparcWeixinSetting.EncodingAESKey;//与微信公众帐号后台的EncodingAESKey设置保持一致,区分大小写。//public static readonly string AppId = Config.SenparcWeixinSetting.WeixinAppId;//与微信公众帐号后台的AppId设置保持一致,区分大小写。

public static string Token =CachedConfigContext.Current.SettingConfig.token;public static string EncodingAESKey =CachedConfigContext.Current.SettingConfig.EncodingAESKey;public static string AppId =CachedConfigContext.Current.SettingConfig.appId;readonly Func _getRandomFileName = () => DateTime.Now.ToString("yyyyMMdd-HHmmss") + Guid.NewGuid().ToString("n").Substring(0, 6);public voidProcessRequest(HttpContext context)

{string postString = string.Empty;

PostModel postModel= newPostModel();

postModel.Signature= HttpContext.Current.Request.QueryString["signature"];

postModel.Timestamp= HttpContext.Current.Request.QueryString["timestamp"];

postModel.Nonce= HttpContext.Current.Request.QueryString["nonce"];

postModel.Msg_Signature= HttpContext.Current.Request.QueryString["msg_signature"];var openid = HttpContext.Current.Request.QueryString["openid"];var encrypt_type = HttpContext.Current.Request.QueryString["encrypt_type"];if (HttpContext.Current.Request.HttpMethod.ToUpper() == "POST")

{//using (Stream stream = HttpContext.Current.Request.InputStream)//{//Byte[] postBytes = new Byte[stream.Length];//stream.Read(postBytes, 0, (Int32)stream.Length);//postString = Encoding.UTF8.GetString(postBytes);//}//if (!string.IsNullOrEmpty(postString))//{// //Execute(postString);//}

if (!CheckSignature.Check(postModel.Signature, postModel.Timestamp, postModel.Nonce, Token))

{

HttpContext.Current.Response.Write("error");

HttpContext.Current.Response.End();

}#region 打包 PostModel 信息postModel.Token= Token;//根据本身后台的设置保持一致

postModel.EncodingAESKey = EncodingAESKey;//根据本身后台的设置保持一致

postModel.AppId = AppId;//根据本身后台的设置保持一致

#endregion

//v4.2.2以后的版本,能够设置每一个人上下文消息储存的最大数量,防止内存占用过多,若是该参数小于等于0,则不限制

var maxRecordCount = 10;//自定义MessageHandler,对微信请求的详细判断操做都在这里面。

var messageHandler = newCustomMessageHandler(HttpContext.Current.Request.InputStream, postModel, maxRecordCount);#region 设置消息去重

/*若是须要添加消息去重功能,只需打开OmitRepeatedMessage功能,SDK会自动处理。

* 收到重复消息一般是由于微信服务器没有及时收到响应,会持续发送2-5条不等的相同内容的RequestMessage*/messageHandler.OmitRepeatedMessage= true;//默认已经开启,此处仅做为演示,也能够设置为false在本次请求中停用此功能

#endregion

try{#region 记录 Request 日志

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

{

Directory.CreateDirectory(logPath);

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

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();#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+

var res = new Senparc.Weixin.MP.MvcExtension.FixWeixinBugWeixinResult(messageHandler);//为了解决官方微信5.0软件换行bug暂时添加的方法,平时用下面一个方法便可

HttpContext.Current.Response.Write(res.Content);

HttpContext.Current.Response.End();

}catch(Exception ex)

{#region 异常处理WeixinTrace.Log("MessageHandler错误:{0}", ex.Message);using (TextWriter tw = new StreamWriter(HttpContext.Current.Server.MapPath("~/logs/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();

}

HttpContext.Current.Response.Write("");

HttpContext.Current.Response.End();#endregion}

}else{if(CheckSignature.Check(postModel.Signature, postModel.Timestamp, postModel.Nonce, Token))

{string echostr = HttpContext.Current.Request.QueryString["echoStr"];//返回随机字符串则表示验证经过

HttpContext.Current.Response.Write(echostr);

HttpContext.Current.Response.End();

}

}

}public boolIsReusable

{get{return false;

}

}

}

你可能感兴趣的:(微信小程序,登录,服务器,c#)