如何优雅的使用阿里云短信服务功能发送验证码呢

如何优雅的使用阿里云短信服务功能发送验证码呢!

1、前提

1.1、获取用户AccessKey

在这里插入图片描述

在这里插入图片描述

如果没有那就按照图示创建一个

1.2、获取短信服务(模版CODE)

1.2.1、首先需要去添加一个签名(具体操作大家可以自行去百度)

在这里插入图片描述

1.2.2、添加一个模板然后获取模板CODE

在这里插入图片描述

1.3、安装Redis(大家自行百度安装吧)

建议大家做一下Redis储存永久性,默认不是,重启Redis值就没了。(具体方式问度娘)

2、正式开始

2.1、创建一个SpringBoot项目

这个相信大家都会就没必要详细说明了

2.2、在pom.xml文件中引入阿里云依赖

<dependencies>
    <dependency>
        <groupId>com.aliyun</groupId>
        <artifactId>aliyun-java-sdk-core</artifactId>
    </dependency>
</dependencies>

2.3、创建配置文件 application.properties

# 服务端口
server.port=8204
# 服务名
spring.application.name=service-msm

#返回json的全局时间格式
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=GMT+8

spring.redis.host=192.168.56.10
spring.redis.port=6379
spring.redis.database= 0
spring.redis.timeout=1800000
spring.redis.lettuce.pool.max-active=20
spring.redis.lettuce.pool.max-wait=-1
#最大阻塞等待时间(负数表示没限制)
spring.redis.lettuce.pool.max-idle=5
spring.redis.lettuce.pool.min-idle=0

# nacos服务地址
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848

aliyun.sms.regionId=default //服务地域与对应的RegionID,这里不需要修改
aliyun.sms.accessKeyId=    //1.1中获取到的accessKeyId
aliyun.sms.secret=		   //1.1中获取到的accessKey secret

2.4、修改启动类

@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)//取消数据源自动配置
@EnableDiscoveryClient
public class ServiceMsmApplication {
   public static void main(String[] args) {
      SpringApplication.run(ServiceMsmApplication.class, args);
   }
}

2.5、创建工具类

2.5.1、ConstantPropertiesUtils

这个工具类的主要作用就是从配置文件中获取值

@Component
public class ConstantPropertiesUtils implements InitializingBean {
    @Value("${aliyun.sms.regionId}")
    private String regionId;

    @Value("${aliyun.sms.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyun.sms.secret}")
    private String secret;

    public static String REGION_Id;
    public static String ACCESS_KEY_ID;
    public static String SECRECT;
    @Override
    public void afterPropertiesSet() throws Exception {
        REGION_Id=regionId;
        ACCESS_KEY_ID=accessKeyId;
        SECRECT=secret;

    }
}

2.5.2、Randomutil

随机生成四位,或六位的随机数

public class Randomutil {
    private static final Random random = new Random();

    private static final DecimalFormat fourdf = new DecimalFormat("0000");

    private static final DecimalFormat sixdf = new DecimalFormat("000000");

    public static String getFourBitRandom() {
        return fourdf.format(random.nextInt(10000));
    }

    public static String getSixBitRandom() {
        return sixdf.format(random.nextInt(1000000));
    }

    /**
     * 给定数组,抽取n个数据
     * @param list
     * @param n
     * @return
     */
    public static ArrayList getRandom(List list, int n) {

        Random random = new Random();

        HashMap<Object, Object> hashMap = new HashMap<Object, Object>();

// 生成随机数字并存入HashMap
        for (int i = 0; i < list.size(); i++) {

            int number = random.nextInt(100) + 1;

            hashMap.put(number, i);
        }

// 从HashMap导入数组
        Object[] robjs = hashMap.values().toArray();

        ArrayList r = new ArrayList();

// 遍历数组并打印数据
        for (int i = 0; i < n; i++) {
            r.add(list.get((int) robjs[i]));
            System.out.print(list.get((int) robjs[i]) + "\t");
        }
        System.out.print("\n");
        return r;
    }

}

2.6、封装service接口和实现类

public interface MsmService {
//    发送验证码
    boolean send(String phone, String sixBitRandom);
}
@Service
public class MsmServiceImpl implements MsmService {
    @Override
    public boolean send(String phone, String sixBitRandom) {
        // 这里传入两个参数 第一个是 手机号码,第二个是 验证码内容
        if(StringUtils.isEmpty(phone)){
            return  false;
        }
//        整合阿里云服务
//        设置相关参数
        DefaultProfile profile = DefaultProfile.
                getProfile(ConstantPropertiesUtils.REGION_Id,
                        ConstantPropertiesUtils.ACCESS_KEY_ID,
                        ConstantPropertiesUtils.SECRECT);
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        //request.setProtocol(ProtocolType.HTTPS);
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");

        //手机号
        request.putQueryParameter("PhoneNumbers", phone);
        //签名名称  1.2中获取到的签名名称  直接用你的来替换#######就行
        request.putQueryParameter("SignName", "#######");
        //模板code 1.2中获取到的模板code  直接用你的来替换#######就行
        request.putQueryParameter("TemplateCode", "######");
        //验证码  使用json格式   {"code":"123456"}  将验证码转换为json格式
        Map<String,Object> param = new HashMap();
        // 这里需要注意一下 这个key需要去看一下你自己的模板里面定义的是什么我这里是number,默认值是code
        param.put("number",sixBitRandom);
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(param));

        //调用方法进行短信发送
        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
            return response.getHttpResponse().isSuccess();
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return false;
    }
}

2.7、封装controller接口

@RestController
@RequestMapping("/api/msm")
public class MsmApiController {
    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @GetMapping("send/{phone}")
    public Result sendCode(@PathVariable String phone){
//        从redis中获取验证码
//        redis的key 为手机号 value 为 验证码
        String s = redisTemplate.opsForValue().get(phone);
// 判断手机号是否在redis中 , 存在表示验证码还在有效期内,不用重复发送
        if(!StringUtils.isEmpty(s)){
            return Result.ok();
        }
//        生成验证码
        String sixBitRandom = Randomutil.getSixBitRandom();

//        整合阿里云发生验证码
      boolean isSend =  msmService.send(phone,sixBitRandom);
        if (isSend) {
            // 发送成功将验证码和手机号以key-value的方式存储在Redis中
            redisTemplate.opsForValue().set(phone,sixBitRandom,5, TimeUnit.MINUTES);
            //我这里设置有效期是5分钟,大家可以自己设置
            return Result.ok().message("短信发生成功,请注意查看有效期五分钟");
        }else {
            return Result.fail().message("短信发生失败");
        }
//
    }
}

到此结束了!

接下来我们做一下测试吧。我在自己的环境里继承了Swagger,大家可以直接下载一个。

3、启动配置类,打开Swagger测试。

接下来我们做一下测试吧。我在自己的环境里继承了Swagger,大家可以直接下载一个。

3.1、打开Swagger测试

在这里插入图片描述

在这里插入图片描述

3.2、手机截图

在这里插入图片描述

3.2、查看Redis

在这里插入图片描述

3.3、到这里就结束了。

有任何问题,欢迎大家在评论区讨论,或私信哦!

  • 5
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值