05
2015
05

Asp.Net 微信菜单自定义开发功能实现源代码

1、配置文件中,配置好微信自定义菜单开发需要的AppID和AppSecret:

<?xml version="1.0"?>
<configuration>
  <appSettings>
    <add key="AppID" value="appid的值"/>
    <add key="AppSecret" value="appsecret的值"/>
  </appSettings>
    <connectionStrings />
    <system.web>
        <compilation debug="true">
        </compilation>
        <!--
            通过 <authentication> 节可以配置
            安全身份验证模式,ASP.NET 
            使用该模式来识别来访用户身份。 
        -->
        <authentication mode="Windows" />
        <!--
            如果在执行请求的过程中出现未处理的错误,
            则通过 <customErrors> 节
            可以配置相应的处理步骤。具体而言,
            开发人员通过该节可配置要显示的 html 错误页,
            以代替错误堆栈跟踪。
        <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
            <error statusCode="403" redirect="NoAccess.htm" />
            <error statusCode="404" redirect="FileNotFound.htm" />
        </customErrors>
        -->
    </system.web>
</configuration>

2、添加自定义菜单源代码:

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        string getStr = GetModel("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + ConfigurationManager.AppSettings["AppID"] + "&secret=" + ConfigurationManager.AppSettings["AppSecret"]); //授权、返回access_token
        JObject Sobject = JObject.Parse(getStr);
        string ACCESS_TOKEN = ((JValue)Sobject["access_token"]).Value.ToString().Trim();
        string postStr =
            "{\"button\":[{\"name\":\"工作与学习\",\"sub_button\":[" +
            "{\"type\":\"view\",\"name\":\"工作之路\",\"url\":\"https://www.zhengdecai.com/?mod=pad&cate=1\"}," +
            "{\"type\":\"view\",\"name\":\"学习之路\",\"url\":\"https://www.zhengdecai.com/?mod=pad&cate=2\"}" +
            "]}," +
            "{\"name\":\"网络文章\",\"sub_button\":[" +
            "{\"type\":\"view\",\"name\":\"感悟之章\",\"url\":\"https://www.zhengdecai.com/?mod=pad&cate=3\"}," +
            "{\"type\":\"view\",\"name\":\"博文调用\",\"url\":\"https://www.zhengdecai.com/?mod=pad&cate=4\"}," +
            "{\"type\":\"view\",\"name\":\"网络文摘\",\"url\":\"https://www.zhengdecai.com/?mod=pad&cate=6\"}," +
            "{\"type\":\"view\",\"name\":\"知道理解\",\"url\":\"https://www.zhengdecai.com/?mod=pad&cate=7\"}" +
            "]}," +
            "{\"name\":\"其他\",\"sub_button\":[" +
            "{\"type\":\"view\",\"name\":\"项目源码\",\"url\":\"https://www.zhengdecai.com/?mod=pad&cate=8\"}," +
            "{\"type\":\"view\",\"name\":\"爱上旅行\",\"url\":\"https://www.zhengdecai.com/?mod=pad&cate=10\"}," +
            "{\"type\":\"view\",\"name\":\"开心一刻\",\"url\":\"https://www.zhengdecai.com/?mod=pad&cate=5\"}]}]}";
        string postUrlStr = GetHtmlFromPost("https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + ACCESS_TOKEN, Encoding.UTF8, postStr);
        JObject Sobject1 = JObject.Parse(postUrlStr);
        string ACCESS_TOKEN1 = ((JValue)Sobject1["errmsg"]).Value.ToString().Trim();
        if (ACCESS_TOKEN1 == "ok")
        {
            Response.Write("添加成功!");
        }
        else
        {
            Response.Write("添加失败!失败问题:" + ACCESS_TOKEN1);
        }
    }
}
/// <summary>
/// get方式读取数据
/// </summary>
/// <param name="strUrl">地址</param>
/// <returns>返回数据</returns>
private string GetModel(string strUrl)
{
    string strRet = null;
    try
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strUrl);
        request.Timeout = 2000;
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        System.IO.Stream resStream = response.GetResponseStream();
        Encoding encode = System.Text.Encoding.UTF8;
        StreamReader readStream = new StreamReader(resStream, encode);
        Char[] read = new Char[256];
        int count = readStream.Read(read, 0, 256);
        while (count > 0)
        {
            String str = new String(read, 0, count);
            strRet = strRet + str;
            count = readStream.Read(read, 0, 256);
        }
        resStream.Close();
    }
    catch (Exception e)
    {
        strRet = "";
    }
    return strRet;
}
/// <summary>
/// 提供通过POST方法获取页面的方法
/// </summary>
/// <param name="urlString">请求的URL</param>
/// <param name="encoding">页面使用的编码</param>
/// <param name="postDataString">POST数据</param>
/// <returns>获取的页面</returns>
public static string GetHtmlFromPost(string urlString, Encoding encoding, string postDataString)
{
    //定义局部变量
    CookieContainer cookieContainer = new CookieContainer();
    HttpWebRequest httpWebRequest = null;
    HttpWebResponse httpWebResponse = null;
    Stream inputStream = null;
    Stream outputStream = null;
    StreamReader streamReader = null;
    string htmlString = string.Empty;
    //转换POST数据
    byte[] postDataByte = encoding.GetBytes(postDataString);
    //建立页面请求
    try
    {
        httpWebRequest = WebRequest.Create(urlString) as HttpWebRequest;
    }
    //处理异常
    catch (Exception ex)
    {
        throw new Exception("建立页面请求时发生错误!", ex);
    }
    //指定请求处理方式
    httpWebRequest.Method = "POST";
    httpWebRequest.KeepAlive = false;
    httpWebRequest.ContentType = "application/x-www-form-urlencoded";
    httpWebRequest.CookieContainer = cookieContainer;
    httpWebRequest.ContentLength = postDataByte.Length;
    //向服务器传送数据
    try
    {
        inputStream = httpWebRequest.GetRequestStream();
        inputStream.Write(postDataByte, 0, postDataByte.Length);
    }
    //处理异常
    catch (Exception ex)
    {
        throw new Exception("发送POST数据时发生错误!", ex);
    }
    finally
    {
        inputStream.Close();
    }
    //接受服务器返回信息
    try
    {
        httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse;
        outputStream = httpWebResponse.GetResponseStream();
        streamReader = new StreamReader(outputStream, encoding);
        htmlString = streamReader.ReadToEnd();
    }
    //处理异常
    catch (Exception ex)
    {
        throw new Exception("接受服务器返回页面时发生错误!", ex);
    }
    finally
    {
        streamReader.Close();
    }
    foreach (Cookie cookie in httpWebResponse.Cookies)
    {
        cookieContainer.Add(cookie);
    }
    return htmlString;
}

