3,143
社区成员
发帖
与我相关
我的任务
分享
public class wxapi : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.Write("欢迎关注!");
string postString = string.Empty;
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);
}
}
else
{
Auth(); //微信接入的测试
}
}
public bool IsReusable
{
get
{
return false;
}
}
/// <summary>
/// 成为开发者的第一步,验证并相应服务器的数据
/// </summary>
private void Auth()
{
//string token = ConfigurationManager.AppSettings["WeixinToken"];//从配置文件获取Token
string token = "123456";
if (string.IsNullOrEmpty(token))
{
//LogTextHelper.Error(string.Format("WeixinToken 配置项没有配置!"));
}
string echoString = HttpContext.Current.Request.QueryString["echoStr"];
string signature = HttpContext.Current.Request.QueryString["signature"];
string timestamp = HttpContext.Current.Request.QueryString["timestamp"];
string nonce = HttpContext.Current.Request.QueryString["nonce"];
if (CheckSignature(token, signature, timestamp, nonce))
{
if (!string.IsNullOrEmpty(echoString))
{
HttpContext.Current.Response.Write(echoString);
HttpContext.Current.Response.End();
}
}
}
/// <summary>
/// 验证微信签名
/// </summary>
public bool CheckSignature(string token, string signature, string timestamp, string nonce)
{
string[] ArrTmp = { token, timestamp, nonce };
Array.Sort(ArrTmp);
string tmpStr = string.Join("", ArrTmp);
tmpStr = FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1");
tmpStr = tmpStr.ToLower();
if (tmpStr == signature)
{
return true;
}
else
{
return false;
}
}
}
if (CheckSignature(token, signature, timestamp, nonce))
{
context.Response.Write(echoString);
}
else
{
context.Response.Write("验证失败:" + signature);
}