前言
一切準備工作就緒時就先實現一個關注公眾號後向客戶端推送一條訊息。關注後推播訊息需要一個get請求、一個post請求,get請求主要是為了向微信伺服器驗證,post請求主要就是處理微信訊息了。 調接口時傳遞的appid和appsecret請傳遞自己公眾號對應的參數。
微信事件互動
微信事件交互主要是向微信伺服器推送XML封包
看程式碼
[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>"; } }