这里的前提是你已经成功配置了公众号的服务器接口信息,即微信公众号的开发之 服务器配置(一)所说的内容,微信服务器和公众号之间的沟通都通过这个地址,有且只有一个。
/// <summary>
/// 微信推送地址
/// </summary>
/// <returns></returns>
public string go()
{
string xml = "error";
if (Request.QueryString["echostr"] != null)
{
//signature 验证服务器地址的有效性
string signature = Request.QueryString["signature"].ToString();
string timestamp = Request.QueryString["timestamp"].ToString();
string nonce = Request.QueryString["nonce"].ToString();
string echostr = Request.QueryString["echostr"].ToString();
xml = renzhen(signature, timestamp, nonce, echostr);
}
else
{
//推送消息和事件
xml = ProcessRequest(HttpContext);
}
return xml;
}
/// <summary>
/// 回复
/// </summary>
/// <param name="param_context"></param>
/// <returns></returns>
private string ProcessRequest(HttpContextBase param_context)
{
string postString = string.Empty;
if (HttpContext.Request.HttpMethod.ToUpper() == "POST")
{
using (Stream stream = HttpContext.Request.InputStream)
{
Byte[] postBytes = new Byte[stream.Length];
stream.Read(postBytes, 0, (Int32)stream.Length);
postString = Encoding.UTF8.GetString(postBytes);
return Responsexml(postString);
}
}
return "error";
}
/// <summary>
/// 处理信息并应答
/// </summary>
private string Responsexml(string postStr)
{
XmlDocument xml = new XmlDocument();
xml.LoadXml(postStr);
string responseContent = "";
//开发者id
XmlNode APPName = xml.SelectSingleNode("/xml/ToUserName");
//用户id
XmlNode UserName = xml.SelectSingleNode("/xml/FromUserName");
//内容
XmlNode Content = xml.SelectSingleNode("/xml/Content");
//消息类型
XmlNode MsgType = xml.SelectSingleNode("/xml/MsgType");
//事件类型
XmlNode Event = xml.SelectSingleNode("/xml/Event");
//菜单key
XmlNode EventKey = xml.SelectSingleNode("/xml/EventKey");
//回复的内容
string text = "";
try
{
switch (MsgType.InnerText)
{
//事件
case "event":
switch (Event.InnerText)
{
//关注
case "subscribe":
text = "欢迎关注";
break;
//case "unsubscribe":
// text = "欢迎您下次关注";
// break;
case "CLICK":
switch (EventKey.InnerText)
{
case "one":
text = "你点击的是菜单一";
break;
case "two":
text = "你点击的是菜单二";
break;
case "three":
text = "你点击的是菜单三";
break;
default:
text = "";
break;
}
break;
default:
break;
}
break;
case "text":
text = Content.InnerText;
break;
}
responseContent = string.Format(Message_Text,
UserName.InnerText,
APPName.InnerText,
DateTime.Now.Ticks,
text);
return responseContent;
}
catch (Exception x)
{
return string.Format(Message_Text,
UserName.InnerText,
APPName.InnerText,
DateTime.Now.Ticks,
x.Message);
}
}
/// <summary>
/// 回复普通文本消息
/// </summary>
private string Message_Text
{
get
{
return @"<xml>
<ToUserName><![CDATA[{0}]]></ToUserName>
<FromUserName><![CDATA[{1}]]></FromUserName>
<CreateTime>{2}</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[{3}]]></Content>
<FuncFlag>0</FuncFlag>
</xml>";
}
}
这里实现的功能是当用户发送文本消息时,回复一样的消息,当用户点击自定义菜单时则回复对应的菜单消息,这里只针对文本消息,其他将出错。
微信提示公众号暂时无法提供服务。
出现这个错误的原因:
你没有实现相对应的功能。
你的代码出错抛异常了,这个得好好检查。
另外最简单的可能就是你的服务器关机,微信访问不到了。
目前这个星期就只学到了这么多,还挺好玩的呢。