首先判斷用戶是否登陸過(關注並且進入過微信公衆號)
//判斷用戶是否已經登陸
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;
}