c#.NET微信自定义菜单

时间:2023-12-24 11:37:37
  private void customMenu()
{ //获取access_token
string access_token = GetAccessToken();
StringBuilder sb = new StringBuilder();
sb.Append("{\"button\":[{\"type\":\"click\",\"name\":\"今日歌曲\",\"key\":\"V1001_TODAY_MUSIC\"},{\"name\":\"菜单\",\"sub_button\":[{\"type\":\"view\",\"name\":\"搜索\",\"url\":\"http://www.soso.com/\"},{\"type\":\"view\",\"name\":\"视频\",\"url\":\"http://v.qq.com/\"},{\"type\":\"click\",\"name\":\"赞一下我们\",\"key\":\"V1001_GOOD\"}]}]}");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + access_token);
byte[] requestBytes = Encoding.UTF8.GetBytes(sb.ToString());
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = requestBytes.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(requestBytes, , requestBytes.Length);
requestStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.Default);
string backstr = sr.ReadToEnd();
sr.Close();
response.Close();
} private static string GetAccessToken()
{
WebClient webClient = new WebClient();
Byte[] bytes = webClient.DownloadData("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx44bc0f54a52d905d&secret=2328cba30d97f8ec3e613f7764a604a9");
string token = Encoding.UTF8.GetString(bytes);
string[] result = token.Split(',');
string access_token1 = result[].Split(':')[];
string access_token= access_token1.Substring(,access_token1.Length-);
return access_token;
}