網站接入qq登錄可以省去注冊賬號,增加網站的體驗度。那么要實現我自己搭建的站點天天博客的qq單點登錄需要以下幾個步驟:
1,申請appid和appkey
首先要去https://connect.qq.com/去申請一個網站的qq接入,申請成功時會給一個appid和appkey,前提是要有一個站點。
2,qq登錄跳轉
申請成功后,開始進行qq登錄開發,根據官方文檔,需要在放置一個qq登錄的圖標,然后點擊這個圖標跳轉qq認證登錄頁。
如下圖:
點擊登錄之后會跳轉到相應的頁面如下:要確保你的回調頁面和申請里面寫的一樣並且要將url進行URLEncode
當qq登錄成功后悔跳轉到回調頁面,並且會在url里面帶上上Authorization Code的值。
3,獲取AccessToken
通過Authorization Code獲取Access Token,我選擇通過后端代碼調用,因為前段會出現跨域問題,以下是我的封裝的方法
/// <summary> /// 獲取AccessToken /// </summary> /// <param name="authorizationCode"></param> /// <returns></returns> public static async Task<string> GetAccessToken(string authorizationCode) { if (string.IsNullOrEmpty(authorizationCode)) throw new AuthException("qq認證登錄失敗:authorizationCode為空"); string url = string.Format("https://graph.qq.com/oauth2.0/token?" + "grant_type=authorization_code&client_id={0}&client_secret={1}&code={2}&redirect_uri={3}&fmt=json", appId, appKey, authorizationCode, redirectUrl); HttpClient httpClient = new HttpClient(); string response = await httpClient.GetStringAsync(url); dynamic result = JsonHelper.DeserializeObject(response); string error = result.error; if (!string.IsNullOrEmpty(error)) throw new AuthException("qq認證登錄失敗:" + result.error_description); return result.access_token; }

4,獲取openid
通過token獲取openid,其中openid就想當與一個qq號碼,唯一的:
/// <summary> /// 獲取OpenId /// </summary> /// <param name="authorizationCode"></param> /// <returns></returns> public static async Task<string> GetOpenId(string accessToken) { if (string.IsNullOrEmpty(accessToken)) throw new AuthException("qq認證登錄失敗:accessToken無效"); string url = "https://graph.qq.com/oauth2.0/me?fmt=json&access_token=" + accessToken; HttpClient httpClient = new HttpClient(); string response = await httpClient.GetStringAsync(url); dynamic result = JsonHelper.DeserializeObject(response); string error = result.error; if (!string.IsNullOrEmpty(error)) throw new AuthException("qq認證登錄失敗:"+result.error_description); return result.openid; }

5,通過token和openid獲取qq信息:
/// <summary> /// 獲取qq信息 /// </summary> /// <param name="authorizationCode"></param> /// <returns></returns> public static async Task<UserModel> GetQQUser(string accessToken,string openId) { if (string.IsNullOrEmpty(accessToken)) throw new AuthException("accessToken無效"); if (string.IsNullOrEmpty(openId)) throw new AuthException("openId"); string url = string.Format("https://graph.qq.com/user/get_user_info" + "?access_token={0}&openid={1}&appid={2}&fmt=json", accessToken, openId, appId); HttpClient httpClient = new HttpClient(); string response = await httpClient.GetStringAsync(url); dynamic result = JsonHelper.DeserializeObject(response); if (result.ret != 0) throw new AuthException("qq認證登錄失敗:" + result.msg); UserModel userModel = new UserModel(); userModel.Account = openId; userModel.Username = result.nickname; userModel.LoginType = Blog.Domain.Core.LoginType.QQ; userModel.Sex = result.gender; userModel.HeadPhoto = result.figureurl_qq_2; return userModel; }

6,處理qq信息
到此,qq賬號的信息以及獲取完成了,接下來就是根據自己的業務來處理qq賬號信息了,我選擇將qq信息存入user表,后端將qq信息轉為對應的user,放入jwt里面生成token:
[Route("login/{code}")] [HttpGet] public async Task<ApiResult> Login(string code) { string accessToken =await QQClient.GetAccessToken(code); string openId = await QQClient.GetOpenId(accessToken); UserModel userModel = await QQClient.GetQQUser(accessToken, openId); _userService.Insert(userModel); IList<Claim> claims = new List<Claim>() { new Claim("account", userModel.Account), new Claim("username", userModel.Username), new Claim("sex", userModel.Sex), new Claim("birthDate",string.IsNullOrEmpty(userModel.BirthDate)?"":userModel.BirthDate), new Claim("email", string.IsNullOrEmpty(userModel.Email)?"":userModel.Email), new Claim("sign", string.IsNullOrEmpty(userModel.Sign)?"":userModel.Sign), new Claim("phone",string.IsNullOrEmpty(userModel.Phone)?"":userModel.Phone), new Claim("headPhoto", string.IsNullOrEmpty(userModel.HeadPhoto)?"":userModel.HeadPhoto) }; string jwtToken = new JWT(_cacheClient).CreateToken(claims); return ApiResult.Success(jwtToken); }

7,前端存儲token
qq登錄后根據你申請里面寫的回調頁面,qq會自動跳轉到這個頁面,我的回調頁面就一個空白頁面,加上一個loading提示,加載這個頁面時,調用后端api,進行認證操作,成功后,存入token並且跳轉到網站首頁:
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width = device-width" /> <title>qq認證登錄中...</title> <link rel="icon" href="/style/images/title.png"> </head> <body> <div> qq認證登錄中... </div> <script src="/style/js/jquery.js"></script> <script src="/style/layui/layui.js"></script> <script src="/style//js/request.js?v=20112171144"></script> <script src="/style/js/util.js?v=202009091015"></script> <script> layui.use(["layer"], function () { var layer = layui.layer; var loading = layer.load(2,{offset: ['100px', '720px']}); var code = getSearchString('code'); if(code==undefined){ layer.msg('code無效', { icon: 5 }); return; } $.ajax({ url: url + 'qq/login/' + code, type: 'get', dataType: 'json', success: function (res) { if (res.code == "200") { localStorage.setItem("token", res.data); window.location.href = "../home/index.html"; } else { layer.close(loading) layer.msg(res.message, { icon: 5 }); } } }) }) </script> </body> </html>

通過以上操作,我的個人站點:http://www.ttblog.site已經是完成了qq接入的功能,這只是我自己摸索出來的實現方式,給以參考,設計之中難免有不合理之處,希望有人能給出建議。