微信公众平台开发之认证"成为开发者".Net代码解析

时间:2022-09-18 19:29:43

.Net 实现微信公共服务平台开发的认证,认证成为开发者,具体内容如下

这些代码也就开始认证的时候用一次,以后就不用了:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
const string Token = "XXXXX";//你的token
protected void Page_Load(object sender, EventArgs e)
{
  string postStr = "";
  if (Request.HttpMethod.ToLower() == "post")
  {
    System.IO.Stream s = System.Web.HttpContext.Current.Request.InputStream;
    byte[] b = new byte[s.Length];
    s.Read(b, 0, (int)s.Length);
    postStr = System.Text.Encoding.UTF8.GetString(b);
    if (!string.IsNullOrEmpty(postStr))
    {
      //ResponseMsg(postStr);
      Response.Write(ResponseMsg(postStr));
      Response.End();
    }
   //WriteLog("postStr:" + postStr);
  }
  else
  {
    Valid();
  }
}   
 
/// <summary>
/// 验证微信签名
/// </summary>
/// * 将token、timestamp、nonce三个参数进行字典序排序
/// * 将三个参数字符串拼接成一个字符串进行sha1加密
/// * 开发者获得加密后的字符串可与signature对比,标识该请求来源于微信。
/// <returns></returns>
private bool CheckSignature()
{
  string signature = Request.QueryString["signature"].ToString();
  string timestamp = Request.QueryString["timestamp"].ToString();
  string nonce = Request.QueryString["nonce"].ToString();
  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;
  }
}
.private void Valid()
{
  string echoStr = Request.QueryString["echoStr"].ToString();
  if (CheckSignature())
  {
    if (!string.IsNullOrEmpty(echoStr))
    {
      Response.Write(echoStr);
      Response.End();
    }
  }
}   
 
/// <summary>
/// 写日志(用于跟踪)
/// </summary>
private void WriteLog(string strMemo)
{
  string filename = Server.MapPath("/logs/log.txt");
  if (!Directory.Exists(Server.MapPath("//logs//")))
    Directory.CreateDirectory("//logs//");
  StreamWriter sr = null;
  try
  {
    if (!File.Exists(filename))
    {
      sr = File.CreateText(filename);
    }
    else
    {
      sr = File.AppendText(filename);
    }
    sr.WriteLine(strMemo);
  }
  catch
  {
 
  }
  finally
  {
    if (sr != null)
      sr.Close();
  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。