java代码通过code调取openid出现的bug
40163,code been used 微信通过code获取openid
errcode:{} errmsg:{},40163,code been used, hints: [ req_id: hekcL14ce-y_G1Ta ]
出现这个错误时因为code被重复使用,下面是避免出现code被重复使用和openid丢失的问题的处理逻辑
/* start */
//在后台数据库插入关注用户绑定的个人信息,用户绑定成功之后,接着就去验证该用户是否存在数据库
@RequestMapping("/reportByOpenid")
public void submitInformation(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
request.setCharacterEncoding("UTF-8");
//这里要将你的授权回调地址处理一下,否则微信识别不了
String redirect_uri= URLEncoder.encode(hospitalServices.getDomainUrl()+"reportQuery/getResultItem", "UTF-8");
//简单获取openid的话参数response_type与scope与state参数固定写死即可
StringBuffer url=new StringBuffer("https://open.weixin.qq.com/connect/oauth2/authorize?redirect_uri="
+redirect_uri+"&appid="+hospitalServices.getAppid()+"&response_type=code&scope=snsapi_base&state=1#wechat_redirect");
response.sendRedirect(url.toString());//这里请不要使用get请求单纯的将页面跳转到该url即可
}
@RequestMapping("/getResultItem")
public String getResultItem(Model model,HttpServletRequest request,
@RequestParam(name = "openId", required = false) String openId) {
if ( StringUtils.isEmpty(openId)) {
String code = request.getParameter("code");//微信返回code值,用code获取openid
openId = WeixinUtil.getOpendId(code);
return "redirect:getResultItem?openId="+openId;
}
List<PersonBinding> listPersonBinding = new ArrayList<PersonBinding>();
listPersonBinding = personalDataServices.getPatientList(openId);
model.addAttribute("list",listPersonBinding);
model.addAttribute("listSize",listPersonBinding.size());
model.addAttribute("openId", openId);
return view+"getResultItem";
}
/* end */
if ( StringUtils.isEmpty(openId)) {
String code = request.getParameter("code");//微信返回code值,用code获取openid
openId = WeixinUtil.getOpendId(code);
return "redirect:getResultItem?openId="+openId;
}
通过判断openId为空,如果为空通过code去获取openId,否则不在获取openId,首次进入页面openId为空,重定向到getResultItem方法并且将openId带过去,这样就可以避免微信公众号刷新页面时出现出现openId以及再次通过code获取openId导致的code重复使用的问题。