微信網頁受權共分爲兩種方式:snsapi_base、snsapi_userinfo。 snsapi_base須要關注公衆號,獲取用戶信息時不彈出用戶受權界面。 snsapi_userinfo是在用戶未關注公衆號的狀況下瀏覽頁面,會先彈出一個用戶受權界面,用戶受權後才能拿到用戶信息。這一篇咱們先看snsapi_base實現。html
這裏注意只填寫到域名git
這裏看咱們經過oauth snsapi_base已經拿到用戶的基本信息,對於通常諮詢類的開發也就夠用了。github
一、經過回掉地址先拿到code。json
二、經過code拿到openid。api
三、經過appid和appsecret拿到全局access_token(這一點區別於snsapi_userinfo)。微信
四、經過全局access_token和openid拿到用戶信息。app
到這裏也就簡單了,主要是get方式調微信接口,同時準備好你的get和post請求方式,返回參數用json轉化成實體類。post
public ActionResult OAuthSnsApiBase() { string code = Request.QueryString["code"]; try { if (!string.IsNullOrEmpty(code)) { OAuthToken oauthToken = HttpUtility.Get<OAuthToken>(string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code", appID, appsecret, code)); string accesstoken = string.Empty; AccessToken token = HttpUtility.Get<AccessToken>(string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}",appID,appsecret)); if (token != null && !string.IsNullOrEmpty(token.access_token)) { accesstoken = token.access_token; } if (oauthToken != null && !string.IsNullOrEmpty(oauthToken.openid)) { OAuthUserInfo userInfo = HttpUtility.Get<OAuthUserInfo>(string.Format("https://api.weixin.qq.com/cgi-bin/user/info?access_token={0}&openid={1}&lang=zh_CN", accesstoken, oauthToken.openid)); if (userInfo != null) { ViewData["headImage"] = userInfo.headimgurl; ViewData["openid"] = userInfo.openid; ViewData["nickName"] = userInfo.nickname; if (userInfo.sex == 0) { ViewData["sex"] = "未知"; } else if (userInfo.sex == 1) { ViewData["sex"] = "男"; } else { ViewData["sex"] = "女"; } ViewData["province"] = userInfo.province; ViewData["city"] = userInfo.city; } else { } } else { } } else { return Redirect(string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope=snsapi_base&state=123456#wechat_redirect", appID,"http://"+Request.Url.Host + Url.Action("OAuthSnsApiBase"))); } } catch (Exception ex) { ViewData["errmsg"] = ex.Message; } return View(); }
public class OAuthToken { public string access_token { get; set; } public int expires_in { get; set; } public string refresh_token { get; set; } public string openid { get; set; } public string scope { get; set; } } public class AccessToken { public string access_token { get; set; } public int expires_in { get; set; } } public class OAuthUserInfo { public string openid { get; set; } public string nickname { get; set; } public int sex { get; set; } public string province { get; set; } public string city { get; set; } public string country { get; set; } public string headimgurl { get; set; } public string privilege { get; set; } public string unionid { get; set; } }
這裏獲取用戶信息的接口是https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN。和網頁受權二獲取用戶接口是不同的。url
代碼所有上傳到github裏:https://github.com/garfieldzf8/WeChatspa