Exemplo n.º 1
0
        /// <summary>
        /// 根据当前日期 判断Access_Token 是否超期  如果超期返回新的Access_Token   否则返回之前的Access_Token
        /// </summary>
        /// <param name="datetime"></param>
        /// <returns></returns>
        public string IsExistAccess_Token()
        {
            string   Token = string.Empty;
            DateTime YouXRQ;
            // 读取XML文件中的数据,并显示出来 ,注意文件路径

            string filepath = System.Web.HttpContext.Current.Server.MapPath("/XMLWXACCESS.xml");

            StreamReader str = new StreamReader(filepath, System.Text.Encoding.UTF8);
            XmlDocument  xml = new XmlDocument();

            xml.Load(str);
            str.Close();
            //str.Dispose();
            Token  = xml.SelectSingleNode("xml").SelectSingleNode("Access_Token").InnerText;
            YouXRQ = Convert.ToDateTime(xml.SelectSingleNode("xml").SelectSingleNode("Access_YouXRQ").InnerText);

            if (DateTime.Now > YouXRQ)
            {
                DateTime     _youxrq = DateTime.Now;
                Access_token mode    = GetAccess_token();
                if (mode.access_token != null && mode.expires_in != null)
                {
                    xml.SelectSingleNode("xml").SelectSingleNode("Access_Token").InnerText = mode.access_token;
                    //_youxrq = _youxrq.AddSeconds(int.Parse(mode.expires_in));
                    _youxrq = _youxrq.AddSeconds(300);
                    xml.SelectSingleNode("xml").SelectSingleNode("Access_YouXRQ").InnerText = _youxrq.ToString();
                    xml.Save(filepath);
                    Token = mode.access_token;
                }
            }
            return(Token);
            //string _access_token = IsExistAccess_Token();
        }
Exemplo n.º 2
0
        public Access_token GetAccess_token()
        {
            string       aid    = Utils.GetAppSetting("WeiXinAppid");
            string       secret = Utils.GetAppSetting("WeiXinCode");
            string       strUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + aid + "&secret=" + secret;
            Access_token mode   = new Access_token();

            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(strUrl);

            req.Method = "GET";
            using (WebResponse wr = req.GetResponse())
            {
                HttpWebResponse myResponse = (HttpWebResponse)req.GetResponse();

                StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);

                string content = reader.ReadToEnd();
                //Response.Write(content);
                //在这里对Access_token 赋值
                Access_token token = new Access_token();
                token             = JsonHelper.JsonToObject <Access_token>(content);
                mode.access_token = token.access_token;
                mode.expires_in   = token.expires_in;
            }
            return(mode);
        }