频道栏目
首页 > 资讯 > 微信公众平台开发 > 正文

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

15-12-27        来源:[db:作者]  
收藏   我要投稿

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

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

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

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

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

1、项目:MVC

2、我们要接收微信服务器推送的消息,那么很简单,知道aspx页面的肯定知道对应的cs中会有一个PageLoad(),比如说我们部署到服务器上的是http://www.hskchw.com/Index.aspx

当我们访问这个页面的时候就会加载到PageLoad里面是不是,那么好了我们就在这里面接收不就好了吗,然后再根据相应的类型去做判断,符合条件的调用相应的方法去返回数据。好了整个交互流程结束了,

代码就完成了。

3、

  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         }
 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         }
 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         }
 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     }
 1     public abstract class ReceiveModel
 2     {
 3 
 4         /// 
 5         /// 接收方帐号(收到的OpenID)
 6         /// 
 7         public string ToUserName { get; set; }
 8         /// 
 9         /// 发送方帐号(一个OpenID)
10         /// 
11         public string FromUserName { get; set; }
12         /// 
13         /// 消息创建时间 (整型)
14         /// 
15         public string CreateTime { get; set; }
16         /// 
17         /// 消息类型
18         /// 
19         public string MsgType { get; set; }
20 
21         /// 
22         /// 当前实体的XML字符串
23         /// 
24         public string Xml { get; set; }
25     }
26     /// 
27     /// 接收普通消息-文本消息
28     /// 
29     public class Receive_Text : ReceiveModel
30     {
31 
32         /// 
33         ///  文本消息内容
34         /// 
35         public string Content { get; set; }
36 
37         /// 
38         ///  消息id,64位整型
39         /// 
40         public string MsgId { get; set; }
41     }
public class Xml
    {
        #region 文本xml
        /// <summary>
        /// ToUserName:用户ID(OpenID)
        /// FromUserName:开发者
        /// CreateTime:时间
        /// Content:内容
        /// </summary>
        public static string TextMsg
        {
            get
            {
                return @"
                    <xml>
                    <ToUserName><![CDATA[{0}]]></ToUserName>
                    <FromUserName><![CDATA[{1}]]></FromUserName> 
                    <CreateTime>{2}</CreateTime>
                    <MsgType><![CDATA[text]]></MsgType>
                    <Content><![CDATA[{3}]]></Content>
                    </xml>
                    ";
            }
        }
        #endregion
}
相关TAG标签
上一篇:微商怎么做,微信快速加人方法
下一篇:iOS微信小视频优化心得
相关文章
图文推荐

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站