首先你們要看下微信的API文檔。json
微信網頁受權,獲取用戶的微信官方API文檔地址:https://open.weixin.qq.com/api
點擊資源中心,查看微信登陸文檔微信
三次握手
微信認證流程(我本身簡稱三次握手):
一、用戶贊成受權,獲取code
二、經過code換取網頁受權access_token,用戶openId等信息
三、經過access_token和用戶的openId獲取該用戶的用戶信息app
第三方微信接口登陸流程圖:dom
用戶掃描二維碼jsp
https://open.weixin.qq.com/connect/qrconnect?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirectspa
redirect_uri是用戶容許受權後,將會重定向到redirect_uri的網址上,而且帶上code和state參數code
redirect_uri?code=CODE&state=STATE
若用戶禁止受權,則重定向後不會帶上code參數,僅會帶上state參數blog
redirect_uri?state=STATE
/** * 微信引導頁進入的方法 * @return */ @RequestMapping("/loginByWeiXin") public String loginByWeiXin(HttpServletRequest request, Map<String, Object> map) { // 獲取code和state 2 個參數 String code = request.getParameter("code"); String state = request.getParameter("state"); System.out.println("code -------" + code + ", state ------- " + state); if(code != null && !"".equals(code)) { // 受權成功, 獲取用戶token和openID OAuthInfo authInfo = WeiXinUtil.getAccess_token(code); String openid = authInfo.getOpenid(); String access_token = authInfo.getAccess_token(); if(access_token == null) { // Code 使用過 異常 System.out.println("Code 使用過 異常....."); return "redirect:" + 跳轉的路徑; } // 查詢微信號是否綁定第三方平臺 SysUser sysUser = weiXinService.getUserByWeiXinID(openid); if(sysUser == null) { //獲取隨機字符串長度是57的 String randomStr = StringUtil.getRandomString(57); request.getSession().setAttribute(openid, randomStr); // 還沒有綁定帳號 System.out.println("還沒有綁定帳號....."); return "redirect:/index.jsp?openid=" + openid + "&state=" + randomStr; } userController.doSomeLoginWorkToHomePage(sysUser.getMcid(), map); // 登陸成功 return "homePage"; } // 未受權 return "redirect:" + 路徑; }
根據code獲取token(實體類OAuthInfo封裝微信返回來的用戶信息)token
public static OAuthInfo getAccess_token(String code){ String authUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code "; authUrl= authUrl.replace("APPID", Param.APPID); authUrl = authUrl.replace("SECRET", Param.SECRET); authUrl = authUrl.replace("CODE", code); String jsonString = HTTPRequestUtil.sendPost(authUrl,""); System.out.println("jsonString: " + jsonString); OAuthInfo auth = null; try { auth = (OAuthInfo) JacksonUtil.parseJSONToObject(OAuthInfo.class, jsonString); } catch (Exception e) { e.printStackTrace(); } return auth; }
返回的用戶信息格式:
{ "access_token":"ACCESS_TOKEN", "expires_in":7200, "refresh_token":"REFRESH_TOKEN", "openid":"OPENID", "scope":"SCOPE", "unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL" //客戶受權後纔會有這個字段 }