java实现阿里云短信验证注册--详细教程

java实现阿里云短信验证注册–详细教程

  1. .项目中先引入依赖
<!--阿里云短信包-->
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-core</artifactId>
            <version>4.4.0</version>
        </dependency>
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-dysmsapi</artifactId>
            <version>1.0.0</version>
        </dependency>
  • .在配置文件中配置相关的信息

java实现阿里云短信验证注册--详细教程_第1张图片

  • .控制层代码
//发送短信验证码
    @GetMapping(value = "/sendsms/{phone}")
    public RestResponse sendSms(@PathVariable String phone) {
     
        try {
     
            userService.sendSms(phone);
            return RestResponse.ok("发送成功");
        } catch (Exception e) {
     
            e.printStackTrace();
            return RestResponse.fail(2, e.getMessage());
        }
    }
  • .业务层代码
//发送短信
    @Override
    public void sendSms(String phone) {
     

        User user = userStudentMapper.selectOne(
                new LambdaQueryWrapper<User>()
                        .eq(StringUtils.isNotBlank(phone), User::getPhone, phone)
                        .last("limit 1")

        );

        if (ObjectUtil.isNotNull(user)) {
     
            throw new RuntimeException("您已注册~");
        }

        String code = RandomStringUtils.randomNumeric(6);
        String accessKeyId = env.getProperty("aliyun.sms.accesskeyid");
        String accessSecret = env.getProperty("aliyun.sms.secret");
        DefaultProfile profile = DefaultProfile.getProfile("default", accessKeyId, accessSecret);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", signName);
        request.putQueryParameter("TemplateCode", templateCode);
        request.putQueryParameter("TemplateParam", "{\"code\":\"" + code + "\"}");

        try {
     
            CommonResponse response = client.getCommonResponse(request);
        } catch (ClientException e) {
     
            e.printStackTrace();
        }

        redisTemplate.opsForValue().set("code:" + phone, code, 5, TimeUnit.MINUTES);
    }
  • 注册控制层
    /**
     * 注册
     */
    @PostMapping("/register/{code}")
    public RestResponse register(@PathVariable String code, @RequestBody User user) {
     

        String password = user.getPassword();
        if (password.length() < 6) {
     
            return RestResponse.fail(SystemCode.ParameterValidError.getCode(), "密码不能少于六位~");
        }

        String checkCode = redisTemplate.opsForValue().get("code:" + user.getUserName());
        if (StringUtils.isEmpty(checkCode)) {
     
            return RestResponse.fail(SystemCode.ParameterValidError.getCode(), "请重新获取验证码~");
        }

        if (!code.equals(checkCode)) {
     
            return RestResponse.fail(SystemCode.ParameterValidError.getCode(), "验证码不正确~");
        }

        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getUserName, user.getUserName());
        User user1 = userStudentMapper.selectOne(lambdaQueryWrapper);
        if (user1 != null) {
     
            return RestResponse.fail(SystemCode.ParameterValidError.getCode(), "该手机号已注册啦~");
        }

        try {
     
            String encodePwd = authenticationService.pwdEncode(user.getPassword());
            user.setPassword(encodePwd);
            user.setRole(1);
            userService.register(code, user);
            return RestResponse.ok("注册成功");
        } catch (Exception e) {
     
            e.printStackTrace();
            return RestResponse.fail(SystemCode.ParameterValidError.getCode(), e.getMessage());
        }

    }
  • 注册业务层
    //注册
    @Override
    public void register(String code, User user) {
     
        user.setUserName(user.getUserName());
        user.setPhone(user.getUserName());
        user.setCreateTime(new Date());
        user.setStatus(1);
        user.setDeleted(false);
        user.setUserUuid(UUID.randomUUID().toString());
        userStudentMapper.insert(user);
    }

代码有些不太规范,请见谅!

你可能感兴趣的:(springboot,阿里云,java,spring)