微信公衆平臺(開發模式)

Ps:是一名菜鳥,第一次寫文章,寫得很差還請多多指教!!!最近恰好應公司需求研究開發微信公衆平臺,就記錄起來!!!web

如今的不少商家、媒體都有開發對應的微信公衆平臺,咱們能夠從http://mp.weixin.qq.com/網上進行註冊申請。註冊能夠註冊我的的和組織的,我的的沒有自定義菜單功能,組織的能夠自定義菜單,註冊成功後,能夠在高級功能裏面看到編輯模式和開發模式,只能選擇其中一種,本文主要介紹開發模式。api

在進行開發模式前,得先了解微信消息的幾種類型,能夠登陸後,查看公衆平臺API裏面查看,而後咱們能夠根據消息類型建立對應的實體類,接收和發送的格式都xml格式。服務器

運用開發模式,須要有本身的域名和服務器,進去開發模式須要填寫,你須要先把你開發的程序部署在服務器上,才能填寫微信

  

  1  const string Token = "你定義的Token";
  2       
  3         protected void Page_Load(object sender, EventArgs e)
  4         {
  5             if (Request.HttpMethod.ToLower() == "post")
  6             {
  7                 //WriteLog(Request.ContentLength.ToString());
  8                 System.IO.Stream s = System.Web.HttpContext.Current.Request.InputStream;
  9                 byte[] b = new byte[s.Length];
 10                 s.Read(b, 0, (int)s.Length);
 11                 string postStr = System.Text.Encoding.UTF8.GetString(b);
 12                 if (!string.IsNullOrEmpty(postStr))
 13                 {
 14 
 15                     WriteLog(postStr);
 16                     DealPost(postStr);
 17                 }
 18 
 19             }
 20             else
 21             {
 22                 Valid();
 23                 //string get = Request["echostr"];
 24                 //Response.Write(get);
 25                
 26             }
 27         }
 28      
 29         
 30         private bool CheckSignature()
 31         {
 32             string signature = Request.QueryString["signature"].ToString();
 33             string timestamp = Request.QueryString["timestamp"].ToString();
 34             string nonce = Request.QueryString["nonce"].ToString();
 35             string[] ArrTmp = { Token, timestamp, nonce };
 36             Array.Sort(ArrTmp);     //字典排序
 37             string tmpStr = string.Join("", ArrTmp);
 38             tmpStr = FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1");
 39             tmpStr = tmpStr.ToLower();
 40             if (tmpStr == signature)
 41             {
 42                 return true;
 43             }
 44             else
 45             {
 46                 return false;
 47             }
 48         }
 49 
 50         private void Valid()
 51         {
 52             string echoStr = Request.QueryString["echoStr"]??"test";
 53             if (CheckSignature())
 54             {
 55                 if (!string.IsNullOrEmpty(echoStr))
 56                 {
 57                     Response.Write(echoStr);
 58                    // Response.End();
 59                 }
 60             }
 61         }
 62 
 63         private void DealPost(string postStr)
 64         {
 65            
 66             csWXLogic wx = new csWXLogic();
 67             DealXml dx = new DealXml(postStr);
 68             string res = "";
 69            
 70             int mdatetime = ResponseWeixin.ConvertDateTimeInt(DateTime.Now);               
 71             if (dx.MsgType.Equals("text"))
 72             {
 73                 //處理文本消息
 74                TextType tt = dx.NewTextType(dx.Xn);
 75                 res = wx.GlobalExecute(tt.Content + "#" + tt.FromUserName);
 76               
 77                 Response.ContentEncoding = Encoding.UTF8;
 78                 Response.Write(ResponseWeixin.ResponseText(res, tt.FromUserName, tt.ToUserName, mdatetime.ToString()));
 79             }
 80             if (dx.MsgType.Equals("event"))
 81             {
 82                 EventType et = dx.NewEnentType(dx.Xn);
 83                 switch (et.Event)
 84                 {
 85                     case "subscribe":
 86                         res = wx.GlobalExecute("000");break;
 87                     case "CLICK":
 88                        res = wx.GlobalExecute(et.EventKey + "#" + et.FromUserName); break;
 89                        
 90                 }
 91                 
 92                    
 93                 
 94                 Response.ContentEncoding = Encoding.UTF8;
 95                 Response.Write(ResponseWeixin.ResponseText(res, et.FromUserName, et.ToUserName, mdatetime.ToString()));
 96             }
 97             if (dx.MsgType.Equals("location"))
 98             {
 99                 LocationType lt = dx.NewLocationType(dx.Xn);
100                 res = wx.GlobalExecute(lt.Location_X + "" + lt.Location_Y + "#" + lt.FromUserName);
101                 Response.ContentEncoding = Encoding.UTF8;
102                 Response.Write(ResponseWeixin.ResponseText(res, lt.FromUserName, lt.ToUserName, mdatetime.ToString()));
103             } 
104            
105         }
View Code

