繼續完成驗證碼

财神给你送元宝發表於2024-06-18

由於昨天的獲取驗證碼只是實現了一半隻完成了頁面的基本邏輯和生成驗證碼但是還無法是傳送簡訊,今天要在昨天的基礎上實現使用者的驗證碼傳送簡訊。

 這裡的呼叫傳送簡訊的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 = '';
      }
    },      
複製程式碼

相關文章