java

java方式接入QQ登录

2021-01-28  本文已影响0人  星钻首席小管家

1.工具类
·HttpClientUtils https://www.jianshu.com/p/2786284d8bbd
·URLEncodeUtil

public class URLEncodeUtil {

    private final static String ENCODE = "UTF-8";
    /**
     * URL 解码
     */
    public static String getURLDecoderString(String str) {
        String result = "";
        if (null == str) {
            return "";
        }
        try {
            result = java.net.URLDecoder.decode(str, ENCODE);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }
    /**
     * URL 转码
     */
    public static String getURLEncoderString(String str) {
        String result = "";
        if (null == str) {
            return "";
        }
        try {
            result = java.net.URLEncoder.encode(str, ENCODE);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }

}

2.QQ配置信息

public class QqConfig {

    @Value("${qq.appId}")
    private String qqAppId;

    @Value("${qq.appSecret}")
    private String qqAppSecret;

    @Value("${qq.redirectUrl}")
    private String qqRedirectUrl;
}

3.获取code,token,openId

public class QqConnectServiceImpl implements QqConnectService {


    /**
     * QQ :读取Appid相关配置信息静态类
     */
    @Autowired
    private QqConfig qqConfig;

    @Override
    public String getCode(String state) throws Exception {
        // 拼接url
        StringBuilder url = new StringBuilder();
        url.append("https://graph.qq.com/oauth2.0/authorize?");
        url.append("response_type=code");
        url.append("&client_id=" + qqConfig.getQqAppId());
        // 回调地址 ,回调地址要进行Encode转码
        String redirect_uri = qqConfig.getQqRedirectUrl();
        // 转码
        url.append("&redirect_uri=" + URLEncodeUtil.getURLEncoderString(redirect_uri));
        url.append("&state="+URLEncodeUtil.getURLEncoderString(state));
        System.out.println(url.toString());
        //HttpClientUtils.get(url.toString(), "UTF-8");
        return url.toString();
    }



    /**
     * 开始登录
     * @param code
     * @return
     * @throws Exception
     */
    @Override
    public QQUserVO qqLogin(String code) throws Exception {
        if (code != null) {
            System.out.println(code);
        }
        //获取tocket
        Map<String, Object> qqProperties = getToken(code);
        //获取openId(每个用户的openId都是唯一不变的)
        QQUserVO openId = getOpenId(qqProperties);
        qqProperties.put("openId",openId.getOpenid());

        //获取数据
        QQUserVO userInfo =  getQqUserInfo(qqProperties);
        userInfo.setOpenid(openId.getOpenid());
        userInfo.setUnionid(openId.getUnionid());
        return userInfo;
    }

    /**
     * 获得token信息(授权,每个用户的都不一致) --> 获得token信息该步骤返回的token期限为一个月
     */
    private Map<String, Object> getToken(String code) throws Exception {
        StringBuilder url = new StringBuilder();
        url.append("https://graph.qq.com/oauth2.0/token?");
        url.append("grant_type=authorization_code");

        url.append("&client_id=" + qqConfig.getQqAppId());
        url.append("&client_secret=" + qqConfig.getQqAppSecret());
        url.append("&code=" + code);
        // 回调地址
        String redirect_uri = qqConfig.getQqRedirectUrl();
        // 转码
        url.append("&redirect_uri=" + URLEncodeUtil.getURLEncoderString(redirect_uri));
        // 获得token
        String result = HttpClientUtils.get(url.toString(), "UTF-8");
        log.info("result___________"+result);
        // 把token保存
        String[] items = StringUtils.splitByWholeSeparatorPreserveAllTokens(result, "&");
        String accessToken = StringUtils.substringAfterLast(items[0], "=");
        Long expiresIn = new Long(StringUtils.substringAfterLast(items[1], "="));
        String refreshToken = StringUtils.substringAfterLast(items[2], "=");
        //token信息
        Map<String,Object > qqProperties = new HashMap<String,Object >();
        qqProperties.put("accessToken", accessToken);
        qqProperties.put("expiresIn", String.valueOf(expiresIn));
        qqProperties.put("refreshToken", refreshToken);
        return qqProperties;
    }


    /**
     * 获取用户openId(根据token)
     *
     //     * @param 把openId存到map中
     * @return
     * @throws Exception
     */
    private QQUserVO getOpenId(Map<String,Object> qqProperties) throws Exception {
        // 获取保存的用户的token
        String accessToken = (String) qqProperties.get("accessToken");
        if (!StringUtils.isNotEmpty(accessToken)) {
            // return "未授权";
        }
        StringBuilder url = new StringBuilder("https://graph.qq.com/oauth2.0/me?");
        url.append("access_token=" + accessToken);
        url.append("&unionid=1" );
        String result = HttpClientUtils.get(url.toString(), "UTF-8");
        log.info("result___________"+result);
        String openId = StringUtils.substringBetween(result, "\"openid\":\"", "\",\"unionid\"");
        String unionid = StringUtils.substringBetween(result, "\"unionid\":\"", "\"}");
        QQUserVO qqUserVO = new QQUserVO();
        qqUserVO.setOpenid(openId);
        qqUserVO.setUnionid(unionid);
        return qqUserVO;
    }

    /**
     * 根据token,openId获取用户信息
     */
    private QQUserVO getQqUserInfo(Map<String,Object> qqProperties) throws Exception {
        // 取token
        String accessToken = (String) qqProperties.get("accessToken");
        String openId = (String) qqProperties.get("openId");
        if (!StringUtils.isNotEmpty(accessToken) || !StringUtils.isNotEmpty(openId)) {
            return null;
        }
        //拼接url
        StringBuilder url = new StringBuilder("https://graph.qq.com/user/get_user_info?");
        url.append("access_token=" + accessToken);
        url.append("&oauth_consumer_key=" + qqConfig.getQqAppId());
        url.append("&openid=" + openId);
        // 获取qq相关数据
        String result = HttpClientUtils.get(url.toString(), "UTF-8");
        log.info("result___________"+result);
        Object json = JSON.parseObject(result, QQUserVO.class);
        QQUserVO qqUserVO = (QQUserVO) json;
        return qqUserVO;
    }
上一篇 下一篇

猜你喜欢

热点阅读