寫在前面
閱讀目錄:
- 服務号和訂閱号
- URL配置
- 建立菜單
- 查詢、删除菜單
- 接受消息
- 發送消息(圖文、菜單事件響應)
- 示例Demo下載下傳
- 後記
最近公司在做微信開發,其實就是接口開發,網上找了很多資料,當然園友也寫了很多教程,但都是理論說了一大堆,實用指導或代碼很少。如果你自己仔細研究下,其實就那麼點東西,C#實作起來也很簡單,原本不想寫這篇文章的,但是本人當時摸索走了很多彎路,這邊總結下,希望初次接觸微信公衆平台的朋友别像當時的我一樣。
自己動手,豐衣足食。
服務号是公司申請的微信公共賬号,訂閱号是個人申請的,我個人也申請了一個,不過沒怎麼用。
服務号
- 1個月(30天)内僅可以發送1條群發消息。
- 發給訂閱使用者(粉絲)的消息,會顯示在對方的聊天清單中。
- 在發送消息給使用者時,使用者将收到即時的消息提醒。
- 服務号會在訂閱使用者(粉絲)的通訊錄中。
- 可申請自定義菜單。
訂閱号
- 每天(24小時内)可以發送1條群發消息。
- 發給訂閱使用者(粉絲)的消息,将會顯示在對方的訂閱号檔案夾中。
- 在發送消息給訂閱使用者(粉絲)時,訂閱使用者不會收到即時消息提醒。
- 在訂閱使用者(粉絲)的通訊錄中,訂閱号将被放入訂閱号檔案夾中。
- 訂閱号不支援申請自定義菜單。
啟用開發模式需要先成為開發者,而且編輯模式和開發模式隻能選擇一個,進入微信公衆平台-開發模式,如下:

