微信網頁授權--Java發開
阿新 • • 發佈:2018-12-26
授權步驟:
1、引導使用者進入授權頁面同意授權,獲取code
2、通過code換取網頁授權access_token(與基礎支援中的access_token不同)
3、通過網頁授權access_token和openid獲取使用者基本資訊
Java實現:
1、引導使用者進入授權頁面同意授權,獲取code
這一步其實就是將需要授權的頁面url拼接到微信的認證請求接口裡面,比如需要使用者在訪問頁面 lovebread.tunnel.qydev.com/auth 時進行授權認證,那麼拼接後的授權驗證地址為:
https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx88888888
這裡面需要替換appid、redirect_uri為實際的資訊。其中的scope引數有兩個值:
snsapi_base:只能獲取到使用者openid。好處是靜預設證,無需使用者手動點選認證按鈕,感覺上像是直接進入網站一樣。
snsapi_userinfo:可以獲取到openid、暱稱、頭像、所在地等資訊。需要使用者手動點選認證按鈕。
相關程式碼:
/** * 生成用於獲取access_token的Code的Url * * @param redirectUrl * @return */ public String getRequestCodeUrl(String redirectUrl) { return String.format("https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=%s&state=%s#wechat_redirect", APPID, redirectUrl,"snsapi_userinfo", "xxxx_state"); }
2、通過第一步獲取的code換取網頁授權access_token(與基礎支援中的access_token不同)
這一步需要在控制器中獲取微信回傳給我們的code,通過這個code來請求access_token。
/** * 路由控制 * * @param request * @param code * @return */ @GET @Path("auth") public Response auth(@Context HttpServletRequest request, @QueryParam("code") String code) { Map<String, String> data = new HashMap(); Map<String, String> result = wechatUtils.getUserInfoAccessToken(code);//通過這個code獲取access_token String openId = result.get("openid"); if (StringUtils.isNotEmpty(openId)) { logger.info("try getting user info. [openid={}]", openId); Map<String, String> userInfo = wechatUtils.getUserInfo(result.get("access_token"), openId);//使用access_token獲取使用者資訊 logger.info("received user info. [result={}]", userInfo); return forward("auth", userInfo); } return Response.ok("openid為空").build(); }
/** * 獲取請求使用者資訊的access_token * * @param code * @return */ public Map<String, String> getUserInfoAccessToken(String code) { JsonObject object = null; Map<String, String> data = new HashMap(); try { String url = String.format("https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code", APPID, APPSECRET, code); logger.info("request accessToken from url: {}", url); DefaultHttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(url); HttpResponse httpResponse = httpClient.execute(httpGet); HttpEntity httpEntity = httpResponse.getEntity(); String tokens = EntityUtils.toString(httpEntity, "utf-8"); Gson token_gson = new Gson(); object = token_gson.fromJson(tokens, JsonObject.class); logger.info("request accessToken success. [result={}]", object); data.put("openid", object.get("openid").toString().replaceAll("\"", "")); data.put("access_token", object.get("access_token").toString().replaceAll("\"", "")); } catch (Exception ex) { logger.error("fail to request wechat access token. [error={}]", ex); } return data; }
請求access_token返回樣例:
[result={
"access_token":"OezXcEiiBSKSxW0eoylIeK6mXnzDdGmembMkERL1o1PtpJBEFDaCSwseSTzvZhiKK7Q35O-YctaOFfyJYSPMMEsMq62zw8T6VDljgKJY6g-tCMdTr3Yoeaz1noL6gpJeshMPwEXL5Pj3YBkw",
"expires_in":7200,
"refresh_token":"OezXcEiiBSKSxW0eoylIeK6mXnzDdGmembMkERL1o1PtpJBEFDaCSwseSTOIGqz3ySJRe-lv124wxxtrBdXGd3X1YGysFJnCxjtIE-jaMkvT7aN-12nBa4YtDvr5VSKCU-_UeFFnfW0K3JmZGRA",
"openid":"oN9UryuC0Y01aQt0jKxZXbfe658w",
"scope":"snsapi_userinfo"}]
通過access_token和openid獲取使用者基本資訊:
/** * 獲取使用者資訊 * * @param accessToken * @param openId * @return */ public Map<String, String> getUserInfo(String accessToken, String openId) { Map<String, String> data = new HashMap(); String url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + accessToken + "&openid=" + openId + "&lang=zh_CN"; logger.info("request user info from url: {}", url); JsonObject userInfo = null; try { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(url); HttpResponse httpResponse = httpClient.execute(httpGet); HttpEntity httpEntity = httpResponse.getEntity(); String response = EntityUtils.toString(httpEntity, "utf-8"); Gson token_gson = new Gson(); userInfo = token_gson.fromJson(response, JsonObject.class); logger.info("get userinfo success. [result={}]", userInfo); data.put("openid", userInfo.get("openid").toString().replaceAll("\"", "")); data.put("nickname", userInfo.get("nickname").toString().replaceAll("\"", "")); data.put("city", userInfo.get("city").toString().replaceAll("\"", "")); data.put("province", userInfo.get("province").toString().replaceAll("\"", "")); data.put("country", userInfo.get("country").toString().replaceAll("\"", "")); data.put("headimgurl", userInfo.get("headimgurl").toString().replaceAll("\"", "")); } catch (Exception ex) { logger.error("fail to request wechat user info. [error={}]", ex); } return data; }
獲取使用者資訊返回樣例:
[result={
"openid":"oN9UryuC0Y01aQt0jKxZXbfe658w",
"nickname":"lovebread",
"sex":1,
"language":"zh_CN",
"city":"",
"province":"",
"country":"中國",
"headimgurl":"http://wx.qlogo.cn/mmopen/bRLXzTf2f6HNfBTd72heAA7vNKsGKvK3dfreewrewsPff9OaMWib0GibbA8daQmNQvQhagtiaicf4vNC5nYU3ia821QQ/0",
"privilege":[]}]