具体思路:菜单编辑实现的主要功能就是对菜单的增删改,以及同步到手机客户端上。
微信前端页面:
前端代码
<%@ Page Language="C#" AutoEventWireup="true" Inherits="WX_MenuAdm, DHERP.Web" EnableEventValidation="false" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
<link rel="Stylesheet" type="text/css" href="http://oa.datahelp.cn:808/erp/Public/Style/sub.css" />
<link rel="Stylesheet" type="text/css" href="../../Public/css/ace.css" />
<link rel="Stylesheet" type="text/css" href="../../Public/css/bootstrap.min.css" />
</head>
<body>
<form id="form1" runat="server">
<div class="col-xs-3" style="padding-left: 6px; padding-right: 0px;">
<div class="widget-box widget-color-blue2">
<div class="widget-header" style="background-image: -webkit-linear-gradient(bottom,#5090c1 0,#d7dcf2 100%)!important">
<h4 class="widget-title lighter smaller">选择</h4>
</div>
<div class="widget-body" id="tree">
<div class="widget-main padding-8">
<div id="tree-style" style="padding-right: 10px; overflow-y: auto; padding-left: 10px; scrollbar-face-color: #ffffff; font-size: 10pt; padding-bottom: 0px; scrollbar-shadow-color: #919192; color: blue; scrollbar-3dlight-color: #ffffff; line-height: 100%; scrollbar-arrow-color: #919192; padding-top: 0px; scrollbar-track-color: #ffffff; scrollbar-darkshadow-color: #ffffff; letter-spacing: 1pt; text-align: left; background-repeat: no-repeat;">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="conditional" ChildrenAsTriggers="false">
<ContentTemplate>
<asp:TreeView ID="TreeView1" runat="server" ShowLines="True" OnSelectedNodeChanged="TreeView1_SelectedNodeChanged">
<SelectedNodeStyle BackColor="#7d8abe" BorderColor="White" />
</asp:TreeView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnAdds" EventName="Click" />
<asp:AsyncPostBackTrigger ControlID="btnAdd" EventName="Click" />
<asp:AsyncPostBackTrigger ControlID="btnMod" EventName="Click" />
<asp:AsyncPostBackTrigger ControlID="btnDel" EventName="Click" />
<asp:AsyncPostBackTrigger ControlID="btnSch" EventName="Click" />
<asp:AsyncPostBackTrigger ControlID="btnUpdateWx" EventName="Click" />
<asp:AsyncPostBackTrigger ControlID="TreeView1" EventName="SelectedNodeChanged" />
</Triggers>
</asp:UpdatePanel>
</div>
</div>
</div>
</div>
</div>
<div class="col-xs-9">
<div class="widget-box widget-color-blue2" id="max-box">
<div class="widget-header" style="background-image: -webkit-linear-gradient(bottom,#5090c1 0,#d7dcf2 100%)!important">
<h4 class="widget-title lighter smaller">菜单编辑</h4>
</div>
<div class="widget-body-table" id="widget-body-table" style="width: 100%; height: 100%; overflow: scroll;">
<asp:UpdatePanel ID="UpdatePanel2" runat="server" ChildrenAsTriggers="false" UpdateMode="Conditional">
<ContentTemplate>
<fieldset class="layui-elem-field">
<legend>编辑信息</legend>
<div class="layui-form-item">
<div class="layui-inline">
<lable class="layui-form-label">菜单URL:</lable>
<div class="layui-input-inline layui-input-long">
<asp:TextBox ID="tbUrl" runat="server" CssClass="layui-input-inline layui-input-long"></asp:TextBox>
</div>
</div>
</div>
<div class="layui-form-item">
<div class="layui-inline">
<lable class="layui-form-label">菜单类型:</lable>
<div class="layui-input-inline">
<asp:DropDownList ID="ddlWxMenuType" runat="server" CssClass="select">
<asp:ListItem Value="click">click</asp:ListItem>
<asp:ListItem Value="view">view</asp:ListItem>
</asp:DropDownList>
</div>
</div>
<div class="layui-inline">
<lable class="layui-form-label">菜单名称:</lable>
<div class="layui-input-inline">
<asp:TextBox ID="tbBarText" runat="server" CssClass="layui-input"></asp:TextBox>
</div>
</div>
<div class="layui-inline">
<lable class="layui-form-label">菜单key:</lable>
<div class="layui-input-inline">
<asp:TextBox ID="tbWxMenuKey" runat="server" CssClass="layui-input"></asp:TextBox>
</div>
</div>
</div>
</fieldset>
<span style="display: none">
<asp:Button ID="btnSch" runat="server" ToolTip="刷新" Text="刷新" CssClass="btn btn-minier btn-purple" OnClick="btnSch_Click" UseSubmitBehavior="false" />
<asp:HiddenField ID="hfDepth" runat="server" Value="0" />
<asp:HiddenField ID="hfValuePath" runat="server" />
<asp:HiddenField ID="hfTemp" runat="server" />
<asp:HiddenField ID="hfRecID" runat="server" Value="-1" />
<asp:HiddenField ID="hfparentID" runat="server" Value="-1" />
</span>
<fieldset>
<legend> </legend>
<div style="text-align: center;">
<asp:Button ID="btnAdds" runat="server" ToolTip="新建分类" Text="新建分类" CssClass="btn btn-minier btn-purple" OnClientClick="if(ChkAdds()==false)return false;" UseSubmitBehavior="false" OnClick="btnAdds_Click" />
<asp:Button ID="btnAdd" runat="server" ToolTip="新建子类" Text="新建子类" CssClass="btn btn-minier btn-purple" OnClientClick="if(ChkAdd()==false)return false;" UseSubmitBehavior="false" OnClick="btnAdd_Click" />
<asp:Button ID="btnMod" runat="server" ToolTip="修改" Text="修改" CssClass="btn btn-minier btn-purple" OnClientClick="if(ChkMod()==false)return false;" UseSubmitBehavior="false" OnClick="btnMod_Click" />
<asp:Button ID="btnDel" runat="server" ToolTip="删除" Text="删除" CssClass="btn btn-minier btn-purple" OnClientClick="if(confirmAct('确定要删除吗?')==false)return false;" OnClick="btnDel_Click" UseSubmitBehavior="false" />
<input id="btnMove" type="button" value="移动" class="btn btn-minier btn-purple" onclick="parent.layer_show(parent.layer.getFrameIndex(window.name), '移动菜单项目', '../Crm/Weixin/WeinxinMenuMove.aspx?id=' + document.getElementById('hfRecID').value, '800', '600');" />
<asp:Button ID="btnUpdateWx" runat="server" ToolTip="同步微信" Text="同步微信" CssClass="btn btn-minier btn-purple" OnClick="btnUpdateWx_Click" />
<input id="btnCls" type="button" value="关闭" class="btn btn-minier btn-purple" onclick="alert($('hfParent').value); CloseWindowClr('1');" />
</fieldset>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="TreeView1" EventName="SelectedNodeChanged" />
<asp:AsyncPostBackTrigger ControlID="btnAdds" EventName="Click" />
<asp:AsyncPostBackTrigger ControlID="btnAdd" EventName="Click" />
<asp:AsyncPostBackTrigger ControlID="btnMod" EventName="Click" />
<asp:AsyncPostBackTrigger ControlID="btnDel" EventName="Click" />
<asp:AsyncPostBackTrigger ControlID="btnUpdateWx" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
<span style="display: none">
<input name="hfparent" type="text" id="hfparent" />
<asp:HiddenField ID="hfActiveTab" runat="server" />
</span>
</div>
</div>
</div>
</form>
</body>
</html>
<script type="text/javascript" src="../../Public/js/jquery-2.1.4.min.js"></script>
<script type="text/javascript" src="../../Public/js/erpcommon.js"></script>
<script type="text/javascript" src="../../Public/h-ui.admin/js/H-ui.admin.js"></script>
<script type="text/javascript">
function ChkAdds() {
if (document.getElementById("btnAdds").value == "保存") {
if (ChkSave() == false) return false;
}
}
function ChkAdd() {
if (document.getElementById("hfRecID").value == "-1") {
alert("请选择一条分类后操作!");
return false;
}
if (document.getElementById("btnAdd").value == "保存") {
if (ChkSave() == false) return false;
}
}
function ChkMod() {
if (document.getElementById("hfRecID").value == "-1") {
alert("请选择一条分类后操作!");
return false;
}
if (document.getElementById("btnMod").value == "保存") {
if (ChkSave() == false) return false;
}
}
function ChkSave() {
if (isNull(document.getElementById("tbBarText").value)) {
window.alert("操作失败!分类名不能为空");
document.getElementById("tbBarText").focus();
return false
}
if (!isNull(document.getElementById("tbWxMenuKey").value)) {
if (!CheckNum(document.getElementById("tbWxMenuKey").value)) {
window.alert("排序必须为数字.");
document.getElementById("tbWxMenuKey").select();
return false
}
}
}
function ChkFocus() {
document.getElementById("tbBarText").select();
}</script>
<script type="text/javascript">autodivheight();
function autodivheight() { //函数:获取尺寸
//获取浏览器窗口高度
var winHeight = 0;
if (window.innerHeight) winHeight = window.innerHeight;
else if ((document.body) && (document.body.clientHeight)) winHeight = document.body.clientHeight;
//通过深入Document内部对body进行检测,获取浏览器窗口高度
if (document.documentElement && document.documentElement.clientHeight) winHeight = document.documentElement.clientHeight;
//DIV高度为浏览器窗口的高度
document.getElementById("widget-body-table").style.height = winHeight - 55 + "px";
document.getElementById("tree").style.height = winHeight - 55 + "px";
var treeheight = winHeight - 65 + "px";
document.getElementById("tree-style").style.height = treeheight;
}
window.onresize = autodivheight; //浏览器窗口发生变化时同时变化DIV高度
</script>
选中左侧分类点击新建分类按钮,不可编辑区域变为可编辑区域,新建分类按钮变为保存按钮
页面后台代码
using System;
using System.Data;
using System.Web;
using System.Web.Profile;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using DHERP.DAL;
using DHERP.Library;
using DHERP.Model;
using DHERP.BLL;
using System.IO;
using System.Text;
using System.Net;
public class WX_MenuAdm : Page, IRequiresSessionState
{
protected HtmlHead Head1;
protected ScriptManager ScriptManager1;
protected TreeView TreeView1;
protected UpdatePanel UpdatePanel1;
protected TextBox tbBarText;
protected TextBox tbIcoPci;
protected TextBox tbWxMenuKey;
protected TextBox tbUrl;
protected TextBox tbRemark;
protected DropDownList ddlWxMenuType;
protected HiddenField hfValuePath;
protected HiddenField hfTemp;
protected HiddenField hfRecID;
protected HiddenField hfparentID;
protected Button btnAdds;
protected Button btnUpdateWx;
protected Button btnAdd;
protected Button btnMod;
protected Button btnDel;
protected UpdatePanel UpdatePanel2;
protected HtmlForm form1;
private int id;
protected DefaultProfile Profile
{
get
{
return (DefaultProfile)this.Context.Profile;
}
}
protected HttpApplication ApplicationInstance
{
get
{
return this.Context.ApplicationInstance;
}
}
protected void Page_Load(object sender, EventArgs e)
{
int.TryParse(base.Request["id"], out this.id);//
if (this.id == 0)
{
base.Response.End();
}
FunLibrary.ChkLogin();
if (!base.IsPostBack)
{
int num = int.Parse((string)this.Session["Session_GrantID"]);
if (num > 0)
{
DALGrant dALGrant = new DALGrant();
if (!dALGrant.GetGrant(num, "bg_r38"))
{
this.btnAdds.Enabled = false;
this.btnMod.Enabled = false;
this.btnDel.Enabled = false;
this.btnAdd.Enabled = false;
}
}
this.SetEnable();
this.FillData();
}
}
protected void FillData()
{
int num = 0;
DataTable dt = DALCommon.GetList_HL(0, "WX_WxMenu", "name as BarText,* ", 0, 0, "", " ID asc", out num).Tables[0];
this.TreeView1.Nodes.Clear();
TreeNode treeNode = new TreeNode();
treeNode.Text = "全部(" + num.ToString() + ")";
treeNode.Value = "-1";
this.TreeView1.Nodes.Add(treeNode);
BindControl.BindTreeNodePl(treeNode, dt, treeNode.Value);
this.TreeView1.ExpandAll();
}
protected void CleanText()
{
this.tbBarText.Text = string.Empty;
}
protected void SetEnable()
{
this.tbBarText.Enabled = false;
}
protected void SetDisEnable()
{
this.tbBarText.Enabled = true;
}
protected void btnSch_Click(object sender, EventArgs e)
{
this.FillData();
}
protected void btnAdds_Click(object sender, EventArgs e)
{
if (this.btnAdds.Text == "新建分类")
{
this.btnDel.Enabled = false;
this.btnMod.Enabled = false;
this.btnAdd.Enabled = false;
this.btnAdds.Text = "保存";
this.CleanText();
this.SetDisEnable();
this.SysInfoSlt("ChkFocus();");
}
else
{
MenuDal _MenuDal = new MenuDal();
WxMenuModel _WxMenuModel = new WxMenuModel();
_WxMenuModel.Name = FunLibrary.ChkInput(this.tbBarText.Text);
_WxMenuModel.Type = this.ddlWxMenuType.SelectedItem.Value;
_WxMenuModel.MenuKey = FunLibrary.ChkInput(this.tbWxMenuKey.Text);
_WxMenuModel.Url = FunLibrary.ChkInput(this.tbUrl.Text);
_WxMenuModel.OrgID = "";
_WxMenuModel.Parent = -1;
string str;
int num = _MenuDal.Add("WX_WxMenu", _WxMenuModel, out str);
if (num == 0)
{
this.btnDel.Enabled = true;
this.btnMod.Enabled = true;
this.btnAdd.Enabled = true;
this.btnAdds.Text = "新建分类";
this.SysInfoSlt("document.getElementById('btnAdds').focus();");
this.SetEnable();
this.FillData();
this.hfRecID.Value = "-1";
}
else
{
if (num == -1)
{
this.SysInfo("window.alert('" + str + "');document.getElementById('tbBarText').select();");
}
else
{
this.SysInfo("window.alert('" + num + "');");
}
}
}
this.FillData();
}
protected void btnMod_Click(object sender, EventArgs e)
{
if (this.btnMod.Text == "修改")
{
this.btnDel.Enabled = false;
this.btnAdds.Enabled = false;
this.btnAdd.Enabled = false;
this.btnMod.Text = "保存";
this.SetDisEnable();
}
else
{
int id = 0;
int.TryParse(this.hfRecID.Value, out id);
if (id > 0)
{
string menuId = this.hfRecID.Value;
string name = this.tbBarText.Text;
string type = this.ddlWxMenuType.SelectedItem.Value;
string key = this.tbWxMenuKey.Text;
string url = this.tbUrl.Text;
int uprow = MenuDal.UpdateMenu(menuId, name, type, key, url);
if (uprow == 1)
{
this.SysInfo("window.alert('保存成功');");
}
else
{
this.SysInfo("window.alert('保存失败');");
}
}
else
{
this.SysInfo("window.alert('错误,请选择左侧菜单项目');");
}
}
this.FillData();
}
protected void btnDel_Click(object sender, EventArgs e)
{
int iD = int.Parse(this.hfRecID.Value);
DALSideBarMenu dALSideBarMenu = new DALSideBarMenu();
string empty = string.Empty;
int num = dALSideBarMenu.Delete("WX_WxMenu", iD, out empty);
if (num == 0)
{
this.hfRecID.Value = "-1";
this.FillData();
this.hfRecID.Value = "-1";
this.CleanText();
}
else
{
if (num == -1)
{
this.SysInfo("window.alert('" + empty + "');");
}
else
{
this.SysInfo("window.alert('系统错误!请查看错误日志');");
}
}
this.FillData();
}
protected void btnAdd_Click(object sender, EventArgs e)
{
if (this.btnAdd.Text == "新建子类")
{
this.btnDel.Enabled = false;
this.btnMod.Enabled = false;
this.btnAdds.Enabled = false;
this.btnAdd.Text = "保存";
this.CleanText();
this.SetDisEnable();
this.SysInfoSlt("ChkFocus();");
}
else
{
MenuDal _MenuDal = new MenuDal();
WxMenuModel _WxMenuModel = new WxMenuModel();
_WxMenuModel.Name = FunLibrary.ChkInput(this.tbBarText.Text);
_WxMenuModel.Type = this.ddlWxMenuType.SelectedItem.Value;
_WxMenuModel.MenuKey = FunLibrary.ChkInput(this.tbWxMenuKey.Text);
_WxMenuModel.Url = FunLibrary.ChkInput(this.tbUrl.Text);
WeixinUserInfo user = AdminUtil.GetWxInfo(this.id);//获取用户信息
_WxMenuModel.OrgID = user.OrgID;//获取OrgID
int iparent = 0;
int.TryParse(this.hfRecID.Value, out iparent);
_WxMenuModel.Parent = iparent;
string str;
int num = _MenuDal.Add("WX_WxMenu", _WxMenuModel, out str);
this.SysInfo("window.alert('" + num + "');document.getElementById('tbBarText').select();");
if (num == 0)
{
this.btnDel.Enabled = true;
this.btnMod.Enabled = true;
this.btnAdd.Enabled = true;
this.btnAdds.Text = "新建分类";
this.SysInfoSlt("document.getElementById('btnAdds').focus();");
this.SetEnable();
this.FillData();
this.hfRecID.Value = "-1";
}
else
{
if (num == -1)
{
this.SysInfo("window.alert('" + str + "');document.getElementById('tbBarText').select();");
}
else
{
this.SysInfo("window.alert('" + num + "');");
}
}
}
this.FillData();
}
protected void btnUpdateWx_Click(object sender, EventArgs e)
{
WeixinUserInfo user = AdminUtil.GetWxInfo(this.id);
string tok = AdminUtil.GetAccessToken(this.id);
string result = WXApi.CreateMenu(tok, user.OrgID);
this.SysInfoSlt("window.alert('" + result + "');");
}
private string GetPage(string posturl, string postData)
{
Stream outstream = null;
Stream instream = null;
StreamReader sr = null;
HttpWebResponse response = null;
HttpWebRequest request = null;
Encoding encoding = Encoding.UTF8;
byte[] data = null;
if (postData.Length > 0) //有值代表创建菜单
{
data = encoding.GetBytes(postData);
}
// 准备请求...
try
{
// 设置参数
request = WebRequest.Create(posturl) as HttpWebRequest;
CookieContainer cookieContainer = new CookieContainer();
request.CookieContainer = cookieContainer;
request.AllowAutoRedirect = true;
if (postData.Length > 0)
{
request.Method = "POST"; //创建菜单
}
else
{
request.Method = "GET"; //删除菜单
}
request.ContentType = "application/x-www-form-urlencoded";
if (postData.Length > 0) //有值代表创建菜单
{
request.ContentLength = data.Length;
outstream = request.GetRequestStream();
outstream.Write(data, 0, data.Length);
outstream.Close();
}
//发送请求并获取相应回应数据
response = request.GetResponse() as HttpWebResponse;
//直到request.GetResponse()程序才开始向目标网页发送Post请求
instream = response.GetResponseStream();
sr = new StreamReader(instream, encoding);
//返回结果网页(html)代码
string content = sr.ReadToEnd();
string err = string.Empty;
return content;
}
catch (Exception ex)
{
string err = ex.Message;
Response.Write(err);
Response.End();
return string.Empty;
}
}
protected void CreateMenu(object sender, EventArgs e)
{
FileStream fs = new FileStream(HttpContext.Current.Server.MapPath(".") + "\\menu.txt", FileMode.Open);
StreamReader sr = new StreamReader(fs, Encoding.GetEncoding("GBK"));
string menu = sr.ReadToEnd();
sr.Close();
fs.Close();
sr.Dispose();
fs.Dispose();
string AccessToken = AdminUtil.GetAccessToken(this.id); //获取access_token
this.SysInfoSlt("window.alert('" + AccessToken + "');");
string i = GetPage("https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + AccessToken, menu);
Response.Write("创建菜单结果:" + i);
Response.End();
}
protected void TreeView1_SelectedNodeChanged(object sender, EventArgs e)
{
this.tbBarText.Text = this.TreeView1.SelectedNode.Text;
//this.tbArray.Text = this.TreeView1.SelectedNode.Text;
//this.tbUrl.Text = this.TreeView1.SelectedNode.Text;
//this.wxMenuType.Text = this.TreeView1.SelectedNode.Text;
this.hfTemp.Value = this.TreeView1.SelectedNode.Text;
this.hfRecID.Value = this.TreeView1.SelectedNode.Value;
this.hfValuePath.Value = this.TreeView1.SelectedNode.ValuePath;
DataTable dt = MenuDal.GetMenuListID(int.Parse(this.hfRecID.Value));
if(dt.Rows.Count>0)
{
this.tbWxMenuKey.Text = dt.Rows[0]["MenuKey"].ToString();
this.tbBarText.Text = dt.Rows[0]["Name"].ToString();
this.tbUrl.Text = dt.Rows[0]["Url"].ToString();
//this.wxMenuType.Text = dt.Rows[0]["Type"].ToString();
this.ddlWxMenuType.ClearSelection();
for (int i = 0; i < this.ddlWxMenuType.Items.Count; i++)
{
if (this.ddlWxMenuType.Items[i].Value == dt.Rows[0]["Type"].ToString())
{
this.ddlWxMenuType.Items[i].Selected = true;
break;
}
}
}
if (this.TreeView1.FindNode(this.hfValuePath.Value).Parent != null)
{
this.hfparentID.Value = this.TreeView1.FindNode(this.hfValuePath.Value).Parent.Value;
}
else
{
this.tbBarText.Text = string.Empty;
this.hfparentID.Value = "-1";
}
}
protected void SysInfo(string str)
{
ScriptManager.RegisterClientScriptBlock(this.UpdatePanel1, this.UpdatePanel1.GetType(), "SysInfo", str, true);
}
protected void SysInfoSlt(string str)//前台弹出消息方法
{
ScriptManager.RegisterClientScriptBlock(this.UpdatePanel2, this.UpdatePanel2.GetType(), "SysInfo", str, true);
}
}
同步菜单方法
protected void btnUpdateWx_Click(object sender, EventArgs e)
{
WeixinUserInfo user = AdminUtil.GetWxInfo(this.id);
string tok = AdminUtil.GetAccessToken(this.id);
string result = WXApi.CreateMenu(tok, user.OrgID);
this.SysInfoSlt("window.alert('" + result + "');");
}
获取数据库中用户信息
public static WeixinUserInfo GetWxInfo(int id)
{
if (id >0)
{
DataTable dt = DbHelperSQL.Query(string.Format("select * from WX_Config where ID='{0}'", id)).Tables[0];
if (dt.Rows.Count > 0)
{
int BranchID = 0;
int IsAdmin = 0;
int.TryParse(dt.Rows[0]["BranchID"].ToString(), out BranchID);
int.TryParse(dt.Rows[0]["IsAdmin"].ToString(), out IsAdmin);
WeixinUserInfo userInfo = new WeixinUserInfo();
userInfo.UserName = dt.Rows[0]["UserName"].ToString();
userInfo.BranchID = BranchID;
userInfo.OrgID = dt.Rows[0]["OrgID"].ToString();
userInfo.AppID = dt.Rows[0]["AppID"].ToString();
userInfo.Token = dt.Rows[0]["Token"].ToString();
userInfo.EncodingAESKey = dt.Rows[0]["EncodingAESKey"].ToString();
userInfo.access_token = dt.Rows[0]["access_token"].ToString();
userInfo.AppSecret = dt.Rows[0]["AppSecret"].ToString();
userInfo.IsAdmin = IsAdmin;
return userInfo;
}
}
return null;
}
获取微信的Access Token
public static string GetAccessToken( int id)
{
string access_token = string.Empty;
WeixinUserInfo user = GetWxInfo(id);
if (user != null)
{
if (user.access_token == "0" || user.access_token == "" || user.access_token == string.Empty) //尚未保存过access_token
{
access_token = WXApi.GetToken(user.AppID, user.AppSecret);
DbHelperSQL.ExecuteSql(string.Format("update WX_Config set access_token='{0}' where UserName='{1}'", access_token, user.UserName));
}
else
{
if (WXApi.TokenExpired(user.access_token)) //access_token过期
{
access_token = WXApi.GetToken(user.AppID, user.AppSecret);
DbHelperSQL.ExecuteSql(string.Format("update WX_Config set access_token='{0}' where UserName='{1}'", access_token, user.UserName));
}
else
{
return user.access_token;
}
}
}
return access_token;
}
创建菜单返回菜单 json数组
#region 创建菜单
/// <summary>
/// 创建菜单
/// </summary>
public static string CreateMenu(string access_token, string orgID)
{
string menuJsonStr = MenuDal.GetMenuJsonStr(orgID);
return CreateMenu2(access_token, menuJsonStr);
}
protected void SysInfoSlt(string str)
{
ScriptManager.RegisterClientScriptBlock(this.UpdatePanel2, this.UpdatePanel2.GetType(), "SysInfo", str, true);
}
/// <summary>
/// 创建菜单
/// </summary>
public static string CreateMenu2(string access_token, string menuJsonStr)
{
return HttpRequestUtil.PostUrl(string.Format("https://api.weixin.qq.com/cgi-bin/menu/create?access_token={0}", access_token), menuJsonStr);
}
菜单json数组拼接
注意:菜单分级根据数据库的code 长度决定 2位长度是一级菜单,4位长度是2级菜单。子集菜单根据前两位对应父及菜单。
#region 生成菜单Json
/// <summary>
/// 生成菜单Json
/// </summary>
public static string GetMenuJsonStr(string orgID)
{
StringBuilder sb = new StringBuilder();
sb.Append("{ \"button\":[");
DataTable dt = GetMenuListByOrgID(orgID);
foreach (DataRow dr in dt.Rows)
{
string sCode = dr["Code"].ToString();
if (sCode.Length == 2)
{
sb.AppendFormat("{{\"type\":\"{0}\"", dr["Type"].ToString());
sb.AppendFormat(",\"name\":\"{0}\"", dr["Name"].ToString());
if (dr["Type"].ToString() == "click")
{
sb.AppendFormat(",\"key\":\"{0}\"", dr["MenuKey"].ToString());
}
if (dr["Type"].ToString() == "view")
{
sb.AppendFormat(",\"url\":\"{0}\"", dr["Url"].ToString());
}
if (dr["Type"].ToString() == "scancode_waitmsg")
{
sb.AppendFormat(",\"key\":\"rselfmenu_0_0\",\"sub_button\":[]", dr["MenuKey"].ToString());
}
if (dr["Type"].ToString() == "scancode_push")
{
sb.AppendFormat(",\"key\":\"rselfmenu_0_1\",\"sub_button\":[]", dr["MenuKey"].ToString());
}
if (dr["Type"].ToString() == "pic_sysphoto")
{
sb.AppendFormat(",\"key\":\"rselfmenu_1_0\",\"sub_button\":[]", dr["MenuKey"].ToString());
}
if (dr["Type"].ToString() == "pic_photo_or_album")
{
sb.AppendFormat(",\"key\":\"rselfmenu_1_1\",\"sub_button\":[]", dr["MenuKey"].ToString());
}
if (dr["Type"].ToString() == "pic_weixin")
{
sb.AppendFormat(",\"key\":\"rselfmenu_1_2\",\"sub_button\":[]", dr["MenuKey"].ToString());
}
if (dr["Type"].ToString() == "location_select")
{
sb.AppendFormat(",\"key\":\"rselfmenu_2_0\",\"sub_button\":[]", dr["MenuKey"].ToString());
}
bool subMenuExists = false;
bool first = true;
foreach (DataRow drSub in dt.Rows)
{
string sSubCode = drSub["Code"].ToString();
if (sSubCode.Length == 4 && sSubCode.IndexOf(sCode) == 0)
{
subMenuExists = true;
if (subMenuExists && first)
{
sb.Append(",\"sub_button\":[");
}
if (!first) sb.Append(",");
if (first) first = false;
sb.AppendFormat("{{\"type\":\"{0}\"", drSub["Type"].ToString());
sb.AppendFormat(",\"name\":\"{0}\"", drSub["Name"].ToString());
if (drSub["Type"].ToString() == "click")
{
sb.AppendFormat(",\"key\":\"{0}\"", drSub["MenuKey"].ToString());
}
if (drSub["Type"].ToString() == "view")
{
sb.AppendFormat(",\"url\":\"{0}\"", drSub["Url"].ToString());
}
if (drSub["Type"].ToString() == "scancode_waitmsg")
{
sb.AppendFormat(",\"key\":\"rselfmenu_0_0\",\"sub_button\":[]", drSub["MenuKey"].ToString());
}
if (drSub["Type"].ToString() == "scancode_push")
{
sb.AppendFormat(",\"key\":\"rselfmenu_0_1\",\"sub_button\":[]", drSub["MenuKey"].ToString());
}
if (drSub["Type"].ToString() == "pic_sysphoto")
{
sb.AppendFormat(",\"key\":\"rselfmenu_1_0\",\"sub_button\":[]", drSub["MenuKey"].ToString());
}
if (drSub["Type"].ToString() == "pic_photo_or_album")
{
sb.AppendFormat(",\"key\":\"rselfmenu_1_1\",\"sub_button\":[]", drSub["MenuKey"].ToString());
}
if (drSub["Type"].ToString() == "pic_weixin")
{
sb.AppendFormat(",\"key\":\"rselfmenu_1_2\",\"sub_button\":[]", drSub["MenuKey"].ToString());
}
if (drSub["Type"].ToString() == "location_select")
{
sb.AppendFormat(",\"key\":\"rselfmenu_2_0\",\"sub_button\":[]", drSub["MenuKey"].ToString());
}
sb.Append("}");
}
}
if (subMenuExists) sb.Append("]");
sb.Append("},");
}
}
if (sb.Length > 1 && sb.ToString(sb.Length - 2, 2) == "},")
{
sb.Remove(sb.Length - 1, 1);
}
sb.Append("]}");
return sb.ToString();
}
#endregion
创建新菜单对应的code生成是通过数据库过程实现的,通过拼接自身id与父层id实现。
生成的菜单