为了方便测试 。debug 建议大家搞个花生壳或者其他的可以映射公网IP的软件。
貌似涨价了8元一个。鄙人捡了个便宜1元买的。还是个二级域名
1.设置一个菜单调用授权接口的URL (https://open.weixin.qq.com/和这个网站的是不一样的东西)获取code
https://open.weixin.qq.com/connect/oauth2/authorize?appid=CORPID&redirect_uri=REDIRECTURI&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect
2.写一个方法接收上图中reurl 获取code 与 access_token
public String execute() throws Exception {
HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse response = ServletActionContext.getResponse();
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
String code = request.getParameter("code");
if(!"authdeny".equals(code)){
String access_token = WeixinUtil.getAccessToken(您的企业号corpId,您的企业号secret).getToken();
String UserID = oAuth2Service.getUserID(access_token, code, "2"); //第3步
request.setAttribute("UserId", UserID);
}
request.getRequestDispatcher("/index.jsp").forward(request,response);
return null;
}
3.getUserID获取员工userid 这个id并不是用户openid
/**
* 获取员工信息的接口地址
**/
public String CODE_TO_USERINFO = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=ACCESS_TOKEN&code=CODE&agentid=AGENTID";
/**
* 根据code获取成员信息
* @param access_token 调用接口凭证
* @param code 通过员工授权获取到的code,每次员工授权带上的code将不一样,code只能使用一次,5分钟未被使用自动过期
* @param agentid 跳转链接时所在的企业应用ID 管理员须拥有agent的使用权限;agentid必须和跳转链接时所在的企业应用ID相同
* */
public String getUserID(String access_token, String code, String agentid) {
String UserId = "";
CODE_TO_USERINFO = CODE_TO_USERINFO.replace("ACCESS_TOKEN", access_token).replace("CODE", code).replace("AGENTID", agentid);
JSONObject jsonobject = WeixinUtil.httpRequest(CODE_TO_USERINFO, "GET", null);
if (null != jsonobject) {
UserId = jsonobject.getString("UserId");
if (!"".equals(UserId)) {
System.out.println("获取信息成功,o(∩_∩)o ————UserID:" + UserId);
} else {
int errorrcode = jsonobject.getInt("errcode");
String errmsg = jsonobject.getString("errmsg");
String error = "错误码:" + errorrcode + "————" + "错误信息:" + errmsg;
log.error(error);
}
} else {
log.error("获取授权失败了");
}
return UserId;
}
4.再根据第2步的转发 将获取的数据传递到页面 测试是否正确
4.1 首先点击微信企业号里面有授权菜单的应用 的菜单
4.2 走第2步的Action 获取code、 access_token换取userid 并转发到指定页面