首先判断用户是否登陆过(关注并且进入过微信公众号)
//判断用户是否已经登陆
User userWechat=(User) request.getSession().getAttribute("userWechat");
if(userWechat!=null)//用户不为空,则跳转到指定页面,
如:redirect:/wechat/customer/index.html
如果用户没有登陆过
//第一步:用户同意授权,获取code
String url ="https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appid
+ "&redirect_uri="+URLEncoder.encode(backUrl)
+ "&response_type=code"
+ "&scope=snsapi_userinfo"
+ "&state="+state
+ "#wechat_redirect";
redirectUrl= "redirect:"+url;
微信回调地址,获取用户的基本信息
@RequestMapping("/callBack")
public String auth(@RequestParam("code") String code, String state ,HttpServletRequest req,HttpServletResponse response) throws Exception {
//第二步:通过code换取网页授权access_token
String access_tokenUrl="https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appid + "&secret=" + secret + "&code="+ code + "&grant_type=authorization_code";
RestTemplate restTemplate = new RestTemplate();
String respose = restTemplate.getForObject(access_tokenUrl, String.class);
JSONObject jsonObject = JSONObject.fromObject(respose);
String openid = jsonObject.getString("openid");
String access_token = jsonObject.getString("access_token");
String refresh_token = jsonObject.getString("refresh_token");
// 第三步:拉取用户信息(需scope为 snsapi_userinfo)
String infoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token="+access_token+"&openid="+openid+"&lang=zh_CN";
String infoString = restTemplate.getForObject(infoUrl, String.class);
infoString=new String(infoString.getBytes("iso8859-1"), "utf-8");
JSONObject userInfo = JSONObject.fromObject(infoString);
System.out.println("infoString:"+infoString);
//设置用户信息并存储到session中
User userWechat=new User();
userWechat.setOpenid(openid);
userWechat.setNickname(userInfo.getString("nickname"));
userWechat.setUsericon(userInfo.getString("headimgurl"));
System.out.println(userInfo.getString("headimgurl"));
int sexWechat=Integer.parseInt(userInfo.getString("sex"));
boolean sexFg=sexWechat==0?true:false;
userWechat.setSex(sexFg);
userWechat.setUserverify(false);
userWechat.setUsertype(false);
userWechat.setCountry(userInfo.getString("country"));
userWechat.setProvince(userInfo.getString("province"));
userWechat.setCity(userInfo.getString("city"));
userWechat.setUsertype(false);
req.getSession().setAttribute("userWechat", userWechat);
String redirectUrl="";
redirectUrl= "redirect:/wechat/customer/index.html";
return redirectUrl;
}
最后:获取微信用户信息
@RequestMapping(value="/getUserMessage")
public @ResponseBody User getUserMessage(HttpServletRequest request) throws Exception {
//获取用户信息
HttpSession session=request.getSession();
User userWechat=(User)session.getAttribute("userWechat");
return userWechat;
}