前言: 这里就可以凸显使用APIController的一个优势了,因为可以通过MVC的路由设置相同的路由,但改变请求的方式(HttpPost),可以单独写被动回复接口。
毕竟,微信服务器转入到咱们自己的代码服务器地址是唯一的。 废话不多说,开始正文:
先粘贴帮助博客:http://www.cnblogs.com/shuang121/p/4009365.html
1-基本介绍:
入门指引:http://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1472017492_58YV5&token=&lang=zh_CN 中如下描述:
官方对应接口描述:http://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140543&token=&lang=zh_CN
2-通过上面的介绍,我们可以发现我们只需回复一个XML类型的消息即可。 但是XML类型中包含了:发送者,接受者,消息时间,消息类型,消息内容。
消息时间,消息类型,消息内容: 这三项我们可以轻松搞定, 但是发送者和接受者怎么办呢?
呵呵,其实这两个信息,用户已经给我们发过来了,我们只需要把用户发送过来的消息中的:发送人和接收人拿到就可以搞定了。
那么,就再来看下怎么接受消息吧。
3-如何接受消息:
4-OK,所有资料准备完毕,下面就将代码粘贴如下:
几个关键点:
a-获取请求XML字符串:Request.Content.ReadAsStringAsync().Result;
b-获取每个请求参数具体值(有很多种方法):这里使用正则表达式获取。
c-将时间类型转换为整形:
System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
return (int)(time - startTime).TotalSeconds;
[RoutePrefix("GzhTest")] public class MyLearnController : ApiController { private static readonly Regex ToUserNameReg = new Regex(@"(?<=<ToUserName><![CDATA[).*?(?=]]></ToUserName>)", RegexOptions.Compiled); private static readonly Regex FromUserNameReg = new Regex(@"(?<=<FromUserName><![CDATA[).*?(?=]]></FromUserName>)", RegexOptions.Compiled); private static readonly Regex CreateTimeReg = new Regex(@"(?<=<CreateTime>)d*?(?=</CreateTime>)", RegexOptions.Compiled); private static readonly Regex MsgTypeReg = new Regex(@"(?<=<MsgType><![CDATA[).*?(?=]]></MsgType>)", RegexOptions.Compiled); private static readonly Regex ContentReg = new Regex(@"(?<=<Content><![CDATA[).*?(?=]]></Content>)", RegexOptions.Compiled); private static readonly Regex MsgIdReg = new Regex(@"(?<=<MsgId>)d*?(?=</MsgId>)", RegexOptions.Compiled); private static readonly Regex EventReg = new Regex(@"(?<=<Event><![CDATA[).*?(?=]]></Event>)", RegexOptions.Compiled); private static readonly Regex EventKeyReg = new Regex(@"(?<=<EventKey><![CDATA[).*?(?=]]></EventKey>)", RegexOptions.Compiled); /// <summary> /// 获取消息体中正则所能匹配到的内容 /// </summary> /// <param name="message">消息内容</param> /// <param name="regex">正则</param> /// <returns>返回正则匹配的所有内容</returns> private string GetItemValue(string message, Regex regex) { if (regex.IsMatch(message)) return regex.Match(message).Value; return ""; } /// <summary> /// 接受微信消息,如果需要反馈,则调用回复接口进行答复 /// </summary> /// <param name="ToUserName">开发者微信号</param> /// <param name="FromUserName">发送方帐号(一个OpenID)</param> /// <param name="CreateTime">消息创建时间 (整型)</param> /// <param name="MsgType">text</param> /// <param name="Content">文本消息内容</param> /// <param name="MsgId">消息id,64位整型</param> /// <returns>successful or not</returns> [HttpPost] [Route("Check")] public HttpResponseMessage ReceiveMessage() { var message = Request.Content.ReadAsStringAsync().Result; var toUserName = GetItemValue(message, ToUserNameReg); var fromUserName = GetItemValue(message, FromUserNameReg); var createTime = GetItemValue(message, CreateTimeReg); var msgType = GetItemValue(message, MsgTypeReg); var content = GetItemValue(message, ContentReg); var msgId = GetItemValue(message, MsgIdReg); var eventStr = GetItemValue(message, EventReg); var eventKey = GetItemValue(message, EventKeyReg); var logStr = string.Format("Message:{8} ToUserName:{0} FromUserName:{1} CreateTime:{2} MsgType:{3} Content:{4} MsgId:{5} Event:{6} EventKey:{7}", toUserName, fromUserName, createTime, msgType, content, msgId, eventStr, eventKey, message); //logger.Debug(logStr); Log.WriteLog("接受数据"); Log.WriteLog(fromUserName); Log.WriteLog(toUserName); switch (msgType) { case "text": { var returnMessage = content; // 这块是获取反馈信息的方法,你的和我的应该不一样,所以这块你得修改一下。 var sendMessage = GetSendMessage(fromUserName, returnMessage, toUserName); //logger.Debug("MsgId:" + msgId + Environment.NewLine + sendMessage); Log.WriteLog("发送数据"); Log.WriteLog(sendMessage); return GetReturn(sendMessage); // 这个函数在上面已经贴出来了,在这块就不在贴了 } case "event": { if (eventStr == "subscribe") // 关注事件 { var returnMessage = "欢迎关注**账号 [微笑]"; var sendMessage = GetSendMessage(fromUserName, returnMessage, toUserName); return GetReturn(sendMessage); } return GetReturn("error"); } default: return GetReturn("error"); } } /// <summary> /// 发送被动响应消息 /// </summary> /// <param name="ToUserName">接收方帐号(收到的OpenID)</param> /// <param name="Content">回复的消息内容(换行:在content中能够换行,微信客户端就支持换行显示)</param> /// <param name="FromUserName">开发者微信号</param> /// <param name="CreateTime">消息创建时间 (整型)</param> /// <param name="MsgType">text</param> /// <returns></returns> public string GetSendMessage(string ToUserName, string Content, string FromUserName, string MsgType = "text") { var createTime = ConvertDateTimeInt(DateTime.Now); return string.Format(@"<xml><ToUserName><![CDATA[{0}]]></ToUserName><FromUserName><![CDATA[{1}]]></FromUserName><CreateTime>{2}</CreateTime><MsgType><![CDATA[{3}]]></MsgType><Content><![CDATA[{4}]]></Content></xml>", ToUserName, FromUserName, createTime, MsgType, Content); } /// <summary> /// datetime转换为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; } public static HttpResponseMessage GetReturn(string message) { return new HttpResponseMessage { Content = new StringContent(message, Encoding.UTF8, "text/html") }; } }