javaweb调用qq认证登录接口

javaweb调用qq认证登录接口

前言

要使用qq认证登录,前提必须要已经审核通过的域名和服务器,一定要注意这一点。

申请appid和appkey

申请地址
https://connect.qq.com/manage.html#/
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
域名:你购买的域名,阿里,腾讯。。。都可以,但一定要和云服务器绑定审核通过的。
回调地址:在qq官方对你要登录的qq审核登录成功后,要跳转的地址,回调地址要和我的一样(应为我让回调到Controller的方法里面了)
在这里插入图片描述
在这里插入图片描述
成功后会有一个审核中的,不用管它,现在就可以用了。希望你可以审核通过。点开查看
在这里插入图片描述
应用接口中会有你这个申请都可以调什么接口的信息
在这里插入图片描述

代码

我用的是eclipse,ssm框架,代码不包含框架代码。代码复制下来后不要先写,先把方法与方法之间的调用搞清楚。要不然还是懵逼。
在这里插入图片描述
你需要建的目录
新建UserEntity

package com.cn.wjp.entity;

import java.io.Serializable;

public class UserEntity implements Serializable {

    private String uid;

  

    private String openid;

    private String name;

   
    private String image; //头像
    private String username;

    private String passwore;

   
   

    public String getUid() {
		return uid;
	}

	public void setUid(String uid) {
		this.uid = uid;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPasswore() {
		return passwore;
	}

	public void setPasswore(String passwore) {
		this.passwore = passwore;
	}

	public String getOpenid() {
        return openid;
    }

    public void setOpenid(String openid) {
        this.openid = openid;
    }

   

   

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }

    @Override
    public String toString() {
        return "UserEntity{" +
                "uid='" + uid + '\'' +
                
                ", openid='" + openid + '\'' +
                ", name='" + name + '\'' +
               
                ", image='" + image + '\'' +
                '}';
    }
}

新建UserMapper

package com.cn.wjp.mapper;




import com.cn.wjp.entity.UserEntity;


public interface UserMapper {

    //通过openid得到用户信息
    UserEntity getOpenid( String openid);

   
  //添加信息
    int insertQQ(UserEntity userEntity);

   //修改信息
    int updateQQ(UserEntity userEntity);

   //QQ授权过之后会给一个openid,通过openid进行查找,如果没有就是首次登陆直接添,如果有先修改信息
 


}

新建UserMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.cn.wjp.mapper.UserMapper" >
 
   
    <select id="getOpenid" resultType="com.cn.wjp.entity.UserEntity" parameterType="com.cn.wjp.entity.UserEntity"> 
 select * from hh where openid = #{openid}
  </select>
  <insert id="insertQQ" parameterType="com.cn.wjp.entity.UserEntity" > 
 insert into hh(uid,  openid, name,  image) values(#{uid}, #{openid}, #{name}, #{image})
 </insert>
  <update id="updateQQ" parameterType="com.cn.wjp.entity.UserEntity"  >
 update hh set name = #{name}, image = #{image} where openid = #{openid}
  </update>

  
</mapper>

新建UserService

package com.cn.wjp.service;


import org.springframework.stereotype.Service;

import com.cn.wjp.entity.UserEntity;
import com.cn.wjp.mapper.UserMapper;

import javax.annotation.Resource;

@Service
public class UserService {

    @Resource
    private UserMapper userMapper;

    public UserEntity getOpenid(String openid) {
        return userMapper.getOpenid(openid);
    }

    public int insert(UserEntity userEntity) {
        return userMapper.insertQQ(userEntity);
    }

    public int update(UserEntity userEntity) {
        return userMapper.updateQQ(userEntity);
    }

  /*  public int register(String openid, String phone, String email) {
        return userMapper.register(openid, phone, email);
    }*/

}

新建QQHttpClient

package com.cn.wjp.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;

public class QQHttpClient {
//注意修改
    public static final String APPID = "APPID";

    public static final String APPKEY = "APPKEY";
    //注册的时候会给你的  例子如下但是是错误的
   /* public static final String APPID = "100008777";

    public static final String APPKEY = "1010121f2a41efe310101205cb31020";*/

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

    /**
     * 获取 Access_Token
     * @param url
     * @return
     * @throws IOException
     */
    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;
    }

    /**
     * 获取 OpenID
     * @param url
     * @return
     * @throws IOException
     */
    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;
    }

    /**
     * 获取用户信息
     * @param url
     * @return
     * @throws IOException
     */
    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;
    }

}

