C# 微信公衆平臺開發(2)-- 微信菜單

 上一篇瞭解微信開發者中心 URL的配置驗證;html

  1.   驗證成功後,就能夠對獲取的接口權限進行操做 

 

 

自定義菜單接口可實現多種類型按鈕,用的比較多的是json

1.click:點擊推事件api

   用戶點擊click類型按鈕後,微信服務器會經過消息接口推送消息類型爲event 的結構給開發者(參考消息接口指南),而且帶上按鈕中開發者填寫的key值,開發者能夠經過自定義的key值與用戶進行交互;服務器

二、view:跳轉URL微信

  用戶點擊view類型按鈕後,微信客戶端將會打開開發者在按鈕中填寫的網頁URL,可與網頁受權獲取用戶基本信息接口結合,得到用戶基本信息。cookie

 

自定義菜單接口調用:
微信開發

  http請求方式:POST(請使用https協議) https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKENapp

  ACCESS_TOKEN 須要經過接口獲取ide

 

 

因爲ACCESS_TOKEN 一天只能調用 2000,能夠將ACCESS_TOKEN  保存起來,有效時間內不須要從新調用接口post

  /// <summary>
        /// 獲取憑證接口
        /// </summary>
        /// <param name="grant_type">獲取access_token填寫client_credential</param>
        /// <param name="appid">第三方用戶惟一憑證</param>
        /// <param name="secret">第三方用戶惟一憑證密鑰,既appsecret</param>
        /// <returns></returns>
        public static string GetAccessToken(string appid, string secret)
        {
            string token = OperationXml.GetXMLToken();
            if (token == "")
            {
                string strJson = RequestUrl(string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", appid, secret));
                token = GetJsonValue(strJson, "access_token");
                OperationXml.UpdateXMLToken(token, DateTime.Now);
            }

            return token;
        }
 public static string RequestUrl(string strUrl)
        {
            // 設置參數
            HttpWebRequest request = WebRequest.Create(strUrl) as HttpWebRequest;
            CookieContainer cookieContainer = new CookieContainer();
            request.CookieContainer = cookieContainer;
            request.AllowAutoRedirect = true;
            request.Method = "POST";
            request.ContentType = "text/html";
            request.Headers.Add("charset", "utf-8");

            //發送請求並獲取相應迴應數據
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            //直到request.GetResponse()程序纔開始向目標網頁發送Post請求
            Stream responseStream = response.GetResponseStream();
            StreamReader sr = new StreamReader(responseStream, Encoding.UTF8);
            //返回結果網頁(html)代碼
            string content = sr.ReadToEnd();
            return content;
        }

#region 獲取Json字符串某節點的值

        /// <summary>
        /// 獲取Json字符串某節點的值
        /// </summary>
        public static string GetJsonValue(string jsonStr, string key)
        {
            string result = string.Empty;
            if (!string.IsNullOrEmpty(jsonStr))
            {
                key = "\"" + key.Trim('"') + "\"";
                int index = jsonStr.IndexOf(key) + key.Length + 1;
                if (index > key.Length + 1)
                {
                    //先截逗號,如果最後一個,截「}」號,取最小值
                    int end = jsonStr.IndexOf(',', index);
                    if (end == -1)
                    {
                        end = jsonStr.IndexOf('}', index);
                    }

                    result = jsonStr.Substring(index, end - index);
                    result = result.Trim(new char[] { '"', ' ', '\'' }); //過濾引號或空格
                }
            }
            return result;
        }

        #endregion

  /// <summary>
        /// 獲取XML文件路徑
        /// </summary>
        public static string xmlName = AppDomain.CurrentDomain.BaseDirectory + @"\AccessToken.xml";

        /// <summary>
        /// 讀取XML  Token
        /// </summary>
        /// <param name="xmlUrl"></param>
        /// <returns></returns>
        public static string GetXMLToken()
        {
            try
            {
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(xmlName);

                XmlNode xn = xmlDoc.SelectSingleNode("ACCESS_TOKEN");
                XmlElement xe = (XmlElement)xn;//將子節點類型轉換爲XmlElement類型 
                string Token = "";
                string CreateTime = "";
                foreach (XmlNode xn1 in xe)//遍歷 
                {
                    XmlElement xe2 = (XmlElement)xn1;//轉換類型 
                    if (xe2.Name == "Token")//若是找到 
                    {
                        Token = xe2.InnerText;//則修改
                    }
                    if (xe2.Name == "CreateTime")//若是找到 
                    {
                        CreateTime = xe2.InnerText;//則修改
                    }
                }

                int seconds = 0;

                if (CreateTime.Trim() != "")
                {
                    DateTime ct = Convert.ToDateTime(CreateTime);
                    TimeSpan ts = (DateTime.Now - ct);
                    seconds = ts.Milliseconds;
                }
                LogTextHelper.WriteLogToFile("Token:" + Token);
                if (seconds > 7200 || seconds == 0)
                {
                    return "";
                }
                else
                {
                    return Token;
                }
            }
            catch (Exception ex)
            {
                LogTextHelper.WriteLogToFile("異常:" + ex.ToString());
                return "";
            }
        }

        /// <summary>
        /// 修改Token
        /// </summary>
        /// <param name="token"></param>
        /// <param name="createTime"></param>
        public static void UpdateXMLToken(string token, DateTime createTime)
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(xmlName);

            XmlNode xn = xmlDoc.SelectSingleNode("ACCESS_TOKEN");
            XmlElement xe = (XmlElement)xn;//將子節點類型轉換爲XmlElement類型 

            foreach (XmlNode xn1 in xe)//遍歷 
            {
                XmlElement xe2 = (XmlElement)xn1;//轉換類型 
                if (xe2.Name == "Token")//若是找到 
                {
                    xe2.InnerText = token;//則修改
                }
                if (xe2.Name == "CreateTime")//若是找到 
                {
                    xe2.InnerText = createTime.ToString();//則修改
                }
            }
            xmlDoc.Save(xmlName);

        }
