1. 程式人生 > >微信公眾號的開發之 自定義選單(二)

微信公眾號的開發之 自定義選單(二)

首先,個人訂閱號沒有自定義選單的許可權,這時候可以使用測試公眾號

步驟:定義json檔案

{
  "button": [
    {
      "type": "click",
      "name": "選單一",
      "key": "one"
    },
    {
      "type": "click",
      "name": "選單二",
      "key": "two"
    },
    {
      "type": "click",
      "name": "選單三",
      "key": "three"

    }
  ]
}
具體的json欄位含義可以看
http://mp.weixin.qq.com/wiki/10/0234e39a2025342c17a7d23595c6b40a.html

然後josn資料post到微信伺服器

/// <summary>
        /// 建立自定義選單
        /// </summary>
        /// <returns></returns>
        public string createMenu()
        {


            try
            {
                Hashtable hash = new Hashtable();
                hash.Add("access_token", access_token());
                string menu = readJson(Server.MapPath("..") + "\\menu.json");

                string result = Util.HttpRequestPostBody("https://api.weixin.qq.com/cgi-bin/menu/create", hash, menu);

                Hashtable hr = JsonConvert.DeserializeObject<Hashtable>(result);
                if (hr["errcode"].ToString().ToInt32() != 0)
                {
                    throw new Exception(hr["errmsg"].ToString());
                }
                return hr["errmsg"].ToString();
            }
            catch (Exception x)
            {
                return x.Message;
            }
        } 



private string readJson(string jsonPath)
        {
            FileStream fs1 = new FileStream(jsonPath, FileMode.Open);

            StreamReader sr = new StreamReader(fs1, Encoding.GetEncoding("GBK"));

            string json = sr.ReadToEnd();

            sr.Close();
            fs1.Close();
            return json;
        }





/// <summary>
        /// 訪問微信介面 包含body引數的函式
        /// </summary>
        /// <param name="url">絕對url</param>
        /// <param name="hash">除body以外的引數</param>
        /// <param name="postData">要post的資料,body引數值</param>
        /// <returns></returns>
        public static string HttpRequestPostBody(string url, Hashtable hash, string postData = "")
        {
            List<string> post = new List<string>();
            foreach (DictionaryEntry d in hash)
            {
                post.Add(d.Key + "=" + d.Value);
            }
            url = url + "?" + string.Join("&", post);
            Stream outstream = null;

            Stream instream = null;
            StreamReader sr = null;

            HttpWebResponse response = null;

            HttpWebRequest request = null;
            Encoding encoding = Encoding.UTF8;
            byte[] data = encoding.GetBytes(postData);
            // 準備請求...

            try

            {
                // 設定引數
                request = WebRequest.Create(url) as HttpWebRequest;

                CookieContainer cookieContainer = new CookieContainer();

                request.CookieContainer = cookieContainer;

                request.AllowAutoRedirect = true;

                if (postData == "")
                {
                    request.Method = "GET";
                }
                else
                {
                    request.Method = "POST";

                    request.ContentType = "application/x-www-form-urlencoded";

                    request.ContentLength = data.Length;

                    outstream = request.GetRequestStream();

                    outstream.Write(data, 0, data.Length);

                    outstream.Close();
                }


                //傳送請求並獲取相應迴應資料
                response = request.GetResponse() as HttpWebResponse;
                //直到request.GetResponse()程式才開始向目標網頁傳送Post請求

                instream = response.GetResponseStream();

                sr = new StreamReader(instream, encoding);

                //返回結果網頁(html)程式碼

                string content = sr.ReadToEnd();
                return content;

            }

            catch (Exception ex)
            {
                string err = ex.Message;

                return string.Empty;

            }


        }

我這裡JsonConvert.DeserializeObject<Hashtable>(result)使用了Newtonsoft.Json的第三方dll。

至此程式碼完成,執行函式,成功

然後可以獲取一下,或者到手機微信看一看,到微信手機看的時候要先取消關注,清空快取,再關注就可以看到最新的了,如果還不行,多試幾次。

 /// <summary>
        /// 拉取微信自定義選單
        /// </summary>
        /// <returns></returns>
        public string getMenu()
        {
            try
            {
                Hashtable hash = new Hashtable();
                hash.Add("access_token", access_token());
                string menu = Util.HttpRequestPostBody("https://api.weixin.qq.com/cgi-bin/menu/get", hash);
                Hashtable hr = JsonConvert.DeserializeObject<Hashtable>(menu);
                if (hr.Contains("errmsg"))
                {
                    throw new Exception(hr["errmsg"].ToString());
                }
                return menu;
            }
            catch (Exception x)
            {
                throw new Exception(x.Message);
            }
        }