整合SpringBoot微信公眾平臺授權登入測試
* 微信公眾平臺授權登入
*/
@RequestMapping(value = "/wxLogin", method = RequestMethod.GET)
public String wxLogin(HttpServletRequest request, HttpServletResponse response) throws ClientProtocolException, IOException{
String myPublicDomain = "http://19516980.ngrok.io";//內網對映域名,使用ngrok
//String backUrl = myPublicDomain + "/wxCallBack";
/* 在確保微信公眾賬號擁有授權作用域(scope引數)的許可權的前提下(服務號獲得高階介面後,預設擁有scope引數中的snsapi_base和snsapi_userinfo)
* ,引導關注者開啟如下頁面:
* https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect
*
* 尤其注意:
* 由於授權操作安全等級較高,所以在發起授權請求時,微信會對授權連結做正則強匹配校驗,
* 如果連結的引數順序不對,授權頁面將無法正常訪問
* 跳轉回調redirect_uri,應當使用https連結來確保授權code的安全性
*
*/
System.out.println("wxLogin------------");
String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + WxAuthUtil.APPID
+ "&redirect_uri=" + URLEncoder.encode(myPublicDomain)
+ "&response_type=code"
+ "&scope=snsapi_userinfo"
+ "&state=STATE#wechat_redirect";
/*try {
response.sendRedirect(url);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
JSONObject json = WxAuthUtil.doGetJson(url);
/*try {
json = WxAuthUtil.doGetJson(url);
} catch (ClientProtocolException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}*/
//獲取code值
String code = json.getString("code");
System.out.println("json.code----------"+code);
/* 獲取code後,請求以下連結獲取access_token:
* 這裡通過code換取的是一個特殊的網頁授權access_token,與基礎支援中的access_token(該access_token用於呼叫其他介面)不同
*/
String url_1 = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + WxAuthUtil.APPID
+ "&secret=" + WxAuthUtil.APPSECRET
+ "&code=" + code
+ "&grant_type=authorization_code";
JSONObject jsonObject = WxAuthUtil.doGetJson(url_1);
/*try {
jsonObject = WxAuthUtil.doGetJson(url_1);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
String openid = jsonObject.getString("openid");
String tokentest= jsonObject.getString("access_token");
/*
* 拉去使用者的資訊
*/
String infoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + tokentest
+ "&openid=" + openid
+ "&lang=zh_CN";
JSONObject userInfo = WxAuthUtil.doGetJson(infoUrl);
/*try {
userInfo = WxAuthUtil.doGetJson(infoUrl);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
//1、使用微信使用者資訊直接登入,無需註冊和繫結
request.setAttribute("info", userInfo);
//request.getRequestDispatcher("/index.jsp").forward(request, response);
return "testIndex";
}