微信进入公众号后,可以后台调取其接口获取opendid,但在规范中通常要求用户有交互才能获取,而且用户进入公众号这步是无法获取到这个交互,只有进公众号之后的点击操作才行。所以思路就是在用户点击菜单后,获取其opendid并设法存储在自己网站的session中。
这里开发文档有描述:
因此在菜单跳转链接以snsapi_base方式之后,在跳转的链接url里面的代码中获取code在以上面的方式去获取opendid,核心代码
WxMenu menu = new WxMenu();
WxMenuButton button1 = new WxMenuButton();
button1.setType(MenuButtonType.VIEW);
button1.setName("用户列表");
//封装了跳转微信网页的菜单,跳转到自己开发的公众号网站
button1.setUrl(wxService.oauth2buildAuthorizationUrl(NetConfig.Host_url + "user/index", "snsapi_base", ""));
@ModelAttribute
public void init(HttpServletRequest request) throws WxErrorException {
Object opendid = request.getSession().getAttribute("opendid");
if(opendid == null) { //避免页面重复调用接口获取opendid并操作session
String code = request.getParameter("code"); //这个code值很关键
if(code != null) {
WxMpOAuth2AccessToken accessToken = NetConfig.WxService.oauth2getAccessToken(code);
WxMpUser user = NetConfig.WxService.getUserService().userInfo(accessToken.getOpenId());
request.getSession().setAttribute("opendid", user.getOpenId());
request.getSession().setAttribute("nikeName", user.getNickname());
}
}
}
这样,其它页面调用,直接用HttpServletRequest对象的getSession().getAttribute("opendid").toString()方法,即可获取session中的opendid并使用它。