微信授權登陸程式碼例項
阿新 • • 發佈:2019-01-10
1.controller
@Controller public class WeiXinToken extends BaseController { @Autowired private WeiXinService weiXinService; @Autowired private SystemService systemService; @Autowired private InformationMessageService informationMessageService; @RequestMapping(value = "${adminPath}/check", method = RequestMethod.GET) public String checkSignature(HttpServletRequest request,HttpServletResponse response, Model model) { //微信公眾號驗證URL,如果驗證成功,則繫結URL if(!StringUtils.isBlank(request.getParameter("echostr"))){ String signature = request.getParameter("signature"); String timestamp = request.getParameter("timestamp"); String nonce = request.getParameter("nonce"); String echostr = request.getParameter("echostr"); PrintWriter pw = null; try { pw = response.getWriter(); } catch (IOException e) { e.printStackTrace(); } pw.append(echostr); pw.flush(); pw.close(); } String str = "code"; if (request.getParameter(str) != null) { String code = request.getParameter("code"); Map<String, String> map = null; map = weiXinService.getAccessToken(code); CacheUtils.put("AccessToken", map); map = (Map<String, String>) CacheUtils.get("AccessToken"); WeiXinEntity result = weiXinService.getUserInfo(map); model.addAttribute("weixin", result); if(result == null){ return null; } User user = systemService.findByOpenId(result.getOpenid()); String openId = result.getOpenid(); if (user != null) { UsernamePasswordToken token = new UsernamePasswordToken(); token.setOpenId(result.getOpenid()); token.setHost(StringUtils.getRemoteAddr(request)); token.setRememberMe(true); UserUtils.getSubject().login(token); return "modules/sys/sysIndex"; } else { addMessage(model, "您在本網站還沒有賬號,請完善賬號資訊!"); HttpSession session = request.getSession(); session.setAttribute("openId", openId); session.setAttribute("photoImg", result.getHeadimgurl()); return "modules/sys/sysIndex"; } } } return "modules/sys/sysLogin"; } /** * 微信 服務號 驗證內容 * * @author * @date 2018-40-20 9:40 */ @RequestMapping(value = "MP_verify_VLoeGPPI5akc4iV8.txt", method = RequestMethod.GET) public void weiXin(HttpServletResponse response) throws IOException { String str = Global.getConfig("MP_verify_VLoeGPPI5akc4iV8"); response.getWriter().write(str.replaceAll("\"", "")); }
2 service
@Service public class WeiXinService extends BaseService { /** * 通過code 獲取accessToken * * @param code 使用者同意授權 獲得的code * @return java.util.Map * @author * @date 2018-33-20 9:33 */ public Map<String, String> getAccessToken(String code) { //取出配置檔案中的AccessTokenURL String accessTokenURL = Global.getConfig("AccessTokenURL"); //取出配置檔案中的Secret String secret = Global.getConfig("Secret"); //取出配置檔案中的APPId String appId = Global.getConfig("AppId"); //傳送求情 String result = sendGET(accessTokenURL.replaceAll("APPID", appId) .replaceAll("SECRET", secret) .replaceAll("CODE", code)); //將微信返回的Json轉為Map if (StringUtils.isNotEmpty(result)) { //使用Gson 轉為Map return new Gson().fromJson(result, new TypeToken<Map<String, String>>() { }.getType()); } return null; } /** * 通過accessToken獲取使用者基本資訊 * * @param map json 轉為map * @return WeiXinEntity 使用者基本資訊 * @author * @date 2018-32-20 9:32 */ public WeiXinEntity getUserInfo(Map<String, String> map) { if (map.containsKey("access_token") && map.containsKey("openid")) { String userInfo = Global.getConfig("UserInfo"); if (!checkAccessToken(map)) { //失效則刷accessToken Map<String, String> res = getRefreshToken(map.get("refresh_token")); if (res != null) { String retu = sendGET(userInfo.replaceAll("ACCESS_TOKEN", res.get("access_token")) .replaceAll("OPENID", res.get("openid"))); return new Gson().fromJson(retu, new TypeToken<WeiXinEntity>() { }.getType()); } } //通過 ACCESS_TOKEN 和 OPENID 獲取使用者資訊 String result = sendGET(userInfo.replaceAll("ACCESS_TOKEN", map.get("access_token")) .replaceAll("OPENID", map.get("openid"))); return new Gson().fromJson(result, new TypeToken<WeiXinEntity>() {}.getType()); } return null; } /** * 檢查accessToken 是否有效 * @author * @date 2018-41-20 14:41 * @param map getAccessToken 獲取到的 * @return boolean */ private boolean checkAccessToken(Map<String, String> map) { if (map.containsKey("access_token") && map.containsKey("openid")) { String authAccessToken = Global.getConfig("AuthAccessToken"); String result = sendGET(authAccessToken.replaceAll("ACCESS_TOKEN", map.get("access_token")).replaceAll("OPENID", map.get("openid"))); return result.contains("ok"); } return false; } /** * 通過 appId refresh_token 重新整理 accessToken * * @param refresh_token 重新整理 accessToken 需要的憑證 * @return java.util.Map<java.lang.String , java.lang.String> * @author * @date 2018-34-20 9:34 */ private Map<String, String> getRefreshToken(String refresh_token) { if (StringUtils.isNotBlank(refresh_token)) { String refreshToken = Global.getConfig("RefreshToken"); String result = sendGET(refreshToken.replaceAll("APPID", Global.getConfig("AppId")).replaceAll("REFRESH_TOKEN", refresh_token)); return new Gson().<Map<String, String>>fromJson(result, new TypeToken<Map<String, String>>() { }.getType()); } return null; } /** * 傳送請求通用方法 * * @param sendURL 請求url * @return java.lang.String 返回json * @author * @date 2018-46-19 18:46 */ private String sendGET(String sendURL) { StringBuilder result = new StringBuilder(); BufferedReader in = null; try { URL url = new URL(sendURL); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); in = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8")); String line = ""; while ((line = in.readLine()) != null) { result.append(line); } logger.info(result.toString()); } catch (IOException e) { logger.error(sendURL); logger.error("獲取資料異常:" + e.getMessage()); e.printStackTrace(); } return result.toString(); } }