服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|JavaScript|易语言|

服务器之家 - 编程语言 - Java教程 - 微信公众号开发之设置自定义菜单实例代码【java版】

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

2021-05-10 10:57YuanlongWang Java教程

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

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

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

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

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

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

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/// <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;
      }
    }

总结

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

原文链接:https://blog.csdn.net/lwpoor123/article/details/80728866

延伸 · 阅读

精彩推荐