VerificationCodeUtil.java 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package platform.common.util;
  2. import com.aliyuncs.exceptions.ClientException;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.context.annotation.Bean;
  5. import org.springframework.stereotype.Service;
  6. import platform.common.Constant;
  7. import platform.common.exception.BaseException;
  8. import java.util.Date;
  9. import java.util.Objects;
  10. @Service
  11. public class VerificationCodeUtil {
  12. private static String VerificationCode = "SND_VerificationCode_";
  13. private static String LatestVerificationTime = "SND_LatestVerificationTime_";
  14. @Autowired
  15. private RedisUtil redisUtil;
  16. //加入验证码 有效期五分钟
  17. public void setVerificationCode(String phone) {
  18. int code = (int) ((Math.random() * 9 + 1) * 100000);
  19. String templateParam = "{\"validate_code\":\"" + code + "\"}";
  20. try {
  21. AlibabaSMSUtil.sendSMS(phone, Constant.SMS_TemplateCode.VALIDATE_CODE, Constant.SINGNAMW, templateParam);
  22. } catch (ClientException e) {
  23. e.printStackTrace();
  24. } catch (InterruptedException e) {
  25. e.printStackTrace();
  26. }
  27. redisUtil.set(VerificationCode + phone, code, 300L);
  28. redisUtil.set(LatestVerificationTime + phone, new Date(), 60L);
  29. }
  30. //验证 验证码
  31. public boolean validateVerificationCode(String phone, String code) {
  32. String verificationCode = redisUtil.get(VerificationCode + phone) + "";
  33. //验证成功 销毁原来的验证码
  34. if (Objects.equals(code, verificationCode)) {
  35. redisUtil.remove(VerificationCode + phone);
  36. return true;
  37. }
  38. return false;
  39. }
  40. //验证 距离上次发送是否大于一分钟
  41. public Integer validateVerificationTime(String phone, Long time) {
  42. Date verificationTime = (Date) redisUtil.get(LatestVerificationTime + phone);
  43. Date now = new Date();
  44. Long t = 0L;
  45. if (null == verificationTime) {
  46. t = now.getTime() - 0;
  47. } else {
  48. t = now.getTime() - verificationTime.getTime();
  49. }
  50. if (t >= 1000 * time) {
  51. return 0;
  52. }
  53. return (int) (time - t / 1000);
  54. }
  55. }