java后端-qq登录

项目代码复制出来的,请自行验证

 

/**
     * qq获取unionid
     *
     * @param accessToken
     * @return
     */
    public String getUnionid(String accessToken) {
        try {
            RestTemplate restTemplate = new RestTemplate();
            //if (StringUtils.isBlank(accessToken)) return AjaxJson.error("accessToken不能为空");
            String url = "https://graph.qq.com/oauth2.0/me?access_token=" + accessToken + "&unionid=" + "1" + "&fmt=" + "json";
            // 返回结果转换为json对象
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
            HttpEntity<String> entity = new HttpEntity<String>(headers);
            ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
            String body = responseEntity.getBody();
            // 返回结果转换为json对象
            JSONObject jObject = JSONObject.parseObject(body);
            String unionid = jObject.getString("unionid");
            return unionid;
        } catch (RestClientException e) {
            e.printStackTrace();
        }
        return null;
    }
/**
     * QQ授权登录
     *
     * @param accessToken accessToken
     * @return
     */
    @RequestMapping("/qqLogin")
    public AjaxJson qqLogin(String accessToken) throws Exception {
        if (StringUtils.isBlank(accessToken)) return AjaxJson.error("accessToken不能为空");
        String unionid = getUnionid(accessToken);
        Member qquniqueId = memberService.findQquniqueId(unionid);
        if (qquniqueId == null) {
            AjaxJson json = new AjaxJson();
            json.setCode(101);
            json.setMsg("请前往绑定手机号");
            json.setSuccess(false);
            json.put("unionid", unionid);
            return json;
        }
        
        String token = JWTUtils.createAccessToken(qquniqueId.getId(), qquniqueId.getPhone(), qquniqueId.getId());
        return AjaxJson.success("登陆成功").put("token", token).put("user", qquniqueId);


    }

无用代码自己删除即可

 

posted @ 2022-03-10 15:37  知行IT讲堂  阅读(185)  评论(0编辑  收藏  举报