相比微信只需一步就可以通过code换取到openid,qq登录的openid获取流程需要分为2步
一、获取用户的token
先使用授权码code换取到token
String token = getToken(code, qqConfig);
private String getToken(String code, QQConfig qqConfig) {
String url = "https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&client_id=" +
qqConfig.getAppId() +
"&client_secret=" +
qqConfig.getSecret() +
"&code=" +
code +
"&redirect_uri=" +
redirectUri;
String result = restTemplate.getForObject(url, String.class);
String token = getParams(result).get("access_token");
if (!StringUtils.hasLength(token)) {
throw new ServiceException("登录失效");
}
return token;
}
private static final String URL_PARTITION = "&";
public static Map<String, String> getParams(String url) {
Map<String, String> params = new HashMap<>(16);
try {
String[] urlParts = url.split("?");
String query = urlParts[urlParts.length - 1];
for (String param : query.split(URL_PARTITION)) {
String[] pair = param.split("=");
String key = URLDecoder.decode(pair[0], StandardCharsets.UTF_8);
String value = "";
if (pair.length > 1) {
value = URLDecoder.decode(pair[1], StandardCharsets.UTF_8);
}
params.put(key, value);
}
} catch (Exception e) {
e.printStackTrace();
}
return params;
}
在请求服务器获取token时,服务器的返回值不是json格式的,无法直接转换为对象,这里使用getParams方法来获取我们需要的参数access_token
二、通过token获取openid
public QQAuthResp qqLogin(String token) {
String url = "https://graph.qq.com/oauth2.0/me?access_token=" +
token;
String result = restTemplate.getForObject(url, String.class);
int start = result.indexOf("{");
int end = result.lastIndexOf("}") + 1;
result = result.substring(start, end);
QQAuthResp userResp = JSONObject.parseObject(result, QQAuthResp.class);
return userResp;
}
public class QQAuthResp {
@JSONField(name = "client_id")
private String clientId;
private String openid;
}
有了token之后,调用获取用户信息的接口可以获取到openid