【微信公众号】获取opendid并存储在session中

微信进入公众号后,可以后台调取其接口获取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并使用它。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值