成爲代碼民工多年了,一直在別人的帖子下成長,想一想本身也應該寫寫東西回報你們了。html
直接代碼說話:git
1.由於成爲開發者,騰訊須要一個url,這個url又要能get,又能post.因此原來的RESTful WCF應該做以下標記:github
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" + "一、查看案例;\r\n" + "二、聯繫方式;\r\n" + "三、幫助或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(); } } } }
這裏參考了微信
2.同時,我作了一個建立菜單的androd客戶端,若有須要可在https://github.com/tuolin2013/CreatWeChatMenu 下載,更改本身的appid和appsecret.app