微信网页授权code请求多次回调的坑

在之前的项目里需要用到微信授权,我也是一次第一次用,看着微信开发文档写了,然后就掉进了一个坑里。

刚开始在授权页面写的微信授权链接:

https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx5250b8b9d4cfdf76&redirect_uri=(将code直接回调到业务controller)&response_type=code&scope=snsapi_userinfo&state=state#wechat_redirect';

我自己进行测试的时候,那是一点问题都没,然后就叫同事过来一起测试下,问题就出现了。。。当时那是一脸的懵逼啊。。。

我去好好看了下微信开发文档也没找到什么有用的消息。。。。。。。上网查了下有人说请求code会多次回调。。。我开启远程debug走了几圈还真是那么一会事,在用code拿openId那边那边报错了,这样子我接下去的业务代码就执行不下去了。

 

//=====================下面代码不用看================================

做个幂等就好了

 

===============================================================================

 

 

 

然后我开始重新改造代码了,在到达真正业务controller前,先走一个中间controller(这个来获得回调的code,去拿openId),然后重定向到真正的业务controller

 


修改后的代码

https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx5250b8b9d4cfdf76&redirect_uri=(将code直接回调到中间controller)&response_type=code&scope=snsapi_userinfo&state=state#wechat_redirect';

中间controller

@RequestMapping("xxxxx")
	public void accreditBack(String data, Model model,HttpServletRequest request,HttpServletResponse response) throws Exception{
		String code = request.getParameter("code");
		String publishId = request.getParameter("state");
		String contextPath = request.getContextPath();//获取项目名
	
		String url=contextPath+"/xxxx";
		if(!StringUtils.isEmpty(code)){
			WxCommoneUtils wxCommoneUtils =new WxCommoneUtils();
			//String openId = wxCommoneUtils.getOpenId(code);
			JSONObject wxUserInfo = wxCommoneUtils.getWxUserInfo(code);
			String openId = wxUserInfo.getString("openid");
			String headImgUrl = wxUserInfo.getString("headimgurl");//用户头像 
//			BASE64Encoder be =new  BASE64Encoder();
//			String encode = be.encode(headImgUrl.getBytes());
//			String string = encode.replaceAll(" ", "");
			url=url+"?"openId="+openId+"&headImgUrl="+headImgUrl;
			
		}
		response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);  
		response.setHeader("Location",url);
		 //清除缓存
		response.setHeader( "Connection", "close" );
		response.setHeader( "Pragma", "no-cache" );
		response.addHeader( "Cache-Control", "must-revalidate" );
		response.addHeader( "Cache-Control", "no-cache" );
		response.addHeader( "Cache-Control", "no-store" );
		response.setDateHeader("Expires", 0);
	}

真正的业务controller

@RequestMapping(value="xxxxxxxx")
		public String fxDetails(   String openId, String headImgUrl,Model model,HttpSession session,HttpServletResponse response) throws IOException {
			return "xxxxxxx";
	}	return "xxxxxxx";
	}

 

 

 

  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 8
    评论
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值