Java实现QQ第三方登录

1.云服务器

2.备案的域名

3.本地调试需要修改hosts文件,将域名映射到127.0.0.1

如何修改hosts文件:https://www.cnblogs.com/toSeeMyDream/p/9313440.html

申请QQ互联,并成为开发者

申请QQ互联创建应用时需要备案域名,所以建议提前准备备案域名。

QQ互联:https://connect.qq.com/index.html

登录后,点击头像,进入认证页面,填写信息,等待审核。

审核通过后创建应用

应用创建通过审核后,就可以使用APP ID 和 APP Key

前期工作就这些了,后面可以开始写代码了。

项目结构:

properties或者yml配置文件(这里就是简单的配置了一下,可以自行添加数据库等配置)


 
 
  1. server.port= 80
  2. server.servlet.context-path=/
  3. #qq互联
  4. qq.oauth.http:QQ互联中申请填写的网站地址

在pom中添加依赖


 
 
  1. <!--httpclient-->
  2. <dependency>
  3. <groupId>org.apache.httpcomponents </groupId>
  4. <artifactId>httpclient </artifactId>
  5. <version>4.5.6 </version>
  6. </dependency>
  7. <!--阿里 JSON-->
  8. <dependency>
  9. <groupId>com.alibaba </groupId>
  10. <artifactId>fastjson </artifactId>
  11. <version>1.2.47 </version>
  12. </dependency>

发送QQ登录请求

定义全局变量获取配置文件中的网站地址


 
 
  1. @Value("${qq.oauth.http}")
  2. private String http;

定义登录回调地址(可以用网站地址拼接或者直接写)


 
 
  1. //QQ互联中的回调地址
  2. String backUrl = http + "/index";

登录请求方法代码


 
 
  1. @GetMapping( "/qq/login")
  2. public String qq(HttpSession session) throws UnsupportedEncodingException {
  3. //QQ互联中的回调地址
  4. String backUrl = http + "/index";
  5. //用于第三方应用防止CSRF攻击
  6. String uuid = UUID.randomUUID().toString().replaceAll( "-", "");
  7. session.setAttribute( "state",uuid);
  8. //Step1:获取Authorization Code
  9. String url = "https://graph.qq.com/oauth2.0/authorize?response_type=code"+
  10. "&client_id=" + QQHttpClient.APPID +
  11. "&redirect_uri=" + URLEncoder.encode(backUrl, "utf-8") +
  12. "&state=" + uuid;
  13. return "redirect:" + url;
  14. }

回调返回参数信息说明:

参数名称描述
ret返回码。详见公共返回码说明#OpenAPI V3.0 返回码
msg如果错误,返回错误信息。
is_lost判断是否有数据丢失。如果应用不使用cache,不需要关心此参数。

0或者不返回:没有数据丢失,可以缓存。
1:有部分数据丢失或错误,不要缓存。

nickname昵称。
gender性别。
country国家(当pf=qzone、pengyou或qplus时返回)。
province省(当pf=qzone、pengyou或qplus时返回)。
city市(当pf=qzone、pengyou或qplus时返回)。
figureurl头像URL。详见:前端页面规范#6. 关于用户头像的获取和尺寸说明
openid用户QQ号码转化得到的ID(当pf=qplus时返回)。
qq_level用户QQ等级(当pf=qplus时返回)。
qq_vip_level用户QQ会员等级(当pf=qplus时返回)。
qplus_level用户Q+等级(当pf=qplus时返回)。
is_yellow_vip是否为黄钻用户(0:不是; 1:是)。

(当pf=qzone、pengyou或qplus时返回)

is_yellow_year_vip是否为年费黄钻用户(0:不是; 1:是)。

(当pf=qzone、pengyou或qplus时返回)

yellow_vip_level黄钻等级,目前最高级别为黄钻8级(如果是黄钻用户才返回此参数)。

(当pf=qzone、pengyou或qplus时返回)

is_yellow_high_vip是否为豪华版黄钻用户(0:不是; 1:是)。

(当pf=qzone、pengyou或qplus时返回)

is_blue_vip是否为蓝钻用户(0:不是; 1:是)。

(当pf=qqgame或3366时返回)

is_blue_year_vip是否为年费蓝钻用户(0:不是; 1:是)。

(当pf=qqgame或3366时返回)

blue_vip_level蓝钻等级(如果是蓝钻用户才返回此参数)。

(当pf=qqgame或3366时返回)

3366_level3366用户的大等级。

(当pf=3366时返回)

3366_level_name3366用户的等级名,如小游游、小游仙。

