1. 程式人生 > 程式設計 >Java實現QQ第三方登入的示例程式碼

Java實現QQ第三方登入的示例程式碼

前期準備工作

1.雲伺服器

2.備案的域名

3.本地除錯需要修改hosts檔案,將域名對映到127.0.0.1

如何修改hosts檔案:https://www.jb51.net/diannaojichu/319774.html

申請QQ互聯,併成為開發者

申請QQ互聯建立應用時需要備案域名,所以建議提前準備備案域名。

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

登入後,點選頭像,進入認證頁面,填寫資訊,等待稽核。

稽核通過後建立應用

應用建立通過稽核後,就可以使用APP ID 和 APP Key

前期工作就這些了,後面可以開始寫程式碼了。

專案結構:

properties或者yml配置檔案(這裡就是簡單的配置了一下,可以自行新增資料庫等配置)

server.port=80
server.servlet.context-path=/
 
#qq互聯
qq.oauth.http:QQ互聯中申請填寫的網站地址

在pom中新增依賴

<!--httpclient-->
<dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId>httpclient</artifactId>
  <version>4.5.6</version>
</dependency>
<!--阿里 JSON-->
<dependency>
  <groupId>com.alibaba</groupId>
  <artifactId>fastjson</artifactId>
  <version>1.2.47</version>
</dependency>

傳送QQ登入請求

定義全域性變數獲取配置檔案中的網站地址

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

定義登入回撥地址(可以用網站地址拼接或者直接寫)

//QQ互聯中的回撥地址
String backUrl = http + "/index";

登入請求方法程式碼

@GetMapping("/qq/login")
public String qq(HttpSession session) throws UnsupportedEncodingException {
  //QQ互聯中的回撥地址
  String backUrl = http + "/index";
 
  //用於第三方應用防止CSRF攻擊
  String uuid = UUID.randomUUID().toString().replaceAll("-","");
  session.setAttribute("state",uuid);
 
  //Step1:獲取Authorization Code
  String url = "https://graph.qq.com/oauth2.0/authorize?response_type=code"+
      "&client_id=" + QQHttpClient.APPID +
      "&redirect_uri=" + URLEncoder.encode(backUrl,"utf-8") +
      "&state=" + uuid;
 
  return "redirect:" + url;
}

回撥返回引數資訊說明:

引數名稱 描述
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示例:

Content-type: text/html; charset=utf-8
{
"ret":0,"is_lost":0,"nickname":"Peter","gender":"男","country":"中國","province":"廣東","city":"深圳","figureurl":"http://imgcache.qq.com/qzone_v4/client/userinfo_icon/1236153759.gif","is_yellow_vip":1,"is_yellow_year_vip":1,"yellow_vip_level":7,"is_yellow_high_vip": 0
}

錯誤返回示例

Content-type: text/html; charset=utf-8
{
"ret":1002,"msg":"請先登入"
}

使用者資料的介面文件:https://wiki.open.qq.com/wiki/v3/user/get_info

請求成功,使用者確認登入後回撥方法

@GetMapping("/index")
public String qqcallback(HttpServletRequest request,HttpServletResponse response) throws Exception {
  HttpSession session = request.getSession();
  //qq返回的資訊
  String code = request.getParameter("code");
  String state = request.getParameter("state");
  String uuid = (String) session.getAttribute("state");
 
  if(uuid != null){
    if(!uuid.equals(state)){
      throw new QQStateErrorException("QQ,state錯誤");
    }
  }
 
 
  //Step2:通過Authorization Code獲取Access Token
  String backUrl = http + "/index";
  String url = "https://graph.qq.com/oauth2.0/token?grant_type=authorization_code"+
      "&client_id=" + QQHttpClient.APPID +
      "&client_secret=" + QQHttpClient.APPKEY +
      "&code=" + code +
      "&redirect_uri=" + backUrl;
 
  String access_token = QQHttpClient.getAccessToken(url);
 
  //Step3: 獲取回撥後的 openid 值
  url = "https://graph.qq.com/oauth2.0/me?access_token=" + access_token;
  String openid = QQHttpClient.getOpenID(url);
 
  //Step4:獲取QQ使用者資訊
  url = "https://graph.qq.com/user/get_user_info?access_token=" + access_token +
      "&oauth_consumer_key="+ QQHttpClient.APPID +
      "&openid=" + openid;
 
  //返回使用者的資訊
  JSONObject jsonObject = QQHttpClient.getUserInfo(url);
 
  //也可以放到Redis和mysql中,只取出了部分資料,根據自己需要取
  session.setAttribute("openid",openid); //openid,用來唯一標識qq使用者
  session.setAttribute("nickname",(String)jsonObject.get("nickname")); //QQ名
  session.setAttribute("figureurl_qq_2",(String)jsonObject.get("figureurl_qq_2")); //大小為100*100畫素的QQ頭像URL
 
  //響應重定向到home路徑
  return "redirect:/home";
}

