+发表新主题
查看: 1939|回复: 1

[代码片段] .NET 微信开放平台接口

[复制链接]

[代码片段] .NET 微信开放平台接口

[复制链接]
边缘世界 发表于 2013-12-23 23:37:06 浏览:  1939 回复:  1 [显示全部楼层] 回帖奖励 |倒序浏览 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有帐号?立即注册

x
  1. <%@ WebHandler Language="C#" Class="WeixinInterface" %>

  2. using System;
  3. using System.Web;

  4. public class WeixinInterface : IHttpHandler
  5. {
  6.     HttpContext context = null;
  7.     string postStr = "";
  8.     public void ProcessRequest(HttpContext param_context)
  9.     {
  10.         context = param_context;

  11.         //以写日志为荣,以打断点为耻.
  12.         //WriteLog("before valid \n");
  13.         //valid();//用于验证
  14.         //WriteLog("after valid, before post \n");
  15.         if (context.Request.HttpMethod.ToLower() == "post")
  16.         {
  17.             System.IO.Stream s = context.Request.InputStream;
  18.             byte[] b = new byte[s.Length];
  19.             s.Read(b, 0, (int)s.Length);
  20.             postStr = System.Text.Encoding.UTF8.GetString(b);
  21.             if (!string.IsNullOrEmpty(postStr))
  22.             {
  23.                 responseMsg(postStr);
  24.             }
  25.             //WriteLog("-------AfterResponseMsg:-------\n" + postStr);
  26.         }
  27.     }

  28.     public void valid()
  29.     {
  30.         var echostr = context.Request["echoStr"].ToString();
  31.         if (checkSignature() && !string.IsNullOrEmpty(echostr))
  32.         {
  33.             context.Response.Write(echostr);
  34.             context.Response.End();//推送...不然微信平台无法验证token
  35.         }
  36.     }

  37.     public bool checkSignature()
  38.     {
  39.         var signature = context.Request["signature"].ToString();
  40.         var timestamp = context.Request["timestamp"].ToString();
  41.         var nonce = context.Request["nonce"].ToString();
  42.         var token = "faketoken";
  43.         string[] ArrTmp = { token, timestamp, nonce };
  44.         Array.Sort(ArrTmp);     //字典排序
  45.         string tmpStr = string.Join("", ArrTmp);
  46.         tmpStr = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1");
  47.         tmpStr = tmpStr.ToLower();
  48.         if (tmpStr == signature)
  49.         {
  50.             return true;
  51.         }
  52.         else
  53.         {
  54.             return false;
  55.         }
  56.     }

  57.     public string GetSha1(System.Collections.Generic.List<string> codelist)
  58.     {
  59.         codelist.Sort();
  60.         var combostr = string.Empty;
  61.         for (int i = 0; i < codelist.Count; i++)
  62.         {
  63.             combostr += codelist[i];
  64.         }
  65.         return EncryptToSHA1(combostr);
  66.     }

  67.     public string EncryptToSHA1(string str)
  68.     {
  69.         System.Security.Cryptography.SHA1CryptoServiceProvider sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider();
  70.         byte[] str1 = System.Text.Encoding.UTF8.GetBytes(str);
  71.         byte[] str2 = sha1.ComputeHash(str1);
  72.         sha1.Clear();
  73.         (sha1 as IDisposable).Dispose();
  74.         return Convert.ToBase64String(str2);
  75.     }

  76.     public void responseMsg(string postStr)
  77.     {
  78.         System.Xml.XmlDocument postObj = new System.Xml.XmlDocument();
  79.         postObj.LoadXml(postStr);
  80.         WriteLog("responseMsg:-------" + postStr);
  81.         var FromUserNameList = postObj.GetElementsByTagName("FromUserName");
  82.         string FromUserName = string.Empty;
  83.         for (int i = 0; i < FromUserNameList.Count; i++)
  84.         {
  85.             if (FromUserNameList[i].ChildNodes[0].NodeType == System.Xml.XmlNodeType.CDATA)
  86.             {
  87.                 FromUserName = FromUserNameList[i].ChildNodes[0].Value;
  88.             }
  89.         }
  90.         var toUsernameList = postObj.GetElementsByTagName("ToUserName");
  91.         string ToUserName = string.Empty;
  92.         for (int i = 0; i < toUsernameList.Count; i++)
  93.         {
  94.             if (toUsernameList[i].ChildNodes[0].NodeType == System.Xml.XmlNodeType.CDATA)
  95.             {
  96.                 ToUserName = toUsernameList[i].ChildNodes[0].Value;
  97.             }
  98.         }
  99.         var keywordList = postObj.GetElementsByTagName("Content");
  100.         string Content = string.Empty;
  101.         for (int i = 0; i < keywordList.Count; i++)
  102.         {
  103.             if (keywordList[i].ChildNodes[0].NodeType == System.Xml.XmlNodeType.CDATA)
  104.             {
  105.                 Content = keywordList[i].ChildNodes[0].Value;
  106.             }
  107.         }
  108.         var time = DateTime.Now;
  109.         var textpl = "<xml><ToUserName><![CDATA[" + FromUserName + "]]></ToUserName>" +
  110.             "<FromUserName><![CDATA[" + ToUserName + "]]></FromUserName>" +
  111.             "<CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[text]]></MsgType>" +
  112.             "<Content><![CDATA[欢迎来到微信世界---" + Content + "]]></Content><FuncFlag>0</FuncFlag></xml> ";
  113.         context.Response.Write(textpl);
  114.         context.Response.End();
  115.     }
  116.      
  117.     private DateTime UnixTimeToTime(string timeStamp)
  118.     {
  119.         DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
  120.         long lTime = long.Parse(timeStamp + "0000000");
  121.         TimeSpan toNow = new TimeSpan(lTime);
  122.         return dtStart.Add(toNow);
  123.     }

  124.     private int ConvertDateTimeInt(System.DateTime time)
  125.     {
  126.         System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
  127.         return (int)(time - startTime).TotalSeconds;
  128.     }

  129.     private void WriteLog(string strMemo)
  130.     {
  131.         string filename = "D:/WEBHOME/logs/log.txt";
  132.         if (!System.IO.Directory.Exists("D:/WEBHOME/logs/"))
  133.             System.IO.Directory.CreateDirectory("D:/WEBHOME/logs/");
  134.         System.IO.StreamWriter sr = null;
  135.         try
  136.         {
  137.             if (!System.IO.File.Exists(filename))
  138.             {
  139.                 sr = System.IO.File.CreateText(filename);
  140.             }
  141.             else
  142.             {
  143.                 sr = System.IO.File.AppendText(filename);
  144.             }
  145.             sr.WriteLine(strMemo);
  146.         }
  147.         catch
  148.         {
  149.         }
  150.         finally
  151.         {
  152.             if (sr != null)
  153.                 sr.Close();
  154.         }
  155.     }

  156.     public bool IsReusable
  157.     {
  158.         get
  159.         {
  160.             return false;
  161.         }
  162.     }
  163. }
复制代码


1.如果是为了验证微信接口的token是否通过, 将valid注释去掉2.如果要返回给用户值, 注释掉valid
回复

使用道具 举报

0

主题

2

帖子

4

积分

略知一二

Rank: 1

积分
4
单于真一 发表于 2014-11-6 10:43:32 显示全部楼层
这个类放到项目中了,但是需要怎么来用?
回复 支持 反对

使用道具 举报


您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

手机版| 赣南网

© 2013-2016 Comsenz Inc. Powered by Discuz! X3.4

用微信扫一扫

赣南网