WEB接入第三QQ授权登录

/**
 * 项目: b2b-pc
 * 文件: QQAuthority.java
 * 包名: com.b2b.pc.auth
 * 日期: 2017年11月24日下午8:39:03
 * Copyright (c) 2017.
 *
*/


package com.b2b.pc.auth;


import java.util.Map;


import javax.servlet.http.HttpServletRequest;


import org.beetl.ext.spring.BeetlGroupUtilConfiguration;
import org.beetl.sql.core.kit.StringKit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;


import com.b2b.core.exception.AbstractException;
import com.b2b.core.exception.common.ParameterMissingException;
import com.b2b.core.utils.HttpKit;
import com.b2b.core.utils.LogKit;
import com.b2b.core.utils.RSAKit;
import com.b2b.core.utils.RequestKit;
import com.b2b.core.web.WebSession;
import com.b2b.core.web.token.TokenGenerator;
import com.b2b.friends.domain.Member;
import com.b2b.friends.domain.MemberExt;
import com.b2b.friends.service.intf.IMemberExtService;
import com.b2b.friends.service.intf.IMemberService;
import com.b2b.friends.type.MemberThirdPartyInfoType;
import com.b2b.friends.view.MemberInfoView;


import net.sf.json.JSONObject;


/**
 * 类名: QQAuthority

 * 描述: QQ授权登录回调.

 * 日期: 2017年11月24日 下午8:39:03

 * 作者: HuangTianLiang
 */
