欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

阿里云短信服务

程序员文章站 2022-04-26 13:30:13
...

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;
    }
相关标签: 学习 sms java