最近公司开发微信公众号,发现微信oauth2授权重定向服务器url时会请求两次并且带着同一个code,仔细考虑解决方案之后想到了两种解决方案,一种是重定向的方法中判断code的有效性若有效即通过code获取openId并存入session;另一种就是通过return redirect的方式将生成的openId以参数形式传给重定向的方法中。这里贴出第二种方法希望给碰到这种问题的开发友友们一些参考。
@RequestMapping(value = "/test") public String test(@RequestParam(required = false) String code) { String openId = ""; String appsecret = PropertiesUtils.appSecret; String appid = PropertiesUtils.appID; try { String requestUrl = go_url.replace("APPID", appid).replace("APPSECRET", appsecret).replace("CODE", code); JSONObject jsonObject = WeixinUtil.httpRequst(requestUrl, "GET", null); openId = jsonObject.get("openid").toString(); } catch (Exception e) { return ""; } return "redirect:http://xxx.com.cn/wechat/weixin/test2?openId="+openId;
}
@RequestMapping(value = "/test2") public ModelAndView test2(String openId) { ModelAndView mv = this.getModelAndView(); mv.addObject("openId", openId); mv.setViewName("xxx/xxx/xxx"); return mv; }