微信菜单更新,可以支持多个服务号更新C#。
效果Demo页面
/// <summary>
/// 更新菜单
/// </summary>
/// <param name="sender"></param>
/// <param
name="e"></param>
protected void Button4_Click(object
sender, EventArgs e)
{
WXResponse.GetInstance().UpdateMenu(TextBox1.Text.Trim());
}
using System;
using System.Collections.Generic;
using
System.Configuration;
using System.IO;
using System.Linq;
using
System.Net;
using System.Text;
using System.Web;
using
System.Xml;
using LitJson;
using log4net;
using
Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace DemoWXUpdateMenu
{
public class WXResponse
{
/// <summary>
/// 构造方法
/// </summary>
public WXResponse()
{
}
private static WXResponse _instance;
public static
WXResponse GetInstance()
{
if (_instance == null)
{
_instance = new WXResponse();
}
return _instance;
}
private ILog _log = log4net.LogManager.GetLogger(typeof(WXResponse));
/// <summary>
/// 加载菜单信息
///
</summary>
/// <param name="organID"></param>
/// <returns></returns>
public void
UpdateMenu(string organID)
{
string json =
GetJsonString(organID);
WXCreateMenu(json, organID);
}
public string GetJsonString(string organID)
{
string re = string.Empty;
try
{
//后期要改为从缓存中取数据,测试
OrganBankConfig menu =
GetCacheOrganConfigMenu(organID);
#region 菜单格式化
if (menu
!= null)
{
MenuConfig mc = new
MenuConfig();
List<Level1> l1List = new
List<Level1>();
for (int i = 0; i <
menu.Level1List.Count; i++)
{
Level1 l1 = new Level1();
l1.name =
menu.Level1List[i].Name;
l1.type =
menu.Level1List[i].Type;
l1.url =
menu.Level1List[i].Url;
l1.key =
menu.Level1List[i].Key;
if
(menu.Level1List[i].Level2List != null &&
menu.Level1List[i].Level2List.Count > 0)
{
List<Level2> l2List = new List<Level2>();
for (int j = 0; j <
menu.Level1List[i].Level2List.Count; j++)
{
Level2 l2 = new Level2();
l2.type = menu.Level1List[i].Level2List[j].Type;
l2.name = menu.Level1List[i].Level2List[j].Name;
l2.url = menu.Level1List[i].Level2List[j].Url;
l2.key = menu.Level1List[i].Level2List[j].Key;
if (l2 != null && l2.name != null)
{
l2List.Add(l2);
}
}
l1.sub_button = l2List;
}
if (l1 != null && l1.name != null)
{
l1List.Add(l1);
}
}
mc.button = l1List;
re = JsonMapper.ToJson(mc);
re = re.Replace("null", "\"\"");
//re=re.Replace("","\"sub_button"\"\:\"\"\"""");
string
replaceString = ",\"sub_button\":\"\"";
re = re.Replace(replaceString, "");
}
#endregion
}
catch (Exception ex)
{
_log.Error("对象转换失败,"
+ ex);
}
return re;
}
/// <summary>
/// 调用微信接口,自定义菜单token的获取 是用 下面的两个参数
获取的 不能直接用 公众平台的token
/// </summary>
public void
WXCreateMenu(string json, string organID)
{
try
{
OrganBankConfig ob =
GetCacheOrganConfigMenu(organID);
if (ob == null)
{
_log.Info("配置数据为空,请检查配置.");
}
string wXSAppId = ob.WXSAppId;
string wXSAppSecret =
ob.WXSAppSecret;
if (wXSAppId == null || wXSAppSecret ==
null)
{
_log.Info("WXSAppId,WXSAppSecret为空,不能修改菜单");
return;
}
string wXAPIUrl =
ConfigurationManager.AppSettings["WXAPIUrl"].ToString();
string weixin1 = json;
string to = GetData(wXAPIUrl +
@"cgi-bin/token?grant_type=client_credential&appid=" + wXSAppId +
"&secret=" + wXSAppSecret);
//后台 json的操作 得到的就是 token 或者
自己 获取 json的token
string token =
string.Empty;
JObject jo =
(JObject)JsonConvert.DeserializeObject(to);
if (jo != null
&& jo["access_token"] != null)
{
token = jo["access_token"].ToString().Replace("\"", "");
string re = GetPage(wXAPIUrl + @"cgi-bin/menu/create?access_token=" + token,
weixin1);
_log.Info("创建或修改菜单成功" + re);
}
else
{
_log.Info("获取token失败,请查看日志");
}
}
catch
(Exception ex)
{
_log.Error("创建或修改菜单失败," +
ex);
}
}
#region 取配置文件或从缓存中取
/// <summary>
///
根据机构号取菜单数据
/// </summary>
/// <param
name="organId"></param>
///
<returns></returns>
public OrganBankConfig
GetCacheOrganConfigMenu(string organId)
{
OrganBankConfig result = new OrganBankConfig();
result =
LoadXMLMenu(organId);
return result;
}
/// <summary>
/// 根据机构号取回复数据
///
</summary>
/// <param name="organId"></param>
/// <returns></returns>
public Dictionary<string,
ReplyInfo> GetCacheOrganConfigReply(string organId)
{
Dictionary<string, ReplyInfo> result = new Dictionary<string,
ReplyInfo>();
result = LoadXMLReply(organId);
return result;
}
/// <summary>
/// 根据缓存中所有机构号数据
///
</summary>
/// <param name="organId"></param>
/// <returns></returns>
public Dictionary<string,
string> GetCacheOrganBankIDList()
{
Dictionary<string, string> result = new Dictionary<string,
string>();
result = LoadOrganBankIDList();
return result;
}
/// <summary>
/// 查询所有的机构银行编号
///
</summary>
/// <param name="BankSysNo"></param>
/// <returns></returns>
public
Dictionary<string, string> LoadOrganBankIDList()
{
Dictionary<string, string> organIDList = new Dictionary<string,
string>();
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(HttpContext.Current.Server.MapPath("~/App_Data/Mis.xml"));
if (xmlDoc != null)
{
XmlNodeList
nodes = xmlDoc.SelectSingleNode("//Mis").ChildNodes;
foreach
(XmlNode node in nodes)
{
if
(node.Attributes != null && node.Attributes["OrganBankID"] != null
&& node.Attributes["OrganBankID"].Value != null)
{
string organBankID =
node.Attributes["OrganBankID"].Value;
organIDList.Add(organBankID, organBankID);
}
}
}
if (organIDList != null &&
organIDList.Count > 0)
{
return
organIDList;
}
else
{
_log.Info("配置文件中找不到OrganBankID,请检查配置");
return null;
}
}
/// <summary>
/// 加载菜单信息
/// </summary>
/// <param name="organID"></param>
///
<returns></returns>
public OrganBankConfig
LoadXMLMenu(string organID)
{
try
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(HttpContext.Current.Server.MapPath("~/App_Data/Mis.xml"));
if (xmlDoc != null)
{
XmlNode
xmlOrganBank = xmlDoc.SelectSingleNode("//Mis//OrganBank[@OrganBankID=" +
organID + "]");
OrganBankConfig menu =
XmlMapEntity.XmlToObj<OrganBankConfig>("<OrganBankConfig>" +
xmlOrganBank.InnerXml + "</OrganBankConfig>");
return menu;
}
}
catch
(Exception ex)
{
_log.Error("App_Data/Mis.xml加载失败," + ex);
}
return
null;
}
/// <summary>
/// 加载回复消息
/// </summary>
/// <param name="organID"></param>
///
<returns></returns>
public Dictionary<string,
ReplyInfo> LoadXMLReply(string organID)
{
try
{
Dictionary<string, ReplyInfo> di = new
Dictionary<string, ReplyInfo>();
XmlDocument xmlDoc =
new XmlDocument();
xmlDoc.Load(HttpContext.Current.Server.MapPath("~/App_Data/Mis.xml"));
if (xmlDoc != null)
{
XmlNodeList xnl = xmlDoc.SelectNodes("//Mis//OrganBank[@OrganBankID=" + organID
+ "]//ReplyList//ReplyInfo");
if (xnl == null)
{
_log.Info("xmlDoc.SelectNodes(//Mis//OrganBank[@OrganBankID=" + organID +
"]//ReplyList//ReplyInfo)为null");
return null;
}
foreach (XmlNode btn in xnl)
{
ReplyInfo re = new ReplyInfo();
re.Key = btn.Attributes["Key"].Value;
re.Type = int.Parse(btn.Attributes["Type"].Value);
XmlNodeList ff = btn.ChildNodes;
foreach (XmlNode xxx
in ff)
{
re.KeyInfo =
xxx.InnerXml;
}
di.Add(re.Key, re);
}
}
return di;
}
catch (Exception ex)
{
_log.Error("回复消息App_Data/Mis.xml加载失败," + ex);
}
return null;
}
#endregion
#region 公共方法
/// <summary>
/// Get请求数据
///
</summary>
/// <param name="url"></param>
/// <returns></returns>
private string GetData(string
url)
{
HttpWebRequest myRequest =
(HttpWebRequest)WebRequest.Create(url);
myRequest.Method =
"GET";
HttpWebResponse myResponse =
(HttpWebResponse)myRequest.GetResponse();
StreamReader reader =
new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
string content = reader.ReadToEnd();
_log.Info("GetData()content:" + content);
reader.Close();
return content;
}
/// <summary>
/// 保存结果返回
/// </summary>
/// <param name="posturl"></param>
/// <param
name="postData"></param>
///
<returns></returns>
public 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 = encoding.GetBytes(postData);
// 准备请求...
try
{
// 设置参数
request = WebRequest.Create(posturl) as
HttpWebRequest;
CookieContainer cookieContainer = new
CookieContainer();
request.CookieContainer =
cookieContainer;
request.AllowAutoRedirect = true;
request.Method = "POST";
request.ContentType =
"application/x-www-form-urlencoded";
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();
_log.Info("GetPage()content:" + content);
string err = string.Empty;
return content;
}
catch (Exception ex)
{
_log.Error(ex.Message);
return string.Empty;
}
}
/// <summary>
/// 发送Post数据
///
</summary>
/// <param name="para"></param>
/// <returns></returns>
private string PostData(string
para, string url)
{
Encoding encoding =
Encoding.UTF8;
byte[] data = encoding.GetBytes(para);
System.Net.HttpWebRequest req =
(System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url);
req.Method = "POST";
//req.ContentType =
"application/x-www-form-urlencoded";
req.ContentType =
"application/json";
req.ContentLength = data.Length;
System.IO.Stream newStream = req.GetRequestStream();
//发送数据
newStream.Write(data, 0, data.Length);
newStream.Close();
System.Net.HttpWebResponse res =
(System.Net.HttpWebResponse)req.GetResponse();
StreamReader
reader = new StreamReader(res.GetResponseStream(), Encoding.UTF8);
string re = reader.ReadToEnd();
_log.Info("SendDataPost返回字符:" +
re);
return re;
}
#endregion
}
#region 菜单配置数据
/// <summary>
/// 菜单配置数据
/// </summary>
[Serializable]
public class OrganBankConfig
{
public
List<Level1Info> Level1List { get; set; }
public string WXToken
{ get; set; }
public string WXID { get; set; }
public string WXSAppId { get; set; }
public string
WXSAppSecret { get; set; }
public string MisApiBasePath { get; set; }
public string
MisAppKey { get; set; }
public string MisAppValue { get; set; }
}
#region JSON格式数据
/// <summary>
/// 自定义的菜单
/// </summary>
[Serializable]
public class MenuConfig
{
public
List<Level1> button { get; set; }
//public string name { get;
set; }
}
/// <summary>
/// 一级菜单里面的数据,属性
/// </summary>
[Serializable]
public class Level1
{
public string
name { get; set; }
public string type { get; set; }
public
string url { get; set; }
public string key { get; set; }
public List<Level2> sub_button { get; set; }
}
/// <summary>
/// 二级菜单里面的数据,属性
/// </summary>
[Serializable]
public class Level2
{
public string
type { get; set; }
public string name { get; set; }
public
string url { get; set; }
public string key { get; set; }
}
#endregion
/// <summary>
/// 一级菜单里面的数据,属性
///
</summary>
[Serializable]
public class Level1Info
{
public string Name { get; set; }
public string Type {
get; set; }
public string Url { get; set; }
public string
Key { get; set; }
public List<Level2Info> Level2List { get;
set; }
}
/// <summary>
/// 二级菜单里面的数据,属性
/// </summary>
[Serializable]
public class Level2Info
{
public string
Name { get; set; }
public string Type { get; set; }
public
string Url { get; set; }
public string Key { get; set; }
}
/// <summary>
/// 回复属性,回复菜单配置数据
/// </summary>
[Serializable]
public class ReplyInfo
{
public string
Key { get; set; }
public string KeyInfo { get; set; }
public int Type { get; set; } //0文本,1图文
}
#endregion
}
微信菜单更新,可以支持多个服务号更新C#。,布布扣,bubuko.com
原文地址:http://www.cnblogs.com/xiaozw/p/3761474.html