微信公众号开发之网页授权认证获取用户的详细信息,实现自动登陆
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了微信公众号开发之网页授权认证获取用户的详细信息,实现自动登陆相关的知识,希望对你有一定的参考价值。
原创声明:本文转来源本人另一博客【http://blog.csdn.net/liaohaojian/article/details/70175835】绝非他人处转载
从接触公众号到现在,开发维护了2个公众号,开发过程中遇到很多问题,现在把部分模块功能在这备案一下,做个总结也希望能给其他人帮助
工欲善其事,必先利其器,先看看开发公众号需要准备或了解什么
web开发工具:官方提供的开发工具,使用自己的微信号来调试微信网页授权、调试、检验页面的 JS-SDK 相关功能与权限,模拟大部分 SDK 的输入和输出。下载地址:web开发工具下载
登录微信测试公众号,获取公众号的appID、appsecret,登录地址:http://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login (一般测试开发阶段,都不拿正式公众号测试,因为存在风险并且你调试时不用担心影响到正式公众号的正常使用,而且有些接口在正式公众号上比较严格,而在测试公众号上可以放开,如模板信息)
下面进入正题,实现微信网页授权,获取微信信息,主要用于以微信帐号作为用户登录,如果你只是需要绑定微信,就可以不用授权,直接请求获取微信OpenId(对当前公众号唯一),进行用户绑定(在下面代码时是写明如何实现),该功能可在开发文档:微信网页开发-》微信网页授权里查看详细信息,下面正式开始。
1.填写授权回调页面域名
进入测试公众号,在体验接口权限表中找到网页帐号,右侧添加自己的域名,测试公众号可填写本地IP,如你是正式公众号只能填写自己的域名,如果未填写,当进行接口调用时,会提示:redirect_uri参数错误!如果还有其他不了解的配置,可以在开发文档里查看详信息,
2.代码展示
1).调用微信接口返回的参数都是JSON格式,封装个Http请求方法
public class WeixinUtil { /** * 发起https请求并获取结果 * @param requestUrl 请求地址 * @param requestMethod 请求方式(GET、POST) * @param outputStr 提交的数据 * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值) */ public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) { JSONObject jsonObject = null; StringBuffer buffer = new StringBuffer(); try { // 创建SSLContext对象,并使用我们指定的信任管理器初始化 TrustManager[] tm = { new MyX509TrustManager() }; SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE"); sslContext.init(null, tm, new java.security.SecureRandom()); // 从上述SSLContext对象中得到SSLSocketFactory对象 SSLSocketFactory ssf = sslContext.getSocketFactory(); URL url = new URL(requestUrl); HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection(); httpUrlConn.setSSLSocketFactory(ssf); httpUrlConn.setDoOutput(true); httpUrlConn.setDoInput(true); httpUrlConn.setUseCaches(false); // 设置请求方式(GET/POST) httpUrlConn.setRequestMethod(requestMethod); if ("GET".equalsIgnoreCase(requestMethod)) httpUrlConn.connect(); // 当有数据需要提交时 if (null != outputStr) { OutputStream outputStream = httpUrlConn.getOutputStream(); // 注意编码格式,防止中文乱码 outputStream.write(outputStr.getBytes("UTF-8")); outputStream.close(); } // 将返回的输入流转换成字符串 InputStream inputStream = httpUrlConn.getInputStream(); InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8"); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String str = null; while ((str = bufferedReader.readLine()) != null) { buffer.append(str); } bufferedReader.close(); inputStreamReader.close(); // 释放资源 inputStream.close(); inputStream = null; httpUrlConn.disconnect(); jsonObject = JSONObject.fromObject(buffer.toString()); } catch (ConnectException ce) { log.error("Weixin server connection timed out."); } catch (Exception e) { log.error("https request error:{}", e); } return jsonObject; } }
2).下面展示访问个人中心时,进行用户授权
/** * 个人中心 * @param request * @param response * @return */ @RequestMapping("/gotoPeopleIndex") public String gotoPeopleIndex(HttpServletRequest request,HttpServletResponse response){ //判断是否授权过,授权通过时,会保存session“WeixinUserInfo”,这样下次访问时,如果WeixinUserInfo存在,说明已经授权过,用户信息已经存在 WeixinUserInfo WeixinUserInfo = (WeixinUserInfo) session.getAttribute("WeixinUserInfo"); if(WeixinUserInfo==null){//没有授权过,跳转授权页面,如果你不需要授权,则scope为snsapi_base,这是不会弹出授权页面 String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+TimedTask.appid+"&redirect_uri="+TimedTask.websiteAndProject+"/weixinF/getOpenInfo/gotoPeopleIndex&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect"; return "redirect:"+url; }else{ return "weixin/customer/userInfo"; } } /** * 微信网页授权获得微信详情 * @param code * @param state * @param view 授权后调整的视图 * @param request * @param appid 公众号appid * @param appsecret 公众号appsecret * @param websiteAndProject 请求地址跟工程名,如我当前的为http://192.168.2.113/seafood * @param response * @throws ServletException * @throws IOException */ @RequestMapping("/getOpenInfo/{view}") public void getOpenInfo(@RequestParam("code") String code,@RequestParam("state") String state,@PathVariable("view") String view,HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{ // 用户同意授权 if (!"authdeny".equals(code)) { //获取OpenId OpenIdResult open = WeixinUtil.getOpenId(request, code, TimedTask.appid, TimedTask.appsecret); //检验授权凭证(access_token)是否有效 int result = WeixinUtil.checkAccessToken(open.getAccess_token(), open.getOpenid()); if(0 != result){ open = WeixinUtil.getNewAccess_Token(open,open.getRefresh_token(),TimedTask.appid); } // 网页授权接口访问凭证 String accessToken = open.getAccess_token(); String openId = open.getOpenid(); //获取微信用户详细信息,如果你不需要授权,可跳过该步骤,直接以微信的OpenId,查找是否已经绑定,没有跳转到绑定界面 WeixinUserInfo user = WeixinUtil.getWeixinUserInfo(accessToken, openId); Customer customer = weixinFirstServer.getCustomerDetailByOpenId(user.getOpenId()); if(customer!=null){ if(customer.getAccountStatus()==2){ response.setContentType("text/html; charset=UTF-8"); try { response.sendRedirect(TimedTask.websiteAndProject+"/weixin/customer/noAuthority.jsp"); } catch (IOException e) { e.printStackTrace(); } return; } customer.setHeadPhoto(user.getHeadImgUrl()); }else{ Customer newuser = new Customer(); newuser.setCustomerWeixinId(openId); newuser.setCustomerWNickname(user.getNickname()); newuser.setSex(user.getSex()); //绑定 result = weixinFirstServer.addCustomerInfo(newuser); if(result<=0){ response.setContentType("text/html; charset=UTF-8"); try { response.sendRedirect(TimedTask.websiteAndProject+"/weixin/customer/error.jsp"); } catch (IOException e) { e.printStackTrace(); } }else{ customer = weixinFirstServer.getCustomerDetailByOpenId(user.getOpenId()); if(customer.getAccountStatus()==2){ response.setContentType("text/html; charset=UTF-8"); try { response.sendRedirect(TimedTask.websiteAndProject+"/weixin/customer/noAuthority.jsp"); } catch (IOException e) { e.printStackTrace(); } return; } } } session.setAttribute("customerInfo", customer); session.setAttribute("WeixinUserInfo", user); request.setAttribute("state", state); response.setContentType("text/html; charset=UTF-8"); try { response.sendRedirect(TimedTask.websiteAndProject+"/weixinF/"+view); } catch (IOException e) { e.printStackTrace(); } }else{ response.setContentType("text/html; charset=UTF-8"); try { response.sendRedirect(TimedTask.websiteAndProject+"/weixin/customer/error.jsp"); } catch (IOException e) { e.printStackTrace(); } } }
微信工具类代码:
public class WeixinUtil { public final static String getOpen_id_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code"; /** * 检验授权凭证(access_token)是否有效 * @param accessToken 凭证 * @param openid id * @return */ public static int checkAccessToken(String accessToken, String openid) { String requestUrl = "https://api.weixin.qq.com/sns/auth?access_token="+accessToken+"&openid="+openid; JSONObject jsonObject = httpRequest(requestUrl, "GET", null); int result = 1; // 如果请求成功 if (null != jsonObject) { try { result = jsonObject.getInt("errcode"); } catch (JSONException e) { accessToken = null; // 获取token失败 log.error("获取token失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg")); } } return result; } /** * 用户授权,使用refresh_token刷新access_token * @return */ public static OpenIdResult getNewAccess_Token(OpenIdResult open,String refresh_token,String openId) { String requestUrl = getNewAccess_token.replace("REFRESH_TOKEN", refresh_token).replace("APPID", openId); JSONObject jsonObject = httpRequest(requestUrl, "GET", null); // 如果请求成功 if (null != jsonObject) { try { open.setAccess_token(jsonObject.getString("access_token")); } catch (JSONException e) { // 获取token失败 log.error("获取token失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg")); } } return open; } /** * 获得用户基本信息 * @param request * @param code * @param appid * @param appsecret * @return */ public static OpenIdResult getOpenId(HttpServletRequest request, String code,String appid, String appsecret) { String requestURI = request.getRequestURI(); String param = request.getQueryString(); if(param!=null){ requestURI = requestURI+"?"+param; } String url = getOpen_id_url.replace("APPID",appid).replace("SECRET",appsecret).replace("CODE",code); JSONObject jsonObject = httpRequest(url, "POST", null); OpenIdResult result = new OpenIdResult(); if (null != jsonObject) { Object obj = jsonObject.get("errcode"); if (obj == null) { result.setAccess_token(jsonObject.getString("access_token")); result.setExpires_in(jsonObject.getString("expires_in")); result.setOpenid(jsonObject.getString("openid")); result.setRefresh_token(jsonObject.getString("refresh_token")); result.setScope(jsonObject.getString("scope")); }else{ System.out.println("获取openId回执:"+jsonObject.toString()+"访问路径:"+requestURI); log.error("访问路径:"+requestURI); log.error("获取openId失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg")); } } return result; } /** * 通过网页授权获取用户信息 * @param accessToken 网页授权接口调用凭证 * @param openId 用户标识 * @return WeixinUserInfo */ public static WeixinUserInfo getWeixinUserInfo(String accessToken, String openId) { WeixinUserInfo user = null; // 拼接请求地址 String requestUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID"; requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openId); // 通过网页授权获取用户信息 JSONObject jsonObject = httpRequest(requestUrl, "GET", null); if (null != jsonObject) { try { user = new WeixinUserInfo(); // 用户的标识 user.setOpenId(jsonObject.getString("openid")); // 昵称 user.setNickname(jsonObject.getString("nickname")); // 性别(1是男性,2是女性,0是未知) user.setSex(jsonObject.getInt("sex")); // 用户所在国家 user.setCountry(jsonObject.getString("country")); // 用户所在省份 user.setProvince(jsonObject.getString("province")); // 用户所在城市 user.setCity(jsonObject.getString("city")); // 用户头像 user.setHeadImgUrl(jsonObject.getString("headimgurl")); // 用户特权信息 user.setPrivilegeList(JSONArray.toList(jsonObject.getJSONArray("privilege"), List.class)); } catch (Exception e) { user = null; int errorCode = jsonObject.getInt("errcode"); String errorMsg = jsonObject.getString("errmsg"); log.error("获取用户信息失败 errcode:{} errmsg:{},reqUrl{}", errorCode, errorMsg); } } return user; } }
下面展示,当用户session失效时,自动登录的代码,这时是不需要授权的
@RequestMapping("/gotoGoodsView") public String gotoGoodsView(@RequestParam(value="longitude",defaultValue="",required=false) String longitude,@RequestParam(value="latitude",defaultValue="",required=false) String latitude){ String param = request.getQueryString(); String url = request.getServletPath(); if(param!=null){ url = url+"?"+param.replaceAll("&","-");//如果不把&替换成别的,当重新登录成功后调整会参数丢失 } Customer customerInfo = (Customer) session.getAttribute("customerInfo"); if(customerInfo==null){//session失效,跳转到获取微信详情页面(授权) return "redirect:/weixinF/getCode?view="+TimedTask.websiteAndProject+"/weixinF/autoLogin&view2="+TimedTask.websiteAndProject+url; } return "/weixin/customer/goodsList"; } @RequestMapping("/getCode") public void getCode(HttpServletResponse response){ String view = request.getParameter("view");//获取openId的路径 String view2 = request.getParameter("view2");//获取openId成功后跳转的路径 String redirect_url = ""; try { redirect_url = URLEncoder.encode(view,"UTF-8"); if(view2!=null && !"".equals(view2)){ view2 = view2.replaceAll("-","&"); redirect_url = redirect_url +"?redirect_url="+ URLEncoder.encode(URLEncoder.encode(view2,"UTF-8"),"UTF-8"); } } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } String url = WeixinUtil.getCode_url.replace("APPID",TimedTask.appid).replace("REDIRECT_URI",redirect_url); response.setContentType("text/html; charset=UTF-8"); try { response.sendRedirect(url); } catch (IOException e) { e.printStackTrace(); } } /** * 自动登录并跳转 * @param code * @param appid 公众号appid * @param appsecret 公众号appsecret * @param websiteAndProject 请求地址跟工程名,如我当前的为http://192.168.2.113/seafood * @param url 自动登录后跳转路径 * @return */ @RequestMapping("/autoLogin") public String autoLogin(HttpServletResponse response,@RequestParam(value="code",defaultValue="") String code,@RequestParam(value="redirect_url",defaultValue="") String url){ OpenIdResult open = WeixinUtil.getOpenId(request,code,TimedTask.appid,TimedTask.appsecret);//根据Code获取OpenId //根据OpenId查找是否有该客户,没有进行绑定 Customer customerInfo = weixinFirstServer.getCustomerDetailByOpenId(open.getOpenid()); if(customerInfo!=null){ if(customerInfo.getAccountStatus()==2){//用户账户是否正常 return "redirect:"+TimedTask.websiteAndProject+"/weixin/customer/noAuthority.jsp"; } session.setAttribute("customerInfo", customerInfo);//把用户信息存在session中 response.setContentType("text/html; charset=UTF-8"); try { response.sendRedirect(url); } catch (IOException e) { e.printStackTrace(); } return null; }else{ url= url.replaceAll("&","-"); url = url.replace(TimedTask.websiteAndProject,""); String redirectUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+TimedTask.appid+"&redirect_uri="+TimedTask.websiteAndProject+"/weixinF/getOpenInfoRedirectAction?actionName="+url+"&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect"; response.setContentType("text/html; charset=UTF-8"); try { response.sendRedirect(redirectUrl); } catch (IOException e) { e.printStackTrace(); } return null; } }
到此,微信网页授权认证,与session失效自动登录已经完成,如果有问题欢迎在评论区指出
本文出自 “半山闲人” 博客,转载请与作者联系!
以上是关于微信公众号开发之网页授权认证获取用户的详细信息,实现自动登陆的主要内容,如果未能解决你的问题,请参考以下文章