/**
* 微信新受權回調地址
* @param req
* @param rsp
* @param code
* @param sourceType
* @param state
* @return
* @throws Exception
* @return Object
* @author tyg
* @date 2019年4月1日下午2:33:35
*/
@RequestMapping(value = "/api/wechat/authBack")
public void authBack(HttpServletRequest req, HttpServletResponse rsp, Long id, Long shareId, Integer sourceType, String code, String state) throws Exception {
Assert.isBlank(code, "code can't be null!");
Assert.isBlank(state, "url can't be null!");
// 獲取用戶openid和unionid,沒有頭像、暱稱
JSONObject info = wechatService.getUserOpenId(code);
// 登陸,若是不存在則返回爲null,再獲取用戶的頭像和暱稱信息
UserQuery userInfo = userI.weCharLogin(new WeChatUser(shareId, sourceType, info.getString("openid"), info.getString("unionid")));
if(userInfo == null) {
// 獲取微信用戶信息,有頭像、暱稱
info = wechatService.getUserInfoByOpenId(info.getString("access_token"), info.getString("openid"));
// 登陸
userInfo = userI.weCharLogin(new WeChatUser(shareId, sourceType, info.getString("openid"),
info.getString("unionid"), info.getString("nickname"), info.getString("headimgurl")));
Assert.isNull(userInfo, "user is null!");
}
String encode = URLEncoder.encode(JSON.toJSONString(userInfo), "UTF-8");
state = URLDecoder.decode(state, "UTF-8");
state += state.contains("?") ? "&" : "?";
state = String.format("%sid=%s&shareId=%s&userInfo=%s", state, id == null ? "" : id, shareId == null ? "" : shareId, encode);
rsp.sendRedirect(state);
}
/**
* 獲取用戶的openid
* @param code
* @return
* @throws Exception
* @return JSONObject
* @author tyg
* @date 2019年4月12日上午10:31:46
*/
private JSONObject getUserOpenId(String code) throws Exception {
Map<String, String> params = new HashMap<String, String>();
params.put("grant_type", "authorization_code");//
params.put("appid", WeChatProperties.AppID);
params.put("secret", WeChatProperties.AppSecret);
params.put("code", code);
String jstoken = HttpUtils.sendGet("https://api.weixin.qq.com/sns/oauth2/access_token", params);
if (jstoken == null) {
LOG.error("jstoken is null");
return null;
}
JSONObject jsonResult = JSONObject.parseObject(jstoken);
if (null != jsonResult.get("errcode")) {
LOG.error("wechat web auth err:" + jsonResult.get("errcode") + ":" + jsonResult.get("errmsg"));
return null;
}
return jsonResult;
}
/**
* 根據openid獲取用戶信息,有頭像、暱稱
* @param access_token
* @param openid
* @return
* @throws Exception
* @return JSONObject
* @author tyg
* @date 2019年4月9日上午10:00:56
*/
public JSONObject getUserInfoByOpenId(String access_token,String openid) throws Exception {
Map<String, String> params = new HashMap<String, String>();
params.put("access_token", access_token);
params.put("openid", openid);
params.put("lang", "zh_CN");
String userinfo = HttpUtils.sendGet("https://api.weixin.qq.com/sns/userinfo", params);
JSONObject userJson = JSONObject.parseObject(userinfo);
if (null != userJson.get("errcode")) {
LOG.error(userJson.get("errmsg") + " get wechat user error:");
}
return userJson;
}