成为代码民工多年了,一直在别人的帖子下成长,想想自己也应该写写东西回报大家了。
直接代码说话:
1.因为成为开发者,腾讯需要一个url,这个url又要能get,又能post.所以原来的RESTful WCF应该作如下标记:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ServiceModel; using System.ServiceModel.Web; using System.IO; namespace HCWcfLib { [ServiceContract] interface IWeChat { [OperationContract] [WebInvoke(UriTemplate = "/Token", Method = "*", BodyStyle = WebMessageBodyStyle.Bare)] Stream Token(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ServiceModel.Activation; using System.Web.Security; using System.IO; using System.ServiceModel.Web; using System.Web; using System.Xml.Linq; using System.ServiceModel; namespace HCWcfLib { [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] public class WeChatService : IWeChat { #region IWeChat 成员 public Stream Token() { IncomingWebRequestContext request = WebOperationContext.Current.IncomingRequest; var method = request.Method; string result = ""; switch (method) { case "POST": string postStr = OperationContext.Current.RequestContext.RequestMessage.ToString();//获取post数据 //System.IO.Stream s = HttpContext.Current.Request.InputStream; //byte[] b = new byte[s.Length]; //s.Read(b, 0, (int)s.Length); //string postStr = System.Text.Encoding.UTF8.GetString(b); WriteLog("post data is" + postStr + " at " + DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToLongTimeString()); if (!string.IsNullOrEmpty(postStr)) { WriteLog("response " + postStr + " at " + DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToLongTimeString()); result = DoPost(postStr); } break; case "DELETE": break; case "PUT": break; default: WriteLog("token get request at:" + DateTime.Now.ToShortDateString()); result = doGet(request); break; } //HttpContext.Current.ApplicationInstance.CompleteRequest();//推送...不然微信平台无法验证token byte[] resultBytes = Encoding.UTF8.GetBytes(result); return new MemoryStream(resultBytes); } #endregion public string doGet(IncomingWebRequestContext request) { string result = ""; string token = "yunjubao"; var signature = request.UriTemplateMatch.QueryParameters["signature"]; var timestamp = request.UriTemplateMatch.QueryParameters["timestamp"]; var nonce = request.UriTemplateMatch.QueryParameters["nonce"]; var echostr = request.UriTemplateMatch.QueryParameters["echoStr"]; string[] tempArray = { token, timestamp, nonce }; Array.Sort(tempArray); string tmpStr = string.Join("", tempArray); tmpStr = FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1"); tmpStr = tmpStr.ToLower(); if (tmpStr == signature) { result = echostr; } else { result = "invalidate parameter"; } return result; } public string DoPost(string postStr) { string result = ""; try { var xDoc = XDocument.Parse(postStr); var q = (from c in xDoc.Elements() select c).ToList(); var msgType = q.Elements("MsgType").First().Value; // 获取信息内容的类型 var _tmpContent = ""; #region =============== 处理MsgType:text ===================== if (0 == string.Compare("text", msgType, true)) { var model = new { ToUserName = q.Elements("ToUserName").First().Value, FromUserName = q.Elements("FromUserName").First().Value, CreateTime = q.Elements("CreateTime").First().Value, MsgType = q.Elements("MsgType").First().Value, Content = ("" + q.Elements("Content").First().Value).Trim(), MsgId = q.Elements("MsgId").First().Value }; if (false == string.IsNullOrWhiteSpace(model.Content)) { _tmpContent = "使用帮助说明:\r\n------------------------\r\n" + "常用命令:\r\n" + "1、查看案例;\r\n" + "2、联系方式;\r\n" + "3、帮助或help;\r\n" + "------------------------\r\n如果喜欢就推荐给您的朋友,\r\n我们的微信号:yunjubao"; if (false == string.IsNullOrWhiteSpace(_tmpContent)) { var textTpl = "<xml>" + "<ToUserName><![CDATA[{0}]]></ToUserName>" + "<FromUserName><![CDATA[{1}]]></FromUserName>" + "<CreateTime>{2}</CreateTime>" + "<MsgType><![CDATA[{3}]]></MsgType>" + "<Content><![CDATA[{4}]]></Content>" + "</xml>"; result = string.Format(textTpl, model.FromUserName, model.ToUserName, ConvertDateTimeInt(DateTime.Now), "text", _tmpContent); } } } #endregion } catch (Exception ex) { WriteLog(ex.ToString()); } return result; } private int ConvertDateTimeInt(System.DateTime time) { System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); return (int)(time - startTime).TotalSeconds; } private void WriteLog(string strMemo) { string filename = "E:/WEBHOME/logs/log.txt"; if (!System.IO.Directory.Exists("E:/WEBHOME/logs/")) System.IO.Directory.CreateDirectory("E:/WEBHOME/logs/"); System.IO.StreamWriter sr = null; try { if (!System.IO.File.Exists(filename)) { sr = System.IO.File.CreateText(filename); } else { sr = System.IO.File.AppendText(filename); } sr.WriteLine(strMemo); } catch { } finally { if (sr != null) sr.Close(); } } } }
这里参考了
- http://bbs.cfxixi.com/showtopic-889.aspx
- http://www.soaspx.com/dotnet/asp.net/tech/tech_20130125_10057.html
- http://lazy2009.iteye.com/blog/1889144的文章。感谢!
2.同时,我做了一个创建菜单的androd客户端,如有需要可在https://github.com/tuolin2013/CreatWeChatMenu 下载,更改自己的appid和appsecret.