记录开发内容demo-java第三方WX登录


前言

第三方登录之PCWX生成二维码 成功并回调


一、所需参数

    @Resource
    private UserAccountService userAccountService;

    @Resource
    private RedisCache redisCache;

    //应用AppID
    private String wxAppId = "";

    //应用AppSecret
    private String wxAppSecret = "";

    //微信Scope,固定snsapi_login
    private String wxScope = "snsapi_login";

    //回调方法路径
    yml配置
    project:
  	  servlet: xxx
    @Value("${project.servlet}")
    private String wxCallback;
	//模版
    private RestTemplate restTemplate = new RestTemplate();

二、前端调用接口

1.生成二维码

代码如下(示例):

    /**
     * 生成登录二维码
     * return: 前端展示二维码路径,可以直接用a标签包裹
     **/
    @GetMapping("/getCode")
    public R getCode(String type) throws UnsupportedEncodingException {
        String wxOauthUrl = "https://open.weixin.qq.com/connect/qrconnect?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect";
        String wx_redirect_uri = URLEncoder.encode(wxCallback+ "/wxLogin/wxCallback", "utf-8");
        wxOauthUrl =  wxOauthUrl.replace("APPID",wxAppId).replace("REDIRECT_URI",wx_redirect_uri).replace("SCOPE",wxScope);
        //判断是否 绑定微信号
        if ("1".equals(type))
        //redis记录
         redisCache.setCacheObject("user",SecurityUtil.getCurrentUserId());
         //二维码
        return data(wxOauthUrl);
    }

2.成功回调

代码如下(示例):


    /**
     *回调方法(用户扫描二维码授权后调用)
     **/
    @GetMapping("/wxCallback")
    public void wxCallback(@RequestParam(name = "code", required = false) String code,HttpServletResponse response) throws IOException {
        if (code == null || "".equals(code)) {
//            return "用户禁止授权";
            return;
        }

        //1.通过code获取access_token
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
        url = url.replace("APPID", wxAppId).replace("SECRET", wxAppSecret).replace("CODE", code);
        ResponseEntity<String> tokenData = restTemplate.getForEntity(url, String.class);
        String tokenInfoStr = tokenData.getBody();

        JSONObject tokenInfoObject = JSONObject.parseObject(tokenInfoStr);
        R.ok("tokenInfoObject:{}", tokenInfoObject);
        if (tokenInfoObject.getString("access_token") == null || "".equals(tokenInfoObject.getString("access_token"))) {
//            return "用code获取access_token失败";
            return;
        }

        //2.通过access_token和openid获取用户信息
        String userInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID";
        userInfoUrl = userInfoUrl.replace("ACCESS_TOKEN", tokenInfoObject.getString("access_token")).replace("OPENID", tokenInfoObject.getString("openid"));
        ResponseEntity<String> userData = restTemplate.getForEntity(userInfoUrl, String.class);
        String userInfoStr = userData.getBody();
        JSONObject userInfoObject = JSONObject.parseObject(userInfoStr);
        if (userInfoObject.getString("openid") == null || "".equals(userInfoObject.getString("openid"))) {
//            return  "获取用户信息失败";
            return;
        }
        //第三方唯一id
        String openid = userInfoObject.getString("openid");
        //-----------业务处理
        LambdaQueryWrapper<UserAccount> wrapper = Wrappers.lambdaQuery(new UserAccount()).eq(UserAccount::getWxOpenid, openid).ne(UserAccount::getIsDelete, 1);
        UserAccount userAccount = userAccountService.getOne(wrapper);
        //判断是否是第三方绑定
        if (redisCache.getCacheObject("user") !=null ){
            LambdaQueryWrapper<UserAccount> wrapper1 = Wrappers.lambdaQuery(new UserAccount()).eq(UserAccount::getId, redisCache.getCacheObject("user")).ne(UserAccount::getIsDelete, 1);
            UserAccount userAccount1 = userAccountService.getOne(wrapper1);
            userAccount1.setWxOpenid(openid);
            //判断是否已被绑定
            if (userAccount !=null){
                userAccount.setWxOpenid(null);
                userAccountService.updateByPrimaryKey(userAccount);
            }
            userAccountService.updateByPrimaryKey(userAccount1);
            StpUtil.login(userAccount1.getId(), "pc");
            redisCache.deleteObject("user");
            response.sendRedirect("http://xxx/#/?token=" + StpUtil.getTokenValue());
            //判断用户是否存在直接登录
        } else if (userAccount != null) {
            StpUtil.login(userAccount.getId(), "pc");
            response.sendRedirect("http://xxx/#/?token=" + StpUtil.getTokenValue());
            //用户不存在注册登录
        }else{
            UserAccount userAccount1 = new UserAccount();
            String salt = "qazwsx";
            userAccount1.setSalt(salt);//加密方式、、、、、、
            String randomStr = String.valueOf((long) ((Math.random() * 9.0 + 1) * (Math.pow(10, 10 - 1))));
            userAccount1.setNickName(randomStr);
            userAccount1.setRegistrationTime(new Date());
            userAccount1.setType(0);
            userAccount1.setPicture("xxx");
            userAccount1.setWxOpenid(openid);
             userAccountService.save(userAccount1);
            StpUtil.login(userAccount1.getId(), "pc");
            response.sendRedirect("http://xxx/#/?token=" + StpUtil.getTokenValue());
        }

        /**
         * 根据openid查询平台用户:
         *  1. 如果没有查询到用户,则将openid与平台用户绑定,或者注册新账户
         *  2. 如果查询到用户,则调用本地登录方法
         */
    }

总结

第三方微信登录 首先调用生成二维码 扫码登陆成功后回调

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值