本文轉自:http://www.it165.net/pro/html/201403/11102.htmlphp
服務號和訂閱號 URL配置 建立菜單 查詢、刪除菜單 接受消息 發送消息(圖文、菜單事件響應) 示例Demo下載 後記html
最近公司在作微信開發,其實就是接口開發,網上找了不少資料,固然園友也寫了不少教程,但都是理論說了一大堆,實用指導或代碼不多。若是你本身仔細研究下,其實就那麼點東西,C#實現起來也很簡單,本來不想寫這篇文章的,可是本人當時摸索走了不少彎路,這邊總結下,但願初次接觸微信公衆平臺的朋友別像當時的我同樣。json
本身動手,豐衣足食。api
服務號是公司申請的微信公共帳號,訂閱號是我的申請的,我我的也申請了一個,不過沒怎麼用。服務器
服務號微信
1個月(30天)內僅能夠發送1條羣發消息。 發給訂閱用戶(粉絲)的消息,會顯示在對方的聊天列表中。 在發送消息給用戶時,用戶將收到即時的消息提醒。 服務號會在訂閱用戶(粉絲)的通信錄中。 可申請自定義菜單。 cookie
訂閱號微信開發
天天(24小時內)能夠發送1條羣發消息。 發給訂閱用戶(粉絲)的消息,將會顯示在對方的訂閱號文件夾中。 在發送消息給訂閱用戶(粉絲)時,訂閱用戶不會收到即時消息提醒。 在訂閱用戶(粉絲)的通信錄中,訂閱號將被放入訂閱號文件夾中。 訂閱號不支持申請自定義菜單。app
啓用開發模式須要先成爲開發者,並且編輯模式和開發模式只能選擇一個,進入微信公衆平臺-開發模式,以下:微信公衆平臺
須要填寫url和token,當時本人填寫這個的時候花了很久,我本覺得填寫個服務器的url就能夠了(80端口),可是不行,主要是沒有仔細的閱讀提示信息,因此老是提示
從上面能夠看出,點擊提交後微信會向咱們填寫的服務器發送幾個參數,而後須要原樣返回出來,因此在提交url的時候,先在服務器建立接口測試返回echostr參數內容。代碼:
01.
1
//成爲開發者url測試,返回echoStr
02.
2
public
void
InterfaceTest()
03.
3
{
04.
4
string token =
"填寫的token"
;
05.
5
if
(string.IsNullOrEmpty(token))
06.
6
{
07.
7
return
;
08.
8
}
09.
9
10.
10
string echoString = HttpContext.Current.Request.QueryString[
"echoStr"
];
11.
11
string signature = HttpContext.Current.Request.QueryString[
"signature"
];
12.
12
string timestamp = HttpContext.Current.Request.QueryString[
"timestamp"
];
13.
13
string nonce = HttpContext.Current.Request.QueryString[
"nonce"
];
14.
14
15.
15
if
(!string.IsNullOrEmpty(echoString))
16.
16
{
17.
17
HttpContext.Current.Response.Write(echoString);
18.
18
HttpContext.Current.Response.End();
19.
19
}
20.
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數據,示例代碼:
01.
1
public
partial
class
createMenu : System.Web.UI.Page
02.
2
{
03.
3
protected
void
Page_Load(object sender, EventArgs e)
04.
4
{
05.
5
FileStream fs1 =
new
FileStream(Server.MapPath(
"."
)+
"\\menu.txt"
, FileMode.Open);
06.
6
StreamReader sr =
new
StreamReader(fs1, Encoding.GetEncoding(
"GBK"
));
07.
7
string menu = sr.ReadToEnd();
08.
8
sr.Close();
09.
9
fs1.Close();
10.
10
GetPage(
"https://api.weixin.<;a class="
keylink
" href="
http://www.it165.net/qq/
" target="
_blank
">qq</a>.com/cgi-bin/menu/create?access_token=access_token"
, menu);
11.
11
}
12.
12
public
string GetPage(string posturl, string postData)
13.
13
{
14.
14
Stream outstream =
null
;
15.
15
Stream instream =
null
;
16.
16
StreamReader sr =
null
;
17.
17
HttpWebResponse response =
null
;
18.
18
HttpWebRequest request =
null
;
19.
19
Encoding encoding = Encoding.UTF8;
20.
20
byte
[] data = encoding.GetBytes(postData);
21.
21
// 準備請求...
22.
22
try
23.
23
{
24.
24
// 設置參數
25.
25
request = WebRequest.Create(posturl) as HttpWebRequest;
26.
26
CookieContainer cookieContainer =
new
CookieContainer();
27.
27
request.CookieContainer = cookieContainer;
28.
28
request.AllowAutoRedirect =
true
;
29.
29
request.Method =
"POST"
;
30.
30
request.ContentType =
"application/x-www-form-urlencoded"
;
31.
31
request.ContentLength = data.Length;
32.
32
outstream = request.GetRequestStream();
33.
33
outstream.Write(data,
0
, data.Length);
34.
34
outstream.Close();
35.
35
//發送請求並獲取相應迴應數據
36.
36
response = request.GetResponse() as HttpWebResponse;
37.
37
//直到request.GetResponse()程序纔開始向目標網頁發送Post請求
38.
38
instream = response.GetResponseStream();
39.
39
sr =
new
StreamReader(instream, encoding);
40.
40
//返回結果網頁(html)代碼
41.
41
string content = sr.ReadToEnd();
42.
42
string err = string.Empty;
43.
43
Response.Write(content);
44.
44
return
content;
45.
45
}
46.
46
catch
(Exception ex)
47.
47
{
48.
48
string err = ex.Message;
49.
49
return
string.Empty;
50.
50
}
51.
51
}
52.
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請求,不須要傳數據,看下示例代碼:
01.
1
public
partial
class
selectMenu : System.Web.UI.Page
02.
2
{
03.
3
protected
void
Page_Load(object sender, EventArgs e)
04.
4
{
05.
5
GetPage(
"https://api.weixin.qq.com/cgi-bin/menu/get?access_token=access_token"
);
06.
6
//GetPage("https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=access_token");
07.
7
}
08.
8
public
string GetPage(string posturl)
09.
9
{
10.
10
Stream instream =
null
;
11.
11
StreamReader sr =
null
;
12.
12
HttpWebResponse response =
null
;
13.
13
HttpWebRequest request =
null
;
14.
14
Encoding encoding = Encoding.UTF8;
15.
15
// 準備請求...
16.
16
try
17.
17
{
18.
18
// 設置參數
19.
19
request = WebRequest.Create(posturl) as HttpWebRequest;
20.
20
CookieContainer cookieContainer =
new
CookieContainer();
21.
21
request.CookieContainer = cookieContainer;
22.
22
request.AllowAutoRedirect =
true
;
23.
23
request.Method =
"GET"
;
24.
24
request.ContentType =
"application/x-www-form-urlencoded"
;
25.
25
//發送請求並獲取相應迴應數據
26.
26
response = request.GetResponse() as HttpWebResponse;
27.
27
//直到request.GetResponse()程序纔開始向目標網頁發送Post請求
28.
28
instream = response.GetResponseStream();
29.
29
sr =
new
StreamReader(instream, encoding);
30.
30
//返回結果網頁(html)代碼
31.
31
string content = sr.ReadToEnd();
32.
32
string err = string.Empty;
33.
33
Response.Write(content);
34.
34
return
content;
35.
35
}
36.
36
catch
(Exception ex)
37.
37
{
38.
38
string err = ex.Message;
39.
39
return
string.Empty;
40.
40
}
41.
41
}
42.
42
}
access_token獲取方式上面已經講過了,查詢菜單返回的是json數據,其實就是咱們建立菜單的menu.txt裏面的內容。
刪除成功返回信息提示:{"errcode":0,"errmsg":"ok"},這個也只要在本地運行就能夠了。
微信公衆平臺開發者文檔:http://mp.weixin.qq.com/wiki/index.php?title=接收普通消息,咱們使用微信就是要對用戶發送的信息進行處理,這邊以接受普通消息爲例,語音、圖片消息等,觸類旁通可得。
從文檔上能夠看出接受消息得到的是一個xml格式文件,當時有點犯傻的是,我要在哪邊進行接受消息啊?還鬱悶了半天,其實就是你一開始填寫的url,是否是很汗顏啊,哈哈。
1.
1
<xml>
2.
2
<ToUserName><![CDATA[toUser]]></ToUserName>
3.
3
<FromUserName><![CDATA[fromUser]]></FromUserName>
4.
4
<CreateTime>
1348831860
</CreateTime>
5.
5
<MsgType><![CDATA[text]]></MsgType>
6.
6
<Content><![CDATA[
this
is a test]]></Content>
7.
7
<MsgId>
1234567890123456
</MsgId>
8.
8
</xml>
咱們在ashx添加下面代碼:
01.
1
public
void
ProcessRequest(HttpContext param_context)
02.
2
{
03.
3
string postString = string.Empty;
04.
4
if
(HttpContext.Current.Request.HttpMethod.ToUpper() ==
"POST"
)
05.
5
{
06.
6
using (Stream stream = HttpContext.Current.Request.InputStream)
07.
7
{
08.
8
Byte[] postBytes =
new
Byte[stream.Length];
09.
9
stream.Read(postBytes,
0
, (Int32)stream.Length);
10.
10
postString = Encoding.UTF8.GetString(postBytes);
11.
11
Handle(postString);
12.
12
}
13.
13
}
14.
14
}
15.
15
16.
16
/// <summary>
17.
17
/// 處理信息並應答
18.
18
/// </summary>
19.
19
private
void
Handle(string postStr)
20.
20
{
21.
21
messageHelp help =
new
messageHelp();
22.
22
string responseContent = help.ReturnMessage(postStr);
23.
23
24.
24
HttpContext.Current.Response.ContentEncoding = Encoding.UTF8;
25.
25
HttpContext.Current.Response.Write(responseContent);
26.
26
}
messageHelp是消息處理幫助類,這邊提供下部分代碼,完整的能夠下載來,獲取的postString是xml,格式如上,咱們這邊只須要轉換成XmlDocument進行解析就好了:
01.
1
//接受文本消息
02.
2
public
string TextHandle(XmlDocument xmldoc)
03.
3
{
04.
4
string responseContent =
""
;
05.
5
XmlNode ToUserName = xmldoc.SelectSingleNode(
"/xml/ToUserName"
);
06.
6
XmlNode FromUserName = xmldoc.SelectSingleNode(
"/xml/FromUserName"
);
07.
7
XmlNode Content = xmldoc.SelectSingleNode(
"/xml/Content"
);
08.
8
if
(Content !=
null
)
09.
9
{
10.
10
responseContent = string.Format(ReplyType.Message_Text,
11.
11
FromUserName.InnerText,
12.
12
ToUserName.InnerText,
13.
13
DateTime.Now.Ticks,
14.
14
"歡迎使用微信公共帳號,您輸入的內容爲:"
+ Content.InnerText+
"\r\n<a href=\"http://www.cnblogs.com\">點擊進入</a>"
);
15.
15
}
16.
16
return
responseContent;
17.
17
}
18.
18
/// <summary>
19.
19
/// 普通文本消息
20.
20
/// </summary>
21.
21
public
static
string Message_Text
22.
22
{
23.
23
get {
return
@"<xml>
24.
24
<ToUserName><![CDATA[{
0
}]]></ToUserName>
25.
25
<FromUserName><![CDATA[{
1
}]]></FromUserName>
26.
26
<CreateTime>{
2
}</CreateTime>
27.
27
<MsgType><![CDATA[text]]></MsgType>
28.
28
<Content><![CDATA[{
3
}]]></Content>
29.
29
</xml>"; }
30.
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格式爲:
01.
1
<xml>
02.
2
<ToUserName><![CDATA[toUser]]></ToUserName>
03.
3
<FromUserName><![CDATA[fromUser]]></FromUserName>
04.
4
<CreateTime>
12345678
</CreateTime>
05.
5
<MsgType><![CDATA[news]]></MsgType>
06.
6
<ArticleCount>
2
</ArticleCount>
07.
7
<Articles>
08.
8
<item>
09.
9
<Title><![CDATA[title1]]></Title>
10.
10
<Description><![CDATA[description1]]></Description>
11.
11
<PicUrl><![CDATA[picurl]]></PicUrl>
12.
12
<Url><![CDATA[url]]></Url>
13.
13
</item>
14.
14
<item>
15.
15
<Title><![CDATA[title]]></Title>
16.
16
<Description><![CDATA[description]]></Description>
17.
17
<PicUrl><![CDATA[picurl]]></PicUrl>
18.
18
<Url><![CDATA[url]]></Url>
19.
19
</item>
20.
20
</Articles>
21.
21
</xml>
圖文消息分爲兩種,咱們先看下效果,找的圓通速遞的微信服務號作示例:
剛開始作的時候,我覺得這兩種應該不是用的同一個接口,可是在文檔中找了半天也沒有找到除這個以外的,就試了下兩個圖文消息,發現就是這個接口發送的,若是多個的話,item中的Description會失效,只會顯示Title,你們試下就知道了,示例代碼:
01.
1
//事件
02.
2
public
string EventHandle(XmlDocument xmldoc)
03.
3
{
04.
4
string responseContent =
""
;
05.
5
XmlNode Event = xmldoc.SelectSingleNode(
"/xml/Event"
);
06.
6
XmlNode EventKey = xmldoc.SelectSingleNode(
"/xml/EventKey"
);
07.
7
XmlNode ToUserName = xmldoc.SelectSingleNode(
"/xml/ToUserName"
);
08.
8
XmlNode FromUserName = xmldoc.SelectSingleNode(
"/xml/FromUserName"
);
09.
9
if
(Event!=
null
)
10.
10
{
11.
11
//菜單單擊事件
12.
12
if
(Event.InnerText.Equals(
"CLICK"
))
13.
13
{
14.
14
if
(EventKey.InnerText.Equals(
"click_one"
))
//click_one
15.
15
{
16.
16
responseContent = string.Format(ReplyType.Message_Text,
17.
17
FromUserName.InnerText,
18.
18
ToUserName.InnerText,
19.
19
DateTime.Now.Ticks,
20.
20
"你點擊的是click_one"
);
21.
21
}
22.
22
else
if
(EventKey.InnerText.Equals(
"click_two"
))
//click_two
23.
23
{
24.
24
responseContent = string.Format(ReplyType.Message_News_Main,
25.
25
FromUserName.InnerText,
26.
26
ToUserName.InnerText,
27.
27
DateTime.Now.Ticks,
28.
28
"2"
,
29.
29
string.Format(ReplyType.Message_News_Item,
"我要寄件"
,
""
,
30.
30
"http://www.soso.com/orderPlace.jpg"
,
31.
31
"http://www.soso.com/"
)+
32.
32
string.Format(ReplyType.Message_News_Item,
"訂單管理"
,
""
,
33.
33
"http://www.soso.com/orderManage.jpg"
,
34.
34
"http://www.soso.com/"
));
35.
35
}
36.
36
else
if
(EventKey.InnerText.Equals(
"click_three"
))
//click_three
37.
37
{
38.
38
responseContent = string.Format(ReplyType.Message_News_Main,
39.
39
FromUserName.InnerText,
40.
40
ToUserName.InnerText,
41.
41
DateTime.Now.Ticks,
42.
42
"1"
,
43.
43
string.Format(ReplyType.Message_News_Item,
"標題"
,
"摘要"
,
44.
44
"http://www.soso.com/jieshao.jpg"
,
45.
45
"http://www.soso.com/"
));
46.
46
}
47.
47
}
48.
48
}
49.
49
return
responseContent;
50.
50
}
51.
51
/// <summary>
52.
52
/// 圖文消息主體
53.
53
/// </summary>
54.
54
public
static
string Message_News_Main
55.
55
{
56.
56
get
57.
57
{
58.
58
return
@"<xml>
59.
59
<ToUserName><![CDATA[{
0
}]]></ToUserName>
60.
60
<FromUserName><![CDATA[{
1
}]]></FromUserName>
61.
61
<CreateTime>{
2
}</CreateTime>
62.
62
<MsgType><![CDATA[news]]></MsgType>
63.
63
<ArticleCount>{
3
}</ArticleCount>
64.
64
<Articles>
65.
65
{
4
}
66.
66
</Articles>
67.
67
</xml> ";
68.
68
}
69.
69
}
70.
70
/// <summary>
71.
71
/// 圖文消息項
72.
72
/// </summary>
73.
73
public
static
string Message_News_Item
74.
74
{
75.
75
get
76.
76
{
77.
77
return
@"<item>
78.
78
<Title><![CDATA[{
0
}]]></Title>
79.
79
<Description><![CDATA[{
1
}]]></Description>
80.
80
<PicUrl><![CDATA[{
2
}]]></PicUrl>
81.
81
<Url><![CDATA[{
3
}]]></Url>
82.
82
</item>";
83.
83
}
84.
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/1i3kMpwh
關於微信公衆平臺固然還有許多其餘的東西,本篇只是一些經驗之談,但願能夠起到拋磚引玉的做用。有時候咱們發現一些新鮮事物,以爲很難,就遠遠的看着,若是你用心的去感覺它,其實也就這麼回事。
不要高估別人,低估本身,其實深刻心裏,不少你自覺得很了不得的人,其實也沒什麼,真是這樣。
若是你以爲本篇文章對你有所幫助,請點擊右下部「推薦」,^_^