在Spring Boot应用中实现阿里云短信功能的整合

1.程序员必备程序网站

天梦星服务平台 (tmxkj.top)https://tmxkj.top/#/

2.导入坐标

复制代码
       <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-core</artifactId>
            <version>4.5.0</version>
        </dependency>
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-dysmsapi</artifactId>
            <version>1.0.0</version>
        </dependency>

3.yml文件配置

复制代码
aliyun:
  sms: #阿里云发短信
    access-key-id: "********"  #角色的id
    access-key-secret: "******" #角色的密匙
    sign-name: "天梦星科技"
    template-code: "*******"

4.核心代码

复制代码
@Component
public class SmsUtil {

    @Value("${aliyun.sms.access-key-id}")
    private String accessKeyId;

    @Value("${aliyun.sms.access-key-secret}")
    private String accessKeySecret;

    @Value("${aliyun.sms.sign-name}")
    private String signName;

    @Value("${aliyun.sms.template-code}")
    private String templateCode;

    public Result sendSms(String phone, String code) throws ClientException {
        Result result = new Result();
        IAcsClient client = new DefaultAcsClient(DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret));
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", signName);
        request.putQueryParameter("TemplateCode", templateCode);
        request.putQueryParameter("TemplateParam", "{\"code\":\"" + code + "\"}");
        CommonResponse response = client.getCommonResponse(request);
        if (JSON.parseObject(response.getData()).get("Message").equals("OK")){
        result.setCode(200);
        result.setMsg("短信发送成功");
        }else {
            result.setCode(400);
            result.setMsg(JSON.parseObject(response.getData()).get("Message"));
        }
        return result;
    }

}

public class ToolUtil {

    /**
     * 判断是否是手机号
     * @param phoneNumber
     * @return
     */
    public static boolean isPhoneNumber(String phoneNumber) {
        String regex = "^1[3-9]\\d{9}$";
        return Pattern.matches(regex, phoneNumber);
    }

 /**
     * 获取长度为 5 的随机数字
     * @return 随机数字
     *  用途短信验证码
     */
    public static String getSmsRandomNumber() {
        char[] nonceChars = new char[5];  //指定长度为6位/自己可以要求设置
        for (int index = 0; index < nonceChars.length; ++index) {
            nonceChars[index] = SYMBOLS2.charAt(RANDOM.nextInt(SYMBOLS2.length()));
        }
        return new String(nonceChars);
    }
}

5.调用测试

复制代码
    /**
     * 发送短信验证嘛
     */
    @GetMapping("/sendMessage")
    public Result sendMessage(@RequestParam("phone") String phone){
        Result result = new Result();
        String code = getSmsRandomNumber(); // 生成随机验证码
        try {
            if(isPhoneNumber(phone)){
                //redisDao.vSet(code,code,imaileEpxtime);
                result = smsUtil.sendSms(phone, code);
            }else {
                result.setCode(400);
                result.setMsg("手机号格式错误!");
            }
        } catch (ClientException e) {
            e.fillInStackTrace();
            result.setCode(500);
            result.setMsg(e.getErrMsg());
        }
        return result;
    }

6.成功示例

相关推荐
凉栀お_19 分钟前
MySQL第四次作业(索引、视图)
数据库·mysql
睡前要喝豆奶粉25 分钟前
.NET Core Web API中数据库相关配置
数据库·c#·.netcore
大G的笔记本38 分钟前
高频 Redis 面试题答案解析
数据库·redis·缓存
李白的粉44 分钟前
基于springboot的新闻资讯系统
java·spring boot·毕业设计·课程设计·源代码·新闻资讯系统
摇滚侠1 小时前
Spring Boot3零基础教程,为什么有Reactive-Stream 规范,响应式编程,笔记101
java·spring boot·笔记
万事大吉CC1 小时前
SQL语法基础教程
数据库·oracle
betazhou2 小时前
Oracle dgbroker常规命令管理简介
数据库·oracle·adg·dbbroker
山河亦问安2 小时前
Spring Boot异步接口性能优化:从单线程到高并发的优化历程
spring boot·后端·性能优化
海边夕阳20062 小时前
PostgreSQL性能调优:解决表膨胀、索引碎片和无效索引问题
数据库·经验分享·postgresql·性能优化
陈果然DeepVersion2 小时前
Java大厂面试真题:Spring Boot+微服务+AI智能客服三轮技术拷问实录(四)
spring boot·redis·微服务·kafka·spring security·智能客服·java面试