需要填寫url和token,當時本人填寫這個的時候花了好久,我本以為填寫個伺服器的url就可以了(80端口),但是不行,主要是沒有仔細的閱讀提示資訊,是以總是提示
從上面可以看出,點選送出後微信會向我們填寫的伺服器發送幾個參數,然後需要原樣傳回出來,是以在送出url的時候,先在伺服器建立接口測試傳回echostr參數内容。代碼:
1 //成為開發者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的方法内調用上面的方法,url填寫的就是這個ashx的伺服器位址,token是一個伺服器标示,可以随便輸入,代碼中的token要和申請填寫的一緻,成為開發者才能做開發。
我們添加一些微信服務号,聊天視窗下面有些菜單,這個可以在編輯模式簡單配置,也可以在開發模式代碼配置。微信公衆平台開發者文檔:http://mp.weixin.qq.com/wiki/index.php?title=自定義菜單建立接口,可以看到建立菜單的一些要點,下面的使用網頁調試工具調試該接口,隻是調試接口是否可用,并不是直接建立菜單的,菜單分為兩種:
- click: 使用者點選click類型按鈕後,微信伺服器會通過消息接口推送消息類型為event 的結構給開發者(參考消息接口指南),并且帶上按鈕中開發者填寫的key值,開發者可以通過自定義的key值與使用者進行互動。
- view: 使用者點選view類型按鈕後,微信用戶端将會打開開發者在按鈕中填寫的url值 (即網頁連結),達到打開網頁的目的,建議與網頁授權擷取使用者基本資訊接口結合,獲得使用者的登入個人資訊。
click菜單需要填一個key,這個是在我們菜單點選事件的時候會用到,view隻是一個菜單超連結。菜單資料是json格式,官網是php示例,其實C#實作起來也很簡單,就是post發送一個json資料,示例代碼:
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 // 準備請求...
22 try
23 {
24 // 設定參數
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 //發送請求并擷取相應回應資料
36 response = request.GetResponse() as HttpWebResponse;
37 //直到request.GetResponse()程式才開始向目标網頁發送Post請求
38 instream = response.GetResponseStream();
39 sr = new StreamReader(instream, encoding);
40 //傳回結果網頁(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裡面的内容就是json示例菜單,大家可以從示例複制下來,按照你的需要修改一些就行了。
關于access_token,其實就是一個請求标示,擷取方式:https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=appid&secret=secret;appid和secret是開發者标示,在你的資訊裡面可以看到,通過這個連結傳回一個json資料,就可以得到access_token值。
需要注意的是:access_token有一定的時效性,失效的話就需要重新擷取下,這個在本機就可以建立,不需要上傳到伺服器,建立菜單正确,傳回{"errcode":0,"errmsg":"ok"}提示資訊。這邊就不截圖了,大家試下就可以看到效果,一般建立菜單是一到兩分鐘生效,實在不行就重新關注下。
查詢和删除菜單也很簡單,隻不過是get請求,不需要傳資料,看下示例代碼:
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 // 準備請求...
16 try
17 {
18 // 設定參數
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 //發送請求并擷取相應回應資料
26 response = request.GetResponse() as HttpWebResponse;
27 //直到request.GetResponse()程式才開始向目标網頁發送Post請求
28 instream = response.GetResponseStream();
29 sr = new StreamReader(instream, encoding);
30 //傳回結果網頁(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擷取方式上面已經講過了,查詢菜單傳回的是json資料,其實就是我們建立菜單的menu.txt裡面的内容。
删除成功傳回資訊提示:{"errcode":0,"errmsg":"ok"},這個也隻要在本地運作就可以了。
微信公衆平台開發者文檔:http://mp.weixin.qq.com/wiki/index.php?title=接收普通消息,我們使用微信就是要對使用者發送的資訊進行處理,這邊以接受普通消息為例,語音、圖檔消息等,舉一反三可得。
從文檔上可以看出接受消息獲得的是一個xml格式檔案,當時有點犯傻的是,我要在哪邊進行接受消息啊?還郁悶了半天,其實就是你一開始填寫的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 /// 處理資訊并應答
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,格式如上,我們這邊隻需要轉換成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 "歡迎使用微信公共賬号,您輸入的内容為:" + 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 }
上面的代碼就是接受消息,并做一些處理操作,傳回消息。
這邊發送消息我分為三種:普通消息、圖文消息和菜單事件響應。普通消息其實上面說接受消息的時候講到了,完整的代碼下邊下載下傳來看。
我們先看下圖文消息和菜單事件響應,微信公衆平台開發者文檔:http://mp.weixin.qq.com/wiki/index.php?title=回複圖文消息#.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>
圖文消息分為兩種,我們先看下效果,找的圓通速遞的微信服務号做示例:
剛開始做的時候,我以為這兩種應該不是用的同一個接口,但是在文檔中找了半天也沒有找到除這個之外的,就試了下兩個圖文消息,發現就是這個接口發送的,如果多個的話,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, "标題", "摘要",
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")表示事件标示,就是我們建立菜單添加click的key,通過key我們就可以判斷出是點的哪個菜單。
還有一點是回複超連結,有時候在服務号會發送一些連結,我們打開直接就會連結到相關網址,隻需要在回複内容中添加:<a href="http://www.baidu.com">點選進入</a>,就可以了。
下載下傳位址:http://pan.baidu.com/s/1eSAxJns
關于微信公衆平台當然還有許多其他的東西,本篇隻是一些經驗之談,希望可以起到抛磚引玉的作用。有時候我們發現一些新鮮事物,覺得很難,就遠遠的看着,如果你用心的去感受它,其實也就這麼回事。
不要高估别人,低估自己,其實深入内心,很多你自以為很了不起的人,其實也沒什麼,真是這樣。
如果你覺得本篇文章對你有所幫助,請點選右下部“推薦”,^_^
作者:田園裡的蟋蟀
微信公衆号:你好架構
出處:http://www.cnblogs.com/xishuai/
公衆号會不定時的分享有關架構的方方面面,包含并不局限于:Microservices(微服務)、Service Mesh(服務網格)、DDD/TDD、Spring Cloud、Dubbo、Service Fabric、Linkerd、Envoy、Istio、Conduit、Kubernetes、Docker、MacOS/Linux、Java、.NET Core/ASP.NET Core、Redis、RabbitMQ、MongoDB、GitLab、CI/CD(持續內建/持續部署)、DevOps等等。
本文版權歸作者和部落格園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接配接。
分享到:
QQ空間
新浪微網誌
騰訊微網誌
微信
更多