最近一直在看微信,整整一个月了,看到现在说实话还有很多没看的,从前两周一点看不懂到现在单个功能的一步步实现,不知道这样的速度是否太慢了。
不过现在往下看还是有思路了,目前整个文档完成学习只有1/3左右,但是看过的每个接口都是测试过的。学习很重要,但是有人指引将会效率翻倍,但是谁会愿意无偿花自己的时间给你呢,所以嘛。。。就不说了,
好了,牢骚到此,对于我这篇文章有什么不明白的或者需要交流的请加 QQ群:216390234
首先来门要有思路对吧,我们不是流水线的工人,而是系统的创造者,所以我们要有思想而不是一味的写代码,写到最后发现哪哪都不合适然后去修改,发现修改的时间远远大于开发的时间,那样就徒劳了。
这篇很简单适用于刚刚入门的开发者:
对于微信的基本配置我就不阐述了,网上讲解的很详细了。
1、项目:MVC
2、我们要接收微信服务器推送的消息,那么很简单,知道aspx页面的肯定知道对应的cs中会有一个PageLoad(),比如说我们部署到服务器上的是http://www.hskchw.com/Index.aspx
当我们访问这个页面的时候就会加载到PageLoad里面是不是,那么好了我们就在这里面接收不就好了吗,然后再根据相应的类型去做判断,符合条件的调用相应的方法去返回数据。好了整个交互流程结束了,
代码就完成了。
3、
1 publicActionResult Index()2 {3 string result = "";4 string postString = string.Empty;5 if (Request.HttpMethod.ToUpper() == "POST")6 {7 using (Stream stream =System.Web.HttpContext.Current.Request.InputStream)8 {9 Byte[] postBytes = newByte[stream.Length];10 stream.Read(postBytes, 0, (Int32)stream.Length);11 postString =Encoding.UTF8.GetString(postBytes);12 if (!string.IsNullOrEmpty(postString))13 {14 string SendToWx = string.Empty;15 //这里写方法解析Xml
16 XmlDocument xml = new XmlDocument();//17 xml.LoadXml(postString);18 XmlElement xmlElement =xml.DocumentElement;19 //这里进行判断MsgType
20 switch (xmlElement.SelectSingleNode("MsgType").InnerText)21 {22 case "text":23 SendToWx =WxText.GetWxTextXml(postString);24 break;25 case "image":26 SendToWx =WxImage.GetWxImageXml(postString);27 break;28 case "voice":29 break;30 case "video":31 break;32 case "shortvideo":33 break;34 case "location":35 break;36 case "link":37 break;38 case "event":39 string eventKey = xmlElement.SelectSingleNode("EventKey").InnerText == null ? "" : xmlElement.SelectSingleNode("EventKey").InnerText;40 switch (xmlElement.SelectSingleNode("Event").InnerText)41 {42 case "subscribe":43 if (string.IsNullOrEmpty(eventKey))44 {45 //model = new Models.Receive_Event();
46 }47 else
48 {49 //model = new Models.Receive_Event_Scan();
50 }51 break;52 case "unsubscribe":53 break;54 case "SCAN":55 break;56 case "LOCATION":57 break;58 case "CLICK":59 break;60 case "VIEW":61 break;62 default:63 break;64 }65 break;66 default:67 result = "没有识别的类型消息:" + xmlElement.SelectSingleNode("MsgType").InnerText;68 WriteLog(result);69 break;70 }71 if (!string.IsNullOrEmpty(SendToWx))72 {73 System.Web.HttpContext.Current.Response.Write(SendToWx);74 System.Web.HttpContext.Current.Response.End();75 }76 else
77 {78 result = "回传数据为空";79 WriteLog(result);80 }81 }82 else
83 {84 result = "微信推送的数据为:" +postString;85 WriteLog(result);86 }87 }88 }89 else if (Request.HttpMethod.ToUpper() == "GET")90 {91 string token = ConfigurationManager.AppSettings["WXToken"];//从配置文件获取Token
92 if (string.IsNullOrEmpty(token))93 {94 result = string.Format("微信Token配置项没有配置!");95 WriteLog(result);96 }97 string echoString = System.Web.HttpContext.Current.Request.QueryString["echoStr"];98 string signature = System.Web.HttpContext.Current.Request.QueryString["signature"];99 string timestamp = System.Web.HttpContext.Current.Request.QueryString["timestamp"];100 string nonce = System.Web.HttpContext.Current.Request.QueryString["nonce"];101 if(CheckSignature(token, signature, timestamp, nonce))102 {103 if (!string.IsNullOrEmpty(echoString))104 {105 System.Web.HttpContext.Current.Response.Write(echoString);106 System.Web.HttpContext.Current.Response.End();107 result = string.Format("微信Token配置成功,你已成为开发者!");108 WriteLog(result);109 }110 }111 }112 result = string.Format("页面被访问,没有请求数据!");113 WriteLog(result);114 returnView();115 }
View Code
1 public bool CheckSignature(string token, string signature, string timestamp, stringnonce)2 {3 string[] ArrTmp ={ token, timestamp, nonce };4 Array.Sort(ArrTmp);5 string tmpStr = string.Join("", ArrTmp);6 tmpStr = FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1");7 tmpStr =tmpStr.ToLower();8 if (tmpStr ==signature)9 {10 return true;11 }12 else
13 {14 return false;15 }16 }
View Code
1 private void WriteLog(stringstr)2 {3 try
4 {5 using (System.IO.FileStream fs = new System.IO.FileStream(Server.MapPath("//LLog//log.txt"), System.IO.FileMode.Append))6 {7 using (System.IO.StreamWriter sw = newSystem.IO.StreamWriter(fs))8 {9 string strlog = "----" + DateTime.Now.ToString("yyyyMMddHHmmss") + ":" + str + "-----";10 sw.WriteLine(strlog);11 sw.Close();12 }13 }14 }15 catch
16 { }17 }
View Code
1 public classWxText2 {3 public static string GetWxTextXml(stringStrXml)4 {5 string result = string.Empty;6 //加载xml
7 XmlDocument textXml = newXmlDocument();8 textXml.LoadXml(StrXml);9 XmlElement xmlElement =textXml.DocumentElement;10 //转成model对象
11 Receive_Text model = newReceive_Text()12 {13 ToUserName = xmlElement.SelectSingleNode("ToUserName").InnerText,14 FromUserName = xmlElement.SelectSingleNode("FromUserName").InnerText,15 CreateTime = xmlElement.SelectSingleNode("CreateTime").InnerText,16 MsgType = xmlElement.SelectSingleNode("MsgType").InnerText,17 Content = xmlElement.SelectSingleNode("Content").InnerText,18 MsgId = xmlElement.SelectSingleNode("MsgId").InnerText19 };20 //数据组织拼接返回xml
21 if (model.Content == "你好!")22 {23 //返回的xml
24 result = string.Format(Xml.TextMsg,model.FromUserName,model.ToUserName,DateTimeHelper.DateTimeToUnixInt(DateTime.Now),"你好!接口测试通过了!恭喜你!");25 }26 returnresult;27 }28 }
View Code
1 public abstract classReceiveModel2 {3
4 ///
5 ///接收方帐号(收到的OpenID)6 ///
7 public string ToUserName { get; set; }8 ///
9 ///发送方帐号(一个OpenID)10 ///
11 public string FromUserName { get; set; }12 ///
13 ///消息创建时间 (整型)14 ///
15 public string CreateTime { get; set; }16 ///
17 ///消息类型18 ///
19 public string MsgType { get; set; }20
21 ///
22 ///当前实体的XML字符串23 ///
24 public string Xml { get; set; }25 }26 ///
27 ///接收普通消息-文本消息28 ///
29 public classReceive_Text : ReceiveModel30 {31
32 ///
33 ///文本消息内容34 ///
35 public string Content { get; set; }36
37 ///
38 ///消息id,64位整型39 ///
40 public string MsgId { get; set; }41 }
View Code
1 public classXml2 {3 #region 文本xml
4 ///
5 ///ToUserName:用户ID(OpenID)6 ///FromUserName:开发者7 ///CreateTime:时间8 ///Content:内容9 ///
10 public static stringTextMsg11 {12 get
13 {14 return @"
15 16 17 18 {2}19 20 21 22 ";23 }24 }25 #endregion
26 }
View Code
4、上面是代码整个流程所用到的代码都贴出来了,有什么不明白的可以加上面的QQ群
原文:http://www.cnblogs.com/myloveblogs/p/5075967.html