微信開發-網頁授權獲取使用者資訊
阿新 • • 發佈:2018-12-27
是不是大家經常能在微信公眾號上訪問某家應用的時候彈出這樣一個頁面,當你點選確定之後,你進入這家應用的時候會驚奇的發現,你已經登入好了,並且你的微信資訊都被他採集到了。
這是怎麼做的呢,首先我們得了解幾個微信開發介面。
1,授權介面
2,獲取access_token
3,獲取使用者資訊
注意:呼叫此介面的前提,授權介面的scope必須為snsapi_userinfo,如果你不需要獲取使用者的相關資訊,只需要獲取用的openid,那本介面就不用呼叫到。
上述三個介面為微信平臺提供的api,具體可以參考官方文件。
下面是我寫的一個簡單的例子:
OauthGetCode.java
@RequestMapping(value = "/doOAuthLogin") public String doOAuth(HttpServletRequest request, HttpServletResponse response ) throws IOException { String appid = ConfigUtils.APPID; String redirectUrl = ConfigUrlUtils.YUMING + "exhibitFront/OAuthLogin"; String state = "0"; request.setAttribute("appid", appid); request.setAttribute("redirect_url", redirectUrl); request.setAttribute("outTradeNum", state); return "utils/OAuthGetCode"; }
OauthGetCode.jsp
<%@ page language="java" pageEncoding="utf-8"%> <html> <head> <meta name="viewport" content="width=device-width,user-scalable=0"> </head> <body> <script language="javascript" type="text/javascript"> window.location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid }&redirect_uri=${redirect_url }&response_type=code&scope=snsapi_userinfo&state=${outTradeNum }#wechat_redirect"; </script> </body> </html>
OAuthLogin.java
@RequestMapping(value = "/OAuthLogin")
public String oauthLogin(HttpSession session, HttpServletRequest request, @RequestParam(value = "code") String code,
Model model) {
// 獲取使用者的openid
String returnJSON = HttpTool.getToken(ConfigUtils.APPID, ConfigUtils.APPSECRET, "authorization_code", code);
JSONObject obj = JSONObject.fromObject(returnJSON);
System.out.println(obj);//獲取到的使用者資訊
String openid = obj.get("openid").toString(); //例:獲取使用者資訊,詳細可以參考下面進行獲取
/*
* 可獲取的使用者資訊:
openid 使用者的唯一標識
nickname 使用者暱稱
sex 使用者的性別,值為1時是男性,值為2時是女性,值為0時是未知
province 使用者個人資料填寫的省份
city 普通使用者個人資料填寫的城市
country 國家,如中國為CN
headimgurl 使用者頭像,最後一個數值代表正方形頭像大小(有0、46、64、96、132數值可選,0代表640*640正方形頭像),使用者沒有頭像時該項為空。若使用者更換頭像,原有頭像URL將失效。
privilege 使用者特權資訊,json 陣列,如微信沃卡使用者為(chinaunicom)
unionid 只有在使用者將公眾號繫結到微信開放平臺帳號後,才會出現該欄位。詳見:獲取使用者個人資訊(UnionID機制)
*/
return "redirect:/exhibitFront/index";
}
特別注意:測試授權獲取使用者資訊必須要有公眾號且開通了相應介面功能,
此處需要修改成自己訪問的域名地址,否則會授權不通過的哦。