SpringBoot 通过阿里云的短信功能 实现发送手机验证码

x33g5p2x  于2022-02-15 转载在 Spring  
字(3.3k)|赞(0)|评价(0)|浏览(538)

我们在项目中经常遇到 需要通过手机号发送验证码实现登录注册等功能。
这里讲一下,Springboot项目中如果通过阿里云的短信功能, 实现发送手机验证码并验证

一、准备工作

1、购买阿里云的短信服务

https://free.aliyun.com/product/cloudcommunication-free-trial

新用户有免费试用产品

个人使用的话,有3个月内100条的免费服务,如果学习的话,足够用了,否则还需要充钱!!!

2、购买后,设置 AccessKey

阿里云会自动获取绑定的手机号,你只需要获取短信验证码就可以创建成功。

3、设置签名

4、添加模板

开发

开发者可以按照阿里云的这个开发者手册开发。

https://help.aliyun.com/document_detail/101300.html?spm=a2c4g.11186623.6.610.5ed850a4DjrhHY

发送短信这个接口如何调用? 这个网址还提供了调试功能,很方便。

https://help.aliyun.com/document_detail/101414.html?spm=a2c4g.11186623.6.624.15b85f30AyGxea

我们可以直接调用 阿里云为我们提供的API

这里只用自定义的方法

1、导入依赖

  1. <dependency>
  2. <groupId>com.aliyun</groupId>
  3. <artifactId>aliyun-java-sdk-core</artifactId>
  4. <version>4.5.3</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>com.aliyun</groupId>
  8. <artifactId>aliyun-java-sdk-dysmsapi</artifactId>
  9. <version>1.1.0</version>
  10. </dependency>

2、编写工具类

这里自定义工具类进行使用

  1. /**
  2. * description:
  3. *
  4. * @author su
  5. * @date 2022/2/15 14:41
  6. */
  7. @Component
  8. public class SMSUtils {
  9. private static final Logger log = LoggerFactory.getLogger(SMSUtils.class);
  10. @Value("${sms.accessKeyId}")
  11. private String accessKeyId;
  12. @Value("${sms.secret}")
  13. private String secret;
  14. @Value("${sms.signName}")
  15. private String signName; // 短信签名
  16. @Value("${sms.templateCode}")
  17. private String templateCode; //短信模板
  18. @Value("${sms.regionId}")
  19. private String regionId; // 短信服务器区域
  20. public void sendMsg(String phone, String code) {
  21. DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, secret);
  22. DefaultAcsClient client = new DefaultAcsClient(profile);
  23. CommonRequest request = new CommonRequest();
  24. request.setSysMethod(MethodType.POST);
  25. //下面两个不能动
  26. request.setSysProduct("Dysmsapi");
  27. request.setSysDomain("dysmsapi.aliyuncs.com");
  28. request.setSysVersion("2017-05-25");
  29. request.setSysAction("SendSms");
  30. //自定义参数(手机号,验证码,签名,模板)
  31. request.putQueryParameter("RegoinId", regionId);
  32. request.putQueryParameter("PhoneNumbers", phone);
  33. request.putQueryParameter("SignName", signName); //填自己申请的名称
  34. request.putQueryParameter("TemplateCode", templateCode);
  35. request.putQueryParameter("TemplateParam", "{\"code\":\"" + code + "\"}");
  36. try {
  37. CommonResponse response = client.getCommonResponse(request);
  38. log.info("阿里云短信响应信息:" + response.getData());
  39. boolean success = response.getHttpResponse().isSuccess();
  40. log.info("短信发送是否成功:" + success);
  41. } catch (ClientException e) {
  42. e.printStackTrace();
  43. }
  44. }
  45. }

这些变量放在配置文件中,方便维护

  1. sms:
  2. accessKeyId: LTAI5tGF2kkoJbB9ftdH2DwT
  3. secret: YYc2CShh6RVZmMuhQzifAXS5WimvuI
  4. signName: 青橙小店
  5. templateCode: SMS_217145407
  6. regionId: cn-hangzhou
  1. @RestController
  2. @RequestMapping("admin")
  3. public class UserController {
  4. private static final Logger log = LoggerFactory.getLogger(UserController.class);
  5. @Autowired
  6. private RedisTemplate redisTemplate;
  7. @Autowired
  8. public SMSUtils smsUtils;
  9. @PostMapping("/code")
  10. public void sendMsg(@RequestBody MsgVo msgVo) {
  11. if (redisTemplate.hasKey("TOMEOUT:" + msgVo.getPhone())) {
  12. throw new RuntimeException("不允许重复发送");
  13. }
  14. String code = RandomStringUtils.randomNumeric(4);
  15. log.info("发送的验证码:{}" + code);
  16. smsUtils.sendMsg(msgVo.getPhone(), code);
  17. redisTemplate.opsForValue().set(msgVo.getPhone(), code, 60, TimeUnit.SECONDS);
  18. redisTemplate.opsForValue().set("TOMEOUT:" + msgVo.getPhone(), true, 10, TimeUnit.MINUTES);
  19. }
  20. }

启动测试

相关文章