C# .NET 微信開發-------當微信服務器推送消息時如何接收處理

最近一直在看微信,整整一個月了,看到如今說實話還有不少沒看的,從前兩週一點看不懂到如今單個功能的一步步實現,不知道這樣的速度是否太慢了。api

不過如今往下看仍是有思路了,目前整個文檔完成學習只有1/3左右,可是看過的每一個接口都是測試過的。學習很重要,可是有人指引將會效率翻倍,可是誰會願意無償花本身的時間給你呢,因此嘛。。。就不說了,微信

好了,牢騷到此,對於我這篇文章有什麼不明白的或者須要交流的請加   QQ羣:216390234   ide

 

首先來門要有思路對吧,咱們不是流水線的工人,而是系統的創造者,因此咱們要有思想而不是一味的寫代碼,寫到最後發現哪哪都不合適而後去修改,發現修改的時間遠遠大於開發的時間,那樣就徒勞了。post

 

 

這篇很簡單適用於剛剛入門的開發者:學習

 

對於微信的基本配置我就不闡述了,網上講解的很詳細了。測試

 

一、項目:MVC(不是api)spa

二、code

  1  public ActionResult Index()
  2         {
  3             string result = "";
  4             string postString = string.Empty;
  5             if (Request.HttpMethod.ToUpper() == "POST")
  6             {
  7                 using (Stream stream = System.Web.HttpContext.Current.Request.InputStream)
  8                 {
  9                     Byte[] postBytes = new Byte[stream.Length];
 10                     stream.Read(postBytes, 0, (Int32)stream.Length);
 11                     postString = Encoding.UTF8.GetString(postBytes);
 12                     if (!string.IsNullOrEmpty(postString))
 13                     {
 14                         string SendToWx = string.Empty;
 15                         //這裏寫方法解析Xml
 16                         XmlDocument xml = new XmlDocument();//
 17                         xml.LoadXml(postString);
 18                         XmlElement xmlElement = xml.DocumentElement;
 19                         //這裏進行判斷MsgType
 20                         switch (xmlElement.SelectSingleNode("MsgType").InnerText)
 21                         {
 22                             case "text":
 23                                 SendToWx = WxText.GetWxTextXml(postString);
 24                                 break;
 25                             case "image":
 26                                 SendToWx = WxImage.GetWxImageXml(postString);
 27                                 break;
 28                             case "voice":
 29                                 break;
 30                             case "video":
 31                                 break;
 32                             case "shortvideo":
 33                                 break;
 34                             case "location":
 35                                 break;
 36                             case "link":
 37                                 break;
 38                             case "event":
 39                                 string eventKey = xmlElement.SelectSingleNode("EventKey").InnerText == null ? "" : xmlElement.SelectSingleNode("EventKey").InnerText;
 40                                 switch (xmlElement.SelectSingleNode("Event").InnerText)
 41                                 {
 42                                     case "subscribe":
 43                                         if (string.IsNullOrEmpty(eventKey))
 44                                         {
 45                                             //model = new Models.Receive_Event();
 46                                         }
 47                                         else
 48                                         {
 49                                             //model = new Models.Receive_Event_Scan();
 50                                         }
 51                                         break;
 52                                     case "unsubscribe":
 53                                         break;
 54                                     case "SCAN":
 55                                         break;
 56                                     case "LOCATION":
 57                                         break;
 58                                     case "CLICK":
 59                                         break;
 60                                     case "VIEW":
 61                                         break;
 62                                     default:
 63                                         break;
 64                                 }
 65                                 break;
 66                             default:
 67                                 result = "沒有識別的類型消息:" + xmlElement.SelectSingleNode("MsgType").InnerText;
 68                                 WriteLog(result);
 69                                 break;
 70                         }
 71                         if (!string.IsNullOrEmpty(SendToWx))
 72                         {
 73                             System.Web.HttpContext.Current.Response.Write(SendToWx);
 74                             System.Web.HttpContext.Current.Response.End();
 75                         }
 76                         else
 77                         {
 78                             result = "回傳數據爲空";
 79                             WriteLog(result);
 80                         }
 81                     }
 82                     else
 83                     {
 84                         result = "微信推送的數據爲:" + postString;
 85                         WriteLog(result);
 86                     }
 87                 }
 88             }
 89             else if (Request.HttpMethod.ToUpper() == "GET")
 90             {
 91                 string token = ConfigurationManager.AppSettings["WXToken"];//從配置文件獲取Token
 92                 if (string.IsNullOrEmpty(token))
 93                 {
 94                     result = string.Format("微信Token配置項沒有配置!");
 95                     WriteLog(result);
 96                 }
 97                 string echoString = System.Web.HttpContext.Current.Request.QueryString["echoStr"];
 98                 string signature = System.Web.HttpContext.Current.Request.QueryString["signature"];
 99                 string timestamp = System.Web.HttpContext.Current.Request.QueryString["timestamp"];
100                 string nonce = System.Web.HttpContext.Current.Request.QueryString["nonce"];
101                 if (CheckSignature(token, signature, timestamp, nonce))
102                 {
103                     if (!string.IsNullOrEmpty(echoString))
104                     {
105                         System.Web.HttpContext.Current.Response.Write(echoString);
106                         System.Web.HttpContext.Current.Response.End();
107                         result = string.Format("微信Token配置成功,你已成爲開發者!");
108                         WriteLog(result);
109                     }
110                 }
111             }
112             result = string.Format("頁面被訪問,沒有請求數據!");
113             WriteLog(result);
114             return View();
115         }
View Code
 1  public bool CheckSignature(string token, string signature, string timestamp, string nonce)
 2         {
 3             string[] ArrTmp = { token, timestamp, nonce };
 4             Array.Sort(ArrTmp);
 5             string tmpStr = string.Join("", ArrTmp);
 6             tmpStr = FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1");
 7             tmpStr = tmpStr.ToLower();
 8             if (tmpStr == signature)
 9             {
10                 return true;
11             }
12             else
13             {
14                 return false;
15             }
16         }
View Code
 1  private void WriteLog(string str)
 2         {
 3             try
 4             {
 5                 using (System.IO.FileStream fs = new System.IO.FileStream(Server.MapPath("//LLog//log.txt"), System.IO.FileMode.Append))
 6                 {
 7                     using (System.IO.StreamWriter sw = new System.IO.StreamWriter(fs))
 8                     {
 9                         string strlog = "----" + DateTime.Now.ToString("yyyyMMddHHmmss") + ":" + str + "-----";
10                         sw.WriteLine(strlog);
11                         sw.Close();
12                     }
13                 }
14             }
15             catch
16             { }
17         }
View Code
 1  public class WxText
 2     {
 3         public static string GetWxTextXml(string StrXml)
 4         {
 5             string result = string.Empty;
 6             //加載xml
 7             XmlDocument textXml = new XmlDocument();
 8             textXml.LoadXml(StrXml);
 9             XmlElement xmlElement = textXml.DocumentElement;
10             //轉成model對象
11             Receive_Text model = new Receive_Text()
12             {
13                 ToUserName = xmlElement.SelectSingleNode("ToUserName").InnerText,
14                 FromUserName = xmlElement.SelectSingleNode("FromUserName").InnerText,
15                 CreateTime = xmlElement.SelectSingleNode("CreateTime").InnerText,
16                 MsgType = xmlElement.SelectSingleNode("MsgType").InnerText,
17                 Content = xmlElement.SelectSingleNode("Content").InnerText,
18                 MsgId = xmlElement.SelectSingleNode("MsgId").InnerText
19             };
20             //數據組織拼接返回xml
21             if (model.Content == "你好!")
22             {
23                 //返回的xml
24                 result = string.Format(Xml.TextMsg,model.FromUserName,model.ToUserName,DateTimeHelper.DateTimeToUnixInt(DateTime.Now),"你好!接口測試經過了!恭喜你!");
25             }
26             return result;
27         }
28     }
View Code
 1     public abstract class ReceiveModel
 2     {
 3 
 4         /// <summary>
 5         /// 接收方賬號(收到的OpenID)
 6         /// </summary>
 7         public string ToUserName { get; set; }
 8         /// <summary>
 9         /// 發送方賬號(一個OpenID)
10         /// </summary>
11         public string FromUserName { get; set; }
12         /// <summary>
13         /// 消息建立時間 (整型)
14         /// </summary>
15         public string CreateTime { get; set; }
16         /// <summary>
17         /// 消息類型
18         /// </summary>
19         public string MsgType { get; set; }
20 
21         /// <summary>
22         /// 當前實體的XML字符串
23         /// </summary>
24         public string Xml { get; set; }
25     }
26     /// <summary>
27     /// 接收普通消息-文本消息
28     /// </summary>
29     public class Receive_Text : ReceiveModel
30     {
31 
32         /// <summary>
33         ///  文本消息內容
34         /// </summary>
35         public string Content { get; set; }
36 
37         /// <summary>
38         ///  消息id,64位整型
39         /// </summary>
40         public string MsgId { get; set; }
41     }
View Code
 1  public class Xml
 2     {
 3         #region 文本xml
 4         /// <summary>
 5         /// ToUserName:用戶ID(OpenID)
 6         /// FromUserName:開發者
 7         /// CreateTime:時間
 8         /// Content:內容
 9         /// </summary>
10         public static string TextMsg
11         {
12             get
13             {
14                 return @"
15                     <xml>
16                     <ToUserName><![CDATA[{0}]]></ToUserName>
17                     <FromUserName><![CDATA[{1}]]></FromUserName> 
18                     <CreateTime>{2}</CreateTime>
19                     <MsgType><![CDATA[text]]></MsgType>
20                     <Content><![CDATA[{3}]]></Content>
21                     </xml>
22                     ";
23             }
24         }
25         #endregion
26 }
View Code

 

四、上面是代碼整個流程所用到的代碼都貼出來了,有什麼不明白的能夠加上面的QQ羣orm

相關文章
相關標籤/搜索