C#开发微信公众平台-就这么简单(附Demo)(转)
原文:http://www.cnblogs.com/xishuai/p/3625859.html
寫在前面
閱讀目錄:
最近公司在做微信開發(fā),其實就是接口開發(fā),網(wǎng)上找了很多資料,當(dāng)然園友也寫了 很多教程,但都是理論說了一大堆,實用指導(dǎo)或代碼很少。如果你自己仔細研究下,其實就那么點東西,C#實現(xiàn)起來也很簡單,原本不想寫這篇文章的,但是本人 當(dāng)時摸索走了很多彎路,這邊總結(jié)下,希望初次接觸微信公眾平臺的朋友別像當(dāng)時的我一樣。
自己動手,豐衣足食。
服務(wù)號和訂閱號
服務(wù)號是公司申請的微信公共賬號,訂閱號是個人申請的,我個人也申請了一個,不過沒怎么用。
服務(wù)號
訂閱號
URL配置
啟用開發(fā)模式需要先成為開發(fā)者,而且編輯模式和開發(fā)模式只能選擇一個,進入微信公眾平臺-開發(fā)模式,如下:
需要填寫url和token,當(dāng)時本人填寫這個的時候花了好久,我本以為填寫個服務(wù)器的url就可以了(80端口),但是不行,主要是沒有仔細的閱讀提示信息,所以總是提示
從上面可以看出,點擊提交后微信會向我們填寫的服務(wù)器發(fā)送幾個參數(shù),然后需要原樣返回出來,所以在提交url的時候,先在服務(wù)器創(chuàng)建接口測試返回echostr參數(shù)內(nèi)容。代碼:
1 //成為開發(fā)者url測試,返回echoStr 2 public void InterfaceTest() 3 { 4 string token = "填寫的token"; 5 if (string.IsNullOrEmpty(token)) 6 { 7 return; 8 } 9 10 string echoString = HttpContext.Current.Request.QueryString["echoStr"]; 11 string signature = HttpContext.Current.Request.QueryString["signature"]; 12 string timestamp = HttpContext.Current.Request.QueryString["timestamp"]; 13 string nonce = HttpContext.Current.Request.QueryString["nonce"]; 14 15 if (!string.IsNullOrEmpty(echoString)) 16 { 17 HttpContext.Current.Response.Write(echoString); 18 HttpContext.Current.Response.End(); 19 } 20 }在一般處理程序ashx的ProcessRequest的方法內(nèi)調(diào)用上面的方法,url填寫的就是這個ashx的服務(wù)器地址,token是一個服務(wù)器標(biāo)示,可以隨便輸入,代碼中的token要和申請?zhí)顚懙囊恢?#xff0c;成為開發(fā)者才能做開發(fā)。
創(chuàng)建菜單
我們添加一些微信服務(wù)號,聊天窗口下面有些菜單,這個可以在編輯模式簡單配置,也可以在開發(fā)模式代碼配置。微信公眾平臺開發(fā)者文檔:http://mp.weixin.qq.com/wiki/index.php?title=自定義菜單創(chuàng)建接口,可以看到創(chuàng)建菜單的一些要點,下面的使用網(wǎng)頁調(diào)試工具調(diào)試該接口,只是調(diào)試接口是否可用,并不是直接創(chuàng)建菜單的,菜單分為兩種:
- click: 用戶點擊click類型按鈕后,微信服務(wù)器會通過消息接口推送消息類型為event 的結(jié)構(gòu)給開發(fā)者(參考消息接口指南),并且?guī)习粹o中開發(fā)者填寫的key值,開發(fā)者可以通過自定義的key值與用戶進行交互。
- view: 用戶點擊view類型按鈕后,微信客戶端將會打開開發(fā)者在按鈕中填寫的url值 (即網(wǎng)頁鏈接),達到打開網(wǎng)頁的目的,建議與網(wǎng)頁授權(quán)獲取用戶基本信息接口結(jié)合,獲得用戶的登入個人信息。
click菜單需要填一個key,這個是在我們菜單點擊事件的時候會用到,view只是一個菜單超鏈接。菜單數(shù)據(jù)是json格式,官網(wǎng)是php示例,其實C#實現(xiàn)起來也很簡單,就是post發(fā)送一個json數(shù)據(jù),示例代碼:
1 public partial class createMenu : System.Web.UI.Page 2 { 3 protected void Page_Load(object sender, EventArgs e) 4 { 5 FileStream fs1 = new FileStream(Server.MapPath(".")+"\\menu.txt", FileMode.Open); 6 StreamReader sr = new StreamReader(fs1, Encoding.GetEncoding("GBK")); 7 string menu = sr.ReadToEnd(); 8 sr.Close(); 9 fs1.Close(); 10 GetPage("https://api.weixin.qq.com/cgi-bin/menu/create?access_token=access_token", menu); 11 } 12 public string GetPage(string posturl, string postData) 13 { 14 Stream outstream = null; 15 Stream instream = null; 16 StreamReader sr = null; 17 HttpWebResponse response = null; 18 HttpWebRequest request = null; 19 Encoding encoding = Encoding.UTF8; 20 byte[] data = encoding.GetBytes(postData); 21 // 準(zhǔn)備請求... 22 try 23 { 24 // 設(shè)置參數(shù) 25 request = WebRequest.Create(posturl) as HttpWebRequest; 26 CookieContainer cookieContainer = new CookieContainer(); 27 request.CookieContainer = cookieContainer; 28 request.AllowAutoRedirect = true; 29 request.Method = "POST"; 30 request.ContentType = "application/x-www-form-urlencoded"; 31 request.ContentLength = data.Length; 32 outstream = request.GetRequestStream(); 33 outstream.Write(data, 0, data.Length); 34 outstream.Close(); 35 //發(fā)送請求并獲取相應(yīng)回應(yīng)數(shù)據(jù) 36 response = request.GetResponse() as HttpWebResponse; 37 //直到request.GetResponse()程序才開始向目標(biāo)網(wǎng)頁發(fā)送Post請求 38 instream = response.GetResponseStream(); 39 sr = new StreamReader(instream, encoding); 40 //返回結(jié)果網(wǎng)頁(html)代碼 41 string content = sr.ReadToEnd(); 42 string err = string.Empty; 43 Response.Write(content); 44 return content; 45 } 46 catch (Exception ex) 47 { 48 string err = ex.Message; 49 return string.Empty; 50 } 51 } 52 }menu.text里面的內(nèi)容就是json示例菜單,大家可以從示例復(fù)制下來,按照你的需要修改一些就行了。
關(guān)于access_token,其實就是一個請求標(biāo)示,獲取方式:https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=appid&secret=secret;appid和secret是開發(fā)者標(biāo)示,在你的信息里面可以看到,通過這個鏈接返回一個json數(shù)據(jù),就可以得到access_token值。
需要注意的是:access_token 有一定的時效性,失效的話就需要重新獲取下,這個在本機就可以創(chuàng)建,不需要上傳到服務(wù)器,創(chuàng)建菜單正確,返回 {"errcode":0,"errmsg":"ok"}提示信息。這邊就不截圖了,大家試下就可以看到效果,一般創(chuàng)建菜單是一到兩分鐘生效,實在不行就 重新關(guān)注下。
查詢、刪除菜單
查詢和刪除菜單也很簡單,只不過是get請求,不需要傳數(shù)據(jù),看下示例代碼:
1 public partial class selectMenu : System.Web.UI.Page 2 { 3 protected void Page_Load(object sender, EventArgs e) 4 { 5 GetPage("https://api.weixin.qq.com/cgi-bin/menu/get?access_token=access_token"); 6 //GetPage("https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=access_token"); 7 } 8 public string GetPage(string posturl) 9 { 10 Stream instream = null; 11 StreamReader sr = null; 12 HttpWebResponse response = null; 13 HttpWebRequest request = null; 14 Encoding encoding = Encoding.UTF8; 15 // 準(zhǔn)備請求... 16 try 17 { 18 // 設(shè)置參數(shù) 19 request = WebRequest.Create(posturl) as HttpWebRequest; 20 CookieContainer cookieContainer = new CookieContainer(); 21 request.CookieContainer = cookieContainer; 22 request.AllowAutoRedirect = true; 23 request.Method = "GET"; 24 request.ContentType = "application/x-www-form-urlencoded"; 25 //發(fā)送請求并獲取相應(yīng)回應(yīng)數(shù)據(jù) 26 response = request.GetResponse() as HttpWebResponse; 27 //直到request.GetResponse()程序才開始向目標(biāo)網(wǎng)頁發(fā)送Post請求 28 instream = response.GetResponseStream(); 29 sr = new StreamReader(instream, encoding); 30 //返回結(jié)果網(wǎng)頁(html)代碼 31 string content = sr.ReadToEnd(); 32 string err = string.Empty; 33 Response.Write(content); 34 return content; 35 } 36 catch (Exception ex) 37 { 38 string err = ex.Message; 39 return string.Empty; 40 } 41 } 42 }access_token獲取方式上面已經(jīng)講過了,查詢菜單返回的是json數(shù)據(jù),其實就是我們創(chuàng)建菜單的menu.txt里面的內(nèi)容。
刪除成功返回信息提示:{"errcode":0,"errmsg":"ok"},這個也只要在本地運行就可以了。
接受消息
微信公眾平臺開發(fā)者文檔:http://mp.weixin.qq.com/wiki/index.php?title=接收普通消息,我們使用微信就是要對用戶發(fā)送的信息進行處理,這邊以接受普通消息為例,語音、圖片消息等,舉一反三可得。
從文檔上可以看出接受消息獲得的是一個xml格式文件,當(dāng)時有點犯傻的是,我要在哪邊進行接受消息啊?還郁悶了半天,其實就是你一開始填寫的url,是不是很汗顏啊,哈哈。
1 <xml> 2 <ToUserName><![CDATA[toUser]]></ToUserName> 3 <FromUserName><![CDATA[fromUser]]></FromUserName> 4 <CreateTime>1348831860</CreateTime> 5 <MsgType><![CDATA[text]]></MsgType> 6 <Content><![CDATA[this is a test]]></Content> 7 <MsgId>1234567890123456</MsgId> 8 </xml>我們在ashx添加下面代碼:
1 public void ProcessRequest(HttpContext param_context) 2 { 3 string postString = string.Empty; 4 if (HttpContext.Current.Request.HttpMethod.ToUpper() == "POST") 5 { 6 using (Stream stream = HttpContext.Current.Request.InputStream) 7 { 8 Byte[] postBytes = new Byte[stream.Length]; 9 stream.Read(postBytes, 0, (Int32)stream.Length); 10 postString = Encoding.UTF8.GetString(postBytes); 11 Handle(postString); 12 } 13 } 14 } 15 16 /// <summary> 17 /// 處理信息并應(yīng)答 18 /// </summary> 19 private void Handle(string postStr) 20 { 21 messageHelp help = new messageHelp(); 22 string responseContent = help.ReturnMessage(postStr); 23 24 HttpContext.Current.Response.ContentEncoding = Encoding.UTF8; 25 HttpContext.Current.Response.Write(responseContent); 26 }messageHelp是消息處理幫助類,這邊提供下部分代碼,完整的可以下載來,獲取的postString是xml,格式如上,我們這邊只需要轉(zhuǎn)換成XmlDocument進行解析就行了:
1 //接受文本消息 2 public string TextHandle(XmlDocument xmldoc) 3 { 4 string responseContent = ""; 5 XmlNode ToUserName = xmldoc.SelectSingleNode("/xml/ToUserName"); 6 XmlNode FromUserName = xmldoc.SelectSingleNode("/xml/FromUserName"); 7 XmlNode Content = xmldoc.SelectSingleNode("/xml/Content"); 8 if (Content != null) 9 { 10 responseContent = string.Format(ReplyType.Message_Text, 11 FromUserName.InnerText, 12 ToUserName.InnerText, 13 DateTime.Now.Ticks, 14 "歡迎使用微信公共賬號,您輸入的內(nèi)容為:" + Content.InnerText+"\r\n<a href=\"http://www.cnblogs.com\">點擊進入</a>"); 15 } 16 return responseContent; 17 } 18 /// <summary> 19 /// 普通文本消息 20 /// </summary> 21 public static string Message_Text 22 { 23 get { return @"<xml> 24 <ToUserName><![CDATA[{0}]]></ToUserName> 25 <FromUserName><![CDATA[{1}]]></FromUserName> 26 <CreateTime>{2}</CreateTime> 27 <MsgType><![CDATA[text]]></MsgType> 28 <Content><![CDATA[{3}]]></Content> 29 </xml>"; } 30 }上面的代碼就是接受消息,并做一些處理操作,返回消息。
發(fā)送消息(圖文、菜單事件響應(yīng))
這邊發(fā)送消息我分為三種:普通消息、圖文消息和菜單事件響應(yīng)。普通消息其實上面說接受消息的時候講到了,完整的代碼下邊下載來看。
我們先看下圖文消息和菜單事件響應(yīng),微信公眾平臺開發(fā)者文檔:http://mp.weixin.qq.com/wiki/index.php?title=回復(fù)圖文消息#.E5.9B.9E.E5.A4.8D.E5.9B.BE.E6.96.87.E6.B6.88.E6.81.AF,xml格式為:
1 <xml> 2 <ToUserName><![CDATA[toUser]]></ToUserName> 3 <FromUserName><![CDATA[fromUser]]></FromUserName> 4 <CreateTime>12345678</CreateTime> 5 <MsgType><![CDATA[news]]></MsgType> 6 <ArticleCount>2</ArticleCount> 7 <Articles> 8 <item> 9 <Title><![CDATA[title1]]></Title> 10 <Description><![CDATA[description1]]></Description> 11 <PicUrl><![CDATA[picurl]]></PicUrl> 12 <Url><![CDATA[url]]></Url> 13 </item> 14 <item> 15 <Title><![CDATA[title]]></Title> 16 <Description><![CDATA[description]]></Description> 17 <PicUrl><![CDATA[picurl]]></PicUrl> 18 <Url><![CDATA[url]]></Url> 19 </item> 20 </Articles> 21 </xml>圖文消息分為兩種,我們先看下效果,找的圓通速遞的微信服務(wù)號做示例:
剛開始做的時候,我以為這兩種應(yīng)該不是用的同一個接口,但是在文檔中找了半天也沒有找到除這個之外的,就試了下兩個圖文消息,發(fā)現(xiàn)就是這個接口發(fā)送的,如果多個的話,item中的Description會失效,只會顯示Title,大家試下就知道了,示例代碼:
1 //事件 2 public string EventHandle(XmlDocument xmldoc) 3 { 4 string responseContent = ""; 5 XmlNode Event = xmldoc.SelectSingleNode("/xml/Event"); 6 XmlNode EventKey = xmldoc.SelectSingleNode("/xml/EventKey"); 7 XmlNode ToUserName = xmldoc.SelectSingleNode("/xml/ToUserName"); 8 XmlNode FromUserName = xmldoc.SelectSingleNode("/xml/FromUserName"); 9 if (Event!=null) 10 { 11 //菜單單擊事件 12 if (Event.InnerText.Equals("CLICK")) 13 { 14 if (EventKey.InnerText.Equals("click_one"))//click_one 15 { 16 responseContent = string.Format(ReplyType.Message_Text, 17 FromUserName.InnerText, 18 ToUserName.InnerText, 19 DateTime.Now.Ticks, 20 "你點擊的是click_one"); 21 } 22 else if (EventKey.InnerText.Equals("click_two"))//click_two 23 { 24 responseContent = string.Format(ReplyType.Message_News_Main, 25 FromUserName.InnerText, 26 ToUserName.InnerText, 27 DateTime.Now.Ticks, 28 "2", 29 string.Format(ReplyType.Message_News_Item,"我要寄件","", 30 "http://www.soso.com/orderPlace.jpg", 31 "http://www.soso.com/")+ 32 string.Format(ReplyType.Message_News_Item, "訂單管理", "", 33 "http://www.soso.com/orderManage.jpg", 34 "http://www.soso.com/")); 35 } 36 else if (EventKey.InnerText.Equals("click_three"))//click_three 37 { 38 responseContent = string.Format(ReplyType.Message_News_Main, 39 FromUserName.InnerText, 40 ToUserName.InnerText, 41 DateTime.Now.Ticks, 42 "1", 43 string.Format(ReplyType.Message_News_Item, "標(biāo)題", "摘要", 44 "http://www.soso.com/jieshao.jpg", 45 "http://www.soso.com/")); 46 } 47 } 48 } 49 return responseContent; 50 } 51 /// <summary> 52 /// 圖文消息主體 53 /// </summary> 54 public static string Message_News_Main 55 { 56 get 57 { 58 return @"<xml> 59 <ToUserName><![CDATA[{0}]]></ToUserName> 60 <FromUserName><![CDATA[{1}]]></FromUserName> 61 <CreateTime>{2}</CreateTime> 62 <MsgType><![CDATA[news]]></MsgType> 63 <ArticleCount>{3}</ArticleCount> 64 <Articles> 65 {4} 66 </Articles> 67 </xml> "; 68 } 69 } 70 /// <summary> 71 /// 圖文消息項 72 /// </summary> 73 public static string Message_News_Item 74 { 75 get 76 { 77 return @"<item> 78 <Title><![CDATA[{0}]]></Title> 79 <Description><![CDATA[{1}]]></Description> 80 <PicUrl><![CDATA[{2}]]></PicUrl> 81 <Url><![CDATA[{3}]]></Url> 82 </item>"; 83 } 84 }需要注意的是:XmlNode Event = xmldoc.SelectSingleNode("/xml/Event")表示獲取的是事件類型,XmlNode EventKey = xmldoc.SelectSingleNode("/xml/EventKey")表示事件標(biāo)示,就是我們創(chuàng)建菜單添加click的key,通過key我們就可以判斷出是點的哪個菜單。
還有一點是回復(fù)超鏈接,有時候在服務(wù)號會發(fā)送一些鏈接,我們打開直接就會鏈接到相關(guān)網(wǎng)址,只需要在回復(fù)內(nèi)容中添加:<a href="http://www.baidu.com">點擊進入</a>,就可以了。
示例Demo下載
下載地址:http://yun.baidu.com/s/1mgI9nde
后記
關(guān)于微信公眾平臺當(dāng)然還有許多其他的東西,本篇只是一些經(jīng)驗之談,希望可以起到拋磚引玉的作用。有時候我們發(fā)現(xiàn)一些新鮮事物,覺得很難,就遠遠的看著,如果你用心的去感受它,其實也就這么回事。
不要高估別人,低估自己,其實深入內(nèi)心,很多你自以為很了不起的人,其實也沒什么,真是這樣。
如果你覺得本篇文章對你有所幫助,請點擊右下部“推薦”,^_^
?
作者:田園里的蟋蟀出處:http://www.cnblogs.com/xishuai/
本文版權(quán)歸作者和博客園共有,歡迎轉(zhuǎn)載,但未經(jīng)作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接。
轉(zhuǎn)載于:https://www.cnblogs.com/lsgsanxiao/p/5337140.html
總結(jié)
以上是生活随笔為你收集整理的C#开发微信公众平台-就这么简单(附Demo)(转)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 用Paint Tool SAI绘制漫画
- 下一篇: 在C#中开启事务