//获取accessToken
public static AccessToken GetAccessToken()
{
string AppID = JobBase.GetConfParamValue(ParamEnum.AppID);
string AppSecret = JobBase.GetConfParamValue(ParamEnum.AppSecret);
string accessTokenUrl = string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", AppID, AppSecret);//
string accessTokenJson = RequestHelper.SendGet(accessTokenUrl);
JObject json = JObject.Parse(accessTokenJson);
AccessToken Token = new AccessToken();
Token.Access_token = json["access_token"].ToString().Replace("\"", string.Empty).Trim();
Token.Expires_in = json["expires_in"].ToString();//DateTime.Now.AddSeconds(Convert.ToInt32(json["expires_in"])).ToString();
return Token;
} public static string GetExistAccessToken()
{
// 读取XML文件中的数据
//string filePath = System.Web.HttpContext.Current.Server.MapPath("XML/Token.xml");
//string filePath = "http://。。。/QYXML/Token.xml";
string filePath = JobBase.GetConfApiValue(IplatformEnum.TokenXML);
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
XmlDocument xml = new XmlDocument();
//xml.Load(filePath);
xml.Load(fs);
fs.Close();
string Token = xml.SelectSingleNode("xml").SelectSingleNode("AccessToken").InnerText.ToString().Trim();
DateTime AccessExpires = Convert.ToDateTime(xml.SelectSingleNode("xml").SelectSingleNode("AccessExpires").InnerText);
if (DateTime.Now >= AccessExpires)
{
FileStream fstream = new FileStream(filePath, FileMode.Create, FileAccess.Write);
AccessToken mode = GetAccessToken();
xml.SelectSingleNode("xml").SelectSingleNode("AccessToken").InnerText = mode.Access_token;
DateTime _accessExpires = DateTime.Now.AddSeconds(int.Parse(mode.Expires_in) - );//1h45min
xml.SelectSingleNode("xml").SelectSingleNode("AccessExpires").InnerText = _accessExpires.ToString();
//xml.Save(filePath);
xml.Save(fstream);//此处文件保存容易报错,xml文件每次重写全覆盖不完全
fstream.Close();
Token = mode.Access_token;
}
return Token;
} public static void UpdateXML(AccessToken mode)
{
string filePath = JobBase.GetConfApiValue(IplatformEnum.TokenXML);
StreamReader sr = new StreamReader(filePath, System.Text.Encoding.UTF8);
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(sr);
sr.Close();
sr.Dispose();
xmldoc.SelectSingleNode("xml").SelectSingleNode("AccessToken").InnerText = mode.Access_token;
DateTime _accessExpires = DateTime.Now.AddSeconds(int.Parse(mode.Expires_in) - );
xmldoc.SelectSingleNode("xml").SelectSingleNode("AccessExpires").InnerText = _accessExpires.ToString();
xmldoc.Save(filePath);
}