java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > 微信公众号开发之设置自定义菜单

微信公众号开发之设置自定义菜单实例代码【java版】

作者:YuanlongWang

这篇文章主要介绍了微信公众号开发之设置自定义菜单实例代码,本实例是为了实现在管理后台实现微信菜单的添加删除管理。需要的朋友可以参考下

本实例是为了实现在管理后台实现微信菜单的添加删除管理。

1、首先我们需要新建一个数据库表用于存放menu菜单项

可包含的字段有id、父类id、name、排序、是否显示、类型(view、click)、链接、adddate

注意后台存menu菜单数据时,parentId=-1为一级菜单,或parendId为一级菜单的id作为该一级菜单下的二级菜单

2、在设置菜单时需要向微信接口传menuJson字符串,所以要先拼接字符串,后台定义一个creatMenu()

public bool creatMenu() 
    { 
      string menuJson = ""; 
      //这里默认parentId=-1为最外层菜单,isactive=1为显示,responseType=1为click类型 
      DataTable dtAMenu = Service.SelectDataTable("id, name, responseType, jsonStr,url", "WEIXINMENU", " parentId=-1 and isactive=1 order by sort"); 
      if (dtAMenu.Rows.Count > 0) 
      { 
        menuJson = "{\"button\":["; 
        for (int i = 0; i < dtAMenu.Rows.Count; i++) 
        { 
          DataTable dtBMenu = Service.SelectDataTable("id, name, responseType, jsonStr,url", wx, " parentId=" + dtAMenu.Rows[i]["id"].ToString() + " and isactive=1 order by sort"); 
          if (dtBMenu.Rows.Count > 0) 
          { 
            menuJson += "{\"name\":\"" + dtAMenu.Rows[i]["name"].ToString() + "\",\"sub_button\":["; 
            for (int j = 0; j < dtBMenu.Rows.Count; j++) 
            { 
              if (Convert.ToInt32(dtBMenu.Rows[j]["responseType"]) == 2) 
              { 
                menuJson += "{\"type\":\"view\",\"name\":\"" + dtBMenu.Rows[j]["name"].ToString() + "\",\"url\":\"" + dtBMenu.Rows[j]["jsonStr"].ToString() + "\"},"; 
              } 
              else 
              { 
                menuJson += "{\"type\":\"click\",\"name\":\"" + dtBMenu.Rows[j]["name"].ToString() + "\",\"key\":\"eventKey_" + dtBMenu.Rows[j]["id"].ToString() + "\"},"; 
              } 
            } 
            menuJson = menuJson.TrimEnd(','); 
            menuJson += "]},"; 
          } 
          else 
          { 
            //if (Convert.ToInt32(dtAMenu.Rows[i]["responseType"]) == 2) 
            //{ 
              menuJson += "{\"type\":\"view\",\"name\":\"" + dtAMenu.Rows[i]["name"].ToString() + "\",\"url\":\"" + dtAMenu.Rows[i]["jsonStr"].ToString() + "\"},"; 
            //} 
            //else 
            //{ 
            //  menuJson += "{\"type\":\"click\",\"name\":\"" + dtAMenu.Rows[i]["name"].ToString() + "\",\"key\":\"eventKey_" + dtAMenu.Rows[i]["id"].ToString() + "\"},"; 
            //} 
          } 
          dtBMenu.Dispose(); 
        } 
        dtAMenu.Dispose(); 
        menuJson = menuJson.TrimEnd(','); 
        menuJson += "]}"; 
        menuJson = menuJson.Trim(); 
        return requstZmToCreatMent(menuJson); 
      } 
      else 
      { 
        return false; 
      } 
    } 

3、获取到menujson字符串后调用微信接口创建菜单,需先获取assess token,有关assess token获取可参考:获取AccessToken

/// <summary> 
    /// 向微信服务器请求创建自定义菜单 
    /// </summary> 
    /// <param name="jsonStr"></param> 
    /// <returns></returns> 
    ///  
    private bool requstZmToCreatMent(string jsonStr) 
    { 
      try 
      { 
        var AccessToken = "";//accesstoken需例外获取,一般可开始时获取后存数据库,下次从数据库取,注意accesstoken有效期为7200秒 
        //声明一个HttpWebRequest请求 
        string interfaceUrl = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + AccessToken; 
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(interfaceUrl); 
        //设置连接超时时间  
        request.Timeout = 30000; 
        request.KeepAlive = true; 
        Encoding encodeType = Encoding.GetEncoding("UTF-8"); 
        request.Headers.Set("Pragma", "no-cache"); 
        request.Method = "POST"; 
        request.ContentType = "application/x-www-form-urlencoded"; 
        request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; Maxthon; .NET CLR 1.1.4322); Http STdns"; 
        request.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*"; 
        request.CookieContainer = new CookieContainer(); 
        byte[] Bytes = encodeType.GetBytes(jsonStr); 
        request.ContentLength = Bytes.Length; 
        request.AllowAutoRedirect = true; 
        //发送数据 
        using (Stream writer = request.GetRequestStream()) 
        { 
          writer.Write(Bytes, 0, Bytes.Length); 
          writer.Close(); 
        } 
        StringBuilder strb = new StringBuilder(); 
        //接收数据 
        using (Stream reader = request.GetResponse().GetResponseStream()) 
        { 
          StreamReader sr = new StreamReader(reader, encodeType); 
          strb.Append(sr.ReadToEnd()); 
          sr.Close(); 
          reader.Close(); 
        } 
        if ((strb.ToString().IndexOf("\"errcode\":42001") != -1) || (strb.ToString().IndexOf("\"errcode\":40001") != -1) || (strb.ToString().IndexOf("\"errcode\":40014") != -1) || (strb.ToString().IndexOf("\"errcode\":41001") != -1)) //access_token错误 
        { 
          // AccessToken = getAccessToken(); 
          getzmAccessToken(); 
          return requstZmToCreatMent(jsonStr); 
        } 
        else 
        { 
          if (strb.ToString() == "{\"errcode\":0,\"errmsg\":\"ok\"}") 
          { 
            return true; 
          } 
          else 
          { 
            return false; 
          } 
        } 
      } 
      catch (Exception exp) 
      { 
        return false; 
      } 
    } 

总结

以上所述是小编给大家介绍的微信公众号开发之设置自定义菜单实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!

您可能感兴趣的文章:
阅读全文