/// <summary> /// 请求AccessToken /// </summary> /// <param name="credentials">xml的credential凭证列表</param> private Credential RequestAccessToken(List <Credential> credentials) { //获取要请求的Credential类(公众号还是企业号类型) Credential credential = GetCredentialsFromXmlByType(); //请求 //HttpWebRequest webRequest; string strUrl = credential.RequestInfo.Url; if (credential.RequestInfo.RequestType.ToLower() == "get") { string strParams = string.Empty; //组装参数到url上 foreach (string str in credential.RequestInfo.QueryParam) { string[] strKeyValue = str.Split(':'); if (strKeyValue.Length > 1) { strParams += strKeyValue[0] + "=" + strKeyValue[1] + "&"; } else { strParams += strKeyValue[0] + "=" + strKeyValue[0] + "&"; } } strUrl += "?" + strParams.TrimEnd('&'); } //请求 HttpItem hi = new HttpItem(); hi.URL = strUrl; hi.Method = credential.RequestInfo.RequestType; if (credential.RequestInfo.ProtocolType.ToLower() == "https") { hi.IsTrustCertificate = true; } hi.Encoding = Encoding.UTF8; HttpHelper hh = new HttpHelper(); HttpResult hr = hh.GetHtml(hi); string strContext = hr.Html; //转换返回结果为实体 WxAccessToken wxat = JsonConvert.DeserializeObject <WxAccessToken>(strContext); //写入xml this.WriteXmlAccessToken(wxat); //写入cache Credential c = GetCredentialsFromXmlByType(); DateTime dtExpired = new ConvertDateTime().String2DataTime(c.TokenInfo.GetTokenDateTime).AddSeconds(double.Parse(c.TokenInfo.ExpiresIn) - double.Parse(c.TokenInfo.EarlyEnd)); CacheHelper.SetCache(c.WxPlatFormType, c, dtExpired); //返回Credential return(c); }
/// <summary> /// 写入xml元素文本 /// </summary> /// <param name="wxat"></param> private void WriteXmlAccessToken(WxAccessToken wxat) { List <XElement> listEleRtn = this._xo.GetXEleFromStrFormat("Credentials.Credential"); if (listEleRtn == null || listEleRtn.Count <= 0) { return; } foreach (XElement xele in listEleRtn) { string strWxPlatFormType = xele.Element("WxPlatFormType").Value; //如果与平台相同,则写入xml if (strWxPlatFormType.Equals(this._wxPlatFormTypeEnum.ToString())) { xele.Element("TokenInfo").Element("access_token").SetValue(wxat.access_token); xele.Element("TokenInfo").Element("expires_in").SetValue(wxat.expires_in); xele.Element("TokenInfo").Element("gettoken_dt").SetValue(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); this._xo.XElement.Save(strFilePath); break; } } }