獲取Token
  1   #region 建立菜單
  2 
  3         public string CreateMenuPage(string posturl, string postData)
  4         {
  5             Stream outstream = null;
  6             Stream instream = null;
  7             StreamReader sr = null;
  8             HttpWebResponse response = null;
  9             HttpWebRequest request = null;
 10             Encoding encoding = Encoding.UTF8;
 11             byte[] data = encoding.GetBytes(postData);
 12             // 準備請求...
 13             try
 14             {
 15                 // 設置參數
 16                 request = WebRequest.Create(posturl) as HttpWebRequest;
 17                 CookieContainer cookieContainer = new CookieContainer();
 18                 request.CookieContainer = cookieContainer;
 19                 request.AllowAutoRedirect = true;
 20                 request.Method = "POST";
 21                 request.ContentType = "application/x-www-form-urlencoded";
 22                 request.ContentLength = data.Length;
 23                 outstream = request.GetRequestStream();
 24                 outstream.Write(data, 0, data.Length);
 25                 outstream.Close();
 26                 //發送請求並獲取相應迴應數據
 27                 response = request.GetResponse() as HttpWebResponse;
 28                 //直到request.GetResponse()程序纔開始向目標網頁發送Post請求
 29                 instream = response.GetResponseStream();
 30                 sr = new StreamReader(instream, encoding);
 31                 //返回結果網頁(html)代碼
 32                 string content = sr.ReadToEnd();
 33                 string err = string.Empty;
 34                 Response.Write(content);
 35                 return content;
 36             }
 37             catch (Exception ex)
 38             {
 39                 string err = ex.Message;
 40                 return string.Empty;
 41             }
 42         }
 43 
 44         #endregion
 45 
 46         #region 刪除菜單
 47 
 48         public JsonResult DelMenu()
 49         {
 50             string postUrl = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token={0}";
 51             postUrl = string.Format(postUrl, CommonApi.GetAccessToken(strAppID, strAppSecret));
 52             string menuInfo = getMenuInfo();
 53             string result = CommonApi.PostWebRequest(postUrl, menuInfo);
 54 
 55             return Json(result, JsonRequestBehavior.AllowGet);
 56         }
 57 
 58         #endregion
 59 
 60         #region 獲取菜單
 61 
 62         public string GetMenuList(string posturl)
 63         {
 64             Stream instream = null;
 65             StreamReader sr = null;
 66             HttpWebResponse response = null;
 67             HttpWebRequest request = null;
 68             Encoding encoding = Encoding.UTF8;
 69             // 準備請求...
 70             try
 71             {
 72                 // 設置參數
 73                 request = WebRequest.Create(posturl) as HttpWebRequest;
 74                 CookieContainer cookieContainer = new CookieContainer();
 75                 request.CookieContainer = cookieContainer;
 76                 request.AllowAutoRedirect = true;
 77                 request.Method = "GET";
 78                 request.ContentType = "application/x-www-form-urlencoded";
 79                 //發送請求並獲取相應迴應數據
 80                 response = request.GetResponse() as HttpWebResponse;
 81                 //直到request.GetResponse()程序纔開始向目標網頁發送Post請求
 82                 instream = response.GetResponseStream();
 83                 sr = new StreamReader(instream, encoding);
 84                 //返回結果網頁(html)代碼
 85                 string content = sr.ReadToEnd();
 86                 string err = string.Empty;
 87                 Response.Write(content);
 88                 return content;
 89             }
 90             catch (Exception ex)
 91             {
 92                 string err = ex.Message;
 93                 return string.Empty;
 94             }
 95         }
 96 
 97         #endregion
 98 
 99  private string getMenuInfo()
100         {
101  {
102      "button":[
103      {    
104           "type":"click",
105           "name":"今日歌曲",
106           "key":"V1001_TODAY_MUSIC"
107       },
108       {
109            "name":"菜單",
110            "sub_button":[
111            {    
112                "type":"view",
113                "name":"搜索",
114                "url":"http://www.soso.com/"
115             },
116             {
117                "type":"view",
118                "name":"視頻",
119                "url":"http://v.qq.com/"
120             },
121             {
122                "type":"click",
123                "name":"贊一下咱們",
124                "key":"V1001_GOOD"
125             }]
126        }]
127  }
128
菜單操做

 

發佈服務器,執行下,在微信公衆號上就能夠看到本身定義的菜單了

請點擊我 --我愛足球

-------------------------------------------------------------------------------------

若是你以爲有幫助 請關注個人微信公衆號,沒有幫助你也能夠添加喲!o(∩_∩)o 哈哈

相關文章
相關標籤/搜索