前言:通過上一章配置測試公眾號,初步實現了菜單調用網頁的功能,本章主要講如何獲取到微信的用戶信息。獲取微信用戶信息只要三步就可以實現。第一步配置菜單連接獲取微信的code;第二步通過code、appId和appSecret獲取access_token、openId;第三步,通過access_token、openId就可以獲取到微信用戶的信息了。大致步驟就是這樣,下面來講一下具體實現方式。
第一步:配置菜單連接獲取微信的code
先提前拼接好調用的URL:https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect
這個是微信技術文檔的URL實例,我們對這個URL修改的部分是參數,注意的點是redirect_uri是你自己的網頁地址並且進行urlencode編譯(附編譯地址:http://tool.chinaz.com/Tools/urlencode.aspx),將自己的網址輸入進去(例如:http://mysite.test.com/Home/GetWinXinInfo)點擊“urlencode編碼”。其他參數可參考下圖(偷個懶,從微信技術文檔上截的圖)。
創建微信公眾號-菜單按鈕,鏈接為上面拼接好的URL,不會創建自定義菜單的同學可以看我寫的第一篇微信公眾號開發的文章最后一部分《微信公眾號開發-測試號管理配置詳解(.net版)》(https://www.cnblogs.com/hjxh/p/9947814.html)。
第二步和第三步結合:通過code、appId和appSecret獲取access_token、openId,最終獲取用戶信息
通過菜單地址(例如:https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=http://mysite.test.com/Home/GetWinXinInfo&response_type=code&scope=snsapi_base&state=snsapi_userinfo#wechat_redirect,紅色部分需要urlencode轉譯)調用獲取具體實現代碼如下:
public class HomeController : Controller { string appId = "wx4******a1"; string appSecret = "13a9f1*******1b21beb0"; /// <summary> /// 獲取AccessToken /// </summary> /// <param name="code"></param> /// <param name="state"></param> public void GetWinXinInfo(string code, string state) { //獲取AccessToken string getAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appId + "&secret=" + appSecret + "&code=" + code + "&grant_type=authorization_code"; string getAccessTokenReponse = Get(getAccessTokenUrl); AccessTokenReponse modeAccessToken = JsonConvert.DeserializeObject<AccessTokenReponse>(getAccessTokenReponse); //獲取用戶信息 string getUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + modeAccessToken.access_token + "&openid=" + modeAccessToken.openid + "&lang=zh_CN"; string getUserInfoReponse = Get(getUserInfoUrl); Response.Write(getUserInfoReponse); Response.End(); } public string Get(string url, string contentType = "application/json") { HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url); myRequest.Method = "Get"; myRequest.ContentType = contentType; myRequest.Proxy = null; using (HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse()) { using (StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8)) { return reader.ReadToEnd(); } } } }
方法所需要的實體
public class AccessTokenReponse { 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; } }
總結:通過本章節,最終可以獲得微信用戶的相關信息,關於微信用戶的相關信息注意的一點是unionid,如果公眾號沒有綁定到微信開放平台,則此參數為Null。建議保存unionid,因為此參數是針對與微信開放平台生成的,微信開放平台可以掛接多個公眾號,一個微信針對一個開發平台unionid只有一個,而openid會有多個(邏輯如下圖),若需求上有多公眾號聯合登陸的,可以通過驗證unionid進行實現。