天天看点

小程序登录例子,获取code 以及用code获取微信唯一标识。

最近写了一个小程序,写下博客记录,便于以后查阅。也分享出来,希望可以帮助到新人,也希望有大佬可以指出我代码中不规范或者错误的地方!

public ResponseUtils code2Id(String code) throws Exception {
        String parm = "";
        parm = "js_code=" + code + "&" + "appid="+你的appid+"&secret="+你的secret;
        //appid和secret在微信公众平台的小程序后台管理可以获取,code是前端获取后传给你,下面附上前端代码片段。
        String s = HttpRequest.sendPost("https://api.weixin.qq.com/sns/jscode2session?&grant_type=authorization_code", parm);
        //因为返回json字符串,所有转成json对象处理。
        JSONObject jo = JSON.parseObject(new String(s.getBytes(), "utf-8"));
        Object openid = jo.get("openid");
        if (openid == null) {
            Object errmsg = jo.get("errmsg");
            return ResponseUtils.fail(errmsg.toString());
        }
        SecurityUtils.getSubject().getSession().setAttribute("userId", openid);

        //  这儿判断数据库中是否有本用户的数据
        //  没有的话要初始化用户数据

        UserList userList = userListDao.selectByOpenId(openid.toString());
        if (userList == null) {

            userList = new UserList();
            userList.setOpenId(openid.toString());
            userList.setCouponId("");
            userList.setBalance(new BigDecimal(0));
            userList.setBankCard(JSONObject.toJSONString(new ArrayList<bankCar>()));
            userList.setCredit("100");
            userList.setState("1");
            userList.setMember("0");

            int insert = userListDao.insert(userList);

            if (insert <= 0) {
                throw new Exception();
            }
        }

        HashMap<String, Object> stringStringHashMap = new HashMap<>();
        stringStringHashMap.put("userInfo", userList);
        stringStringHashMap.put("token", 	 SecurityUtils.getSubject().getSession().getId().toString());
        return ResponseUtils.ok("登录成功", stringStringHashMap);
    }
           

附微信js获取code方法。

wx.login({
      success (res) {
        console.log(res.code)
      },
      fail: (res) => {
        console.log('LOGIN失败',res)
        reject(res);
      }
    })