qq 第三方登录 前后端实现

 

 微信扫一扫关注个公众号。谢谢各位

第一步:https://connect.qq.com/去此网站进行授权(需要用到域名,域名需要备案通过)

审核通过后。拿到appid

第二步:前端定义个按钮,为按钮绑定好事件(client_id==appid)

window.location.href ="https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=******&state=register&redirect_uri="+encodeURI("http://zhdydet.xyz:8085/api/qqLogin");//http://zhdydet.xyz:8085/api/qqLogin===>回调地址(qq第三方)

 

第三步:编写后台回调代码

//具体此代码要根据业务来。我这边用的是shiro权限框架。回调后。默认进行shiro登录授权,以及根据openid进行添加和修改用户信息

 

@RequestMapping("/qqLogin")
public void  qqLoginAfter(HttpServletResponse response, HttpServletRequest request) {
    try{
        HttpSession session = request.getSession();

        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 Exception("QQ,state错误");
            }
        }
        //Step2:通过Authorization Code获取Access Token
        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=" + QQHttpClient.CALLBACK;

        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;
          User user =   userService.selectByOpenId(openid);
        JSONObject jsonObject = QQHttpClient.getUserInfo(url);
        String avatarImg = jsonObject.getString("figureurl_qq");
        String nickname = jsonObject.getString("nickname");
        String gender = jsonObject.getString("gender");
        User user1 = new User();
        Subject subject = SecurityUtils.getSubject();
          if(user == null){
              user1.setRealName(nickname);
              user1.setPicture(avatarImg);
              user1.setOpenID(openid);
              user1.setUserName(openid);
              String salt = getSalt();
              user1.setSalt(salt);
              String password = MD5Utils.MD5Encode(openid+"_"+salt+"_"+"123456","utf-8");
              user1.setPassword(password);
              user1.setRoleId(5);
              user1.setAddTime(new Date());
              this.userService.insertUser(user1);
              UsernamePasswordToken info = new UsernamePasswordToken(openid, "123456");
              subject.login(info);
             // response.sendRedirect("/api/index");
          }else{
              user1.setRealName(nickname);
              user1.setPicture(avatarImg);
              user1.setOpenID(openid);
              user1.setUserName(openid);
              user1.setId(user.getId());
              user1.setUpdateTime(new Date());
              this.userService.updateUser(user1);
              UsernamePasswordToken info = new UsernamePasswordToken(openid, "123456");
              subject.login(info);
          }
        redisTemplate.opsForValue().set("user:info"+":"+subject.getSession().getId(),user1,1L, TimeUnit.HOURS);

        response.sendRedirect("/api/index");
        response.setStatus(200);
    }catch (IOException e){

    }
}

 

 

QQHttpClient类

需要用到的maven依赖

<!--httpclient-->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.6</version>
</dependency>

 

package com.bus.utils;

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;

/**
 * @author wwz
 * @date 2019-07-24
 * @descrption:
 */
public class QQHttpClient { //QQ互联中提供的 appid 和 appkey
    public static final String APPID = "**********";

    public static final String APPKEY = "*********";
    public static final String CALLBACK = "http://zhdydet.xyz:8085/api/qqLogin";


    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);
    }

    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;
    }

    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;
        }
    }

    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;
    }
}

感谢观看,可以在微信搜索公众号  威信交流,以后准备在 公众号更新一些文章

在 SpringBoot 前后端分离项目中实现微信第三方登录需要以下步骤: 1. 注册微信开放平台账号,创建应用,获取 AppID 和 AppSecret。 2. 在前端页面中调用微信授权登录 API,获取到用户授权后得到的 code。 3. 将 code 发送到后端,后端通过调用微信 API 获取 access_token 和 openid。 4. 根据 openid 查询用户是否已经注册,如果已经注册则直接登录,否则需要跳转到注册页面。 5. 注册用户时需要获取用户的昵称、头像等信息,可以通过调用微信 API 获取。 6. 登录成功后需要生成 token 并返回给前端前端将 token 存储在本地,后续请求需要携带该 token。 下面是一个示例代码: 1. 前端页面调用微信授权登录 API ```javascript function wechatLogin() { window.location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=<AppID>&redirect_uri=<Redirect_URI>&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect"; } ``` 2. 后端获取 access_token 和 openid ```java String code = request.getParameter("code"); String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appId + "&secret=" + appSecret + "&code=" + code + "&grant_type=authorization_code"; JSONObject jsonObject = HttpUtil.getJson(url); String accessToken = jsonObject.getString("access_token"); String openId = jsonObject.getString("openid"); ``` 3. 根据 openid 查询用户是否已经注册 ```java User user = userService.getUserByOpenId(openId); if (user == null) { // 跳转到注册页面 } else { // 直接登录 } ``` 4. 注册用户并获取用户信息 ```java String userInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + accessToken + "&openid=" + openId + "&lang=zh_CN"; JSONObject userInfo = HttpUtil.getJson(userInfoUrl); String nickname = userInfo.getString("nickname"); String avatarUrl = userInfo.getString("headimgurl"); // 注册用户并返回用户信息 ``` 5. 生成 token 并返回给前端 ```java String token = JwtUtil.createToken(user.getId()); return Result.success(token); ``` 需要注意的是,微信授权登录的 API 需要在微信客户端中打开,否则会提示“该链接无法访问”。
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

王威振的csdn

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值