(当pf=3366时返回)

3366_grow_level3366用户的成长等级。

(当pf=3366时返回)

3366_grow_value3366用户的成长值。

(当pf=3366时返回)

is_super_blue_vip是否是豪华蓝钻。

(当pf=qqgame或3366时返回)

正确返回示例:

JSON示例:


 
 
  1. Content- type: text/html; charset=utf -8
  2. {
  3. "ret": 0,
  4. "is_lost": 0,
  5. "nickname": "Peter",
  6. "gender": "男",
  7. "country": "中国",
  8. "province": "广东",
  9. "city": "深圳",
  10. "figureurl": "http://imgcache.qq.com/qzone_v4/client/userinfo_icon/1236153759.gif",
  11. "is_yellow_vip": 1,
  12. "is_yellow_year_vip": 1,
  13. "yellow_vip_level": 7,
  14. "is_yellow_high_vip": 0
  15. }

错误返回示例


 
 
  1. Content- type: text/html; charset=utf -8
  2. {
  3. "ret": 1002,
  4. "msg": "请先登录"
  5. }

用户资料的接口文档:https://wiki.open.qq.com/wiki/v3/user/get_info

请求成功,用户确认登录后回调方法


 
 
  1. @GetMapping( "/index")
  2. public String qqcallback(HttpServletRequest request, HttpServletResponse response) throws Exception {
  3. HttpSession session = request.getSession();
  4. //qq返回的信息
  5. String code = request.getParameter( "code");
  6. String state = request.getParameter( "state");
  7. String uuid = ( String) session.getAttribute( "state");
  8. if(uuid != null){
  9. if(!uuid.equals(state)){
  10. throw new QQStateErrorException( "QQ,state错误");
  11. }
  12. }
  13. //Step2:通过Authorization Code获取Access Token
  14. String backUrl = http + "/index";
  15. String url = "https://graph.qq.com/oauth2.0/token?grant_type=authorization_code"+
  16. "&client_id=" + QQHttpClient.APPID +
  17. "&client_secret=" + QQHttpClient.APPKEY +
  18. "&code=" + code +
  19. "&redirect_uri=" + backUrl;
  20. String access_token = QQHttpClient.getAccessToken(url);
  21. //Step3: 获取回调后的 openid 值
  22. url = "https://graph.qq.com/oauth2.0/me?access_token=" + access_token;
  23. String openid = QQHttpClient.getOpenID(url);
  24. //Step4:获取QQ用户信息
  25. url = "https://graph.qq.com/user/get_user_info?access_token=" + access_token +
  26. "&oauth_consumer_key="+ QQHttpClient.APPID +
  27. "&openid=" + openid;
  28. //返回用户的信息
  29. JSONObject jsonObject = QQHttpClient.getUserInfo(url);
  30. //也可以放到Redis和mysql中,只取出了部分数据,根据自己需要取
  31. session.setAttribute( "openid",openid); //openid,用来唯一标识qq用户
  32. session.setAttribute( "nickname",( String)jsonObject.get( "nickname")); //QQ名
  33. session.setAttribute( "figureurl_qq_2",( String)jsonObject.get( "figureurl_qq_2")); //大小为100*100像素的QQ头像URL
  34. //响应重定向到home路径
  35. return "redirect:/home";
  36. }

QQ客户端类QQHttpClient:

