继续完成验证码

由于昨天的获取验证码只是实现了一半只完成了页面的基本逻辑和生成验证码但是还无法是发送短信,今天要在昨天的基础上实现用户的验证码发送短信。

 这里的调用发送短信的api我还是选择了使用阿里云,毕竟使用过,不用再进行注册。请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。

复制代码
package com.share.viedo_app.util;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.google.gson.Gson;

public class AliMes {
    public boolean sendMes(String phone,String code)
    {
        try {
            Config config=new Config()
                    .setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                    // 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
                    .setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
            config.endpoint = "dysmsapi.aliyuncs.com";
            Client client=new Client(config);
            SendSmsRequest request=new SendSmsRequest();
            request.phoneNumbers=phone;
            request.signName="益享";
            request.templateCode="SMS_468425087";
            request.templateParam="{\"code\":\""+code+"\"}";
            SendSmsResponse response=client.sendSms(request);
            System.out.println(response.getBody().getCode());
            if(response.getBody().code!=null&&response.getBody().getCode().equals("OK"))
            {
                return true;
            }
            else {
                return false;
            }
        }catch (Exception e)
        {
            System.out.println(e);
            return false;
        }

    }
}
复制代码

controller层

复制代码
    @GetMapping("/getcode")
    public Result getCode(@RequestParam String phone)//发送验证码
    {
        String code = String.valueOf(new Random().nextInt(899999) + 100000);
        AliMes aliMes=new AliMes();
        boolean result=aliMes.sendMes(phone,code);
        System.out.println(code);
        if(result)
        {return Result.success();
        }
        else {
            return Result.error("短信发送失败");
        }
    }
复制代码

 

然后我就开始寻找如何实现验证码的验证,该如何存储这个验证码

我在网上找到了redis来储存缓存

使用redis前需要先进行下载配置并运行

 配置

复制代码
package com.share.viedo_app.util;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;

@Configuration
public class RedisConfig {

    @Bean
    public RedisConnectionFactory redisConnectionFactory() {
        return new LettuceConnectionFactory("localhost", 6379);
    }

    @Bean
    public StringRedisTemplate stringRedisTemplate() {
        return new StringRedisTemplate(redisConnectionFactory());
    }
}
复制代码

然后在生成了验证码后就将其存入缓存中,在前端进行下一步验证后就取出来验证

复制代码
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private UserService userService;

    @GetMapping("/getcode")
    public Result getCode(@RequestParam String phone)//发送验证码
    {
        String code = String.valueOf(new Random().nextInt(899999) + 100000);
        AliMes aliMes=new AliMes();
        boolean result=aliMes.sendMes(phone,code);
        System.out.println(code);
        if(result)
        {
            stringRedisTemplate.opsForValue().set(phone, code, Duration.ofMinutes(5));
            System.out.println(result);
            return Result.success();
        }
        else {
            return Result.error("短信发送失败");
        }
    }
    @GetMapping("/verifySmsCode")//验证码验证
    public Result verifySmsCode(@RequestParam String phone,@RequestParam String code)
    {
        String savedCode = stringRedisTemplate.opsForValue().get(phone);
        if (savedCode != null && savedCode.equals(code)) {
            // 验证成功,清除验证码
            System.out.println("验证成功");
            stringRedisTemplate.delete(phone);
            return Result.success();
        }
        return Result.error("验证失败,验证码错误或已过期");
    }
复制代码

然后就开始设计输入密码的页面

复制代码
            <view v-else class="getcodecontainer">
                <view class="logo">
                  <!-- 这里放置你的应用 logo -->
                  <image src="/static/logo.png" class="logo-img" mode="aspectFit" />
                </view>
                <view class="form-group">
                  <text class="label">设置密码:</text>
                  <input type="password" v-model="password" placeholder="请输入密码" />
                </view>
                <view class="form-group">
                  <text class="password-requirement">8-20个字符,必须包含字母和数字</text>
                </view>
                <view class="form-group">
                  <text class="label">确认密码:</text>
                  <input type="password" v-model="confirmPassword" placeholder="请再次输入密码" @blur="checkPasswordMatch" />
                </view>
                <button class="regis-btn" @click="register" :disabled="!isFormValid">注册</button>
                <text  class="error-msg">{{passwordError}}</text>
            </view>
            <view class="login-link" @click="goToLoginPage">已有账号,去登录</view>
        </view>
复制代码

密码初步检验

复制代码
        isPasswordMatch() {
          return this.password === this.confirmPassword;
        },
        isPasswordValid() {
          return this.password.length >= 8 && this.password.length <= 20 && /\d/.test(this.password) && /[a-zA-Z]/.test(this.password);
        },
        isFormValid() {
          return this.isPasswordMatch && this.isPasswordValid;
        }    
复制代码
复制代码
    checkPasswordMatch() {
      if (!this.isPasswordMatch) {
        this.passwordError = '两次输入的密码不一致';
      } else {
        this.passwordError = '';
      }
    },      
复制代码
posted @ 2024-06-18 01:25  财神给你送元宝  阅读(11)  评论(0编辑  收藏  举报