微信公众帐号 服务器配置 代码

自己收藏备份的。

建立一个页面 ,在后台代码里写,摘自http://blog.csdn.net/hougelou/article/details/8462364

  1. using System;  

  2. using System.Collections;  

  3. using System.Configuration;  

  4. using System.Data;  

  5. using System.Linq;  

  6. using System.Web;  

  7. using System.Web.Security;  

  8. using System.Web.UI;  

  9. using System.Web.UI.HtmlControls;  

  10. using System.Web.UI.WebControls;  

  11. using System.Web.UI.WebControls.WebParts;  

  12. using System.Xml.Linq;  

  13. using System.Xml;  

  14. using System.IO;  

  15. using System.Text;  

  16. using System.Collections.Generic;  

  17. using System.Net;  

  18.   

  19. namespace OAuth2Demo  

  20. {  

  21.     public partial class WebForm1 : System.Web.UI.Page  

  22.     {  

  23.         const string Token = "token";       //与那边填写的token一致  

  24.         protected void Page_Load(object sender, EventArgs e)  

  25.         {  

  26.             string postStr = "";  

  27.             if (Request.HttpMethod.ToLower() == "post")  

  28.             {  

  29.                 Stream s = System.Web.HttpContext.Current.Request.InputStream;  

  30.                 byte[] b = new byte[s.Length];  

  31.                 s.Read(b, 0, (int)s.Length);  

  32.                 postStr = Encoding.UTF8.GetString(b);  

  33.   

  34.                 if (!string.IsNullOrEmpty(postStr))  

  35.                 {  

  36.                     //封装请求类  

  37.                     XmlDocument doc = new XmlDocument();  

  38.                     doc.LoadXml(postStr);  

  39.                     XmlElement rootElement = doc.DocumentElement;  

  40.   

  41.                     XmlNode MsgType = rootElement.SelectSingleNode("MsgType");  

  42.   

  43.                     RequestXML requestXML = new RequestXML();  

  44.                     requestXML.ToUserName = rootElement.SelectSingleNode("ToUserName").InnerText;  

  45.                     requestXML.FromUserName = rootElement.SelectSingleNode("FromUserName").InnerText;  

  46.                     requestXML.CreateTime = rootElement.SelectSingleNode("CreateTime").InnerText;  

  47.                     requestXML.MsgType = MsgType.InnerText;  

  48.   

  49.                     if (requestXML.MsgType == "text")  

  50.                     {  

  51.                         requestXML.Content = rootElement.SelectSingleNode("Content").InnerText;  

  52.                     }  

  53.                     else if (requestXML.MsgType == "location")  

  54.                     {  

  55.                         requestXML.Location_X = rootElement.SelectSingleNode("Location_X").InnerText;  

  56.                         requestXML.Location_Y = rootElement.SelectSingleNode("Location_Y").InnerText;  

  57.                         requestXML.Scale = rootElement.SelectSingleNode("Scale").InnerText;  

  58.                         requestXML.Label = rootElement.SelectSingleNode("Label").InnerText;  

  59.                     }  

  60.                     else if (requestXML.MsgType == "image")  

  61.                     {  

  62.                         requestXML.PicUrl = rootElement.SelectSingleNode("PicUrl").InnerText;  

  63.                     }  

  64.   

  65.                     //回复消息  

  66.                     ResponseMsg(requestXML);  

  67.                 }  

  68.             }  

  69.             else  

  70.             {  

  71.                 Valid();  

  72.             }  

  73.         }  

  74.   

  75.         /// <summary>  

  76.         /// 验证微信签名  

  77.         /// </summary>  

  78.         /// * 将token、timestamp、nonce三个参数进行字典序排序  

  79.         /// * 将三个参数字符串拼接成一个字符串进行sha1加密  

  80.         /// * 开发者获得加密后的字符串可与signature对比,标识该请求来源于微信。  

  81.         /// <returns></returns>  

  82.         private bool CheckSignature()  

  83.         {  

  84.             string signature = Request.QueryString["signature"];  

  85.             string timestamp = Request.QueryString["timestamp"];  

  86.             string nonce = Request.QueryString["nonce"];  

  87.             string[] ArrTmp = { Token, timestamp, nonce };  

  88.             Array.Sort(ArrTmp);     //字典排序  

  89.             string tmpStr = string.Join("", ArrTmp);  

  90.             tmpStr = FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1");  

  91.             tmpStr = tmpStr.ToLower();  

  92.             if (tmpStr == signature)  

  93.             {  

  94.                 return true;  

  95.             }  

  96.             else  

  97.             {  

  98.                 return false;  

  99.             }  

  100.         }  

  101.   

  102.         private void Valid()  

  103.         {  

  104.             string echoStr = Request.QueryString["echoStr"];  

  105.             if (CheckSignature())  

  106.             {  

  107.                 if (!string.IsNullOrEmpty(echoStr))  

  108.                 {  

  109.                     Response.Write(echoStr);  

  110.                     Response.End();  

  111.                 }  

  112.             }  

  113.         }  

  114.   

  115.         /// <summary>  

  116.         /// 回复消息(微信信息返回)  

  117.         /// </summary>  

  118.         /// <param name="weixinXML"></param>  

  119.         private void ResponseMsg(RequestXML requestXML)  

  120.         {  

  121.             try  

  122.             {  

  123.                 string resxml = "";  

  124.                 if (requestXML.MsgType == "text")  

  125.                 {  

  126.                     resxml = "<xml><ToUserName><![CDATA[" + requestXML.FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + requestXML.ToUserName + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[正在建设中,稍等时日,更多精彩……]]></Content><FuncFlag>0</FuncFlag></xml>";  

  127.                 }  

  128.                 else if (requestXML.MsgType == "location")  

  129.                 {  

  130.                     string city = GetMapInfo(requestXML.Location_X, requestXML.Location_Y);  

  131.                     if (city == "0")  

  132.                     {  

  133.                         resxml = "<xml><ToUserName><![CDATA[" + requestXML.FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + requestXML.ToUserName + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[Sorry,没有找到" + city + " 的相关产品信息]]></Content><FuncFlag>0</FuncFlag></xml>";  

  134.                     }  

  135.                     else  

  136.                     {  

  137.                         resxml = "<xml><ToUserName><![CDATA[" + requestXML.FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + requestXML.ToUserName + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[Sorry,这是 " + city + " 的产品信息:圈圈叉叉]]></Content><FuncFlag>0</FuncFlag></xml>";  

  138.                     }  

  139.                 }  

  140.                 else if (requestXML.MsgType == "image")  

  141.                 {  

  142.                     //返回10以内条  

  143.                     int size = 10;  

  144.                     resxml = "<xml><ToUserName><![CDATA[" + requestXML.FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + requestXML.ToUserName + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[news]]></MsgType><Content><![CDATA[]]></Content><ArticleCount>" + size + "</ArticleCount><Articles>";  

  145.                     List<string> list = new List<string>();  

  146.                     //假如有20条查询的返回结果  

  147.                     for (int i = 0; i < 20; i++)  

  148.                     {  

  149.                         list.Add("1");  

  150.                     }  

  151.                     string[] piclist = new string[] { "/Abstract_Pencil_Scribble_Background_Vector_main.jpg""/balloon_tree.jpg""/bloom.jpg""/colorful_flowers.jpg""/colorful_summer_flower.jpg""/fall.jpg""/fall_tree.jpg""/growing_flowers.jpg""/shoes_illustration.jpg""/splashed_tree.jpg" };  

  152.   

  153.                     for (int i = 0; i < size && i < list.Count; i++)  

  154.                     {  

  155.                         resxml += "<item><Title><![CDATA[沈阳-黑龙江]]></Title><Description><![CDATA[元旦特价:¥300 市场价:¥400]]></Description><PicUrl><![CDATA[" + "http://www.hougelou.com" + piclist[i] + "]]></PicUrl><Url><![CDATA[http://www.hougelou.com]]></Url></item>";  

  156.                     }  

  157.                     resxml += "</Articles><FuncFlag>1</FuncFlag></xml>";  

  158.                 }  

  159.                 WriteTxt(resxml);  

  160.                 Response.Write(resxml);  

  161.             }  

  162.             catch (Exception ex)  

  163.             {  

  164.                 WriteTxt("异常:"+ex.Message+"Struck:"+ex.StackTrace.ToString());  

  165.             }  

  166.         }  

  167.   

  168.   

  169.   

  170.         /// <summary>  

  171.         /// unix时间转换为datetime  

  172.         /// </summary>  

  173.         /// <param name="timeStamp"></param>  

  174.         /// <returns></returns>  

  175.         private DateTime UnixTimeToTime(string timeStamp)  

  176.         {  

  177.             DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));  

  178.             long lTime = long.Parse(timeStamp + "0000000");  

  179.             TimeSpan toNow = new TimeSpan(lTime);  

  180.             return dtStart.Add(toNow);  

  181.         }  

  182.   

  183.         /// <summary>  

  184.         /// datetime转换为unixtime  

  185.         /// </summary>  

  186.         /// <param name="time"></param>  

  187.         /// <returns></returns>  

  188.         private int ConvertDateTimeInt(System.DateTime time)  

  189.         {  

  190.             System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));  

  191.             return (int)(time - startTime).TotalSeconds;  

  192.         }  

  193.   

  194.         /// <summary>  

  195.         /// 记录bug,以便调试  

  196.         /// </summary>  

  197.         /// <returns></returns>  

  198.         public bool WriteTxt(string str)  

  199.         {  

  200.             try  

  201.             {  

  202.                 FileStream fs = new FileStream(Server.MapPath("/bugLog.txt"), FileMode.Append);  

  203.                 StreamWriter sw = new StreamWriter(fs);  

  204.                 //开始写入  

  205.                 sw.WriteLine(str);  

  206.                 //清空缓冲区  

  207.                 sw.Flush();  

  208.                 //关闭流  

  209.                 sw.Close();  

  210.                 fs.Close();  

  211.             }  

  212.             catch (Exception)  

  213.             {  

  214.                 return false;  

  215.             }  

  216.             return true;  

  217.         }  

  218.   

  219.         /// <summary>  

  220.         /// 调用百度地图,返回坐标信息  

  221.         /// </summary>  

  222.         /// <param name="y">经度</param>  

  223.         /// <param name="x">纬度</param>  

  224.         /// <returns></returns>  

  225.         public string GetMapInfo(string x, string y)  

  226.         {  

  227.             try  

  228.             {  

  229.                 string res = string.Empty;  

  230.                 string parame = string.Empty;  

  231.                 string url = "http://maps.googleapis.com/maps/api/geocode/xml";  

  232.                 parame = "latlng=" + x + "," + y + "&language=zh-CN&sensor=false";//此key为个人申请  

  233.                 res = webRequestPost(url, parame);  

  234.   

  235.                 XmlDocument doc = new XmlDocument();  

  236.   

  237.                 doc.LoadXml(res);  

  238.                 XmlElement rootElement = doc.DocumentElement;  

  239.                 string Status = rootElement.SelectSingleNode("status").InnerText;  

  240.                 if (Status == "OK")  

  241.                 {  

  242.                     //仅获取城市  

  243.                     XmlNodeList xmlResults = rootElement.SelectSingleNode("/GeocodeResponse").ChildNodes;  

  244.                     for (int i = 0; i < xmlResults.Count; i++)  

  245.                     {  

  246.                         XmlNode childNode = xmlResults[i];  

  247.                         if (childNode.Name == "status")  

  248.                         {  

  249.                             continue;  

  250.                         }  

  251.   

  252.                         string city = "0";  

  253.                         for (int w = 0; w < childNode.ChildNodes.Count; w++)  

  254.                         {  

  255.                             for (int q = 0; q < childNode.ChildNodes[w].ChildNodes.Count; q++)  

  256.                             {  

  257.                                 XmlNode childeTwo = childNode.ChildNodes[w].ChildNodes[q];  

  258.   

  259.                                 if (childeTwo.Name == "long_name")  

  260.                                 {  

  261.                                     city = childeTwo.InnerText;  

  262.                                 }  

  263.                                 else if (childeTwo.InnerText == "locality")  

  264.                                 {  

  265.                                     return city;  

  266.                                 }  

  267.                             }   

  268.                         }  

  269.                         return city;  

  270.                     }  

  271.                 }  

  272.             }  

  273.             catch (Exception ex)  

  274.             {  

  275.                 WriteTxt("map异常:" + ex.Message.ToString() + "Struck:" + ex.StackTrace.ToString());  

  276.                 return "0";  

  277.             }  

  278.   

  279.             return "0";  

  280.         }  

  281.   

  282.         /// <summary>  

  283.         /// Post 提交调用抓取  

  284.         /// </summary>  

  285.         /// <param name="url">提交地址</param>  

  286.         /// <param name="param">参数</param>  

  287.         /// <returns>string</returns>  

  288.         public string webRequestPost(string url, string param)  

  289.         {  

  290.             byte[] bs = System.Text.Encoding.UTF8.GetBytes(param);  

  291.   

  292.             HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url+"?"+param);  

  293.             req.Method = "Post";  

  294.             req.Timeout = 120 * 1000;  

  295.             req.ContentType = "application/x-www-form-urlencoded;";  

  296.             req.ContentLength = bs.Length;  

  297.   

  298.             using (Stream reqStream = req.GetRequestStream())  

  299.             {  

  300.                 reqStream.Write(bs, 0, bs.Length);  

  301.                 reqStream.Flush();  

  302.             }  

  303.             using (WebResponse wr = req.GetResponse())  

  304.             {  

  305.                 //在这里对接收到的页面内容进行处理   

  306.   

  307.                 Stream strm = wr.GetResponseStream();  

  308.   

  309.                 StreamReader sr = new StreamReader(strm, System.Text.Encoding.UTF8);  

  310.   

  311.                 string line;  

  312.   

  313.                 System.Text.StringBuilder sb = new System.Text.StringBuilder();  

  314.   

  315.                 while ((line = sr.ReadLine()) != null)  

  316.                 {  

  317.                     sb.Append(line + System.Environment.NewLine);  

  318.                 }  

  319.                 sr.Close();  

  320.                 strm.Close();  

  321.                 return sb.ToString();  

  322.             }  

  323.         }  

  324.   

  325.   

  326.     }  

  327.   

  328.     //微信请求类  

  329.     public class RequestXML  

  330.     {  

  331.         private string toUserName;  

  332.         /// <summary>  

  333.         /// 消息接收方微信号,一般为公众平台账号微信号  

  334.         /// </summary>  

  335.         public string ToUserName  

  336.         {  

  337.             get { return toUserName; }  

  338.             set { toUserName = value; }  

  339.         }  

  340.   

  341.         private string fromUserName;  

  342.         /// <summary>  

  343.         /// 消息发送方微信号  

  344.         /// </summary>  

  345.         public string FromUserName  

  346.         {  

  347.             get { return fromUserName; }  

  348.             set { fromUserName = value; }  

  349.         }  

  350.   

  351.         private string createTime;  

  352.         /// <summary>  

  353.         /// 创建时间  

  354.         /// </summary>  

  355.         public string CreateTime  

  356.         {  

  357.             get { return createTime; }  

  358.             set { createTime = value; }  

  359.         }  

  360.   

  361.         private string msgType;  

  362.         /// <summary>  

  363.         /// 信息类型 地理位置:location,文本消息:text,消息类型:image  

  364.         /// </summary>  

  365.         public string MsgType  

  366.         {  

  367.             get { return msgType; }  

  368.             set { msgType = value; }  

  369.         }  

  370.   

  371.         private string content;  

  372.         /// <summary>  

  373.         /// 信息内容  

  374.         /// </summary>  

  375.         public string Content  

  376.         {  

  377.             get { return content; }  

  378.             set { content = value; }  

  379.         }  

  380.   

  381.         private string location_X;  

  382.         /// <summary>  

  383.         /// 地理位置纬度  

  384.         /// </summary>  

  385.         public string Location_X  

  386.         {  

  387.             get { return location_X; }  

  388.             set { location_X = value; }  

  389.         }  

  390.   

  391.         private string location_Y;  

  392.         /// <summary>  

  393.         /// 地理位置经度  

  394.         /// </summary>  

  395.         public string Location_Y  

  396.         {  

  397.             get { return location_Y; }  

  398.             set { location_Y = value; }  

  399.         }  

  400.   

  401.         private string scale;  

  402.         /// <summary>  

  403.         /// 地图缩放大小  

  404.         /// </summary>  

  405.         public string Scale  

  406.         {  

  407.             get { return scale; }  

  408.             set { scale = value; }  

  409.         }  

  410.   

  411.         private string label;  

  412.         /// <summary>  

  413.         /// 地理位置信息  

  414.         /// </summary>  

  415.         public string Label  

  416.         {  

  417.             get { return label; }  

  418.             set { label = value; }  

  419.         }  

  420.   

  421.         private string picUrl;  

  422.         /// <summary>  

  423.         /// 图片链接,开发者可以用HTTP GET获取  

  424.         /// </summary>  

  425.         public string PicUrl  

  426.         {  

  427.             get { return picUrl; }  

  428.             set { picUrl = value; }  

  429.         }  

  430.     }  

  431. }  


你可能感兴趣的:(服务器配置,微信服务号,token验证)