@Controller
public class QQAuthority {


@Autowired
private BeetlGroupUtilConfiguration configuration;
@Autowired
private IMemberService iMemberService;
@Autowired
private IMemberExtService iMemberExtService;

// 获取用户Id和OpenId
private static final String getClientIdAndOpenIdByAccessToken = "https://graph.qq.com/oauth2.0/me?access_token=%s&callback=callback";
// 获取QQ用户数据
private static final String getUserInfoByAccessTokenAndOpendAndAppId = "https://graph.qq.com/user/get_user_info?access_token=%s&oauth_consumer_key=%s&openid=%s";



/**
* QQCallback:(QQ的回调).

*
* @author HuangTianLiang
* @param request
* @return
* @since JDK 1.6
*/
@RequestMapping(value="qqcallback")
public String QQCallback(HttpServletRequest request){
request.setAttribute("pubKey", RSAKit.getRsaUtils().getPubKeyStr());
return "qqdispose";
}

//QQ绑定页面
@RequestMapping(value="qqbind")
public String  qqBind(HttpServletRequest request){
ThirdUserInfo userInfo=(ThirdUserInfo) RequestKit.getObj(request,"keyInfo");
if(userInfo==null){
return "redirect:/login";
}
//标识的是第三方的:QQ,还是微信,[{QQ:false},{微信:true}]
//request.setAttribute("istf",false);
RequestKit.setObj(request, false,"istf");
return "wechat-bind";
}

/**
* QQAuthCall:(这里用一句话描述这个方法的作用).


* @author HuangTianLiang
* @param request
* @param access_token
* @param expires_in
* @return
* @since JDK 1.6
*/
@RequestMapping(value = "callback")
public String QQAuthCall(HttpServletRequest request, String access_token, String expires_in) {
try {
access_token = request.getParameter("access_token");
expires_in = request.getParameter("expires_in");
//String[] str1 = RSAKit.getPwd(access_token);
//String[] str2 = RSAKit.getPwd(expires_in);
//access_token = str1[0];
//expires_in = str2[0];
// 获取QQ配置信息
Map map = configuration.getGroupTemplate().getSharedVars();
String appId = map.get("qqAppId").toString();
String appKey = map.get("qqAppKey").toString();
if (access_token == null) {
return "redirect:/login";
}
// [1]
QQAccessToken accessToken = getOpendIdByAccessToken(access_token);
if (accessToken == null) {
return "redirect:/login";
}
accessToken.setAccessToken(access_token); // set access_token 参数


// [2]
ThirdUserInfo userInfo = getUserInfo(accessToken.getAccessToken(), accessToken.getOpenid(), appId);
if (userInfo == null) {
return "redirect:/login";
}
userInfo.setOpenId(accessToken.getOpenid());
userInfo.setUnionId(accessToken.getOpenid());
userInfo.setType(MemberThirdPartyInfoType.QQ);

if(userInfo.getUnionId()==null||userInfo.getOpenId()==null){
throw new ParameterMissingException("qqKey未知。");
}

//根据第三方的UnionId判断该账号有没有进行棉纱网账号进行绑定  》》》if未进绑定
Member mb = iMemberService.getMemberByQQ(userInfo.getUnionId());
if(mb==null){
LogKit.info("第三方:【QQ登录,未进行账号绑定,跳转绑定页面进行账号绑定】");
//保存第三方信息数据
RequestKit.setObj(request, userInfo,"keyInfo");
return "redirect:/qqbind";
}

//【检测是否可以登录】
iMemberService.checkLogin(mb);

WebSession session = new WebSession();
session.setAuth(true);
session.setFingerPrint(RequestKit.computeFinger(request));
session.setIdentify(mb.getId());
if(!StringKit.isEmpty(userInfo.getNickname())){
mb.setNickName(userInfo.getNickname());
}

//根据id获取当前登录人的邀请码
MemberExt ext=iMemberExtService.findByMemberId(mb.getId());
//获取当前登录人积分
MemberInfoView member=iMemberService.getMyScoreAndRefCodeAndPcode(mb.getId());

String token = TokenGenerator.generator(request,session);

RequestKit.setSession(request, session);
RequestKit.setObj(request, mb, "MEMBER");
RequestKit.setObj(request, token, "token");
RequestKit.setObj(request, ext.getRefCode(),"refCode");                //登录人邀请码
RequestKit.setObj(request, member.getPointBalance().toBigInteger(), "refScore");   //登录人可用积分

return "redirect:/";
} catch (AbstractException e) {
LogKit.info("第三方:【QQ登录失败】 错误代码:" + e.code() + ",失败原因:" + e.msg());
return "redirect:/login";
} catch (Exception e) {
LogKit.info("第三方:【QQ登录失败】 失败原因" + e.getMessage());
return "redirect:/login";
}
}


// 获取OpenId
public QQAccessToken getOpendIdByAccessToken(String accessToken) {
String json = HttpKit.get(redirectUri(getClientIdAndOpenIdByAccessToken, new Object[] { accessToken }));
QQAccessToken token = null;
if (json != null) {
String str = json.substring(json.indexOf("(") + 1, json.indexOf(")") - 1);
JSONObject jsonObject = JSONObject.fromObject(str);
if (null != jsonObject) {
try {
token = new QQAccessToken();
token.setClientid(jsonObject.getString("client_id"));
token.setOpenid(jsonObject.getString("openid"));
} catch (Exception e) {
int errorCode = jsonObject.getInt("error");
String errorMsg = jsonObject.getString("error_description");
LogKit.info("第三方:【QQ】获取用户信息失败 errcode:{" + errorCode + "} errmsg:{" + errorMsg + "}");
}
}
}
return token;
}


public ThirdUserInfo getUserInfo(String accessToken, String openId, String appId) {
String json = HttpKit.get(
redirectUri(getUserInfoByAccessTokenAndOpendAndAppId, new Object[] { accessToken, appId, openId }));
JSONObject jsonObject = JSONObject.fromObject(json);
ThirdUserInfo userInfo = null;
if (null != jsonObject) {
try {
userInfo = new ThirdUserInfo();
userInfo.setNickname(jsonObject.getString("nickname")); // 昵称
userInfo.setGender(jsonObject.getString("gender")); // 性别
userInfo.setProvince(jsonObject.getString("province")); // 用户所在省份
userInfo.setCity(jsonObject.getString("city")); // 用户所在城市
userInfo.setHeadImgUrl(jsonObject.getString("figureurl"));  // 用户头像


} catch (Exception e) {
int errorCode = jsonObject.getInt("ret");
String errorMsg = jsonObject.getString("msg");
LogKit.info("第三方:【QQ】获取用户信息失败 errcode:{" + errorCode + "} errmsg:{" + errorMsg + "}");
}
}
return userInfo;
}


// 拼接字符串
public String redirectUri(String url, Object[] obj) {
return url.format(url, obj);
}
}

你可能感兴趣的:(Java,python)