标签:
以snsapi_base为scope发起的网页授权,是用来获取进入页面的用户的openid的,并且是静默授权并自动跳转到回调页的。用户感知的就是直接进入了回调页。
以snsapi_userinfo为scope发起的网页授权,是用来获取用户的基本信息的。但这种授权需要用户手动同意,并且由于用户同意过,所以无须关注,就可在授权后获取该用户的基本信息。(见下图)
1、引导用户进入授权页面同意授权,获取code
2、通过code换取网页授权access_token(与基础支持中的access_token不同)
3、如果需要,开发者可以刷新网页授权access_token,避免过期
4、通过网页授权access_token和openid获取用户基本信息(支持UnionID机制)
public static string appid = ConfigurationManager.AppSettings["WeiXinAppID"].ToString(); public static string secret = ConfigurationManager.AppSettings["WeiXinAppSecret"].ToString(); public static string domain = ConfigurationManager.AppSettings["WeiXinDomain"].ToString();
public static string GetMethod(string url) { string result = string.Empty; try { UTF8Encoding encoding = new UTF8Encoding(); HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url); myRequest.Method = "GET"; HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse(); if (myResponse.StatusCode == HttpStatusCode.OK) { StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8); result = reader.ReadToEnd(); } } catch { result = string.Empty; } return result; }
public static string GetCodeUrl(string callback, string scope = "snsapi_base") { return string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}{2}&response_type=code&scope={3}&state=state#wechat_redirect", appid, domain, callback, scope); }
public static string GetOpenID(string code) { string openid = string.Empty; string apiUrl = string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code", appid, secret, code); string result = GetMethod(apiUrl); if (!string.IsNullOrEmpty(result)) { JObject jo = (JObject)JsonConvert.DeserializeObject(result); openid = jo["openid"].ToString(); } return openid; }
标签:
原文地址:http://www.cnblogs.com/talentzemin/p/5462125.html