微信h5页面静默登录

https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html#0
看微信开放平台 h5网页授权
第一个接口
根据当前用户token 获取用户id,查询用户是否授权
代码只可参考不能赋值

  @GetMapping("/h5-auth")
    @ApiOperation(value = "用户h5端是否授权",notes="传入用户id")
    public Result isAuth(){
    	根据token 获取登录用户id 判断静默登录是否授权
        String userId = getAppUserId();
        AppUser appUser = appUserService.getById(userId);
        if(StringUtils.isEmpty(appUser.getH5OpenId())){
            return Result.ok(false);
        }else{
            return Result.ok(true);
        }
    }

第二步 根据用户授权,获取用户openid

 @GetMapping("/h5-openId")
    @ApiOperation(value = "获取h5用户openId",notes="传入code")
    @NoToken
    public Result isAuth(String code){
        RestTemplate restTemplate = new RestTemplate();
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={appId}&secret={secret}&code={code}&grant_type=authorization_code";
        //设置请求参数
        Map<String, String> params = new HashMap<>();
        params.put("appId", WechatConstants.WECHAT_MP_APPID);
        params.put("secret", WechatConstants.WECHAT_MP_SECRET);
        params.put("code", code);
        String json = restTemplate.getForObject(url, String.class, params);
        JSONObject result = JSON.parseObject(json);
        return Result.ok(result);
    }

第三静默登录
指生成一个新的账号或者登录帐号,生成token

  @NoToken
    @GetMapping("/h5-invite")
    @ApiOperation(value = "h5邀请静默登录接口",notes="传入openid")
    public Result h5Invite(String openid, HttpServletResponse response){
        QueryWrapper<AppUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("h5_open_id",openid);
        AppUser appuser = appUserService.getOne(queryWrapper);
        if(Objects.isNull(appuser) || appuser.getId()==null){
            //如果没有就注册
            appuser = new AppUser();
            appuser.setH5OpenId(openid);
//            String mark = RandomStringGeneratorUtil.generateRandomString(6);
//            appuser.setMark(mark);/**唯一标识*/
//            AppUserSequence sequenceInfo = appUserSequenceService.list().get(0);
//            String mark = SquenceUtil.generateCode(sequenceInfo.getSquenceId());
//            appuser.setMark(mark);
            IntegralConfig configure = integralConfigService.getOne(new UpdateWrapper<IntegralConfig>().eq("id",1).eq("status",1));
            if(Objects.nonNull(configure)){/**积分任务不为空*/
                appuser.setIntegral(new BigDecimal(configure.getIntegral()));


                configure.setSumProfit(configure.getSumProfit()
                        .add(new BigDecimal(configure.getIntegral())));
                if(!integralConfigService.updateById(configure)){
                    throw new RuntimeException("更新总的奖励积分");
                }

            }
            appUserService.save(appuser);
            String mark = SquenceUtil.generateCode(Long.parseLong(appuser.getId()));/**根据用户id生成唯一标识*/
            appuser.setMark(mark);
            if(!appUserService.update(new UpdateWrapper<AppUser>().set("mark",appuser.getMark()).eq("id",appuser.getId()))){
                throw new RuntimeException("更新用户标识失败");
            }

            Integral integral = new Integral();
            integral.setUid(appuser.getId());
            integral.setCreateTime(new Date());
            integral.setType(IntegralType.TYPE_INCOME);
            integral.setContent("登录注册获得积分");
            integral.setProfit(new BigDecimal(configure.getIntegral()));
            integral.setBalance(appuser.getIntegral());
            integral.setSourceType(4);
            integral.setConfigId(configure.getId());
            if(!integralService.save(integral)){
                throw new RuntimeException("更新用户积分失败");
            }



        }
        Map<String, Object> result = new HashMap<>();
        String token = UUID.randomUUID().toString() + '-' + appuser.getId();
        redisUtil.set(WechatConstants.APP_NAME + "_APP_TOKEN_" + appuser.getId(), token,60 * 60 * 24 * 7);
        result.put("userInfo", appuser);
        result.put("token", token);
        Cookie cookie = new Cookie("token", token);
        cookie.setMaxAge(60 * 60 * 24 * 7); //cookie超时时间 单位秒
        cookie.setPath("/"); //设置cookie的有效路径为跟路径
        response.addCookie(cookie);
        return Result.OK(result);
    }
  • 8
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在微信H5页面实现微信授权登录,可以按照以下步骤进行操作: 1. 在微信公众平台上申请开发者账号,并创建一个用于开发的公众号。 2. 在公众号设置中,将“网页授权域名”设置为你的H5页面所在的域名。 3. 引入微信JS-SDK,获取JS-SDK签名。 4. 在微信开放平台申请网页授权的方式,获取到AppID和AppSecret。 5. 在后端服务器中,通过AppID和AppSecret获取access_token和openid。 6. 在前端页面中,通过微信JS-SDK的wx.config初始化配置,包括appId、timestamp、nonceStr、signature等参数。 7. 调用微信JS-SDK的wx.ready方法,初始化成功后进行接下来的操作。 8. 在前端页面中,通过微信JS-SDK的wx.checkJsApi方法,判断当前客户端版本是否支持指定的js接口,如微信登录相关接口。 9. 在前端页面中,调用微信JS-SDK的wx.login方法,显示微信登录按钮,用户点击按钮后会调用wx.login方法,获取code。 10. 前端将获取到的code通过ajax等方式发送给后端服务器。 11. 后端服务器通过code、AppID和AppSecret等参数向微信服务器发送请求,获取access_token和openid。 12. 后端服务器将获取到的access_token和openid返回给前端。 13. 前端根据获取到的access_token和openid进行相应的处理,例如获取用户信息,实现微信登录功能。 需要注意的是,以上步骤中需要在微信公众平台、微信开放平台和自己的后端服务器进行相应的配置和开发工作,确保整个流程的正确性和安全性。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值