protected virtual ActionResult UserAuthorised(UserInfo userInfo) { return Json(userInfo, JsonRequestBehavior.AllowGet); }
public ActionResult UserAuth(string code, string type) { var appid = ConfigurationManager.AppSettings["appid"]; if (string.IsNullOrEmpty(appid)) throw Error.AppSettingItemMiss("appid"); var secret = ConfigurationManager.AppSettings["secret"]; if (string.IsNullOrEmpty("secret")) throw Error.AppSettingItemMiss("secret"); if (string.IsNullOrEmpty(type)) type = "snsapi_base";//snsapi_userinfo string url; if (string.IsNullOrEmpty(code)) { var redirectUrl = Request.Url.ToString(); url = string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope={2}&state=STATE#wechat_redirect", appid, HttpUtility.UrlEncode(redirectUrl), type); Trace.WriteLine("Go to WeiXin Auth Page:" + url); Trace.Flush(); return Redirect(url); } var client = new System.Net.WebClient(); client.Encoding = System.Text.Encoding.UTF8; url = string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code", appid, secret, code); var data = client.DownloadString(url); var serializer = new JavaScriptSerializer(); var obj = serializer.Deserialize<Dictionary<string, object>>(data); var userInfo = new UserInfo(); object fieldValue; if (obj.TryGetValue("openid", out fieldValue)) userInfo.OpenId = (string)fieldValue; if (obj.TryGetValue("nickname", out fieldValue)) userInfo.NickName = (string)fieldValue; if (obj.TryGetValue("city", out fieldValue)) userInfo.City = (string)fieldValue; if (obj.TryGetValue("country", out fieldValue)) userInfo.Country = (string)fieldValue; if (obj.TryGetValue("province", out fieldValue)) userInfo.Province = (string)fieldValue; if (obj.TryGetValue("language", out fieldValue)) userInfo.Language = (string)fieldValue; if (obj.TryGetValue("headimgurl", out fieldValue)) userInfo.HeadImgUrl = (string)fieldValue; if (obj.TryGetValue("sex", out fieldValue)) userInfo.Sex = ((int)fieldValue) == 1 ? Gender.Male : (((int)fieldValue) == 2 ? Gender.Female : Gender.Unknown); if (obj.TryGetValue("privilege", out fieldValue)) userInfo.Privilege = (string)fieldValue; if (obj.TryGetValue("unionid", out fieldValue)) userInfo.Unionid = (string)fieldValue; return UserAuthorised(userInfo); }