1、首先需要有个微信测试账号
http://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login
如果可以在下载一个“微信web开发者工具”,在测试得时候会非常方便
2、关注测试号二维码
3、网页服务-网页帐号-网页授权获取用户基本信息-修改
这里需要填录一个域名,这个域名不能带有http。再就是这个域名必须是公网可以访问得。所以我这里用了ngrok进行了域名映射,将本地Ip映射成了公网可以访问得地址。
下载ngrok 下载地址:https://ngrok.com/download
下载解压之后,输入命令:ngrok http 8080,8080是端口号。然后就会得到一个映射到外网的域名
因为ngrok服务器在国外,所以连接较慢,且不稳定。每次退出连接之后再重新映射得到的域名不一样,如果想每次一样需要去官网注册一个账号得到token码,再在ngrok命令行中进行配置。
4、单击网页授权获取用户基本信息,可以进入微信公众平台技术文档
微信网页开发-微信网页授权,这里详细描述了微信公众号权登陆的流程
按照步骤完成,代码如下:
![](https://static.oschina.net/uploads/space/2017/1025/161434_ofH2_3696747.png) ![](https://static.oschina.net/uploads/space/2017/1025/161921_M3Zr_3696747.png) |
public class AuthUtil { //将我们得appid和appsecret public static final String APPID=""; public static final String APPSECRET=""; //根据接口地址进行网络请求 public static JSONObject doGetJson(String url) throws ClientProtocolException, IOException{ JSONObject jsonObject = null; //DefaultHttpClient defaultHttpClient = new DefaultHttpClient(); CloseableHttpClient httpClient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet(url); CloseableHttpResponse response = httpClient.execute(httpGet); HttpEntity entity = response.getEntity(); if(entity!=null){ String result = EntityUtils.toString(entity, "utf-8"); jsonObject = JSONObject.fromObject(result); } httpGet.releaseConnection();//释放 return jsonObject; } } |
@WebServlet("/wxLogin") public class Login extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("开始了"); String backUrl = "https://333d89d2.ngrok.io/WxAuth/callBack"; String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+AuthUtil.APPID + "&redirect_uri="+URLEncoder.encode(backUrl) + "&response_type=code" + "&scope=snsapi_userinfo" + "&state=STATE#wechat_redirect"; response.sendRedirect(url); } } |
@WebServlet("/callBack") public class CallBackServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //获取token和openid String code = request.getParameter("code"); System.out.println(code); String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+AuthUtil.APPID + "&secret="+AuthUtil.APPSECRET + "&code="+code + "&grant_type=authorization_code"; JSONObject doGetJson = AuthUtil.doGetJson(url); System.out.println(doGetJson); String openid = doGetJson.getString("openid"); String token = doGetJson.getString("access_token"); //获取用户信息 String infoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token="+token + "&openid="+openid + "&lang=zh_CN"; JSONObject userInfo = AuthUtil.doGetJson(infoUrl); System.out.println(userInfo); //1、使用微信用户信息直接登陆,无需注册和绑定 request.setAttribute("info", userInfo); request.getRequestDispatcher("index1.jsp").forward(request, response); } } |