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

Java 整合第三方短信平台發送驗證碼完整實戰(Spring MVC + MyBatis)

     編輯:Java 相關知識

業務流程

  1. 用戶提交手機號 → 後端生成 6 位隨機碼
  2. 驗證碼存入 Session(有效期 5 分鐘)
  3. 調用第三方 HTTP 接口發送短信
  4. 返回發送結果,前端提示用戶

第三方接口封裝

依賴:commons-httpclient-3.1.jar、commons-codec-1.4.jar、commons-logging-1.1.1.jar

public class SendMsgWebchineseController {
    public static Map<String, String> send(String phone) throws Exception {
        Map<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分鐘內有效")
        };
        result.put("code", code);
        post.setRequestBody(data);
        client.executeMethod(post);

        String resp = new String(post.getResponseBodyAsString().getBytes("gbk"));
        result.put("result", resp);  // "1" 成功
        post.releaseConnection();
        return result;
    }
}

Controller 實現

@ResponseBody
@PostMapping("/register/sendCode")
public Response sendCode(@RequestBody UserBean user) {
    String phone = user.getTelephone();
    if (userService.existsByPhone(phone)) {
        return Response.error("手機號已註冊");
    }
    try {
        Map<String, String> res = SendMsgWebchineseController.send(phone);
        if ("1".equals(res.get("result").trim())) {
            request.getSession().setAttribute("smsCode", res.get("code"));
            request.getSession().setMaxInactiveInterval(300);
            return Response.success("發送成功");
        }
    } catch (Exception e) {
        log.error("短信發送異常", e);
    }
    return Response.error("發送失敗,請稍後重試");
}

Postman 測試驗證

  • POST https://localhost:8080/register/sendCode
  • Body: {"telephone":"13800000000"}
  • 響應: {"status":"SUCCESS","message":"發送成功"}

生產級增強建議

  1. 限流:同手機號/IP 60s 內僅 1 次(Redis 計數器 + Lua 腳本)
  2. 加密存儲:Session 存 MD5(code + salt),校驗比對摘要
  3. 多通道:主通道(阿里云)+ 備用通道(騰訊云),失敗自動切換
  4. 異步化:引入 MQ 削峰,接口秒級響應
  5. 日誌審計:記錄發送請求、響應、耗時,便於排查到達率問題
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved