C# 微信公众平台开发(3)-- 接受/发送消息

时间:2024-02-29 17:17:43

1.接收事件

  关注/取消关注事件;

  用户在关注与取消关注公众号时,微信会把这个事件推送到开发者填写的URL。

 

通过微信返回的XML,我们通过代码 就可以作相应的处理;

先获取返回的信息:

 1     if (HttpContext.Current.Request.HttpMethod.ToUpper() == "POST")
 2             {
 3                 using (Stream stream = HttpContext.Current.Request.InputStream)
 4                 {
 5                     Byte[] postBytes = new Byte[stream.Length];
 6                     stream.Read(postBytes, 0, (Int32)stream.Length);
 7                     postString = Encoding.UTF8.GetString(postBytes);
 8                     EventHandle(postString);
 9                 }
10 
11                 if (!string.IsNullOrEmpty(postString))
12                 {
13                     responseMsg(postString, context);//关注微信,返回消息
14                 }
15             }
postString  里面 就是XML;我们只需要对 XML作相应的处理就好
   System.Xml.XmlDocument postObj = new      System.Xml.XmlDocument();
                postObj.LoadXml(postStr);

       var eventList = postObj.GetElementsByTagName("Event");
    var textpl = "";
   string FromUserName = string.Empty;

                for (int i = 0; i < FromUserNameList.Count; i++)
                {
                    if (FromUserNameList[i].ChildNodes[0].NodeType == System.Xml.XmlNodeType.CDATA)
                    {
                        FromUserName = FromUserNameList[i].ChildNodes[0].Value;
                    }
                }
   var toUsernameList = postObj.GetElementsByTagName("ToUserName");
                string ToUserName = string.Empty;
                for (int i = 0; i < toUsernameList.Count; i++)
                {
                    if (toUsernameList[i].ChildNodes[0].NodeType == System.Xml.XmlNodeType.CDATA)
                    {
                        ToUserName = toUsernameList[i].ChildNodes[0].Value;
                    }
                }
    if (toEvent == "subscribe")
                    {
                        string rebakcHtml = @"Hi,欢迎来到我爱足球社区";
              //ReceivedText 返回文本消息的格式 textpl
= type.ReceivedText(FromUserName, ToUserName, rebakcHtml); }

 1   /// <summary>
 2         /// 回复文本
 3         /// </summary>
 4         /// <param name="FromUserName"></param>
 5         /// <param name="ToUserName"></param>
 6         /// <param name="Content"></param>
 7         /// <returns></returns>
 8         public string ReceivedText(string FromUserName, string ToUserName, string Content)
 9         {
10 
11             string textpl = string.Empty;
12             textpl = "<xml>" +
13                      "<ToUserName><![CDATA[" + FromUserName + "]]></ToUserName>" +
14                      "<FromUserName><![CDATA[" + ToUserName + "]]></FromUserName>" +
15                      "<CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime>" +
16                      "<MsgType><![CDATA[text]]></MsgType>" +
17                      "<Content><![CDATA[" + Content + "]]></Content>" +
18                      "<FuncFlag>0</FuncFlag>" +
19                      "</xml>";
20 
21             return textpl;
22         }
文本消息

 System.Web.HttpContext.Current.Response.Write(textpl); 我们将文本信息 返回给微信;

2.点击按钮

 1 #region 微信菜单点击事件
 2 
 3         /// <summary>
 4         /// 微信菜单点击事件
 5         /// </summary>
 6         /// <param name="postStr">接受消息</param>
 7         /// <returns></returns>
 8         private void EventHandle(string postStr)
 9         {
10             string responseContent = "";
11             try
12             {
13                 System.Xml.XmlDocument xmldoc = new System.Xml.XmlDocument();
14                 xmldoc.LoadXml(postStr);
15 
16                 XmlNode Event = xmldoc.SelectSingleNode("/xml/Event");
17                 XmlNode EventKey = xmldoc.SelectSingleNode("/xml/EventKey");
18                 XmlNode ToUserName = xmldoc.SelectSingleNode("/xml/ToUserName");
19                 XmlNode FromUserName = xmldoc.SelectSingleNode("/xml/FromUserName");
20 
21                 if (Event != null)
22                 {
23                     if (EventKey.InnerText.Equals("V1001_ORDER"))//EventKey.InnerText.Equals("V1001_ORDER") 就是创建菜单时,click按钮的唯一Key
24                     {
25                         responseContent = string.Format(Message_Text,
26                              FromUserName.InnerText,
27                              ToUserName.InnerText,
28                              DateTime.Now.Ticks,
29                              "您好,小萌为您服务,请回复十四位订单号,查询订单详情。");//生成文本消息
30                     }
31                         responseContent = type.ReceivedText(FromUserName.InnerText, ToUserName.InnerText, rebakcHtml);
32                     }
33                 }
34 
35                 LogTextHelper.WriteLogToFile(responseContent + "------------------" + postStr);
36                 HttpContext.Current.Response.Write(responseContent);//返回给微信
37             }
38             catch (Exception ex)
39             {
40                 LogTextHelper.WriteLogToFile("微信菜单点击事件" + "||" + ex.ToString());
41             }
42         }
43 
44         /// <summary>
45         /// 普通文本消息
46         /// </summary>
47         public static string Message_Text
48         {
49             get
50             {
51                 return @"<xml>                             
52                              <ToUserName><![CDATA[{0}]]></ToUserName>                             
53                              <FromUserName><![CDATA[{1}]]></FromUserName>
54                              <CreateTime>{2}</CreateTime>
55                              <MsgType><![CDATA[text]]></MsgType>
56                              <Content><![CDATA[{3}]]></Content>
57                              </xml>";
58             }
59         }
60 
61         #endregion

3.接受消息:

 接受消息 跟关注微信号有点类似:

消息内容 

var keywordList = postObj.GetElementsByTagName("Content"); 

string Content = string.Empty;
  for (int i = 0; i < keywordList.Count; i++)
  {
    if (keywordList[i].ChildNodes[0].NodeType == System.Xml.XmlNodeType.CDATA)
      {
        Content = keywordList[i].ChildNodes[0].Value;
      }
  }

1 if (toMsgType == "text")//接口文本消息 toMsgType是消息类型
2     {
      //ToDo 根据业务 处理消息内容
3 4 else if (toMsgType == "event")//关注 5 { 6 if (toEvent == "subscribe") 7 { 8 9

请点击我 --我爱足球