新建QQController

package com.cn.wjp.controller;

import com.alibaba.fastjson.JSONObject;
import com.cn.wjp.entity.UserEntity;
import com.cn.wjp.service.UserService;
import com.cn.wjp.utils.QQHttpClient;
import com.cn.wjp.utils.UUIDUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.UUID;

@Controller
@RequestMapping("/qq")
public class QQController {

  //自己的域名
    private String http="http://mantianluanwu.online";

    @Autowired
    private UserService userService;

    /**
     * QQ 授权
     * @return
     */
    @RequestMapping("/oauth")
    public String qq(HttpSession session) {
    	// 自己注册的回调地址  第一个qq为项目名 第二个qq为QQController定义的@RequestMapping("/qq")第三个为方法  @RequestMapping("/callback")
    	String backUrl = http +"/qq/qq/callback";
    

        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) +
                     "&state=" + uuid;
     
        return "redirect:" + url;
    }

    /**
     * QQ 回调
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping("/callback")
    public String qqcallback(HttpServletRequest request) throws IOException {
        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)) {
                System.out.println("TOKEN错误, 防止CSRF攻击, 业务异常处理......");
                return null;
            }
        }

        // Step2: 通过Authorization Code获取Access Token
        String backUrl = http + "/qq/qq/callback";
        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);
        session.setAttribute("nickname", (String)jsonObject.get("nickname"));
        session.setAttribute("figureurl_qq_2", (String)jsonObject.get("figureurl_qq_2"));
        */

        // 绑定数据库, 如果没有QQ授权过的注册一个帐号
        UserEntity userEntity = userService.getOpenid(openid);
        if (userEntity == null) {
            userEntity = new UserEntity();
            userEntity.setUid(UUIDUtil.getUUID());
            userEntity.setOpenid(openid);
            userEntity.setName((String)jsonObject.get("name"));
            userEntity.setImage((String)jsonObject.get("figureurl_qq_2"));
            userService.insert(userEntity);
        } else {
            userEntity.setName((String)jsonObject.get("name"));
            userEntity.setImage((String)jsonObject.get("figureurl_qq_2"));
            userService.update(userEntity);
        }

        session.setAttribute("openid", userEntity.getOpenid());


        return home(session,request);
    }
    @RequestMapping("/home")
    public String home(HttpSession session,HttpServletRequest request) {
    	 
        String openid = (String)session.getAttribute("openid");
        if (openid != null) {
            UserEntity userEntity = userService.getOpenid(openid);
           
            if (StringUtils.isEmpty(userEntity.getPasswore())) {
             //看看是否有密码,如果没有到register可以在给这个qq登陆这只一个密码,添加邮箱。。。
                return register(openid,request);
            }
        
            request.setAttribute("userEntity", userEntity);
        }
       
        return "home";
    }
    //
    @RequestMapping("/register")
    public String register(String openid,HttpServletRequest request) {
        UserEntity userEntity = userService.getOpenid(openid);
        
        request.setAttribute("userEntity", userEntity);
        return "register";
    }

}

欢迎页面
login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<a href="qq/oauth">qq授权登录</a>

</html>

登陆成功注册手机号,邮箱号
register.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
     <%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>QQ第一次授权,请绑定帐号</h1>
<div>
    ${userEntity.nickname}
</div>
<div>
    <img src="${userEntity.image}">
</div>
<form action="<%=path%>/indexController/regsave" method="post">
    <input type="hidden" name="openid" value="${userEntity.openid}" />
    <div>电话:<input type="text" name="phone" value="" /></div>
    <div>邮件:<input type="text" name="email" value="" /></div>
    <div><input type="submit" /></div>
</form>
</body>
</html>

第二次登录
home.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
 <body>
        <#--
        <div>QQ授权成功</div>
        <div>
            OPENID: ${openid}
        </div>
        <div>
            NickName: ${nickname}
        </div>
        <div>
            <img src="${figureurl_qq_2}">
        </div>
        -->

        <div>QQ授权成功</div>
        <div>
            ${userEntity.nickname}
        </div>
        <div>
            <img src="${userEntity.image}">
        </div>
        <div>
            ${userEntity.email?}
        </div>

    </body>
</html>

应为回调地址问题登陆成功后会直接到服务器上面的代码中,所以要把代码放到服务器中测试。虽然没有发源码,但是上面的代码已经是全部了。

我相信,即使看着源码还是会有很多一行不到的错误的。加油,如果实在找不到了,评论里回复。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值