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_level 3366用戶的大等級。

(當pf=3366時返回)

3366_level_name 3366用戶的等級名,如小遊遊、小遊仙。

(當pf=3366時返回)

3366_grow_level 3366用戶的成長等級。

(當pf=3366時返回)

3366_grow_value 3366用戶的成長值。

(當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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章