关于微信oauth登录的坑

这是实习公司里微信公众号的一个小项目,用的是ssm。问题是获取用户openid为空。

分析下步骤

  1. 首先用户点击微信公众号按钮
  2. 访问微信服务器获取code
  3. 跳转到项目url
  4. 拿code访问微信服务器,获取token 以及openid。
  5. 将openid存入session
这是微信按钮链接
https://open.weixin.qq.com/connect/oauth2/authorize?appid=xxxxxxxxxxxxxx&redirect_uri=https:xxx.xx.html&response_type=code&scope=snsapi_base&state=123#wechat_redirect //redirect_uri 是返回的url,指向的项目服务器

这个是url处理的Controller层

    @RequestMapping(method = RequestMethod.GET)
    public String newPage(HttpServletRequest request, ModelMap map, HttpServletResponse response) {
            getOpenid();
    }

其实问题就出在这个controller层里,这个方法的request并不是用户发出请求的request,而是微信服务器的request。
他们原本的做法是直接用微信转发的request.getSession().setAttribute("openid",openid);来设置值,用户发起请求,在通过用户request去getSession.getAttribute("openid"),获取的值当然为空了。

以下是我的做法

先跳转在一个页面,并带上code,然后这个页面在对项目服务器请求一次,这样就拿到用户的request了,然后在controller里去访问微信服务器,拿到token和openid,在存入session

猜你喜欢

转载自www.cnblogs.com/duangL/p/11670760.html