阿里云短信服务

标签: 学习  sms  java

1 开通阿里云短信服务 进入管理控制台
在这里插入图片描述
2 点开国内消息 申请签名,模板。
在这里插入图片描述
3 引入pom

  <dependencies>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.28</version>
        </dependency>
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-core</artifactId>
            <version>4.3.3</version>
        </dependency>
    </dependencies>

4 编写controller 生成验证码并且存入redis,再发短信

@GetMapping("send/{phone}")
    public R sendMsm(@PathVariable String phone){

        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)){
            return R.ok();
        }else {

            //生成随机验证码值
            String sixBitRandom = RandomUtil.getSixBitRandom();
            Map<String, Object> param = new HashMap<>();
            param.put("code", sixBitRandom);
            Boolean isSend = msmService.send(param, phone);
            if (isSend) {
                redisTemplate.opsForValue().set(phone, sixBitRandom, 5, TimeUnit.MINUTES);
                return R.ok();
            } else {
                return R.error().message("短信发送失败");
            }
        }

5 编写service,发送短信 可参考Demo
在这里插入图片描述

 public Boolean send(Map<String, Object> param, String phone) {
            DefaultProfile profile = DefaultProfile.getProfile("default", "LTAI4G9bA2AYLZGkjUu2hqaA", "5xzmpKAAE5HEmvZq6Q68VpEsVg3iT0");
            IAcsClient client = new DefaultAcsClient(profile);
            CommonRequest request = new CommonRequest();
            //固定的不能改
            request.setSysMethod(MethodType.POST);
            request.setSysDomain("dysmsapi.aliyuncs.com");
            request.setSysVersion("2017-05-25");
            request.setSysAction("SendSms");

            request.putQueryParameter("PhoneNumbers", phone);
            //签名名字
            request.putQueryParameter("SignName", "QGB在线教育网站");
            //模版CODE
            request.putQueryParameter("TemplateCode", "SMS_196652644");
            request.putQueryParameter("TemplateParam", JSONObject.toJSONString(param));
            try {
                CommonResponse response = client.getCommonResponse(request);
                System.out.println(response.getData());
                boolean success = response.getHttpResponse().isSuccess();
                return success;
            } catch (ClientException e) {
                e.printStackTrace();
            }
        return false;
    }
版权声明:本文为qq614452400原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq614452400/article/details/108730999