网站引入QQ登录
Posted yang37
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了网站引入QQ登录相关的知识,希望对你有一定的参考价值。
我也是小白,以下内容均为个人理解,大家一定要带思考的去阅读。
在添加QQ登录功能之前,需要在https://connect.qq.com/index.html申请应用,然后得到APP ID、APP Key等信息,此处不再赘述。
网站添加QQ登录功能的步骤如下:
1.填写QQ登录的链接
A.在对应的登录链接处填下如内容
https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=&redirect_uri=&state=
参数说明:
response_type的值固定为code;
client_id的值为申请的appid;
redirect_uri的值为申请时填写的回调地址;
访问这个链接之后就会进入QQ登录的界面。
B.点击登录之后,会返回我们申请的回调地址并携带code码,需要我们编写对应的controller处理。
2.利用得到的Code,获取Access Token。
A.发送请求:
"https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&client_id=" + appid + "&client_secret="+ appkey + "&redirect_uri=" + redirectURI + "&code=" + code
参数说明:
grant_type的值固定为authorization_code;
client_id的值为申请的appid;
client_secret的值为申请的appkey;
redirect_uri的值为申请时填写的回调地址;(注意:需要将url进行编码!!!)
code值为获取到的Authorization Code值
B.请求之后会返回如下内容,绿色部分就是token值。
3.利用得到的token,获取OpenID。
A.发送请求:
"https://graph.qq.com/oauth2.0/me?access_token=" + accessToken;
参数说明:
access_token值为获取到的Access Token值
B.请求之后会返回如下内容,绿色部分就是openid值。
4.利用得到的openid,获取用户信息。
A.发送请求:
https://graph.qq.com/user/get_user_info?access_token=" + access_token+ "&oauth_consumer_key=" + appid + "&openid=" + openid
B.请求之后就能获得用户信息,例如昵称、性别等。
参考代码:
1.处理code
2.请求处理部分参考OkHttp(网址https://square.github.io/okhttp)
//1.得到QQ用户的token
public String getQQAccessToken(AccessTokenDTO accessTokenDTO){
String appid = accessTokenDTO.getClient_id();
String appkey = accessTokenDTO.getClient_secret();
String redirectURI = accessTokenDTO.getRedirect_uri();
String code = accessTokenDTO.getCode();
String asStr ="https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&client_id=" + appid + "&client_secret="+ appkey + "&redirect_uri=" + redirectURI + "&code=" + code;
MediaType mediaType = MediaType.get("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
//RequestBody对象转换成json对象
RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(accessTokenDTO));
Request request = new Request.Builder()
.url(asStr)
.post(body)
.build();
try {
Response response = client.newCall(request).execute();
String string = response.body().string();
//处理得到的字符串,以获得token。
String token = string.split("&")[0].split("=")[1];
return token;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
以上是关于网站引入QQ登录的主要内容,如果未能解决你的问题,请参考以下文章