用户通过微信网页跳转到我们后台,这时需要获取用户信息以便进行自己的业务逻辑,需要用户进行授权,即用户授权给微信后台,由微信后台帮助用户跳转到我们的后台并携带相关获取用户信息需要用的code(开发文档中有对code进行解释)
下面代码是授权之后跳转到我们后台,获取用户信息的代码,springMVC Controller下,演示了获取用户微信唯一识别ID,进行自己平台的业务逻辑(微信号与自己平台用的数据绑定,即同一个人的两个号进行数据合并的业务)
/**
* 跳转微信用户认证(绑定)页面
* @author Draven
* @param request
* @return
*/
@RequestMapping("bindPage")
public ModelAndView bindSystomUserPage(HttpServletRequest request) {
String code = request.getParameter("code");
WXAccessTokenForWeb accessTokenForWeb = null;
ModelAndView modelAndView = new ModelAndView();
if (code != null) {
String s = getWebAccess(code);
Gson gson = new Gson();
accessTokenForWeb = gson.fromJson(s, WXAccessTokenForWeb.class);
if (accessTokenForWeb != null) {
try {
WXUserInfo userInfo=getUserInfo(accessTokenForWeb.getOpenid());
if (userInfo==null) {
modelAndView.addObject("info","获取用户信息失败");
modelAndView.setViewName("wx/bindInfoPage");
return modelAndView;
}
User user=userService.getUserByWechat(userInfo.getUnionid());
if (user!=null) {
if (!user.getUsername().equals(userInfo.getUnionid())) {
modelAndView.addObject("info","该微信已经进行过用户绑定");
modelAndView.setViewName("wx/bindInfoPage");
}else{
modelAndView.addObject("unionID", userInfo.getUnionid());
modelAndView.setViewName("wx/bindPage");
}
}else{
modelAndView.addObject("unionID", userInfo.getUnionid());
modelAndView.setViewName("wx/bindPage");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
modelAndView.addObject("info","绑定出错");
modelAndView.setViewName("wx/bindInfoPage");
}
}
}else{
modelAndView.addObject("info","绑定出错");
modelAndView.setViewName("wx/bindInfoPage");
}
return modelAndView;
}
package cnsts.childDepart.entity;
/**
* 用户授权后用CODE换区的用户AccessToken与OpenID实体,注意此ACCESSTOKEN不是用户接口调用所需的AccessToken
* @author Draven
* @date 2016年10月12日
* @e-mail draven1122@163.com
*/
public class WXAccessTokenForWeb {
private String access_token;
private String expires_in;
private String refresh_token;
private String openid;
private String scope;
public String getAccess_token() {
return access_token;
}
public void setAccess_token(String access_token) {
this.access_token = access_token;
}
public String getExpires_in() {
return expires_in;
}
public void setExpires_in(String expires_in) {
this.expires_in = expires_in;
}
public String getRefresh_token() {
return refresh_token;
}
public void setRefresh_token(String refresh_token) {
this.refresh_token = refresh_token;
}
public String getOpenid() {
return openid;
}
public void setOpenid(String openid) {
this.openid = openid;
}
public String getScope() {
return scope;
}
public void setScope(String scope) {
this.scope = scope;
}
}
//{"access_token":"gvE9Q4-ZTb3Zac9HzXqNbybUjYjn2LElCFeFuHQ9N_SHQJJn3trX0xo0FyW5O3P2lQcXtZZoqOdOZ4zuJAV-ACKO-H40Td6xC2ztvUCFiXs","expires_in":7200,"refresh_token":"njMWHYuHNm1SS6jO84mTuAQ8rxBLgWzHONMLmnBl3dsADnoflX-eqmwbmvp3CHm6M2L0qYJLst1udwkGvQgdWefJsOAjxAKWYU5293Y06Bs","openid":"ohFodw4OciBRqTtQnAygE0k7TpyY","scope":"snsapi_userinfo"}
此处的getUserInfo()方法在本栏目 《获取用户信息》中