操作流程
- 注冊驗證碼平臺
- 創建驗證碼模版
- 開始集成(無需引入第三方庫)
注冊并登陸中昱維信驗證碼平臺
獲取AppID和AppKey。
創建驗證碼模版
創建驗證碼模版,獲取驗證碼模版id
開始集成
- 創建controller
import org.springframework.web.bind.annotation.*; @RestController
@RequestMapping("/api/sms")
public class SmsVerificationController { private final SmsVerificationService smsVerificationService; public SmsVerificationController(SmsVerificationService smsVerificationService) { this.smsVerificationService = smsVerificationService; } @GetMapping("/send") public String sendVerificationCode(@RequestParam String phone) { smsVerificationService.sendVerificationCode(phone); return "發送成功 "; } @PostMapping("/verify") public String verifyCode(@RequestParam String phone, @RequestParam String code) { if (smsVerificationService.verifyCode(phone, code)) { return "驗證成功"; } else { return "驗證碼錯誤"; } }
}
- 創建service
import java.util.concurrent.ConcurrentHashMap;
import java.util.UUID; public class SmsVerificationService { // 使用ConcurrentHashMap來存儲驗證碼和手機號的映射關系 也可以用session存儲private static ConcurrentHashMap<String, String> verificationCodeMap = new ConcurrentHashMap<>(); // 生成隨機驗證碼 private static String generateVerificationCode() { return UUID.randomUUID().toString().substring(0, 6); } // 發送驗證碼 public void sendVerificationCode(String phoneNumber) { // 生成驗證碼 String code = generateVerificationCode(); // 存儲驗證碼 verificationCodeMap.put(phoneNumber, code); // 調用短信服務API發送驗證碼 sendSms(phoneNumber, code); } // 驗證驗證碼 public boolean verifyCode(String phoneNumber, String inputCode) { // 從緩存中獲取存儲的驗證碼 String storedCode = verificationCodeMap.get(phoneNumber); // 驗證輸入的驗證碼是否正確 if (storedCode != null && storedCode.equals(inputCode)) { // 驗證碼正確,從緩存中移除 verificationCodeMap.remove(phoneNumber); return true; } return false; } // 發送短信的方法 private void sendSms(String phone, String code) { // 驗證碼模版idString templateId = "100001";// appIdString appId = "YOUR_APP_ID";// appKeyString appKey = "YOUR_APP_KEY";// API地址String apiUrl = "https://vip.veesing.com/smsApi/verifyCode";try {URL url = new URL(apiUrl + "?phone=" + phone + "&templateId=" + templateId + "&appId=" + appId + "&appKey=" + appKey + "&variables=" + code);HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setRequestMethod("GET");BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));StringBuilder response = new StringBuilder();String line;while ((line = rd.readLine()) != null) {response.append(line);}rd.close();// 解析短信服務的響應response,根據返回結果判斷是否發送成功// 成功{"returnStatus":"1 ","message":"成功","remainPoint":"241","taskId":"3313746","successCounts":"1"}// 失敗{"returnStatus":"0","message":"參數錯誤","remainPoint":null,"taskId":null,"successCounts":null}// 處理成功或失敗的邏輯...} catch (Exception e) {e.printStackTrace();}}
}
有問題請在評論區留言~