首頁  >  文章  >  後端開發  >  C#微信公眾號發展 微信事件交互

C#微信公眾號發展 微信事件交互

高洛峰
高洛峰原創
2017-01-17 10:42:511197瀏覽

前言

一切準備工作就緒時就先實現一個關注公眾號後向客戶端推送一條訊息。關注後推播訊息需要一個get請求、一個post請求,get請求主要是為了向微信伺服器驗證,post請求主要就是處理微信訊息了。 調接口時傳遞的appid和appsecret請傳遞自己公眾號對應的參數。

微信事件互動

微信事件交互主要是向微信伺服器推送XML封包

C#微信公众号开发 微信事件交互

看程式碼

[HttpGet]
[ActionName("Index")]
public ActionResult Get(string signature,string timestamp,string nonce,string echostr)
{
  if (CheckSignature.Check(signature, timestamp, nonce, token))
  {
    return Content(echostr);
  }
  else
  {
    return Content("err");
  }
[HttpPost]
[ActionName("Index")]
public ActionResult Get(string signature, string timestamp, string nonce)
{
   StreamReader sr = new StreamReader(Request.InputStream, Encoding.UTF8);
   XmlDocument doc = new XmlDocument();
   doc.Load(sr);
   sr.Close();
   sr.Dispose();
  
   WxMessage wxMessage = new WxMessage();
   wxMessage.ToUserName = doc.SelectSingleNode("xml").SelectSingleNode("ToUserName").InnerText;
   wxMessage.FromUserName = doc.SelectSingleNode("xml").SelectSingleNode("FromUserName").InnerText;
   wxMessage.MsgType = doc.SelectSingleNode("xml").SelectSingleNode("MsgType").InnerText;
   wxMessage.CreateTime = int.Parse(doc.SelectSingleNode("xml").SelectSingleNode("CreateTime").InnerText);
  
   if (wxMessage.MsgType == "event")
   {
     wxMessage.EventName = doc.SelectSingleNode("xml").SelectSingleNode("Event").InnerText;
     if (!string.IsNullOrEmpty(wxMessage.EventName) && wxMessage.EventName == "subscribe")
     {
       string content = "您好,欢迎访问garfieldzf8测试公众平台";
       content = SendTextMessage(wxMessage, content);
       return Content(content);
    }
  }
      return Content("");
}
  
  
private string SendTextMessage(WxMessage wxmessage,string content)
{
   string result = string.Format(Message, wxmessage.FromUserName,wxmessage.ToUserName,DateTime.Now.Ticks, content);
   return result;
}
  
  
 public string Message
 {
   get
   {
     return @"<xml>
           <ToUserName><![CDATA[{0}]]></ToUserName>
           <FromUserName><![CDATA[{1}]]></FromUserName>
           <CreateTime>{2}</CreateTime>
           <MsgType><![CDATA[text]]></MsgType>
           <Content><![CDATA[{3}]]></Content>
         </xml>";
      }
  }
rr 關鍵的地方記log。

     微信事件互動主要是分析微信傳送的xml封包,解析xml,並依照訊息指定格式拼接xml傳送給response。在Get方法裡用到的CheckSignature 是盛派微信SDK的一個類,也就是對簽章校驗。

     傳送訊息給客戶端時主要ToUserName和FromUserName。我一開始把兩個參數寫反了導致客戶端收不到訊息。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持PHP中文網。

更多C#微信公眾號開發 微信事件互動相關文章請關注PHP中文網!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn