即網頁授權(微信開發文檔:https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html)
准備工作:(在自己的公眾號里面進行設置)
1、引導用戶進入授權頁面:
用戶點擊菜單就會進入到授權頁面,即將菜單對應的URL設置為對應的授權網址
1 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"; 2 /* 3 很長的一個網址 其中appid和redirect_uri(授權后要跳轉到的網頁,可以是jsp或者servlet...)都要換成自己的,其他的不用變 4 */
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); } }