阿里云获取服务
首先进入此链接短信服务
按照如下图的快速学习一步一步走完即可,其中系统设置可以不管

- 签名:短信开头的发信人信息,如【中国移动】
- 模板:短信内容,如 您的验证码为:${code},该验证码5分钟内有效,请勿泄露于他人!
购买套餐
云通信精选特惠这个链接有200条2元的套餐,测试学习必备
导入依赖
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 
 | <dependency><groupId>com.aliyun</groupId>
 <artifactId>aliyun-java-sdk-core</artifactId>
 <version>3.2.6</version>
 </dependency>
 <dependency>
 <groupId>com.aliyun</groupId>
 <artifactId>aliyun-java-sdk-dysmsapi</artifactId>
 <version>1.1.0</version>
 </dependency>
 
 | 
Java代码
新建一个SmsUtil工具类
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 
 | @Slf4j@Component
 public class SmsUtil {
 
 private static final String signName = "中国移动";
 
 private static final String templateCode = "SMS_********";
 
 private static final String accessKeyId = "LTAI5*****************ekr";
 
 private static final String accessKeySecret = "BH*************************D";
 
 private static final String REGION_ID = "cn-chengdu";
 
 private static final String PRODUCT = "Dysmsapi";
 private static final String DOMAIN = "dysmsapi.aliyuncs.com";
 
 
 
 
 
 
 
 public boolean sendSMS(String mobile, String code) {
 try {
 IClientProfile profile = DefaultProfile.getProfile(REGION_ID, accessKeyId, accessKeySecret);
 
 DefaultProfile.addEndpoint(REGION_ID, REGION_ID, PRODUCT, DOMAIN);
 
 IAcsClient acsClient = new DefaultAcsClient(profile);
 
 SendSmsRequest request = new SendSmsRequest();
 
 request.setMethod(MethodType.POST);
 
 
 request.setPhoneNumbers(mobile);
 
 request.setSignName(signName);
 
 request.setTemplateCode(templateCode);
 request.setTemplateParam("{\"code\":\""+ code +"\"}");
 
 SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
 if ((sendSmsResponse.getCode() != null) && (sendSmsResponse.getCode().equals("OK"))) {
 log.info("发送成功,code:" + sendSmsResponse.getCode());
 return true;
 } else {
 log.info("发送失败,code:" + sendSmsResponse.getCode());
 return false;
 }
 } catch (ClientException e) {
 log.error("发送失败,系统错误!", e);
 return false;
 }
 }
 }
 
 | 
调用服务
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 
 | @Resource
 private SmsUtil smsUtil;
 
 @Override
 public Result sendCode(String phone) {
 
 boolean phoneInvalid = RegexUtils.isPhoneInvalid(phone);
 if (phoneInvalid) {
 return Result.fail("请输入正确的手机号!");
 }
 
 String code = RandomUtil.randomNumbers(6);
 
 
 stringRedisTemplate.opsForValue().set(LOGIN_CODE_KEY + phone, code, LOGIN_CODE_TTL, TimeUnit.MINUTES);
 
 
 boolean sendSMS = smsUtil.sendSMS(phone, code);
 if (sendSMS) {
 log.info("发送验证码成功,手机号{},验证码{}", phone, code);
 } else {
 log.error("发送验证码失败!");
 }
 return Result.ok();
 }
 
 |