AliSmsService.java 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package com.izouma.nineth.service.sms;
  2. import com.aliyuncs.CommonRequest;
  3. import com.aliyuncs.CommonResponse;
  4. import com.aliyuncs.DefaultAcsClient;
  5. import com.aliyuncs.IAcsClient;
  6. import com.aliyuncs.exceptions.ClientException;
  7. import com.aliyuncs.http.MethodType;
  8. import com.aliyuncs.profile.DefaultProfile;
  9. import com.izouma.nineth.config.Constants;
  10. import com.izouma.nineth.domain.SmsRecord;
  11. import com.izouma.nineth.exception.BusinessException;
  12. import com.izouma.nineth.repo.SmsRecordRepo;
  13. import lombok.extern.slf4j.Slf4j;
  14. import org.apache.commons.lang3.RandomStringUtils;
  15. import org.springframework.beans.factory.annotation.Autowired;
  16. import org.springframework.beans.factory.annotation.Value;
  17. import org.springframework.boot.configurationprocessor.json.JSONException;
  18. import org.springframework.boot.configurationprocessor.json.JSONObject;
  19. import org.springframework.stereotype.Service;
  20. import java.time.LocalDateTime;
  21. import java.time.ZoneOffset;
  22. @Service
  23. @Slf4j
  24. public class AliSmsService implements SmsService {
  25. @Value("${aliyun.access-key-id}")
  26. private String accessKeyId;
  27. @Value("${aliyun.access-key-secret}")
  28. private String accessKeySecret;
  29. @Autowired
  30. private SmsRecordRepo smsRecordRepo;
  31. @Override
  32. public String sendVerify(String phone) {
  33. smsRecordRepo.findLastByPhoneAndExpiresAtAfterAndExpiredFalse(phone, LocalDateTime.now()).ifPresent(record -> {
  34. if (record.getCreatedAt().plusMinutes(1L).isAfter(LocalDateTime.now())) {
  35. long sec = record.getCreatedAt().plusMinutes(1L).toInstant(ZoneOffset.UTC)
  36. .getEpochSecond() - LocalDateTime.now().toInstant(ZoneOffset.UTC).getEpochSecond() + 1;
  37. throw new BusinessException("请" + sec + "秒后再试");
  38. }
  39. });
  40. String code = RandomStringUtils.randomNumeric(4);
  41. DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
  42. IAcsClient client = new DefaultAcsClient(profile);
  43. CommonRequest request = new CommonRequest();
  44. request.setMethod(MethodType.POST);
  45. request.setDomain("dysmsapi.aliyuncs.com");
  46. request.setVersion("2017-05-25");
  47. request.setAction("SendSms");
  48. request.putQueryParameter("PhoneNumbers", phone);
  49. request.putQueryParameter("SignName", Constants.SMS_SIGN_NAME);
  50. request.putQueryParameter("TemplateCode", Constants.SMS_TEMPLATE_CODE_GENERIC);
  51. request.putQueryParameter("TemplateParam", "{\"code\":\"" + code + "\"}");
  52. try {
  53. CommonResponse response = client.getCommonResponse(request);
  54. if (response.getHttpStatus() != 200) {
  55. throw new BusinessException("发送失败,请稍后再试", response.getHttpStatus() + "," + response.getData());
  56. }
  57. log.info("send sms response {}", response.getData());
  58. JSONObject jsonObject = new JSONObject(response.getData());
  59. if (!"ok".equalsIgnoreCase(jsonObject.getString("Code"))) {
  60. throw new BusinessException("发送失败,请稍后再试", jsonObject.getString("Message"));
  61. }
  62. smsRecordRepo.expire(phone);
  63. String sessionId = RandomStringUtils.randomAlphabetic(10);
  64. smsRecordRepo.save(SmsRecord.builder()
  65. .sessionId(sessionId)
  66. .phone(phone)
  67. .code(code)
  68. .expiresAt(LocalDateTime.now().plusMinutes(5))
  69. .expired(false)
  70. .build());
  71. return sessionId;
  72. } catch (ClientException | JSONException e) {
  73. e.printStackTrace();
  74. throw new BusinessException("发送失败,请稍后再试", e.getMessage());
  75. }
  76. }
  77. @Override
  78. public void verify(String phone, String code) {
  79. SmsRecord smsRecord = smsRecordRepo.findLastByPhoneAndExpiresAtAfterAndExpiredFalse(phone, LocalDateTime.now())
  80. .orElseThrow(new BusinessException("验证码错误"));
  81. if (!smsRecord.getCode().equalsIgnoreCase(code)) {
  82. throw new BusinessException("验证码错误");
  83. }
  84. smsRecord.setExpired(true);
  85. smsRecordRepo.save(smsRecord);
  86. }
  87. }