这篇文章还不错,使用 .net , 对微信用户的想公众号发送的文字进行回复。比较简单,自己可以修改更复杂的回复。
微信公众号开发笔记(C#)
需求分析
根据用户在微信上发送至价值中国公众号的消息,查询与该消息相关的内容返回给用户。
例如,用户发送【美国经济】后收到包含【美国经济】的内容,点击可查看全文。若没有查询到相关内容,则返回默认消息。
运行环境
.NET
准备工作
1.在微信公众平台申请开发者。
2.功能页面完成后上传至自己的网站并能正常访问该URL(以下统称:目标接口)
3.在微信公众平台开启开发模式。
开发流程
1.验证签名,微信服务器会发一个GET请求到目标接口,接收参数后开始验证。
2.首先接收微信服务器发送的请求,然后进行处理,请求为xml格式,携带公众号、发送方微信号、消息类型,消息内容等结点。
3.根据消息类型,从数据库读取相关预设内容返回,要求响应时间在5秒内,返回格式同样是xml格式。
备注
输出内容一定要使用UTF-8的编码方式,否则中文会产生乱码。
如果消息中需要换行,使用\r\n来换行。
支持html的a标签,但是如果是换行是紧邻关系的话可能无法识别换行。
完整代码
using System;
using System.IO;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Xml;
public class WeChat : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
weixin wx = new weixin();
String postStr = String.Empty;
if (HttpContext.Current.Request.HttpMethod.ToUpper() == "POST")
{
Stream s = HttpContext.Current.Request.InputStream;
Byte[] b = new Byte[s.Length];
s.Read(b, 0, (Int32)s.Length);
postStr = Encoding.UTF8.GetString(b);
if (!String.IsNullOrEmpty(postStr))
{
wx.Handle(postStr);
}
}
else
{
wx.Auth();
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
public class weixin
{
private String Token = "改写为自己的Token";
private String DefaultResponseContent = "欢迎关注价值中国\r\n价值中国是中国领先的财经商业领域社会化媒体";
public void Auth()
{
String echoStr = HttpContext.Current.Request.QueryString["echoStr"];
if (CheckSignature())
{
if (!String.IsNullOrEmpty(echoStr))
{
HttpContext.Current.Response.Write(echoStr);
HttpContext.Current.Response.End();
}
}
}
public void Handle(String postStr)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(postStr);
XmlElement rootElement = doc.DocumentElement;
XmlNode MsgType = rootElement.SelectSingleNode("MsgType");
RequestXML requestXML = new RequestXML();
requestXML.ToUserName = rootElement.SelectSingleNode("ToUserName").InnerText;
requestXML.FromUserName = rootElement.SelectSingleNode("FromUserName").InnerText;
requestXML.CreateTime = rootElement.SelectSingleNode("CreateTime").InnerText;
requestXML.MsgType = MsgType.InnerText;
if (requestXML.MsgType == "text")
{
requestXML.Content = rootElement.SelectSingleNode("Content").InnerText;
}
else if (requestXML.MsgType == "location")
{
requestXML.Location_X = rootElement.SelectSingleNode("Location_X").InnerText;
requestXML.Location_Y = rootElement.SelectSingleNode("Location_Y").InnerText;
requestXML.Scale = rootElement.SelectSingleNode("Scale").InnerText;
requestXML.MapInfo = rootElement.SelectSingleNode("Label").InnerText;
}
else if (requestXML.MsgType == "image")
{
requestXML.PicUrl = rootElement.SelectSingleNode("PicUrl").InnerText;
}
ResponseMsg(requestXML);
}
/// 验证微信签名
private bool CheckSignature()
{
String signature = HttpContext.Current.Request.QueryString["signature"];
String timestamp = HttpContext.Current.Request.QueryString["timestamp"];
String nonce = HttpContext.Current.Request.QueryString["nonce"];
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;
}
}
/// <summary>
/// 回复消息
/// </summary>
/// <param name="weixinXML"></param>
private void ResponseMsg(RequestXML requestXML)
{
String responseContent = String.Empty;
if (requestXML.MsgType == "text")
{
responseContent = FormatTextXML(requestXML.FromUserName, requestXML.ToUserName, "从数据库读取的内容");
}
HttpContext.Current.Response.ContentEncoding = Encoding.UTF8;
HttpContext.Current.Response.Write(responseContent);
}
/// 返回格式化文本XML内容
private String FormatTextXML(String fromUserName, String toUserName, String content)
{
return "<xml><ToUserName><![CDATA[" + fromUserName + "]]></ToUserName><FromUserName><![CDATA[" + toUserName + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[" + content + "]]></Content><FuncFlag>1</FuncFlag></xml>";
}
private int ConvertDateTimeInt(System.DateTime time)
{
System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
return (int)(time - startTime).TotalSeconds;
}
}
//微信请求类
public class RequestXML
{
private String toUserName = String.Empty;
/// <summary>
/// 公众号
/// </summary>
public String ToUserName
{
get { return toUserName; }
set { toUserName = value; }
}
private String fromUserName = "";
/// <summary>
/// 发送方微信号
/// </summary>
public String FromUserName
{
get { return fromUserName; }
set { fromUserName = value; }
}
private String createTime = String.Empty;
/// <summary>
/// 创建时间
/// </summary>
public String CreateTime
{
get { return createTime; }
set { createTime = value; }
}
private String msgType = String.Empty;
/// <summary>
/// 信息类型 地理位置:location,文本消息:text,消息类型:image
/// </summary>
public String MsgType
{
get { return msgType; }
set { msgType = value; }
}
private String content = String.Empty;
/// <summary>
/// 信息内容
/// </summary>
public String Content
{
get { return content; }
set { content = value; }
}
private String location_X = String.Empty;
/// <summary>
/// 地理位置纬度
/// </summary>
public String Location_X
{
get { return location_X; }
set { location_X = value; }
}
private String location_Y = String.Empty;
/// <summary>
/// 地理位置经度
/// </summary>
public String Location_Y
{
get { return location_Y; }
set { location_Y = value; }
}
private String scale = String.Empty;
/// <summary>
/// 地图缩放大小
/// </summary>
public String Scale
{
get { return scale; }
set { scale = value; }
}
private String mapInfo = String.Empty;
/// <summary>
/// 地理位置信息
/// </summary>
public String MapInfo
{
get { return mapInfo; }
set { mapInfo = value; }
}
private String picUrl = String.Empty;
/// <summary>
/// 图片链接
/// </summary>
public String PicUrl
{
get { return picUrl; }
set { picUrl = value; }
}
}
台州人在杭州 IT交流群 | 416194041 |
欢迎在杭州的台州老乡加入交流! |
作者:Work Hard Work Smart
出处:http://www.cnblogs.com/linlf03/
欢迎任何形式的转载,未经作者同意,请保留此段声明!