操作流程
- 注册验证码平台
- 创建验证码模版
- 开始集成(无需引入第三方库)
注册并登陆中昱维信验证码平台
获取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();}}
}
有问题请在评论区留言~