1. 在微信公众号中,开发 --> 基本配置
2. post的服务器地址
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Request.HttpMethod.ToLower() == "post")
{
string postStr = "";
postStr = PostInput();//获取xml数据
string weixin = "";
weixin = postStr;//获取xml数据
if (!string.IsNullOrEmpty(postStr) && !string.IsNullOrEmpty(weixin))
{
try
{//注册
XmlDocument doc1 = new XmlDocument();
doc1.LoadXml(weixin);//读取xml字符串
XmlNodeList list = doc1.GetElementsByTagName("xml");
XmlNode xn = list[0];
string Event = xn.SelectSingleNode("//Event").InnerText;
string FromUserName = xn.SelectSingleNode("//FromUserName").InnerText;
string EventKey = xn.SelectSingleNode("//EventKey").InnerText;
}
catch
{
}
XmlDocument doc = new XmlDocument();
doc.LoadXml(postStr);//读取xml字符串
//公众号发消息
XmlElement root = doc.DocumentElement;
ExmlMsg xmlMsg = GetExmlMsg(root);
ResponseMsg(xmlMsg);////调用消息适配器
}
}
Valid();
}
}
#region 获取post请求数据
///
/// 获取post请求数据
///
///
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);
}
#endregion
#region 接收的消息实体类 以及 填充方法
private class ExmlMsg
{
///
/// 本公众账号
///
public string ToUserName { get; set; }
///
/// 用户账号
///
public string FromUserName { get; set; }
///
/// 发送时间戳
///
public string CreateTime { get; set; }
///
/// 发送的文本内容
///
public string Content { get; set; }
///
/// 消息的类型
///
public string MsgType { get; set; }
///
/// 事件名称
///
public string EventName { get; set; }
}
private ExmlMsg GetExmlMsg(XmlElement root)
{
ExmlMsg xmlMsg = new ExmlMsg()
{
FromUserName = root.SelectSingleNode("FromUserName").InnerText,
ToUserName = root.SelectSingleNode("ToUserName").InnerText,
CreateTime = root.SelectSingleNode("CreateTime").InnerText,
MsgType = root.SelectSingleNode("MsgType").InnerText,
};
if (xmlMsg.MsgType.Trim().ToLower() == "text")
{
xmlMsg.Content = root.SelectSingleNode("Content").InnerText;
}
else if (xmlMsg.MsgType.Trim().ToLower() == "event")
{
xmlMsg.EventName = root.SelectSingleNode("Event").InnerText;
}
return xmlMsg;
}
#endregion
// token验证
private void Valid()
{
string echoStr = Request.QueryString["echoStr"].ToString();
if (CheckSignature())
{
if (!string.IsNullOrEmpty(echoStr))
{
Response.Write(echoStr);
Response.End();
}
}
}
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");
tmpStr = tmpStr.ToLower();
if (tmpStr == signature)
{
return true;
}
else
{
return false;
}
}
#region 消息类型适配器
private void ResponseMsg(ExmlMsg xmlMsg)// 服务器响应微信请求
{
string messageType = xmlMsg.MsgType;//获取收到的消息类型。文本(text),图片(image),语音等。
try
{
switch (messageType)
{
//当消息为文本时
case "text":
textCase(xmlMsg);
break;
case "event":
textCase1(xmlMsg);
break;
case "image":
textCase(xmlMsg);
break;
case "voice":
textCase(xmlMsg);
break;
case "vedio":
textCase(xmlMsg);
break;
case "location":
textCase(xmlMsg);
break;
case "link":
textCase(xmlMsg);
break;
default:
break;
}
Response.End();
}
catch (Exception)
{
}
}
#endregion
#region 发送消息 操作文本消息 + void textCase(XmlElement root)
private string getText(ExmlMsg xmlMsg)
{
madmin = badmin.GetModel(3);
System.Text.StringBuilder retsb = new StringBuilder(200);
retsb.Append(madmin.receivename);
//retsb.Append("接收到的消息:" + xmlMsg.Content);
//retsb.Append("用户的OPEANID:" + xmlMsg.FromUserName);
return retsb.ToString();
}
private void textCase(ExmlMsg xmlMsg)
{
int nowtime = ConvertDateTimeInt(DateTime.Now);
string msg = "";
msg = getText(xmlMsg);
string resxml = "" + nowtime + " 0 ";
Response.Write(resxml);
return;
}
#endregion
#region 将datetime.now 转换为 int类型的秒
///
/// datetime转换为unixtime
///
///
///
private int ConvertDateTimeInt(System.DateTime time)
{
System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
return (int)(time - startTime).TotalSeconds;
}
private int converDateTimeInt(System.DateTime time)
{
System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
return (int)(time - startTime).TotalSeconds;
}
///
/// unix时间转换为datetime
///
///
///
private DateTime UnixTimeToTime(string timeStamp)
{
DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
long lTime = long.Parse(timeStamp + "0000000");
TimeSpan toNow = new TimeSpan(lTime);
return dtStart.Add(toNow);
}
#endregion