C# .NET 微信开发-------当微信服务器推送消息时如何接收处理

最近一直在看微信,整整一个月了,看到现在说实话还有很多没看的,从前两周一点看不懂到现在单个功能的一步步实现,不知道这样的速度是否太慢了。

不过现在往下看还是有思路了,目前整个文档完成学习只有1/3左右,但是看过的每个接口都是测试过的。学习很重要,但是有人指引将会效率翻倍,但是谁会愿意无偿花自己的时间给你呢,所以嘛。。。就不说了,

好了,牢骚到此,对于我这篇文章有什么不明白的或者需要交流的请加   QQ群:216390234   

首先来门要有思路对吧,我们不是流水线的工人,而是系统的创造者,所以我们要有思想而不是一味的写代码,写到最后发现哪哪都不合适然后去修改,发现修改的时间远远大于开发的时间,那样就徒劳了。

这篇很简单适用于刚刚入门的开发者:

对于微信的基本配置我就不阐述了,网上讲解的很详细了。

1、项目:MVC(不是api)

2、

  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

4、上面是代码整个流程所用到的代码都贴出来了,有什么不明白的可以加上面的QQ群

原文地址:https://www.cnblogs.com/myloveblogs/p/5075967.html