QQ wechat third party interface call

preface

Recently, I've been working on a third-party login. It's very simple to implement. Just call several interfaces to obtain personal information. Learn more: maven project integration qqauth2 0 third party login details Then, because this website is separated from the front end and the back end, I can't call back the interface and jump directly to the page I want, because my interfaces communicate with the front end and the back end through Ajax. I have consulted a lot of materials. Some say that websocket is used for front end and back-end verification, and there are different opinions. Then I thought, Can I make the callback address of the third-party application be html, and then I adjust the interface in html, so I can give the initiative to me. The answer is yes, so let's teach you how to separate the front and back ends of the website and how to realize the login of third-party such as QQ wechat.

Detailed steps

Step 1: apply for the login interface in the third-party application, and write an html of the website responsible for jump in the callback column, as shown in the figure below

https://funyan.cn

https://funyan.cn/logining.html

Step 2: make use of window. Com at the front end Open opens the qq login page, which needs to be obtained from the background. For details, refer to: maven project integration qqauth2 0 third party login details

//Send verification code
function qqLogin() {

    $.ajax({
        type: "GET",
        url: baseContext.path + "user/getCode",
        success: function (data) {
            var winObj=window.open(data, 'qq Sign in', 'height=800, width=600, top=0, left=0, toolbar=no, menubar=no, scrollbars=no, resizable=no, location=no, status=no');
            //Loop listening to know when the sub page is closed. As long as it is closed, jump to the specified page

            var loop = setInterval(function() {

                if(winObj.closed) {

                    clearInterval(loop);
                    window.location.href="newindex.html";
                }

            }, 500);
        },
        error: function () {
            layer.alert('connection failed', {
                icon: 2,
                skin: 'layer-ext-moon'
            });
        }
    });

}

Step 3: after entering the password, qq will request your callback address, and then jump to the login page you wrote. At this time, you need to request the background interface on that page and obtain access according to the qq code_ Token, openid, personal information, for details: maven project integration qqauth2 0 third party login details

$(function (){
    saveLoginUser();

})

//Get url parameter content
function GetQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);//search, query? And match the regular parameters
    if (r != null) return decodeURI(r[2]);
    return null;
}

//Operation after qq login
function saveLoginUser() {
    var code=GetQueryString("code");
    var loadingIndex = layer.load(2, { //icon supports passing in 0-2
        shade: [1, '#46c37b '], / / gray background with 0.5 transparency
        content: 'Logging in...',
        success: function (layero) {
            layero.find('.layui-layer-content').css({
                'padding-top': '45px',
                'width': '160px'
            });
        }
    });
    $.ajax({
        url: baseContext.path + 'user/loginAfter',
        type: 'GET',
        data: {code:code},
        dataType: 'json',
        success: function (data) {
            if (data.code == 100) {
                console.log("User information obtained successfully");
                //Save user information to localStorage
                localStorage.setItem("token", data.result.token);
                localStorage.setItem("userId", data.result.userId);
                localStorage.setItem("headImg", data.result.userInfo.headPhoto);
                localStorage.setItem("nickname", data.result.userInfo.nickname);
                //Close the window. At this time, the parent window will know that you have closed the window and jump to the home page
                window.open("","_self").close();
            }else{
                layer.confirm('Login failed. Please try again', {
                    btn: ['determine'], //Button
                    icon:2
                }, function(){
                    window.open("","_self").close();
                });
            }
        }
    });
}

Step 4: writing of background interface. Refer to: maven project integration qqauth2 0 third party login details , I've written down a few steps here, which are determined according to your business needs

package cn.funyan.user.controller;

import cn.funyan.base.basic.Res;
import cn.funyan.user.QQUserInfo;
import cn.funyan.user.UserAuths;
import cn.funyan.user.service.UserAuthsService;
import cn.funyan.user.service.UserService;
import cn.funyan.utils.HttpClientsUtils;
import cn.funyan.utils.URLEncodeUtil;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 *
 **/
