package platform.common.util; import com.aliyuncs.exceptions.ClientException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.stereotype.Service; import platform.common.Constant; import platform.common.exception.BaseException; import java.util.Date; import java.util.Objects; @Service public class VerificationCodeUtil { private static String VerificationCode = "SND_VerificationCode_"; private static String LatestVerificationTime = "SND_LatestVerificationTime_"; @Autowired private RedisUtil redisUtil; //加入验证码 有效期五分钟 public void setVerificationCode(String phone) { int code = (int) ((Math.random() * 9 + 1) * 100000); String templateParam = "{\"validate_code\":\"" + code + "\"}"; try { AlibabaSMSUtil.sendSMS(phone, Constant.SMS_TemplateCode.VALIDATE_CODE, Constant.SINGNAMW, templateParam); } catch (ClientException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } redisUtil.set(VerificationCode + phone, code, 300L); redisUtil.set(LatestVerificationTime + phone, new Date(), 60L); } //验证 验证码 public boolean validateVerificationCode(String phone, String code) { String verificationCode = redisUtil.get(VerificationCode + phone) + ""; //验证成功 销毁原来的验证码 if (Objects.equals(code, verificationCode)) { redisUtil.remove(VerificationCode + phone); return true; } return false; } //验证 距离上次发送是否大于一分钟 public Integer validateVerificationTime(String phone, Long time) { Date verificationTime = (Date) redisUtil.get(LatestVerificationTime + phone); Date now = new Date(); Long t = 0L; if (null == verificationTime) { t = now.getTime() - 0; } else { t = now.getTime() - verificationTime.getTime(); } if (t >= 1000 * time) { return 0; } return (int) (time - t / 1000); } }