码迷,mamicode.com
首页 > Web开发 > 详细

网站引入QQ登录

时间:2020-01-06 23:16:16      阅读:216      评论:0      收藏:0      [点我收藏+]

标签:red   tac   信息   etc   author   catch   key   code   用户   

我也是小白,以下内容均为个人理解,大家一定要带思考的去阅读。

在添加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登录

标签:red   tac   信息   etc   author   catch   key   code   用户   

原文地址:https://www.cnblogs.com/yang37/p/12158700.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!