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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
<%@ WebHandler Language="C#" Class="WeixinInterface" %>
 
using System;
using System.Web;
 
public class WeixinInterface : IHttpHandler
{
    HttpContext context = null;
    string postStr = "";
    public void ProcessRequest(HttpContext param_context)
    {
        context = param_context;
 
        //以写日志为荣,以打断点为耻.
        //WriteLog("before valid \n");
        //valid();//用于验证
        //WriteLog("after valid, before post \n");
        if (context.Request.HttpMethod.ToLower() == "post")
        {
            System.IO.Stream s = context.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);
            }
            //WriteLog("-------AfterResponseMsg:-------\n" + postStr);
        }
    }
 
    public void valid()
    {
        var echostr = context.Request["echoStr"].ToString();
        if (checkSignature() && !string.IsNullOrEmpty(echostr))
        {
            context.Response.Write(echostr);
            context.Response.End();//推送...不然微信平台无法验证token
        }
    }
 
    public bool checkSignature()
    {
        var signature = context.Request["signature"].ToString();
        var timestamp = context.Request["timestamp"].ToString();
        var nonce = context.Request["nonce"].ToString();
        var token = "faketoken";
        string[] ArrTmp = { token, timestamp, nonce };
        Array.Sort(ArrTmp);     //字典排序
        string tmpStr = string.Join("", ArrTmp);
        tmpStr = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1");
        tmpStr = tmpStr.ToLower();
        if (tmpStr == signature)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
 
    public string GetSha1(System.Collections.Generic.List<string> codelist)
    {
        codelist.Sort();
        var combostr = string.Empty;
        for (int i = 0; i < codelist.Count; i++)
        {
            combostr += codelist[i];
        }
        return EncryptToSHA1(combostr);
    }
 
    public string EncryptToSHA1(string str)
    {
        System.Security.Cryptography.SHA1CryptoServiceProvider sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider();
        byte[] str1 = System.Text.Encoding.UTF8.GetBytes(str);
        byte[] str2 = sha1.ComputeHash(str1);
        sha1.Clear();
        (sha1 as IDisposable).Dispose();
        return Convert.ToBase64String(str2);
    }
 
    public void responseMsg(string postStr)
    {
        System.Xml.XmlDocument postObj = new System.Xml.XmlDocument();
        postObj.LoadXml(postStr);
        WriteLog("responseMsg:-------" + postStr);
        var FromUserNameList = postObj.GetElementsByTagName("FromUserName");
        string FromUserName = string.Empty;
        for (int i = 0; i < FromUserNameList.Count; i++)
        {
            if (FromUserNameList[i].ChildNodes[0].NodeType == System.Xml.XmlNodeType.CDATA)
            {
                FromUserName = FromUserNameList[i].ChildNodes[0].Value;
            }
        }
        var toUsernameList = postObj.GetElementsByTagName("ToUserName");
        string ToUserName = string.Empty;
        for (int i = 0; i < toUsernameList.Count; i++)
        {
            if (toUsernameList[i].ChildNodes[0].NodeType == System.Xml.XmlNodeType.CDATA)
            {
                ToUserName = toUsernameList[i].ChildNodes[0].Value;
            }
        }
        var keywordList = postObj.GetElementsByTagName("Content");
        string Content = string.Empty;
        for (int i = 0; i < keywordList.Count; i++)
        {
            if (keywordList[i].ChildNodes[0].NodeType == System.Xml.XmlNodeType.CDATA)
            {
                Content = keywordList[i].ChildNodes[0].Value;
            }
        }
        var time = DateTime.Now;
        var textpl = "<xml><ToUserName><![CDATA[" + FromUserName + "]]></ToUserName>" +
            "<FromUserName><![CDATA[" + ToUserName + "]]></FromUserName>" +
            "<CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[text]]></MsgType>" +
            "<Content><![CDATA[欢迎来到微信世界---" + Content + "]]></Content><FuncFlag>0</FuncFlag></xml> ";
        context.Response.Write(textpl);
        context.Response.End();
    }
     
    private DateTime UnixTimeToTime(string timeStamp)
    {
        DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
        long lTime = long.Parse(timeStamp + "0000000");
        TimeSpan toNow = new TimeSpan(lTime);
        return dtStart.Add(toNow);
    }
 
    private int ConvertDateTimeInt(System.DateTime time)
    {
        System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
        return (int)(time - startTime).TotalSeconds;
    }
 
    private void WriteLog(string strMemo)
    {
        string filename = "D:/WEBHOME/logs/log.txt";
        if (!System.IO.Directory.Exists("D:/WEBHOME/logs/"))
            System.IO.Directory.CreateDirectory("D:/WEBHOME/logs/");
        System.IO.StreamWriter sr = null;
        try
        {
            if (!System.IO.File.Exists(filename))
            {
                sr = System.IO.File.CreateText(filename);
            }
            else
            {
                sr = System.IO.File.AppendText(filename);
            }
            sr.WriteLine(strMemo);
        }
        catch
        {
        }
        finally
        {
            if (sr != null)
                sr.Close();
        }
    }
 
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

 

1.如果是为了验证微信接口的token是否通过, 将valid注释去掉

2.如果要返回给用户值, 注释掉valid