ThirdLoginController.java 2.96 KB
package cn.com.glsx.app.modules;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.com.glsx.app.common.enums.LoginType;
import cn.com.glsx.app.modules.entity.UserAuthRel;
import cn.com.glsx.app.modules.model.AppUser;
import cn.com.glsx.app.modules.model.QQOAuth2AccessToken;
import cn.com.glsx.app.modules.service.LoginService;
import cn.com.glsx.app.modules.service.UserService;
import cn.hutool.json.JSONUtil;
import com.glsx.plat.common.annotation.NoLogin;
import com.glsx.plat.core.web.R;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * 第三方登录
 *
 * @author liuyf
 */
@Slf4j
@RestController
public class ThirdLoginController {

    @Resource
    private UserService userService;

    @Autowired
    private LoginService loginService;

    @Autowired
    private WxMaService wxMaService;

    @NoLogin
    @GetMapping(value = "/qqAuth")
    public R qqAuth(@RequestParam String code) {
        //获取openId、unionId等
        QQOAuth2AccessToken accessToken = new QQOAuth2AccessToken();

        log.info("QQ code[{}]获取的Session信息为{}", code, JSONUtil.toJsonStr(accessToken));
        UserAuthRel authRel = loginService.qqAuth(accessToken);

        Map<String, Object> rtnMap = thirdLogin(LoginType.QQ, authRel);

        return R.ok().data(rtnMap);
    }

    @NoLogin
    @GetMapping(value = "/wechatAuth")
    public R wechatAuth(@RequestParam String code) throws WxErrorException {
        //获取openId、unionid、session_key
        WxMaJscode2SessionResult sessionInfo = wxMaService.getUserService().getSessionInfo(code);

        log.info("微信code[{}]获取的Session信息为{}", code, JSONUtil.toJsonStr(sessionInfo));
        UserAuthRel authRel = loginService.wechatAuth(sessionInfo);

        Map<String, Object> rtnMap = thirdLogin(LoginType.WECHAT, authRel);

        return R.ok().data(rtnMap);
    }

    private Map<String, Object> thirdLogin(LoginType loginType, UserAuthRel authRel) {
        Map<String, Object> rtnMap = new HashMap<>();

        Optional<Long> optUserId = Optional.ofNullable(authRel.getUserId());
        if (optUserId.isPresent()) {
            //已绑定本地账号
            AppUser user = userService.getAppUserByUserId(authRel.getUserId());
            String token = userService.createToken(user);
            rtnMap.put("user", user);
            rtnMap.put("token", token);
        } else {
            //未绑定本地账号,跳转登录界面登录,回传此id
            rtnMap.put("authRelId", authRel.getId());
        }
        return rtnMap;
    }

}