小程序的登录注册

小程序的登录注册方法有微信直接授权,手机号+密码,密码登录等。这里我采用的是阿里云提供的接口来实现获取手机号,验证码。
因为采用阿里云的接口,需要阿里云的依赖和utils,自己可以去网上搜索一下,如果找不到可以在评论回复

通过授权获取openid

public class ApiUserInfoController {
private String openid;
    private String session_key;

    @Autowired
    private IRyUserInfoService userInfoService;

    /**
     * 获取openid
     *
     * @param code 临时登录凭证  openid(用户的唯一标识).
     *             appid(小程序唯一标识)  appsecret(小程序的app secret)  session_key(会话秘钥)
     * @return
     */
    @RequestMapping("/saveOpenId")
    @ResponseBody
    private AjaxResult saveOpenId(@RequestParam("code") String code) {

        String appid = "wxd9e2bb08cb0b012a";
        String appsecret = "c6e791e6d7ba86ae317bbf6a16a605b4";
        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        String resultString = "";
        CloseableHttpResponse response = null;
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid + "&secret=" + appsecret + "&js_code=" + code + "&grant_type=authorization_code";
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            URI uri = builder.build();
            // 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);
            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 解析json
        JSONObject jsonObject = (JSONObject) JSONObject.parse(resultString);
        session_key = jsonObject.get("session_key") + "";
        openid = jsonObject.get("openid") + "";
        // System.out.println("session_key==" + session_key);
        System.out.println("openid==" + openid);
        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.put("openId", openid);
        ajaxResult.put("sessionKey", session_key);
        RyUserInfo userInfo = new RyUserInfo();
        userInfo.setOpenId(openid);
        userInfoService.insertRyUserInfo(userInfo);
        ajaxResult.put("userId", userInfo.getUserId());
        return ajaxResult;
    }

小程序授权获取手机号

 public Object getPhoneNumber(String encryptedData, String session_key, String iv, String userId) {
        // 被加密的数据
        byte[] dataByte = Base64.decode(encryptedData);
        // 加密秘钥
        byte[] keyByte = Base64.decode(session_key);
        // 偏移量
        byte[] ivByte = Base64.decode(iv);
        try {
            // 如果密钥不足16位,那么就补足.  这个if 中的内容很重要
            int base = 16;
            if (keyByte.length % base != 0) {
                int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
                byte[] temp = new byte[groups * base];
                Arrays.fill(temp, (byte) 0);
                System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
                keyByte = temp;
            }
            // 初始化
            Security.addProvider(new BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
            AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
            parameters.init(new IvParameterSpec(ivByte));
            cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化
            byte[] resultByte = cipher.doFinal(dataByte);
            if (null != resultByte && resultByte.length > 0) {
                String result = new String(resultByte, "UTF-8");
                JSONObject obj = JSONObject.parseObject(result);
                String phone = obj.get("phoneNumber").toString();
                RyUserInfo userInfo = new RyUserInfo();
                userInfo.setUserId(Long.valueOf(userId));
                userInfo.setUserPhone(phone);
                userInfoService.updateRyUserInfo(userInfo);
                return userInfo;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

登录

 public AjaxResult login(@RequestParam("userId") String userId) {
        AjaxResult ajaxResult = new AjaxResult();
        try {
            RyUserInfo userInfo = new RyUserInfo();
            userInfo.setUserId(Long.valueOf(userId));
            userInfo.setIsInline(0);
            userInfoService.updateRyUserInfo(userInfo);
            ajaxResult.put("code", "0");
            return ajaxResult;
        } catch (Exception e) {
            e.printStackTrace();
            ajaxResult.put("code", "1");
            return ajaxResult;
        }
    }

退出登录

 public AjaxResult logout(@RequestParam("userId") String userId) {
        AjaxResult ajaxResult = new AjaxResult();
        try {
            RyUserInfo userInfo = new RyUserInfo();
            userInfo.setUserId(Long.valueOf(userId));
            userInfo.setIsInline(1);
            userInfoService.updateRyUserInfo(userInfo);
            ajaxResult.put("code", "0");
            return ajaxResult;
        } catch (Exception e) {
            e.printStackTrace();
            ajaxResult.put("code", "1");
            return ajaxResult;
        }
    }

通过手机号发送验证码

 public AjaxResult getCode(String phone, HttpServletRequest request) {
        SendCode sendCode = new SendCode();
        sendCode.getCode(phone, request);
        return AjaxResult.success("发送成功");
    }

校验session验证码

public AjaxResult compareCode(@RequestParam("code") String code, HttpServletRequest request) {
        AjaxResult ajaxResult = new AjaxResult();
//获取session中的验证吗
        HttpSession param = request.getSession();
        String Sparam = param.getAttribute("param").toString();
//        比较连个验证码
        if (Sparam.equals(code)) {
            ajaxResult.put("code", 0);
            return ajaxResult;
        } else {
            ajaxResult.put("code", 1);
            return ajaxResult;
        }

    }

在写代码前,我个人认为应该理清思路,想好需要什么接口,数据库需要什么,然后在实现

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值