C#微信公衆號開發之網頁受權oauth2.0獲取用戶基本信息(一)html
中講解了若是經過微信受權2.0snsapi_base獲取已經關注用戶的基本信息,然而不少狀況下咱們常常須要獲取非關注用戶的信息,方法以下:json
第一步和以前講的同樣:獲取code,可是scope使用方法是snsapi_userinfo;api
第二步,根據code獲取openid和access_token(此處的access_token是經過網頁受權code換取的不是咱們以前講的全局的票據),代碼:微信
1 /// <summary> 2 ///用code換取獲取用戶信息(包括非關注用戶的) 3 /// </summary> 4 /// <param name="Appid"></param> 5 /// <param name="Appsecret"></param> 6 /// <param name="Code">回調頁面帶的code參數</param> 7 /// <returns>獲取用戶信息(json格式)</returns> 8 public string GetUserInfo(string Appid, string Appsecret, string Code) 9 { 10 string url = string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code", Appid, Appsecret, Code); 11 string ReText = CommonMethod.WebRequestPostOrGet(url, "");//post/get方法獲取信息 12 Dictionary<string, object> DicText = (Dictionary<string, object>)Jss.DeserializeObject(ReText); 13 if (!DicText.ContainsKey("openid")) 14 { 15 CommonMethod.WriteTxt("獲取openid失敗,錯誤碼:" + DicText["errcode"].ToString()); 16 return ""; 17 } 18 else 19 { 20 System.Web.HttpContext.Current.Session["Oauth_Token"] = DicText["access_token"]; 21 System.Web.HttpContext.Current.Session.Timeout = 7200; 22 return CommonMethod.WebRequestPostOrGet("https://api.weixin.qq.com/sns/userinfo?access_token=" + DicText["access_token"] + "&openid=" + DicText["openid"] + "&lang=zh_CN", ""); 23 } 24 }
方法已經寫好,只要傳入appid、appsecret、code三個參數就能夠返回帶用戶我的信息的json數據包,格式以下:app
{ "openid":" OPENID", " nickname": NICKNAME, "sex":"1", "province":"PROVINCE" "city":"CITY", "country":"COUNTRY", "headimgurl": "http://wx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/46", "privilege":[ "PRIVILEGE1" "PRIVILEGE2" ], "unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL" }