公眾平臺(tái)信息接口為開發(fā)者提供了一種新的消息處理方式,只有申請成為開發(fā)者后,你才能使用公眾平臺(tái)的開發(fā)功能,在這里你需要填寫一個(gè)URL和一個(gè)Token,這兩項(xiàng)信息也需要你擁有自己的服務(wù)器(外網(wǎng)服務(wù)器)資源,其中的Token可由開發(fā)者任意填寫,URL即是接口配置信息的鏈接地址,在本文中我采用的是創(chuàng)建一個(gè)簡易網(wǎng)站的方式,在其中的一個(gè)頁面的后臺(tái)程序中配置相關(guān)的接口信息,然后發(fā)布到外網(wǎng)服務(wù)器上,最后可以訪問到這個(gè)頁面的鏈接地址即是這里應(yīng)該填寫的URL。
/// summary>
/// 驗(yàn)證微信簽名
/// /summary>
/// returns>/returns>
private bool CheckSignature()
{
string signature = Request.QueryString["signature"].ToString();
string timestamp = Request.QueryString["timestamp"].ToString();
string nonce = Request.QueryString["nonce"].ToString();
string[] ArrTmp = { Token, timestamp, nonce };
Array.Sort(ArrTmp);//字典排序
string tmpStr = string.Join("", ArrTmp);
tmpStr = FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1");//對(duì)該字符串進(jìn)行sha1加密
tmpStr = tmpStr.ToLower();//對(duì)字符串中的字母部分進(jìn)行小寫轉(zhuǎn)換,非字母字符不作處理
//WriteLog(tmpStr, Server);//計(jì)入日志
if (tmpStr == signature)//開發(fā)者獲得加密后的字符串可與signature對(duì)比,標(biāo)識(shí)該請求來源于微信。開發(fā)者通過檢驗(yàn)signature對(duì)請求進(jìn)行校驗(yàn),若確認(rèn)此次GET請求來自微信服務(wù)器,請?jiān)瓨臃祷豦chostr參數(shù)內(nèi)容,則接入生效,否則接入失敗
{
return true;
}
else
return false;
}
/// summary>
/// 獲取post返回來的數(shù)據(jù)
/// /summary>
/// returns>/returns>
private string PostInput()
{
Stream s = System.Web.HttpContext.Current.Request.InputStream;
byte[] b = new byte[s.Length];
s.Read(b, 0, (int)s.Length);
return Encoding.UTF8.GetString(b);
}
/// summary>
///返回微信信息結(jié)果
/// /summary>
/// param name="weixinXML">/param>
private void ResponseMsg(string weixinXML)
{
try
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(weixinXML);//讀取XML字符串
XmlElement rootElement = doc.DocumentElement;
XmlNode MsgType = rootElement.SelectSingleNode("MsgType");//獲取字符串中的消息類型
string resxml = "";
if (MsgType.InnerText == "text")//如果消息類型為文本消息
{
var model = new
{
ToUserName = rootElement.SelectSingleNode("ToUserName").InnerText,
FromUserName = rootElement.SelectSingleNode("FromUserName").InnerText,
CreateTime = rootElement.SelectSingleNode("CreateTime").InnerText,
MsgType = MsgType.InnerText,
Content = rootElement.SelectSingleNode("Content").InnerText,
MsgId = rootElement.SelectSingleNode("MsgId").InnerText
};
resxml += "xml>ToUserName>![CDATA[" + model.FromUserName + "]]>/ToUserName>FromUserName>![CDATA[" + model.ToUserName + "]]>/FromUserName>CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "/CreateTime>";
if (!string.IsNullOrEmpty(model.Content))//如果接收到消息
{
if (model.Content.Contains(" 你好") || model.Content.Contains(" 好") || model.Content.Contains("hi") || model.Content.Contains("hello"))// 你好
{
resxml += "MsgType>![CDATA[text]]>/MsgType>Content>![CDATA[你好,有事請留言,偶會(huì)及時(shí)回復(fù)你的。]]>/Content>FuncFlag>0/FuncFlag>/xml>";
}
}
else//沒有接收到消息
{
resxml += "MsgType>![CDATA[text]]>/MsgType>Content>![CDATA[親,感謝您對(duì)我的關(guān)注,有事請留言。]]>/Content>FuncFlag>0/FuncFlag>/xml>";
}
Response.Write(resxml);
}
if (MsgType.InnerText == "image")//如果消息類型為圖片消息
{
var model = new
{
ToUserName = rootElement.SelectSingleNode("ToUserName").InnerText,
FromUserName = rootElement.SelectSingleNode("FromUserName").InnerText,
CreateTime = rootElement.SelectSingleNode("CreateTime").InnerText,
MsgType = MsgType.InnerText,
PicUrl = rootElement.SelectSingleNode("PicUrl").InnerText,
MsgId = rootElement.SelectSingleNode("MsgId").InnerText
};
resxml += "xml>ToUserName>![CDATA[" + model.FromUserName + "]]>/ToUserName>FromUserName>![CDATA[" + model.ToUserName + "]]>/FromUserName>CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "/CreateTime>MsgType>![CDATA[news]]>/MsgType>ArticleCount>1/ArticleCount>Articles>item>Title>![CDATA[歡迎您的光臨!]]>/Title>Description>![CDATA[非常感謝您的關(guān)注!]]>/Description>PicUrl>![CDATA[http://...jpg]]>/PicUrl>Url>![CDATA[http://www.baidu.com/]]>/Url>/item>/Articles>FuncFlag>0/FuncFlag>/xml>";
Response.Write(resxml);
}
else//如果是其余的消息類型
{
var model = new
{
ToUserName = rootElement.SelectSingleNode("ToUserName").InnerText,
FromUserName = rootElement.SelectSingleNode("FromUserName").InnerText,
CreateTime = rootElement.SelectSingleNode("CreateTime").InnerText,
};
resxml += "xml>ToUserName>![CDATA[" + model.FromUserName + "]]>/ToUserName>FromUserName>![CDATA[" + model.ToUserName + "]]>/FromUserName>CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "/CreateTime>MsgType>![CDATA[text]]>/MsgType>Content>![CDATA[親,感謝您對(duì)我的關(guān)注,有事請留言,我會(huì)及時(shí)回復(fù)你的哦。]]>/Content>FuncFlag>0/FuncFlag>/xml>";
Response.Write(resxml);
}
}
catch (Exception ex)
{
throw ex;
}
Response.End();
}
/// summary>
/// datetime轉(zhuǎn)換成unixtime
/// /summary>
/// param name="time">/param>
/// returns>/returns>
private int ConvertDateTimeInt(System.DateTime time)
{
System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
return (int)(time - startTime).TotalSeconds;
}
/// summary>
/// 寫日志(用于跟蹤),可以將想打印出的內(nèi)容計(jì)入一個(gè)文本文件里面,便于測試
/// /summary>
public static void WriteLog(string strMemo, HttpServerUtility server)
{
string filename = server.MapPath("/logs/log.txt");//在網(wǎng)站項(xiàng)目中建立一個(gè)文件夾命名logs(然后在文件夾中隨便建立一個(gè)web頁面文件,避免網(wǎng)站在發(fā)布到服務(wù)器之后看不到預(yù)定文件)
if (!Directory.Exists(server.MapPath("http://logs//")))
Directory.CreateDirectory("http://logs//");
StreamWriter sr = null;
try
{
if (!File.Exists(filename))
{
sr = File.CreateText(filename);
}
else
{
sr = File.AppendText(filename);
}
sr.WriteLine(strMemo);
}
catch
{
}
finally
{
if (sr != null)
sr.Close();
}
}