Springboot+vue+mongodb基于253的发送短信,把验证码存入数据库,然后验证用户输入的验证码

这些在253的技术文档里也有,只是放到项目中就是这种样子了

@RequestMapping(value = "/send",produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Map<String,Object> send(HttpServletRequest request){
        Map<String,Object> result = new HashMap<String,Object>();
        try {
            String charset = "utf-8";
            // 请登录zz.253.com 获取创蓝API账号(非登录账号,示例:N1234567)
            String account = "";
            // 请登录zz.253.com 获取创蓝API密码(非登录密码)
            String password = "";
            //短信发送的URL 请登录zz.253.com 获取完整的URL接口信息
            String smsSingleRequestServerUrl = "";
            // 设置您要发送的内容:其中“【】”中括号为运营商签名符号,多签名内容前置添加提交
            String code = getRandomCode();
            String msg = "【】您好,登录验证码是" + code;
            //手机号码
            String phone = request.getParameter("phone").trim();
            //状态报告
            String report = "true";
            String rj = "";

            if (verifyPhone(phone)==null){
                result.put("MSG", "非法用户");
                result.put("MSG",false);
            }else{
                SmsSendRequest smsSendRequest = smsSendRequestService.findByPhone(phone);
                if (smsSendRequest == null) {
                    smsSendRequest = new SmsSendRequest();
                    smsSendRequest.setAccount(account);
                    smsSendRequest.setPassword(password);
                    smsSendRequest.setMsg(msg);
                    smsSendRequest.setPhone(phone);
                    smsSendRequest.setReport(report);
                    smsSendRequest.setCode(code);
                    rj = JSON.toJSONString(smsSendRequestService.save(smsSendRequest));
                } else {

                    smsSendRequest.setCode(code);
                    smsSendRequest.setMsg(msg);

                    smsSendRequestService.updateCode(smsSendRequest);
                    rj = JSON.toJSONString(smsSendRequest);
                }

                String response = ChuangLanSmsUtil.sendSmsByPost(smsSingleRequestServerUrl, rj);

                SmsSendResponse smsSingleResponse = JSON.parseObject(response, SmsSendResponse.class);

                String msgid = smsSingleResponse.getErrorMsg();
                if ("".equals(msgid) || msgid == null) {
                    result.put(SystemStaticConst.MSG, "发送验证码成功");
                    result.put(SystemStaticConst.RESULT, SystemStaticConst.SUCCESS);
                } else {
                    result.put(SystemStaticConst.MSG, "发送验证码失败");
                    result.put(SystemStaticConst.RESULT, SystemStaticConst.FAIL);
                }
            }
        }catch(Exception e){
            result.put(SystemStaticConst.MSG, "发送验证码失败");
            result.put(SystemStaticConst.RESULT, SystemStaticConst.FAIL);
        }
        return result;
    }

生成随机6位数验证码的方法:

//随机生成6位数验证码
    public static String getRandomCode(){
        Random random = new Random();
        String result="";
        for (int i=0;i<6;i++){
            result+=random.nextInt(10);
        }
        return result;
    }
//在用户表中查找是否存在手机号
public User verifyPhone(String phone){
        User user = userService.findByLogin(phone);
        return user;
    }

效验验证码的方法:

@RequestMapping(value = "/verify",produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Map<String, Object> verify(HttpServletRequest request)  {
        Map<String, Object> result = new HashMap<>();
        try {
            SmsSendRequest smsSendRequest;
            String phone = request.getParameter("phone");
            User user = verifyPhone(phone);
            if (user==null){
                result.put("MSG", "非法用户");
                result.put("MSG", false);
            }else{
                Query query = new Query();
                query.addCriteria(Criteria.where("phone").is(phone));
                List<SmsSendRequest> sms = smsSendRequestService.find(query);
                smsSendRequest = sms.get(0);
                String code = request.getParameter("code");
                String codev = smsSendRequest.getCode();
                if (code.equalsIgnoreCase(codev)) {
                    smsSendRequestService.deleteById(smsSendRequest);
                    List<UserRole> roles = user.getRoles();
                    String rolenames = "";
                    for(UserRole ur:roles){
                        rolenames = rolenames + ur.getName()+ ",";
                    }
                    String JWT = Jwts.builder()
                            // 保存权限(角色)
                            .claim("authorities", rolenames.substring(0,rolenames.length()-1))
                            // 用户名写入标题
                            .setSubject(phone)
                            // 有效期设置
                            .setExpiration(new Date(System.currentTimeMillis() + SystemStaticConst.TOKEN_EXPIRATIONTIME))
                            // 签名设置
                            .signWith(SignatureAlgorithm.HS512, SystemStaticConst.TOKEN_SECRET)
                            .compact();
                    result.put("jwtToken", JWT);
                    result.put("userName",  userService.findByLogin(phone).getUserName());
                    result.put("login", phone);
                    result.put("MSG",true);
                } else {
                    result.put("MSG", "验证码错误");
                    result.put("MSG",false);
                }
            }
        }catch(Exception e){
            result.put("MSG", "系统错误");
            result.put("MSG",false);
        }
         return result;
    }

权限用不着的话可以注释掉,不影响效验。
SmsSendRequest类:

@Slf4j
@Data
@Setter
@Getter
@ToString
public class SmsSendRequest {
    private ObjectId id;
    //验证码
    private String code;

    /**
     * 创蓝API账号,必填
     */
    private String account;
    /**
     * 创蓝API密码,必填
     */
    private String password;
    /**
     * 短信内容。长度不能超过536个字符,必填
     */
    private String msg;
    /**
     * 机号码。多个手机号码使用英文逗号分隔,必填
     */
    private String phone;


//    /**
//     * 定时发送短信时间。格式为yyyyMMddHHmm,值小于或等于当前时间则立即发送,默认立即发送,选填
//     */
//    private String sendtime;
    /**
     * 是否需要状态报告(默认false),选填
     */
    private String report;
//    /**
//     * 下发短信号码扩展码,纯数字,建议1-3位,选填
//     */
//    private String extend;
//    /**
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
前端代码: ```vue <template> <div> <el-form :model="form" label-width="100px" ref="form"> <el-form-item label="手机号码" prop="phone"> <el-input v-model="form.phone" placeholder="请输入手机号码"></el-input> </el-form-item> <el-form-item label="验证码" prop="captcha"> <el-input v-model="form.captcha" placeholder="请输入验证码" style="width: 200px"></el-input> <el-button type="primary" @click="sendCaptcha" :disabled="isSending">{{ captchaText }}</el-button> </el-form-item> <el-form-item> <el-button type="primary" @click="submitForm">提交</el-button> </el-form-item> </el-form> </div> </template> <script> import { getCaptcha, login } from '@/api/user' export default { data() { return { form: { phone: '', captcha: '' }, captchaText: '获取验证码', isSending: false } }, methods: { sendCaptcha() { if (!this.form.phone) { this.$message.error('请输入手机号码') return } if (this.isSending) { return } this.isSending = true let count = 60 const interval = setInterval(() => { count-- if (count <= 0) { clearInterval(interval) this.captchaText = '重新获取' this.isSending = false } else { this.captchaText = `${count}s后重新获取` } }, 1000) getCaptcha(this.form.phone).then(() => { this.$message.success('验证码发送') }).catch(() => { clearInterval(interval) this.captchaText = '重新获取' this.isSending = false }) }, submitForm() { this.$refs.form.validate(valid => { if (valid) { login(this.form.phone, this.form.captcha).then(() => { this.$router.push('/') }).catch(error => { this.$message.error(error.message) }) } }) } } } </script> ``` 后端代码: ```java @RestController @RequestMapping("/api/user") public class UserController { @Autowired private RedisUtil redisUtil; @PostMapping("/captcha") public ResponseEntity<Object> getCaptcha(@RequestParam String phone) { // 生成4位随机验证码 String captcha = String.valueOf(new Random().nextInt(8999) + 1000); // 将验证码保存到redis中,有效期5分钟 redisUtil.set(phone, captcha, 5 * 60); // TODO 发送短信验证码 return ResponseEntity.ok().build(); } @PostMapping("/login") public ResponseEntity<Object> login(@RequestParam String phone, @RequestParam String captcha) { // 从redis中获取验证码 String redisCaptcha = (String) redisUtil.get(phone); if (StringUtils.isBlank(redisCaptcha)) { throw new BusinessException("验证码已失效,请重新获取"); } if (!StringUtils.equals(redisCaptcha, captcha)) { throw new BusinessException("验证码错误"); } // TODO 验证手机号码是否已注册 // TODO 如果未注册,则自动注册 // TODO 生成token返回给前端 return ResponseEntity.ok().build(); } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值