网站接入qq登录

网站接入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,我选择通过后端代码调用,因为前段会出现跨域问题,以下是我的封装的方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/// <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号码,唯一的:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/// <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信息:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/// <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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
[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并且跳转到网站首页:
 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
<!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接入的功能,这只是我自己摸索出来的实现方式,给以参考,设计之中难免有不合理之处,希望有人能给出建议。

posted @   灬丶  阅读(2145)  评论(0编辑  收藏  举报
编辑推荐:
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· C++代码改造为UTF-8编码问题的总结
阅读排行:
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 清华大学推出第四讲使用 DeepSeek + DeepResearch 让科研像聊天一样简单!
· 实操Deepseek接入个人知识库
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
点击右上角即可分享
微信分享提示