3、删除所有自定义菜单源代码:

protected void Page_Load(object sender, EventArgs e)
{
    string getStr = GetModel("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + ConfigurationManager.AppSettings["AppID"] + "&secret=" + ConfigurationManager.AppSettings["AppSecret"]);
    JObject Sobject = JObject.Parse(getStr);
    string ACCESS_TOKEN = ((JValue)Sobject["access_token"]).Value.ToString().Trim();
    string postUrlStr = GetModel("https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=" + ACCESS_TOKEN);
    JObject Sobject1 = JObject.Parse(postUrlStr);
    string ACCESS_TOKEN1 = ((JValue)Sobject1["errmsg"]).Value.ToString().Trim();
    if (ACCESS_TOKEN1 == "ok")
    {
        Response.Write("删除成功!");
    }
    else
    {
        Response.Write("删除失败!失败问题:" + ACCESS_TOKEN1);
    }
}

4、读取已经设置过的自定义菜单信息源代码:

protected void Page_Load(object sender, EventArgs e)
{
    string getStr = GetModel("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + ConfigurationManager.AppSettings["AppID"] + "&secret=" + ConfigurationManager.AppSettings["AppSecret"]);
    JObject Sobject = JObject.Parse(getStr);
    string ACCESS_TOKEN = ((JValue)Sobject["access_token"]).Value.ToString().Trim();
    string postUrlStr = GetModel("https://api.weixin.qq.com/cgi-bin/menu/get?access_token=" + ACCESS_TOKEN);
    Response.Write(JsonConvert.DeserializeObject(postUrlStr.ToString())); //格式化成JSON数据输出
}

通过这些操作,可以管理自己的微信自定义菜单。

效果图:

« 上一篇下一篇 »

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。