QQ客戶端類QQHttpClient:

主要用於QQ訊息返回

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
 
import java.io.IOException;
 
public class QQHttpClient {
  //QQ互聯中提供的 appid 和 appkey
  public static final String APPID = "appid";
 
  public static final String APPKEY = "appkey";
 
 
  private static JSONObject parseJSONP(String jsonp){
    int startIndex = jsonp.indexOf("(");
    int endIndex = jsonp.lastIndexOf(")");
 
    String json = jsonp.substring(startIndex + 1,endIndex);
 
    return JSONObject.parseObject(json);
  }
  //qq返回資訊:access_token=FE04************************CCE2&expires_in=7776000&refresh_token=88E4************************BE14
  public static String getAccessToken(String url) throws IOException {
    CloseableHttpClient client = HttpClients.createDefault();
    String token = null;
 
    HttpGet httpGet = new HttpGet(url);
    HttpResponse response = client.execute(httpGet);
    HttpEntity entity = response.getEntity();
 
    if(entity != null){
      String result = EntityUtils.toString(entity,"UTF-8");
      if(result.indexOf("access_token") >= 0){
        String[] array = result.split("&");
        for (String str : array){
          if(str.indexOf("access_token") >= 0){
            token = str.substring(str.indexOf("=") + 1);
            break;
          }
        }
      }
    }
 
    httpGet.releaseConnection();
    return token;
  }
  //qq返回資訊:callback( {"client_id":"YOUR_APPID","openid":"YOUR_OPENID"} ); 需要用到上面自己定義的解析方法parseJSONP
  public static String getOpenID(String url) throws IOException {
    JSONObject jsonObject = null;
    CloseableHttpClient client = HttpClients.createDefault();
 
    HttpGet httpGet = new HttpGet(url);
    HttpResponse response = client.execute(httpGet);
    HttpEntity entity = response.getEntity();
 
    if(entity != null){
      String result = EntityUtils.toString(entity,"UTF-8");
      jsonObject = parseJSONP(result);
    }
 
    httpGet.releaseConnection();
 
    if(jsonObject != null){
      return jsonObject.getString("openid");
    }else {
      return null;
    }
  }
 
  //qq返回資訊:{ "ret":0,"msg":"","nickname":"YOUR_NICK_NAME",... },為JSON格式,直接使用JSONObject物件解析
  public static JSONObject getUserInfo(String url) throws IOException {
    JSONObject jsonObject = null;
    CloseableHttpClient client = HttpClients.createDefault();
 
    HttpGet httpGet = new HttpGet(url);
    HttpResponse response = client.execute(httpGet);
    HttpEntity entity = response.getEntity();
 
 
    if(entity != null){
      String result = EntityUtils.toString(entity,"UTF-8");
      jsonObject = JSONObject.parseObject(result);
    }
 
    httpGet.releaseConnection();
 
    return jsonObject;
  }
}

異常類QQStateErrorException:

public class QQStateErrorException extends Exception {
  public QQStateErrorException() {
    super();
  }
 
  public QQStateErrorException(String message) {
    super(message);
  }
 
  public QQStateErrorException(String message,Throwable cause) {
    super(message,cause);
  }
 
  public QQStateErrorException(Throwable cause) {
    super(cause);
  }
 
  protected QQStateErrorException(String message,Throwable cause,boolean enableSuppression,boolean writableStackTrace) {
    super(message,cause,enableSuppression,writableStackTrace);
  }
}

首頁controller用於跳轉頁面

@Controller
public class IndexController {
 
  @GetMapping({"/index","/"})
  public String index(){
    return "index";
  }
 
  @GetMapping("/home")
  public String home(HttpSession session,Model model){
    String openid = (String) session.getAttribute("openid");
    String nickname = (String) session.getAttribute("nickname");
    String figureurl_qq_2 = (String) session.getAttribute("figureurl_qq_2");
 
    model.addAttribute("openid",openid);
    model.addAttribute("nickname",nickname);
    model.addAttribute("figureurl_qq_2",figureurl_qq_2);
 
    return "home";
  }
}

還有兩個簡單的登入頁面和資訊頁面

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
  <a href="/qq/login" rel="external nofollow" >QQ登入</a>
</body>
</html>

home.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<div>
  <img th:src="${figureurl_qq_2}">
</div>
<span th:text="${openid}"></span>
<span th:text="${nickname}"></span>
</body>
</html>

最後附上下載地址:https://github.com/machaoyin/qqdemo

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。