ps:在頁面加載時候判斷是post仍是get請求。若是get請求經行驗證,接口說明文檔有說須要獲取signature、timestamp、nonce參數而後排序加密,進行判斷返回echoStr,也能夠不斷定直接返回echoStr。若是是post請求就是處理用戶發送的消息,咱們判斷消息類型,而後建立對應的消息實體,而後根據須要開發本身的業務邏輯。的地址:域名/該代碼文件。app


接下來是自定義菜單。在設置下,能夠申請自定義菜單,身體經過後會獲得固定的https://api.weixin.qq.com/cgi-bin/menu/create?access_token=XXX地址進行建立菜單,create、get、delete對應建立、查詢、刪除菜單,這些操做天天有次數限制。菜單隻需本地本身執行一次,不用放在用戶請求裏面。微信公衆平臺

  

 1  public string getAccess_token()
 2         {
 3             string url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + AppId + "&secret=" + AppSecret;
 4             string result = "";
 5             CookieContainer cc = new CookieContainer();
 6             HttpWebRequest http = (HttpWebRequest)WebRequest.Create(url);
 7             http.CookieContainer = cc;
 8             http.Method = "GET"; //必須是get方式請求 
 9             http.ContentType = "application/x-www-form-urlencoded";
10             http.Timeout = 30000;
11             HttpWebResponse webResponse = (HttpWebResponse)http.GetResponse();
12             using (Stream streamReceive = webResponse.GetResponseStream())
13             {
14                 using (StreamReader sr = new StreamReader(streamReceive, Encoding.UTF8))
15                 {
16                     result = sr.ReadToEnd();
17                 }
18             }
19 
20             var accessToken = Json.Decode(result);
21             var a = accessToken.access_token;
22             return a;
23         }
24     
25         public void createMenu()
26         {
27             string result = string.Empty;
28             string accessToken = getAccess_token();
29             string user_define_menu = "{\"button\":[{\"type\":\"click\",\"name\":\"停車場信息\",\"key\":\"002\"},{\"name\":\"ECT註冊\",\"sub_button\":[{\"type\":\"click\",\"name\":\"用戶註冊\",\"key\":\"001\"},{\"type\":\"click\",\"name\":\"取消註冊\",\"key\":\"005\"}]},{\"name\":\"ECT查詢\",\"sub_button\":[{\"type\":\"click\",\"name\":\"餘額查詢\",\"key\":\"003\"},{\"type\":\"click\",\"name\":\"消費明細\",\"key\":\"004\"}]}]}";
30             byte[] datamenu = Encoding.Default.GetBytes(user_define_menu);
31             string action = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + accessToken;
32             HttpWebRequest http = (HttpWebRequest)WebRequest.Create(action);
33             CookieContainer cc = new CookieContainer();
34             http.CookieContainer = cc;
35             http.Method = "POST"; //必須是get方式請求 
36             http.ContentType = "application/x-www-form-urlencoded";
37             http.Timeout = 30000;
38             http.ContentLength = datamenu.Length;
39 
40             using (Stream streamReceive = http.GetRequestStream())
41             {
42                 streamReceive.Write(datamenu, 0, datamenu.Length);
43 
44             }
45             HttpWebResponse webResponse = (HttpWebResponse)http.GetResponse();
46             using (StreamReader streamReceive = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8))
47             {
48 
49                 result = streamReceive.ReadToEnd();
50                 webResponse.Close();
51 
52             }
53         
54             
55         }
View Code
相關文章
相關標籤/搜索