阿里云短信业务SMS

1. 了解阿里云用户权限操作

image-20200731193114896

image-20200731193316015

image-20200731193348568

添加用户组

image-20200731193510689

点开用户组

image-20200731193551188

点击权限管理

image-20200731193623485

点击添加权限

image-20200731193728184

点击用户

image-20200731193847752

点击创建用户

image-20200731193954507

在用户添加完成后,会弹出AccessKey和密码,要及时保存密码!!如果密码泄露,要及时删除AccessKey

image-20200731194151643

  1. 开启子用户
  2. 新建用户组(设置添加权限sms)
  3. 创建一个用户(具体用来操作的账号)
  4. 得到AccessKey(id,密码)

2. 开通阿里云短信服务

image-20200731194510095

**短信服务帮助文档:**https://help.aliyun.com/product/44282.html?spm=5176.12207334.0.0.5dd31cbeMp7fV1

计费规则

image-20200731194850325


3. 添加短信模板

image-20200731195506364

添加模板

image-20200731195614019

需要审核!不能乱填

image-20200731195825869

等审核通过后,我们会得到一个模板code

image-20200731195923999


4. 添加签名

添加签名

image-20200731200013266

image-20200731200116698

选择验证码后,下面的内容就无需填写,申请说明要填写正当!!然后等待审核通过!


5. 编写测试代码

新建一个springboot项目

导入依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.0.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>cn.codewei</groupId>
    <artifactId>smstest</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>smstest</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-core</artifactId>
            <version>4.5.0</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

编写配置application.properties

server.port=8080
spring.redis.host=localhost
spring.redis.port=6379

编写测试类

@SpringBootTest
class SmstestApplicationTests {

    @Test
    void contextLoads() {
        // 连接阿里云
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "填写accesskey", "填写accesskey对应的密码");
        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", "发送到的手机号");
        request.putQueryParameter("SignName","签名名称");  // 对应阿里云上申请的
        request.putQueryParameter("TemplateCode","模板code");  // 对应阿里云上申请的
        // 构建一个短信的验证码
        String str = UUID.randomUUID().toString().substring(0, 4);
        HashMap<String,Object> map = new HashMap<>();
        map.put("code",str);
        ObjectMapper mapper = new ObjectMapper();
        String json = null;
        try {
            json = mapper.writeValueAsString(map);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        request.putQueryParameter("TemplateParam",json);


        try {
            // 发送,得到响应
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }

    }

}

6. 编写可复用的微服务接口,实现验证码的发送

编写接口

public interface SendSms {
    // 手机号  模板code  验证码
    public boolean send(String phoneNum, String templateCode, Map<String,Object> code);
}

编写实现类

@Service
public class SendSmsImpl implements SendSms {
    @Override
    public boolean send(String phoneNum, String templateCode, Map<String, Object> code) {

        // 连接阿里云
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "填写accesskey", "accesskey对应的密码");
        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", phoneNum);
        request.putQueryParameter("SignName","签名名称");
        request.putQueryParameter("TemplateCode",templateCode);

        // 构建一个短信的验证码
        ObjectMapper mapper = new ObjectMapper();
        String json = null;
        try {
            json = mapper.writeValueAsString(code);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        request.putQueryParameter("TemplateParam",json);

        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;
    }
}

编写Controller

@RestController
@CrossOrigin  // 跨域支持
public class SendSmsController {

    @Autowired
    private SendSms sendSms;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;


    @RequestMapping("/sendSms/{phone}")
    public String sendSms(@PathVariable("phone") String phone){
        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)){
            return "当前验证码还没过期,请及时填写!";
        }

        String str = UUID.randomUUID().toString().substring(0, 4);
        HashMap<String,Object> map = new HashMap<>();
        map.put("code",str);
        boolean send = sendSms.send(phone, "SMS_190272542", map);
        if (send){
            redisTemplate.opsForValue().set(phone,str,5, TimeUnit.MINUTES);
            return "发送成功";
        }else {
            return "发送失败";
        }
    }
}
posted @ 2021-05-13 14:46  mango1698  阅读(13)  评论(0编辑  收藏  举报  来源