赞
踩
当用户在微信客户端中访问第三方网页,公众号可以通过微信网页授权机制,来获取用户基本信息,进而实现业务逻辑。我们一般通过用户网页授权来无感实现用户登录,并获取用户的微信信息。
注意:用户管理类接口中的“获取用户基本信息接口”,是在用户和公众号产生消息交互或关注后事件推送后,才能根据用户OpenID来获取用户基本信息。这个接口,包括其他微信接口,都是需要该用户(即openid)关注了公众号后,才能调用成功的。
需要先到公众平台官网中的「设置与开发」-「功能设置」-「网页授权域名」的配置选项中,修改授权回调域名。请注意,这里填写的是域名(是一个字符串),而不是URL,因此请勿加 http:// 等协议头;
以snsapi_base为scope发起的网页授权,是用来获取进入页面的用户的openid的,并且是静默授权并自动跳转到回调页的。用户感知的就是直接进入了回调页(往往是业务页面)
以snsapi_userinfo为scope发起的网页授权,是用来获取用户的基本信息的。但这种授权需要用户手动同意,并且由于用户同意过,所以无须关注,就可在授权后获取该用户的基本信息。
在确保微信公众账号拥有授权作用域(scope参数)的权限的前提下(已认证服务号,默认拥有scope参数中的snsapi_base和snsapi_userinfo 权限),引导关注者打开如下页面:
若提示“该链接无法访问”,请检查参数是否填写错误,是否拥有scope参数对应的授权作用域权限。跳转回调redirect_uri,应当使用https链接来确保授权code的安全性,并且是在微信公众号后台配置的网页授权域名的访问地址。
https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect
首先请注意,这里通过code换取的是一个特殊的网页授权access_token,与基础支持中的access_token(该access_token用于调用其他接口)不同。公众号可通过下述接口来获取网页授权access_token。如果网页授权的作用域为snsapi_base,则本步骤中获取到网页授权access_token的同时,也获取到了openid,snsapi_base式的网页授权流程即到此为止。
获取code后,请求以下链接获取access_token:https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
- public class WeChatLogin : Controller
- {
-
- /// <summary>
- /// 获取微信网页授权access_token
- /// </summary>
- /// <param name="state">自定义参数</param>
- /// <param name="code">通过用户授权后得到的code</param>
- /// <returns></returns>
- public async Task<Response> GetWeChatAccessToken(string state, string code)
- {
- string appId = "YourAppId";
- string appSecret = "YourAppSecret";
- string requestUrl = $"https://api.weixin.qq.com/sns/oauth2/access_token?appid={appId}&secret={appSecret}&code={code}&grant_type=authorization_code";
-
- using (var httpClient = new HttpClient())
- {
- var httpRequest = new HttpRequestMessage(HttpMethod.Get, requestUrl);
- using (var response = await httpClient.SendAsync(httpRequest))
- {
- if (response.IsSuccessStatusCode)
- {
- var responseString = await response.Content.ReadAsStringAsync();
- var responseData = JsonConvert.DeserializeObject<WeChatTokenResponse>(responseString);
-
- return new Response
- {
- Code = 1,
- Message = responseData.AccessToken
- };
- }
- else
- {
- var errorResponseString = await response.Content.ReadAsStringAsync();
- var errorData = JsonConvert.DeserializeObject<ErrorResponse>(errorResponseString);
-
- return new Response
- {
- Code = 0,
- Message = $"Failed to get access token: {errorData.ErrMsg}"
- };
- }
- }
- }
- }
- }
-
- public class WeChatTokenResponse
- {
- [JsonProperty("access_token")]
- public string AccessToken { get; set; }
-
- [JsonProperty("expires_in")]
- public int ExpiresIn { get; set; }
-
- [JsonProperty("refresh_token")]
- public string RefreshToken { get; set; }
-
- [JsonProperty("openid")]
- public string OpenId { get; set; }
-
- [JsonProperty("scope")]
- public string Scope { get; set; }
-
- [JsonProperty("is_snapshotuser")]
- public int IsSnapshotUser { get; set; }
-
- [JsonProperty("unionid")]
- public string UnionId { get; set; }
- }
-
- public class ErrorResponse
- {
- [JsonProperty("errcode")]
- public int ErrCode { get; set; }
-
- [JsonProperty("errmsg")]
- public string ErrMsg { get; set; }
- }
如果网页授权作用域为snsapi_userinfo,则此时开发者可以通过access_token和openid拉取用户信息了。
请求方法:https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
- public class WeChatLogin : Controller
- {
- /// <summary>
- /// 用户信息获取
- /// </summary>
- /// <param name="accessToken"> 网页授权接口调用凭证,注意:此access_token与基础支持的access_token不同</param>
- /// <param name="openId">用户的唯一标识</param>
- /// <returns></returns>
- public async Task<Response> GetWeChatUserInfo(string accessToken, string openId)
- {
- string requestUrl = $"https://api.weixin.qq.com/sns/userinfo?access_token={accessToken}&openid={openId}&lang=zh_CN";
-
- using (var httpClient = new HttpClient())
- {
- var request = new HttpRequestMessage(HttpMethod.Get, requestUrl);
- var response = await httpClient.SendAsync(request);
-
- if (response.IsSuccessStatusCode)
- {
- var responseString = await response.Content.ReadAsStringAsync();
- var responseData = JsonConvert.DeserializeObject<WeChatUserInfoResponse>(responseString);
-
- return new Response
- {
- Code = 1,
- Message = $"Nickname: {responseData.Nickname}, Province: {responseData.Province}, City: {responseData.City}"
- };
- }
- else
- {
- var errorResponseString = await response.Content.ReadAsStringAsync();
- var errorData = JsonConvert.DeserializeObject<ErrorResponse>(errorResponseString);
-
- return new Response
- {
- Code = 0,
- Message = $"Failed to get user info: {errorData.ErrMsg}"
- };
- }
- }
- }
-
- public class WeChatUserInfoResponse
- {
- [JsonProperty("openid")]
- public string OpenId { get; set; }
-
- [JsonProperty("nickname")]
- public string Nickname { get; set; }
-
- [JsonProperty("sex")]
- public int Sex { get; set; }
-
- [JsonProperty("province")]
- public string Province { get; set; }
-
- [JsonProperty("city")]
- public string City { get; set; }
-
- [JsonProperty("country")]
- public string Country { get; set; }
-
- [JsonProperty("headimgurl")]
- public string HeadImgUrl { get; set; }
-
- [JsonProperty("privilege")]
- public List<string> Privilege { get; set; }
-
- [JsonProperty("unionid")]
- public string UnionId { get; set; }
- }
-
- public class ErrorResponse
- {
- [JsonProperty("errcode")]
- public int ErrCode { get; set; }
-
- [JsonProperty("errmsg")]
- public string ErrMsg { get; set; }
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。