public class wxmethod
    {
        public static string appid = "***";
        public static string appsecret = "***";

    
        /// <summary>
        /// 微信第一步:请求CODE(公众号)
        /// </summary>
        /// <param name="ticket"></param>
        /// <returns></returns>
        public string getsendtourl(string callbackurl)
        {
            SortedDictionary<string, string> sParaTemp = new SortedDictionary<string, string>();
            sParaTemp.Add("appid", appid);
            sParaTemp.Add("redirect_uri", HttpUtility.UrlDecode("******"));

            sParaTemp.Add("response_type", "code");

            sParaTemp.Add("scope", "snsapi_userinfo");

            sParaTemp.Add("state", "STATE");

            string url = "https://open.weixin.qq.com/connect/oauth2/authorize" + "?" + CreateLinkStringUrlencode(sParaTemp) + "#wechat_redirect";
          
            return url;
        }

/// <summary>
        /// 微信第一步:请求CODE(开发者平台)
        /// </summary>
        /// <param name="ticket"></param>
        /// <returns></returns>

public string getsendtourl(string callbackurl)
        {
            SortedDictionary<string, string> sParaTemp = new SortedDictionary<string, string>();
            sParaTemp.Add("appid", appid);
       
            sParaTemp.Add("response_type", "code");

            sParaTemp.Add("scope", "snsapi_login");

            sParaTemp.Add("state", "STATE");
            sParaTemp.Add("connect_redirect", "1");

            string url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=****&redirect_uri=http://www.***.com/oauth/wxAllCallBack.html?weixincallbanck_ActiveUrl=" + callbackurl + "&response_type=code&scope=snsapi_login&state=STATE&connect_redirect=1#wechat_redirect";

            return url;
        }
       
        /// <summary>
        /// 微信第二步:通过code获取openid,access_token
        /// </summary>
        /// <param name="ticket"></param>
        /// <returns></returns>
        public string getresult(string code)
        {
            LogUtils.WriteLog(LogUtils.LogType.INFO, "微端登录code:" + code);

            string openid = string.Empty;
            string access_token = string.Empty;
            string refresh_token = string.Empty;
            string scope = string.Empty;
            string unionid = string.Empty;

            SortedDictionary<string, string> sParaTemp = new SortedDictionary<string, string>();

            sParaTemp.Add("appid", appid);
            sParaTemp.Add("secret", appsecret);
            sParaTemp.Add("code", code);
            sParaTemp.Add("grant_type", "authorization_code");
            

            string result = HttpGETstring("https://api.weixin.qq.com/sns/oauth2/access_token", sParaTemp);
            if (!string.IsNullOrEmpty(result) && !result.Contains("errcode"))
            {                

               return result;


            }

            LogUtils.WriteLog(LogUtils.LogType.ERROR, "wx获取access_token错误" + result);
            return string.Empty;
        }



        




        /// <summary>
        /// 微信第三步:通过access_token,openid获取个人信息 昵称
        /// </summary>
        /// <param name="ticket"></param>
        /// <returns></returns>
        public UserInfo getuserinfo(string access_token,string openid)
        {
            string nickname = string.Empty;
            string headimgurl = string.Empty;

            SortedDictionary<string, string> sParaTemp = new SortedDictionary<string, string>();

            sParaTemp.Add("access_token", access_token);
            sParaTemp.Add("openid", openid);           
            
            string result = HttpGETstring("https://api.weixin.qq.com/sns/userinfo", sParaTemp);

            LogUtils.WriteLog(LogUtils.LogType.INFO, "getuserinfo:"+result);

            UserInfo myinfo = new UserInfo();
            myinfo = LitJson.JsonMapper.ToObject<UserInfo>(result);

            LogUtils.WriteLog(LogUtils.LogType.INFO, "getuserinfo:" + myinfo.nickname);

            return myinfo;


        }


        /// <summary>
        /// 微信第三步:通过access_token,openid获取个人信息 微信头像
        /// </summary>
        /// <param name="ticket"></param>
        /// <returns></returns>
        public string getuserinfo_headimgurl(string access_token, string openid)
        {
            string nickname = string.Empty;
            string headimgurl = string.Empty;

            SortedDictionary<string, string> sParaTemp = new SortedDictionary<string, string>();

            sParaTemp.Add("access_token", access_token);
            sParaTemp.Add("openid", openid);

            string result = HttpGETstring("https://api.weixin.qq.com/sns/userinfo", sParaTemp);

            
            if (!string.IsNullOrEmpty(result))
            {
                string[] aa = result.Split(",".ToCharArray());
                for (int i = 0; i < aa.Length; i++)
                {
                    if (aa[i].ToString().IndexOf("headimgurl") > 0)
                    {
                        headimgurl = aa[i].Replace("\"headimgurl\":", "");
                        headimgurl = openid.Replace("\"", "");
                    }

                }

                return headimgurl;

                // return result;


            }
            return string.Empty;
        }



        public class UserInfo
        {
            public string openid { get; set; }
            public string nickname { get; set; }
            public string headimgurl { get; set; }

            public int sex { get; set; }

            public string unionid { get; set; }
            //可以添加更多需要用到的用户对象
            //....
        }

        public class JsonToken
        {
            public string access_token { get; set; }
            public double expires_in { get; set; }

            public string refresh_token { get; set; }
            
        }



        public static string HttpGETstring(string baseurl, SortedDictionary<string, string> args)
        {
            string strResponse = string.Empty;
            string url = baseurl + "?" + CreateLinkStringUrlencode(args);
            try
            {
                QBYL.Common.LogUtils.WriteLog(QBYL.Common.LogUtils.LogType.DEBUG, url);
                WebRequest req = WebRequest.Create(url);
                req.Timeout = 3000;
                WebResponse resp = req.GetResponse();
                StreamReader sr = new StreamReader(resp.GetResponseStream(), Encoding.UTF8);
                strResponse = sr.ReadToEnd();
                QBYL.Common.LogUtils.WriteLog(QBYL.Common.LogUtils.LogType.DEBUG, strResponse);
                //T returnData = LitJson.JsonMapper.ToObject<T>(strResponse);
                return strResponse;
            }
            catch (Exception ex)
            {
                LogUtils.WriteLog(LogUtils.LogType.ERROR, string.Format("Com.Snda.SSO.HttpGET:{0}\r\n{1}", url, strResponse), ex);
            }
            return string.Empty;
        }


        public static string CreateLinkStringUrlencode(SortedDictionary<string, string> dicArray)
        {
            StringBuilder prestr = new StringBuilder();
            foreach (KeyValuePair<string, string> temp in dicArray)
            {
                prestr.Append(temp.Key + "=" + HttpUtility.UrlEncode(temp.Value) + "&");
            }

            //去掉最後一個&字符
            int nLen = prestr.Length;
            prestr.Remove(nLen - 1, 1);

            return prestr.ToString();
        }

        //授权登录记录两个token
        public void getAccessToken(string openid,string refresh_token,string access_token)
        {
            // access_token 应该全局存储与更新,以下代码以写入到文件中做示例
            //string access_token = "";
            string path = HttpContext.Current.Server.MapPath(@"/json/"+openid+"_token.json");
            if (!File.Exists(path))
            {
                File.Create(path).Close();
            }
            StreamReader sr = new StreamReader(path, System.Text.Encoding.Default);
            string filecontent = sr.ReadToEnd();
            JsonToken jsonModel = null;
            if (!string.IsNullOrEmpty(filecontent))
            {
                jsonModel = Desrialize<JsonToken>(new JsonToken(), filecontent);
            }
            sr.Close();
            sr.Dispose();
            if (jsonModel == null || jsonModel.expires_in < ConvertDateTimeInt(DateTime.Now))
            {

                string json = "{\"refresh_token\":\"" + refresh_token + "\",\"access_token\":\"" + access_token + "\",\"expires_in\":" + (ConvertDateTimeInt(DateTime.Now) + 600) + "}";
                StreamWriterMetod(json, path);
            }
          
        }

        //获取access_token
        public string getAccessToken(string openid)
        {
            LogUtils.WriteLog(LogUtils.LogType.DEBUG, "gettoken:" + openid);
            string access_token = "";
            try
            {
                
                string refresh_token = "";
                string path = HttpContext.Current.Server.MapPath(@"/json/" + openid + "_token.json");
                if (!File.Exists(path))
                {
                    File.Create(path).Close();
                }
                StreamReader sr = new StreamReader(path, System.Text.Encoding.Default);
                string filecontent = sr.ReadToEnd();
                JsonToken jsonModel = null;
                if (!string.IsNullOrEmpty(filecontent))
                {
                    jsonModel = Desrialize<JsonToken>(new JsonToken(), filecontent);
                }
                sr.Close();
                sr.Dispose();

                LogUtils.WriteLog(LogUtils.LogType.DEBUG, "gettoken:" + jsonModel.expires_in);

                if (jsonModel == null || jsonModel.expires_in < ConvertDateTimeInt(DateTime.Now))
                {
                    SortedDictionary<string, string> sParaTemp = new SortedDictionary<string, string>();

                    sParaTemp.Add("appid", appid);
                    sParaTemp.Add("grant_type", "refresh_token");
                    sParaTemp.Add("refresh_token", jsonModel.refresh_token);

                    string result = HttpGETstring("https://api.weixin.qq.com/sns/oauth2/access_token", sParaTemp); //refresh_token重新获取access_token
                    if (!string.IsNullOrEmpty(result) && !result.Contains("errcode"))
                    {

                        jsonModel = Desrialize<JsonToken>(new JsonToken(), result);
                        access_token = jsonModel.access_token;
                        refresh_token = jsonModel.access_token;
                        if (access_token != "")
                        {
                            string json = "{\"refresh_token\":\"" + refresh_token + "\",\"access_token\":\"" + access_token + "\",\"expires_in\":" + (ConvertDateTimeInt(DateTime.Now) + 600) + "}";
                            StreamWriterMetod(json, path);
                        }
                    }
                }
                else
                {
                    access_token = jsonModel.access_token;
                }
            }
            catch (Exception ex)
            {
                LogUtils.WriteLog(LogUtils.LogType.DEBUG, "gettoken:"+ex);
            }
           

            return access_token;

        }


        /// <summary>
        /// 将c# DateTime时间格式转换为Unix时间戳格式
        /// </summary>
        /// <param name="time">时间</param>
        /// <returns>double</returns>
        public static int ConvertDateTimeInt(System.DateTime time)
        {
            int intResult = 0;
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            intResult = Convert.ToInt32((time - startTime).TotalSeconds);
            return intResult;
        }


        /// <summary>
        /// StreamWriter写入文件方法
        /// </summary>
        public static void StreamWriterMetod(string str, string patch)
        {
            try
            {
                FileStream fsFile = new FileStream(patch, FileMode.OpenOrCreate);
                StreamWriter swWriter = new StreamWriter(fsFile);
                //寫入數據
                swWriter.WriteLine(str);
                swWriter.Close();
            }
            catch (Exception e)
            {
                throw e;
            }
        }


        //发起一个http请球,返回值
        public static string httpGet(string url)
        {
            try
            {


                WebClient MyWebClient = new WebClient();



                MyWebClient.Credentials = CredentialCache.DefaultCredentials;//获取或设置用于向Internet资源的请求进行身份验证的网络凭据


                Byte[] pageData = MyWebClient.DownloadData(url); //从指定网站下载数据


                string pageHtml = System.Text.Encoding.Default.GetString(pageData);  //如果获取网站页面采用的是GB2312,则使用这句             


                //string pageHtml = Encoding.UTF8.GetString(pageData); //如果获取网站页面采用的是UTF-8,则使用这句


                return pageHtml;


            }


            catch (WebException webEx)
            {


                Console.WriteLine(webEx.Message.ToString());
                return null;
            }
        }


        public static T Desrialize<T>(T obj, string str)
        {
            try
            {
                var mStream = new MemoryStream(Encoding.Default.GetBytes(str));
                var serializer = new DataContractJsonSerializer(typeof(T));
                T readT = (T)serializer.ReadObject(mStream);


                return readT;
            }
            catch (Exception ex)
            {
                return default(T);
                throw new Exception("反序列化失败,原因:" + ex.Message);
            }

        }


        /// <summary>
        /// 序列化 对象到字符串
        /// </summary>
        /// <param name="obj">泛型对象</param>
        /// <returns>序列化后的字符串</returns>
        public static string Serialize<T>(T obj)
        {
            try
            {
                var serializer = new DataContractJsonSerializer(typeof(T));
                var stream = new MemoryStream();
                serializer.WriteObject(stream, obj);


                byte[] dataBytes = new byte[stream.Length];


                stream.Position = 0;


                stream.Read(dataBytes, 0, (int)stream.Length);


                string dataString = Encoding.UTF8.GetString(dataBytes);
                return dataString;
            }
            catch (Exception ex)
            {
                return null;
                throw new Exception("序列化失败,原因:" + ex.Message);
            }
        }
    }

 

posted on 2017-06-29 13:57  ftk0  阅读(398)  评论(0)    收藏  举报