@RestController
public class QqLoginController
{
	@Autowired
	private UserAuthsService userAuthsService;
	@Autowired
	private UserService userService;

	private String qqAppId="10108";
	private String qqAppSecret="5964bae5ac3b41b80256e9";
	private String qqRedirectUrl="https://funyan.cn/logining.html";


	@GetMapping("/getCode")
	public String getCode() throws Exception {
		//Splice url
		StringBuilder url = new StringBuilder();
		url.append("https://graph.qq.com/oauth2.0/authorize?");
		url.append("response_type=code");
		url.append("&client_id=" + qqAppId);
		//Callback address. The callback address needs to be encoded
		String redirect_uri = qqRedirectUrl;
		//transcoding 
		url.append("&redirect_uri="+ URLEncodeUtil.getURLEncoderString(redirect_uri));
		url.append("&state=ok");
		String result = HttpClientsUtils.get(url.toString(),"UTF-8");
		System.out.println(url.toString());
		return  url.toString();
	}

	//qq callback address, get qqtoken, get user unionid, user avatar, nickname and other information
	@GetMapping("loginAfter")
	public Res loginAfter(String code) throws Exception{
		//Step 1: get qqtoken
		if (code != null){
			System.out.println(code);
		}
		StringBuilder url = new StringBuilder();
		url.append("https://graph.qq.com/oauth2.0/token?");
		url.append("grant_type=authorization_code");
		url.append("&client_id=" + qqAppId);
		url.append("&client_secret=" + qqAppSecret);
		url.append("&code=" + code);
		//token url 
		String redirect_uri = qqRedirectUrl;
		//transcoding 
		url.append("&redirect_uri="+ URLEncodeUtil.getURLEncoderString(redirect_uri));
		String result = HttpClientsUtils.get(url.toString(),"UTF-8");
		System.out.println("url:" + url.toString());
		//Save the token
		String[] items = StringUtils.splitByWholeSeparatorPreserveAllTokens(result, "&");
		String accessToken = StringUtils.substringAfterLast(items[0], "=");
		//Step 2: obtain openid and unionId
		url.setLength(0);
		if (!StringUtils.isNotEmpty(accessToken)){
			return new Res().failed().setMsg("Unauthorized");
		}
		url.append("https://graph.qq.com/oauth2.0/me?")
				.append("access_token=" + accessToken)
		        .append("&unionid=1");
		result = HttpClientsUtils.get(url.toString(),"UTF-8");
		result= StringUtils.substringBetween(result, "\"openid\":\"", "\"}");
		String[] array =result.split("\",\"unionid\":\"");
		String openId=array[0];
		String unionId = array[1];
		System.out.println(openId+"------"+unionId);
		//Judge whether the database has this unionid, and if so, directly generate a token return
		UserAuths userAuths=new UserAuths();
		userAuths.setUnionId(unionId);
		userAuths.setOpenId(openId);
		userAuths.setType(1);
		userAuths=userAuthsService.selectOne(userAuths);
		if(userAuths!=null){
			return userService.qqLogin(userAuths.getUserId());
		}
		//Step 3: get user information
		url.setLength(0);
		url.append("https://graph.qq.com/user/get_user_info?")
				.append("access_token=" + accessToken)
				.append("&oauth_consumer_key=" + qqAppId)
				.append("&openid=" + openId);
		result = HttpClientsUtils.get(url.toString(),"UTF-8");
		Object json = JSON.parseObject(result,QQUserInfo.class);
		QQUserInfo user = (QQUserInfo)json;
		//Call registration interface
		Integer userId=userService.qqRegister(user.getNickname(),user.getFigureurl_qq());
		//Insert into third party login form
		userAuths=new UserAuths();
		userAuths.setOpenId(openId);
		userAuths.setUnionId(unionId);
		userAuths.setType(1);
		userAuths.setUserId(userId);
		userAuthsService.insert(userAuths);
		//Get token
		return userService.qqLogin(userId);
	}
}

Added by umer on Sun, 23 Jan 2022 02:57:10 +0200