生成默认菜单

关于生成默认菜单接口的说明,请参考:

https://developers.weixin.qq.com/doc/offiaccount/Custom_Menus/Creating_Custom-Defined_Menu.html

直接用代码生成JSON格式的菜单数据比较繁琐,实际开发额时候,可以设计一个窗口,用于输入菜单设置:

窗口的“设置菜单”按钮的代码为:

Dim
URL As String = " https://api.weixin.qq.com/cgi-bin/menu/create?access_token={0}"
Dim
hc As New HttpClient(CExp(URL,Functions.Execute("GetAccessToken")))
hc
.Content = e.Form.Controls("TextBox1").Text
Dim
jo As JObject = JObject.Parse(hc.GetData)
If
jo("errcode") = "0" Then
    MessageBox.Show("菜单设置成功!")

Else

    MessageBox.Show(jo("errcode"))

End
If

根据表生成

首先设计一个表,名为Menu,用于编辑菜单,结构如下:

我根据接口说明,在表中输入了一些测试数据(parent列用于输入父菜单的name属性,如果parent为空,表示这是一级菜单),涵盖了所有十种菜单按钮类型,对应的菜单如下图:

  

然后我们在Foxtable设计一个按钮用于生成菜单,按钮代码如下:

Dim mrs As List(of DataRow)  = DataTables("Menu").Select("[parent] is null","_SortKey") '删选出一级按钮对应的行
Dim
mo As New JObject  '一级菜单对象
Dim
ma As New Jarray '一级菜单按钮数组
mo
("button") = ma '一级菜单属性就一个button属性,这是一个数组属性
For
Each mr As DataRow In mrs
    Dim so As New JObject
    so("name") = mr("name").Tostring
    Dim srs As List(of DataRow)  = DataTables("Menu").Select("[parent] = '" & mr("name") & "'", "_SortKey")
'
筛选出二级按钮
    Dim nms As String() = {"type","name","url","key",
"media_id"} '
注意列名和菜单属性名一直,方便编码,注意大是区分大小写的
   
If srs.Count = 0 Then '如果此一级菜单按钮对应的二级按钮数为0,那么次一级菜单按钮就是一个普通的命令按钮
        For Each nm As String In nms '设置一级菜单按钮的户型
            If mr.IsNull(nm) = False Then
                so(nm) = mr(nm).ToString()
            End If
        Next
    Else '如果此一级菜单按钮有对应的二级菜单按钮,那么此一级菜单按钮是一个菜单按钮
        Dim sa As New JArray '定义一个数组,包括此一级按钮下的所有二级按钮
        For Each sr As DataRow In srs '逐个生成二级按钮
            Dim jo As New JObject '定义二级按钮对象
            For Each nm As String In nms '设置二级按钮属性
               
If sr.IsNull(nm) = False Then
                    jo(nm) = sr(nm).ToString()
                End If
            Next
            sa.Add(jo)
       
Next

        so("sub_button"
) = sa '一级菜单按钮的sub_button属性是一个数组,包括所有二菜单按钮
    End If
    ma.Add(so)

Next
Dim
URL As String = " https://api.weixin.qq.com/cgi-bin/menu/create?access_token={0}"
Dim
AccessToken As String = Functions.Execute("GetAccessToken")
Dim
hc As New HttpClient(CExp(URL,AccessToken))
hc
.Content = mo.Tostring()
Dim
ro As JObject = JObject.Parse(hc.GetData)
If
ro("errcode") = "0" Then
    MessageBox.Show("菜单设置成功!")

Else

    MessageBox.Show(ro("errcode"))

End
If

显然,通过数据表来编写菜单,要轻松很多。


本页地址:http://www.foxtable.com/mobilehelp/topics/0199.htm