是 | ||
是 | ||
是 | ||
是 | ||
否 | ||
是 |
/**
* 第三方登录接口
*/
@RequestMapping("/login")
public void getCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
//拼接url
StringBuilder url = new StringBuilder(); url.append("https://open.weixin.qq.com/connect/oauth2/authorize?"); //微信开放平台的appid
url.append("appid=" + ConfigConstans.wechatAppid); // 项目中的公众号的appid
//转码
try {
//回调地址 ,回调地址要进行Encode转码
String redirect_uri = URLEncoder.encode(ConfigConstans.contextPath + "/callback", "utf-8");
System.out.println("redirect_uri==" + redirect_uri); url.append("&redirect_uri=" + redirect_uri); //微信授权后回调的地址链接,代码如下
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
url.append("&response_type=code"); url.append("&scope=snsapi_userinfo"); // 当前使用的是授权登录,(snsapi_base) 不弹出授权页面,根据需求使用
url.append("&state=" + request.getSession().getId()); // 微信中的回调参数
url.append("#wechat_redirect");
System.out.println("url===" + url.toString());
String s = url.toString(); response.sendRedirect(s);
}
/**
* 微信 授权登录回调
**/
@RequestMapping("/callback")
public String callback(String code, String state, HttpServletRequest request, HttpServletResponse response) throws Exception {
System.out.println("====" + code + "===" + state + "===="); log.info("code===" + code);
log.info("state===" + state);
HttpSession session = request.getSession(); //拼写微信获取access_token访问地址
String url = "https://api.weixin.qq.com/sns/oauth2/access_token"; url += "?appid=" + ConfigConstans.wechatAppid; // 使用项目中的公众号的appid
url += "&secret=" + ConfigConstans.wechatAppsecret; // 使用项目中的公众号的appsecret
url += "&code=" + code; // code==200时,请求正确,信息返回正确 url += "&grant_type=authorization_code";
log.info("url=="+url); //获取返回数据
JSONObject userMap = urlHalder(url); // 接收回调信息
//获取openid
Object openId = userMap.get("openid"); //用户唯一标识,若程序有PC端和AP端,建议是有回调信息中的uuid
Object accessToken = userMap.get("access_token");
String loginurl = "";
if (ObjectUtils.isNotNull(openId) && ObjectUtils.isNotNull(accessToken)) {
String infourl = "https://api.weixin.qq.com/sns/userinfo"; infourl += "?access_token=" + accessToken;
infourl += "&openid=" + openId; //获取返回数据
JSONObject userInfoMap = urlHalder(infourl); //根据openId 获取用户信息
BasUser basUser = basUserService.getUserByopenId(userInfoMap.get("openid"));
if (ObjectUtils.isNull(basUser)){ //没有当前数据时,进入程序中的绑定页面
loginurl = ConfigConstans.contextPath+"/user/login?openId="+userInfoMap.get("openid");
}else { //有当前数据时,进入程序中的首页 loginurl = ConfigConstans.contextPath+"/index";
} session.setAttribute(UserCacheConstans.USER_OPENID,String.valueOf(userInfoMap.get("openid")));
}
return "redirect:" + loginurl;
}
* 正确时返回的JSON数据包
{
"openid": "OPENID",
"nickname": NICKNAME,
"sex": 1,
"province":"PROVINCE",
"city":"CITY",
"country":"COUNTRY", "headimgurl":"https://thirdwx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/46",
"privilege":[ "PRIVILEGE1" "PRIVILEGE2" ],
"unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
}