微信小程序登入(Java服务器)

1, 首先前端会调用授权接口这个不用管, 调用授权接口以后, 会拿到微信用户的头像, 名称, 前端的朋友请往这边走, 微信小程序登入流程, 你可能走错片场了,  我们讨论的是后台的登入

2, 我只需要知道, 当前端调用微信的授权接口以后, 有一个很重要的参数, 那就是code, 这个code是微信授权以后下发的, 我们拿到这个code , 就可以去微信服务器, 拿到这个用户在微信的上面的唯一标识, 理论上我们需要三个参数,  根据业务不同

code :  微信授权以后的就更随机验证码似的

username:  你可要可不要, 我觉得你最好还是好了

userimage: 用户的头像,  这个最好存起来,

上面这三个参数后台都不需要管, 而是前端调用授权接口以后就会有的, 让前端发送回后台就好了

 

3, 使用http请求工具访问微信获取用户信息, http请求工具

    登入控制器

 @RequestMapping("/login")
    public ResultMap login(@Param("code") String code, HttpServletRequest request, @Param("inviteId") final Long inviteId){

            ResultMap resultMap = new ResultMap();
            resultMap.setSuccess(true);
            Map data = resultMap.getData();
        try {
            Map<String,String[]> parameterMap = request.getParameterMap();

            if (StringUtils.isEmpty(code)) {
                throw new RuntimeException("参数异常");
            }

            //去微信查询用户的openid
            StringBuilder urlPath = new StringBuilder("https://api.weixin.qq.com/sns/jscode2session"); 
            urlPath.append(String.format("?appid=%s", appId)); //appid
            urlPath.append(String.format("&secret=%s", secret)); //secretid
            urlPath.append(String.format("&js_code=%s", code));
            urlPath.append(String.format("&grant_type=%s", "authorization_code"));
            JSONObject object = HttpUtil.doGet(urlPath.toString());

            //工具类返回的数据封装成map了
            final Map map = object.parseObject(object.toJSONString());

            //这个就是我们要的
            String openId = (String) map.get("openid");
            String sessionKey = (String) map.get("session_key");

            if (openId == null){
                throw new RuntimeException("登入code错误");
            }

            //查询用户, 拿着openid去数据库查
            Account account = accountService.findByOpenid(openId);

            //查不到就代表未注册
            if(account == null){
                //新用户, 保存参数到数据库
            }else{
                //老用户, 登入操作
            }
     
            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
            ResultMap resultMap = new ResultMap();
            resultMap.setSuccess(false);
            resultMap.setMsg("登入失败");
            return resultMap;
        }
    }

登入以后, 根据去微信查询的信息, 判断哪个openid在数据库里面存在不存在, 判断是否为老用户, 还是新用户, 新用户就做注册, 老用户就登入, 关于微信小程序, 服务器如果保持登入态, 点击这里

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章