首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 綜合教學

Java 整合第三方短信平台實現驗證碼發送與校驗完整方案

     編輯:Java 綜合教學

Java 整合第三方短信平台實現驗證碼發送與校驗完整方案

基於 Spring MVC + Spring + MyBatis 框架,整合第三方短信接口 (以 WebChinese 為例),實現註冊/登錄場景的短信驗證碼發送、Session 存儲、前端校驗閉環。

核心流程設計

  1. 前端輸入手機號 → 發送請求
  2. 後端生成 6 位隨機碼 → 調用第三方接口發送
  3. 發送成功 → 驗證碼存入 Session (設置 5 分鐘過期)
  4. 前端用戶輸入驗證碼 → 提交註冊
  5. 後端比對 Session 中驗證碼 → 一致放行、不一致拒絕

依賴準備

<dependency>
  <groupId>commons-httpclient</groupId>
  <artifactId>commons-httpclient</artifactId>
  <version>3.1</version>
</dependency>
<dependency>
  <groupId>commons-codec</groupId>
  <artifactId>commons-codec</artifactId>
  <version>1.4</version>
</dependency>
<dependency>
  <groupId>commons-logging</groupId>
  <artifactId>commons-logging</artifactId>
  <version>1.1.1</version>
</dependency>

第三方接口封裝 (SendMsg_webchineseController)

public class SendMsg_webchineseController {
    public static HashMap<String, String> getMessageStatus(String phone) throws Exception {
        HashMap<String, String> result = new HashMap<>();
        HttpClient client = new HttpClient();
        PostMethod post = new PostMethod("https://gbk.sms.webchinese.cn");
        
        post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=gbk");
        
        String code = VerifyingCodeGenerator.generate(); // 6位隨機碼
        NameValuePair[] data = {
            new NameValuePair("Uid", "你的用戶名"),
            new NameValuePair("Key", "你的密鑰"),
            new NameValuePair("smsMob", phone),
            new NameValuePair("smsText", "您正在註冊本站會員,本次驗證碼為:" + code + ",有效期5分鐘")
        };
        
        post.setRequestBody(data);
        client.executeMethod(post);
        
        String status = new String(post.getResponseBodyAsString().getBytes("gbk"));
        result.put("code", code);
        result.put("result", status); // "1" 表示成功
        
        post.releaseConnection();
        return result;
    }
}

Controller 層實現 (發送驗證碼端點)

@ResponseBody
@RequestMapping(value = UrlDefine.Register.CHECKMESSAGEWORK, method = RequestMethod.POST)
public Object sendCheckMessage(HttpServletRequest request, @RequestBody UserBean user) throws Exception {
    String phone = user.getTelephone();
    
    // 1. 檢查手機號是否已註冊
    if (userService.getByPhone(phone) != null) {
        return new Response(Status.ERROR, "該手機號已被註冊");
    }
    
    // 2. 調用短信接口
    HashMap<String, String> smsResult = SendMsg_webchineseController.getMessageStatus(phone);
    String status = smsResult.get("result");
    
    if ("1".equals(status.trim())) {
        // 3. 發送成功,存入 Session
        String code = smsResult.get("code");
        HttpSession session = request.getSession();
        session.setAttribute("sms_code", code);
        session.setMaxInactiveInterval(60 * 5); // 5分鐘過期
        logger.info("發送驗證碼: " + code);
        return new Response(Status.SUCCESS, "發送成功");
    } else {
        return new Response(Status.ERROR, "短信發送失敗: " + status);
    }
}

前端測試 (Postman)

Postman 請求 Postman 響應

請求:POST /register/checkMessageWork Body: {"telephone":"13800138000"}
響應:{"status":"SUCCESS","message":"發送成功"}

驗證碼校驗邏輯 (註冊提交時)

@RequestMapping(value = UrlDefine.Register.REGISTER, method = RequestMethod.POST)
public Object register(HttpServletRequest request, @RequestBody RegisterForm form) {
    HttpSession session = request.getSession();
    String sessionCode = (String) session.getAttribute("sms_code");
    
    if (sessionCode == null || !sessionCode.equals(form.getSmsCode())) {
        return new Response(Status.ERROR, "驗證碼錯誤或已過期");
    }
    
    // 驗證通過,執行註冊業務...
    session.removeAttribute("sms_code"); // 一次性使用,移除
    return userService.register(form);
}

關鍵技術點總結

環節關鍵點避坑提示
隨機碼生成使用 SecureRandom 或工具類,保證熵避免 Math.random() 可預測性
接口編碼第三方要求 GBK,需 getBytes("gbk") 解碼響應響應體編碼與請求頭 charset 一致
Session 存儲setMaxInactiveInterval(300) 設置 5 分鐘 TTL分佈式環境需用 Redis 共享 Session
防刷機制同手機號 60 秒限流、IP 限流、圖形驗證碼輔助防止短信轟炸攻擊
錯誤碼處理第三方返回非 "1" 均視為失敗,記錄日誌告警建立短信發送成功率監控大盤

生產環境擴展建議

  1. 分佈式 Session: Spring Session + Redis 替換單機 Session
  2. 異步發送: 引入消息隊列 (RabbitMQ/Kafka),Controller 即時返回,短信異步發送
  3. 多通道備援: 配置多家短信服務商,失敗自動切換
  4. 模板管理: 短信模板配置化,支援變量替換、審核流程
  5. 發送記錄審計: 記錄手機號、內容、狀態、耗時、服務商,便於追溯

短信驗證碼看似簡單,實則涉及安全、可用性、合規多個維度。從「能跑通」到「經得住生產考驗」,還有很長的路要走。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved