手把手教你使用短信验证码「含源码」

阿里云短信验证码

1、注册信息

进入阿里云官网并登录

选择「AccessKey管理」

AccessKey

开始使用子用户AccessKey

开始使用

使用新版本的Web页面

选择新版

新建「用户组」

用户组

编辑用户组权限

搜索「sms」,添加「AliyunDysmsFullAccess

添加权限

创建用户(保存得到的AccessKey「id,密码」,一定不能泄露,如若泄露,立即禁用或删除AccessKey

创建用户

添加用户到组

添加用户到组

2、开通服务

控制台主页搜索「短信服务」

短信服务

开通「短信服务」0.045/条

开通

添加短信模板、等待审核「20分钟」

申请说明一定不能乱填,不然审核不通过

添加模板

输入模板信息

添加签名、等待审核「20分钟」

申请说明一定不能乱填,不然审核不通过

输入签名信息

短信服务帮助文档

说明

3、编写测试代码

添加Maven依赖

<!-- 短信服务 -->
<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>aliyun-java-sdk-core</artifactId>
    <version>4.1.0</version>
</dependency>
<!-- fastjson -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.68</version>
</dependency>
<!-- redis,验证码一般有过期时间,放在redis中储存 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

进行单元测试

测试短信能否发送成功

有些包需要手动导入,导入与aliyun相关的依赖

 @Test
    public void contextLoads() {
        //连接阿里云
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou",
                "你的AccessKey ID ",
                "你的AccessKey Secret");
        IAcsClient client = new DefaultAcsClient(profile);

        //构建请求,默认即可
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");   //不要动
        request.setVersion("2017-05-25");             //不要动
        request.setAction("SendSms");

        //自定义的参数(手机号,验证码,签名,模板)
        request.putQueryParameter("PhoneNumbers", "接收信息的手机号");
        request.putQueryParameter("SignName", "你的短信服务的签名名称");//短信服务中「签名名称」
        request.putQueryParameter("TemplateCode", "你的短信服务的模版CODE"); //短息服务中「模版CODE」
        //构建一个短信的验证码「这里为写死的验证码」
        HashMap<String, Object> map = new HashMap<>();
        map.put("code",2233);
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(map));//JSONObject使用前面Maven导入到fastjson依赖
        try {
            CommonResponse response = client.getCommonResponse(request);
            //是否发送成功
            System.out.println(response.getData());
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
    }

测试成功

4、编写可复用代码

编写配置文件

使用redis

#redis地址
spring.redis.host=「你的redis主机地址」

编写service接口

public interface SendSms {
    public Boolean send(String phoneNum, String templateCode, Map<String,Object> code);
}

编写servive接口实现类

@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 ID",
                "你的AccessKey Secret");
        IAcsClient client = new DefaultAcsClient(profile);

        //构建请求,默认即可
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");   //不要动
        request.setVersion("2017-05-25");             //不要动
        request.setAction("SendSms");

        //自定义的参数(手机号,验证码,签名,模板)
        request.putQueryParameter("PhoneNumbers", phoneNum);
        request.putQueryParameter("SignName", "乐小北");//你的短信服务的「签名」
        request.putQueryParameter("TemplateCode", templateCode); //你的短息服务中的「模版CODE」
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(code));//JSONObject使用前面Maven导入的fastjson依赖
        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 SmsApiController {
    @Autowired
    private SendSms sendSms;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @GetMapping("/send/{phone}")
    public String code(@PathVariable("phone") String phone) {
        //调用发送方法(模拟真实业务 redis)
        String code = redisTemplate.opsForValue().get(phone);
        //如果验证码存在
        if (!StringUtils.isEmpty(code)) {
            return phone + ":" + code + "已存在,未过期";
        }
        
        
        //若验证码不存在,生成验证码并存储到redis中
        //使用UUID生成六位验证码
        code = UUID.randomUUID().toString().substring(0,6);
        HashMap<String, Object> param = new HashMap<>();
        param.put("code", code);
        //调用发送接口
        Boolean isSend = sendSms.send(phone, "SMS_189830844", param);
        //发送成功
        if (isSend) {
            //手机号、验证码保存在redis5分钟
            redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
            return phone + ":" + code + "发送成功";
        } else {
            return "发送失败";
        }
    }
}

发送成功

未过期则不发送

手机显示

原创文章 2 获赞 6 访问量 635

猜你喜欢

转载自blog.csdn.net/Ezresl/article/details/106102920