一切准備工作就緒時就先實現一個關注公眾號後向客戶端推送一條消息。關注後推送消息需要一個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>";
}
}
public class WxMessage
{
public string ToUserName { get; set; }
public string FromUserName { get; set; }
public long CreateTime { get; set; }
public string Content { get; set; }
public string MsgType { get; set; }
public string EventName { get; set; }
public string EventKey { get; set; }
}
開發微信接口的過程中不能調試,唯一排除問題的方式就是在關鍵的地方記log。
微信事件交互主要是分析微信發送的xml數據包,解析xml,並按照消息指定格式拼接xml發送給response。在Get方法裡用到的CheckSignature 是盛派微信SDK的一個類,也就是對簽名校驗。
向客戶端發送消息時主要ToUserName和FromUserName。我一開始把兩個參數寫反了導致客戶端收不到消息。