微信公众平台开发之发送文本消息.Net代码解析

时间:2022-07-07 11:21:22

.Net实现微信公共服务平台开发中的发送文本消息功能,具体内容如下

首先建立一个微信消息类。 

?
1
2
3
4
5
6
7
8
9
class wxmessage
{
 public string FromUserName { get; set; }
 public string ToUserName { get; set; }
 public string MsgType { get; set; }
 public string EventName { get; set; }
 public string Content { get; set; }
 public string EventKey { get; set; }
}

 后台代码如下: 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
protected void Page_Load(object sender, EventArgs e)
  {
   wxmessage wx = GetWxMessage();
   string res = "";
 
   if (!string.IsNullOrEmpty(wx.EventName) && wx.EventName.Trim() == "subscribe")
   {//刚关注时的时间,用于欢迎词
    string content = "";
    content = "/:rose欢迎北京永杰友信科技有限公司/:rose\n直接回复“你好”";
    res = sendTextMessage(wx, content);
   }
   else
   {
    if (wx.MsgType == "text" && wx.Content == "你好")
    {
     res = sendTextMessage(wx, "你好,欢迎使用北京永杰友信科技有限公司公共微信平台!");
    }
    else
    {
     res = sendTextMessage(wx, "你好,未能识别消息!");
    }
   }
 
   Response.Write(res);
  }
 
 private wxmessage GetWxMessage()
  {
   wxmessage wx = new wxmessage();
   StreamReader str = new StreamReader(Request.InputStream, System.Text.Encoding.UTF8);
   XmlDocument xml = new XmlDocument();
   xml.Load(str);
   wx.ToUserName = xml.SelectSingleNode("xml").SelectSingleNode("ToUserName").InnerText;
   wx.FromUserName = xml.SelectSingleNode("xml").SelectSingleNode("FromUserName").InnerText;
   wx.MsgType = xml.SelectSingleNode("xml").SelectSingleNode("MsgType").InnerText;
   if (wx.MsgType.Trim() == "text")
   {
    wx.Content = xml.SelectSingleNode("xml").SelectSingleNode("Content").InnerText;
   }
   if (wx.MsgType.Trim() == "event")
   {
    wx.EventName = xml.SelectSingleNode("xml").SelectSingleNode("Event").InnerText;
   }
 
   
   return wx;
  }
 
///
  /// 发送文字消息
  ///
  /// 获取的收发者信息
  /// 内容
  ///
  private string sendTextMessage(wxmessage wx, string content)
  {
   string res = string.Format(@" ",
    wx.FromUserName, wx.ToUserName, DateTime.Now, content);
   return res;
  }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。