目前 官方小程序验证只有PHP的 ,暂未发现C#版本的 ,本人研究后贴出来大家分享下。
有不懂的请留言,本人会尽快回复的:
废话不多说直接上代码:
/// <summary>
/// C# 微信小程序接入 author:huochengyan
/// </summary>
public class Msg : IHttpHandler
{
//服务器日志类
Log log = new Log(AppDomain.CurrentDomain.BaseDirectory + @"/log/Log.txt");
public void ProcessRequest(HttpContext context)
{
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))
{
log.log("=========================a.WeiXin 服务器验证========================= ");
log.log(postString);
}
else
{
log.log("=========================b.WeiXin 服务器验证========================= ");
log.log(postString);
}
}
else
{
log.log("=========================c.WeiXin 服务器验证========================= ");
Auth(context);
}
}
private void Auth(HttpContext context)
{
var signature = context.Request["signature"];
var timestamp = context.Request["timestamp"];
var nonce = context.Request["nonce"];
var echostr = context.Request["echostr"];
log.log("微信消息服务器验证传入数据" + string.Format("signature:{0},timestamp:{1},nonce:{2},echostr:{3}", signature, timestamp, nonce, echostr));
var token = "myxiaochengxu123";//自定义字段(自己填写3-32个字符)
//timestamp和token和nonce 字典排序
Dictionary<string, string> dic = new Dictionary<string, string>();
dic.Add("token", token);
dic.Add("nonce", nonce);
dic.Add("timestamp", timestamp);
var list = dic.OrderBy(s => s.Value);
var conbineStr = "";
foreach (var s in list)
{
conbineStr = conbineStr + s.Value;
}
string data = conbineStr;
//sha1加密
string secret = FormsAuthentication.HashPasswordForStoringInConfigFile(conbineStr, "SHA1").ToLower();
var success = signature == secret;
if (success)
{
data = echostr;
}
context.Response.ContentType = "text/plain";
context.Response.Write(data);
}
public bool IsReusable
{
get
{
return false;
}
}
}
配置成功即可: 这里注意 http服务的,再接收消息是也能够用https 到才行。
标签:nonce,接入服务器,C#,微信,context,timestamp,var,string,log From: https://blog.51cto.com/51souta/5807358