Springboot项目中使用手机号短信验证码注册登录实现

发布于:2025-06-25 ⋅ 阅读:(22) ⋅ 点赞:(0)

本文将介绍如何在Spring Boot应用中实现短信验证码注册和登录功能,为用户提供便捷的移动端认证体验。

1. 功能概述

我们将实现以下功能:

  • 手机号+验证码注册
  • 手机号+验证码登录

2. 技术栈

  • Spring Boot 3.2.0
  • 互亿无线短信平台
  • MyBatis Flex
  • JWT

原文链接:https://blog.ybyq.wang/archives/647.html

3. 实现步骤

3.1 短信服务集成

首先,需要在application.properties中配置短信平台信息:

# 短信配置
sms.account=C09251523
sms.apikey=826efdf7322e3c49355428a523c10eec

3.2 创建短信工具类

创建SmsUtil工具类处理短信发送:

@Component
public class SmsUtil {
   
    private static final Logger logger = LoggerFactory.getLogger(SmsUtil.class);
    
    // 短信发送API地址
    private static final String SMS_API_URL = "http://106.ihuyi.com/webservice/sms.php?method=Submit";
    
    // API账号和密码
    @Value("${sms.account:C09***523}")
    private String account;
    
    @Value("${sms.apikey:826efdf7322e3c49355***a523c10eec}")
    private String apiKey;
    
    /**
     * 发送短信验证码
     * @param phone 手机号
     * @param code 验证码
     * @return 发送结果,包含code和msg
     */
    public Map<String, String> sendVerificationCode(String phone, String code) {
   
        Map<String, String> result = new HashMap<>();
        
        try {
   
            // 短信内容
            String content = "您的验证码是:" + code + "。请不要把验证码泄露给其他人。";
            
            // 发送请求
            String response = sendSmsRequest(phone, content);
            
            // 解析结果
            result = parseXmlResponse(response);
            
            // 记录日志
            if ("2".equals(result.get("code"))) {
   
                logger.info("短信发送成功,手机号: {}, 验证码: {}", phone, code);
            } else {
   
                logger.error("短信发送失败,手机号: {}, 错误信息: {}", phone, result.get("msg"));
            }
            
        } catch (Exception e) {
   
            logger.error("发送短信验证码异常", e);
            result.put("code", "0");
            result.put("msg", "系统异常,短信发送失败");
        }
        
        return result;
    }
    
    // 省略发送请求和解析响应的方法...
}

3.3 验证码生成和存储

UserServiceImpl中实现验证码管理:

// 在UserServiceImpl中
private final Map<String, String> smsCodeCache = new HashMap<>();

@Override
public boolean sendSmsCode(String phone, String type) {
   
    try {
   
        // 校验手机号格式
        if (!isValidPhoneNumber(phone)) {
   
            return false;
        }
        
        // 生成6位随机验证码
        String code = generateRandomCode(6);
        
        // 将验证码存入缓存,实际项目中应使用Redis等缓存服务
        smsCodeCache.put(phone + ":" + type, code);
        
        // 发送短信
        Map<String, String> result = smsUtil.sendVerificationCode(phone, code);
        
        // 检查发送结果
        return "2".equals(result.get("code"));
    } catch (Exception e) {
   
        logger.error("发送短信验证码失败", e);
        return false;
    }
}

@Override
public String getSmsCode(String phone, String type) {
   
    return smsCodeCache.get(phone + ":" + type);
}

@Override
public void removeSmsCode(String phone, String type) {
   
    smsCodeCache.remove(phone + ":" + type);
}

3.4 控制器实现

发送短信验证码
@PostMapping("/send/sms")
public ResponseEntity<?> sendSmsCode(
        @RequestParam @NotBlank @Pattern(regexp = "^1[3-9]\\d{9}$", message = 

网站公告

今日签到

点亮在社区的每一天
去签到