微信公众号--进入菜单之前获取用户信息
即网页授权(微信开发文档:https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html)
准备工作:(在自己的公众号里面进行设置)
1、引导用户进入授权页面:
用户点击菜单就会进入到授权页面,即将菜单对应的URL设置为对应的授权网址
String pinChe = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=MYAPPID&redirect_uri=http://ddiamondd.w3.luyouxia.net/WeChat/login&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect"; /* 很长的一个网址 其中appid和redirect_uri(授权后要跳转到的网页,可以是jsp或者servlet...)都要换成自己的,其他的不用变 */
2、用户点击同意授权后,就是跳转到redirect_uri中,并携带一个code
/*我上面的redirect_uri是跳转到一个servlet中*/@WebServlet("/login") public class LoginServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String code = request.getParameter("code"); AccessToken accessToken = WXService.getSpecialAccessToken(code); // 通过code换取网页授权access_token// 获取用户信息 String url = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN"; url2 = url.replace("ACCESS_TOKEN", accessToken.getAccessToken()).replace("OPENID", accessToken.getOpenId()); String result = Util.get(url); // 获取到的用户信息 JSONObject jsonObject = JSONObject.fromObject(result); String openid = jsonObject.getString("openid"); request.getSession().setAttribute("openid", openid); request.getRequestDispatcher("/group/car.jsp").forward(request,response); // 跳转到对应页面上 } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }