1. 程式人生 > >.net獲取未關注公眾號的使用者資訊

.net獲取未關注公眾號的使用者資訊

#region 獲取未關注公眾號的使用者資訊
        public string getUserToModel(string code)
        {

            string str = "";
            string openid = GetCurrentRequsetWeChatUserId();
            string url = string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code,config", openid, configService.WeChatSecret, code);
            str = RequestWeChatServer(url);
            var jObject = JObject.Parse(str);


            string _access_token = jObject["access_token"].ToString();//獲取access_token
            url = string.Format("https://api.weixin.qq.com/sns/userinfo?access_token={0}&openid={1}&lang=zh_CN", _access_token, openid);
            str = RequestWeChatServer(url);
            return str;
        }
        #endregion


        #region 私有方法
        string RequestWeChatServer(string url)
        {
            HttpWebRequest hwq = (HttpWebRequest)WebRequest.Create(url);
            hwq.Method = "GET";
            hwq.ContentType = "text/html;charset=UTF-8";
            HttpWebResponse response = (HttpWebResponse)hwq.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();
            return retString;
        }