主要用于QQ消息返回


 
 
  1. import com.alibaba.fastjson.JSONObject;
  2. import org.apache.http.HttpEntity;
  3. import org.apache.http.HttpResponse;
  4. import org.apache.http.client.methods.HttpGet;
  5. import org.apache.http.impl.client.CloseableHttpClient;
  6. import org.apache.http.impl.client.HttpClients;
  7. import org.apache.http.util.EntityUtils;
  8. import java.io.IOException;
  9. public class QQHttpClient {
  10. //QQ互联中提供的 appid 和 appkey
  11. public static final String APPID = "appid";
  12. public static final String APPKEY = "appkey";
  13. private static JSONObject parseJSONP(String jsonp){
  14. int startIndex = jsonp.indexOf( "(");
  15. int endIndex = jsonp.lastIndexOf( ")");
  16. String json = jsonp.substring(startIndex + 1,endIndex);
  17. return JSONObject.parseObject(json);
  18. }
  19. //qq返回信息:access_token=FE04************************CCE2&expires_in=7776000&refresh_token=88E4************************BE14
  20. public static String getAccessToken(String url) throws IOException {
  21. CloseableHttpClient client = HttpClients.createDefault();
  22. String token = null;
  23. HttpGet httpGet = new HttpGet(url);
  24. HttpResponse response = client.execute(httpGet);
  25. HttpEntity entity = response.getEntity();
  26. if(entity != null){
  27. String result = EntityUtils.toString(entity, "UTF-8");
  28. if(result.indexOf( "access_token") >= 0){
  29. String[] array = result.split( "&");
  30. for (String str : array){
  31. if(str.indexOf( "access_token") >= 0){
  32. token = str.substring(str.indexOf( "=") + 1);
  33. break;
  34. }
  35. }
  36. }
  37. }
  38. httpGet.releaseConnection();
  39. return token;
  40. }
  41. //qq返回信息:callback( {"client_id":"YOUR_APPID","openid":"YOUR_OPENID"} ); 需要用到上面自己定义的解析方法parseJSONP
  42. public static String getOpenID(String url) throws IOException {
  43. JSONObject jsonObject = null;
  44. CloseableHttpClient client = HttpClients.createDefault();
  45. HttpGet httpGet = new HttpGet(url);
  46. HttpResponse response = client.execute(httpGet);
  47. HttpEntity entity = response.getEntity();
  48. if(entity != null){
  49. String result = EntityUtils.toString(entity, "UTF-8");
  50. jsonObject = parseJSONP(result);
  51. }
  52. httpGet.releaseConnection();
  53. if(jsonObject != null){
  54. return jsonObject.getString( "openid");
  55. } else {
  56. return null;
  57. }
  58. }
  59. //qq返回信息:{ "ret":0, "msg":"", "nickname":"YOUR_NICK_NAME", ... },为JSON格式,直接使用JSONObject对象解析
  60. public static JSONObject getUserInfo(String url) throws IOException {
  61. JSONObject jsonObject = null;
  62. CloseableHttpClient client = HttpClients.createDefault();
  63. HttpGet httpGet = new HttpGet(url);
  64. HttpResponse response = client.execute(httpGet);
  65. HttpEntity entity = response.getEntity();
  66. if(entity != null){
  67. String result = EntityUtils.toString(entity, "UTF-8");
  68. jsonObject = JSONObject.parseObject(result);
  69. }
  70. httpGet.releaseConnection();
  71. return jsonObject;
  72. }
  73. }

异常类QQStateErrorException:


 
 
  1. public class QQStateErrorException extends Exception {
  2. public QQStateErrorException() {
  3. super();
  4. }
  5. public QQStateErrorException(String message) {
  6. super(message);
  7. }
  8. public QQStateErrorException(String message, Throwable cause) {
  9. super(message, cause);
  10. }
  11. public QQStateErrorException(Throwable cause) {
  12. super(cause);
  13. }
  14. protected QQStateErrorException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
  15. super(message, cause, enableSuppression, writableStackTrace);
  16. }
  17. }

首页controller用于跳转页面


 
 
  1. @Controller
  2. public class IndexController {
  3. @GetMapping({"/index", "/"})
  4. public String index(){
  5. return "index";
  6. }
  7. @GetMapping("/home")
  8. public String home(HttpSession session, Model model){
  9. String openid = (String) session.getAttribute( "openid");
  10. String nickname = (String) session.getAttribute( "nickname");
  11. String figureurl_qq_2 = (String) session.getAttribute( "figureurl_qq_2");
  12. model.addAttribute( "openid",openid);
  13. model.addAttribute( "nickname",nickname);
  14. model.addAttribute( "figureurl_qq_2",figureurl_qq_2);
  15. return "home";
  16. }
  17. }

还有两个简单的登录页面和信息页面

index.html


 
 
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title </title>
  6. </head>
  7. <body>
  8. <a href="/qq/login">QQ登录 </a>
  9. </body>
  10. </html>

home.html


 
 
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title </title>
  6. </head>
  7. <body>
  8. <div>
  9. <img th:src="${figureurl_qq_2}">
  10. </div>
  11. <span th:text="${openid}"> </span>
  12. <span th:text="${nickname}"> </span>
  13. </body>
  14. </html>

最后附上下载地址:https://github.com/machaoyin/qqdemo

    评论
    添加红包

    请填写红包祝福语或标题

    红包个数最小为10个

    红包金额最低5元

    当前余额3.43前往充值 >
    需支付:10.00
    成就一亿技术人!
    领取后你会自动成为博主和红包主的粉丝 规则
    hope_wisdom
    发出的红包
    实付
    使用余额支付
    点击重新获取
    扫码支付
    钱包余额 0

    抵扣说明:

    1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
    2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

    余额充值