springboot集成阿里云短信-短信服务-项目实践

1 前言

​ 线上系统开发中,短信功能是经常要用到的,比如注册、修改手机号、修改密码时短信验证码等。我们这里是一个基于Springboot的微服务项目,选择a-li-yun的短信接口。

2 准备工作

2.1 了解流程

​ 登录a-li-yun短信控制台,了解短信相关知识。我们这里需要短信发送功能,进一步了解相关API。

2.2 配置信息

  • 凭证:登录a-li短信控制台,通过快速学习,我们知道,我们需要创建accessKey,accessKeySecret,即用户的访问凭证,具体如何创建,这里不赘述,自行查阅文档。
  • 域名endpoint:即我们通过那个地址访问a-li-yun的短信接口。

2.3 短信签名和模板

​ 签名和模板是a-li-yun短信功能所必须的,下面讲解下签名和模板的添加。

2.3.1 签名
  • 添加签名:一个账户只能添加一个验证码类型的签名,我已经添加了一个,你们根据需要自行选择,图示:在这里插入图片描述

  • 添加签名后,等待一定时间审核通过即可,图示:在这里插入图片描述

2.3.2 模板
  • 添加模板:在这里插入图片描述

  • 审核不通过原因:

    • 场景连接:这里场景连接一定要填写公网可访问连接,比如你上线的App、网站网址,或者你的博客等待的。
    • 模板内容:如需自定义,仔细阅读变量规范、模板申请规范;或者直接说使用模板库中预定义模块,适当修改文字,可满足大部分应用场景。
  • 效果图示:在这里插入图片描述

2.3.3 存入数据库
  • 与短信功能相关的签名、模板,这些信息保存在数据库的配置表中。
    • 签名:效果就是短信开头的【】中的信息,开发需要用到签名名称signName。
    • 模板:效果就是短信的内容,开发中需要用到模板名称templateCode,其他信息保存在数据库中。

3 SDK

​ 虽然是做了前面的准备工作,但是具体怎么应用还是很模糊,查阅相关技术文档,很多都是旧版本的内容。这里我们还是通过a-li-yun的OpenAPI来学习最新的应用技术,这里我们以短信发送为例,图示:在这里插入图片描述

api参数,示例,依赖一目了然,而且是最新版本的内容,下面我们开始集成到项目中。

4 集成Springboot

4.1 集成

  • pom.xml:复制上面依赖信息

    <dependency>
                <groupId>com.xxx</groupId>
                <artifactId>dysmsapi20170525</artifactId>
                <version>2.0.21</version>
            </dependency>
    
  • 分析:

    • 短信功能我们项目中多个模块需要用到,我们把短信发送功能封装到AliSms类中,AliSms配置为IOC容器中的bean,位置放置在公共模块中。
    • 需要用到的配置信息,比如accessKey,secretKey,endpoint,我们在nacos中配置,图示:在这里插入图片描述
  • 参考官网给出的SDK封装我们自己的AliSms类,源码,xxx-a-li-yun:

    import com.xxx.dysmsapi20170525.Client;
    import com.xxx.dysmsapi20170525.models.SendSmsRequest;
    import com.xxx.dysmsapi20170525.models.SendSmsResponse;
    import com.xxx.teautil.models.RuntimeOptions;
    import cn.hutool.core.bean.BeanUtil;
    
    
    import java.util.Map;
    
    /**
     * @author Administrator
     * @version 1.0
     * @description ali sms
     * @date 2022-09-30 11:19
     * xxx短信类
     */
    public class AliSms {
    
        private final Client client;
        private final SendSmsRequest request;
    
        public AliSms(Client client, SendSmsRequest request) {
            this.client = client;
            this.request = request;
        }
    
        public  Map<String, Object> sendSms(String templateCode, String templateParam, String phoneNumbers) throws Exception {
    
            request.setTemplateCode(templateCode);
            request.setTemplateParam(templateParam);
            request.setPhoneNumbers(phoneNumbers);
    
            RuntimeOptions runtime = new RuntimeOptions();
            SendSmsResponse response = null;
            try {
                response = client.sendSmsWithOptions(request, runtime);
            } catch (Exception e) {
                e.printStackTrace();
                throw new Exception("短信发送失败");
            }
            return BeanUtil.beanToMap(response);
        }
    }
    
    
    
    import com.xxx.dysmsapi20170525.Client;
    import com.xxx.teaopenapi.models.Config;
    import com.xxx.dysmsapi20170525.models.SendSmsRequest;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    /**
     * @author Administrator
     * @version 1.0
     * @description sms短信发送
     * @date 2022-10-04 12:50
     */
    @Configuration
    public class SmsAutoConfiguration {
    
        /**
         * 短信服务账户accessKey
         */
        @Value("${spring.cloud.alicloud.access-key}")
        private String accessKey;
    
        /**
         * 短信服务账户accessKey
         */
        @Value("${spring.cloud.alicloud.secret-key}")
        private String secretKey;
    
        /**
         * 短信服务endpoint
         */
        @Value("${spring.cloud.alicloud.sms.endpoint}")
        private String endpoint;
    
        /**
         * 短信服务签名
         */
        @Value("${spring.cloud.alicloud.sms.signName}")
        private String signName;
    
    
        @Bean
        public AliSms aliSms() {
            return new AliSms(createClient(), sendSmsRequest());
        }
    
        private SendSmsRequest sendSmsRequest() {
            SendSmsRequest request = new SendSmsRequest();
            request.setSignName(signName);
            return request;
        }
    
        private Client createClient(){
            Config config = new Config()
                    // 您的 AccessKey ID
                    .setAccessKeyId(accessKey)
                    // 您的 AccessKey Secret
                    .setAccessKeySecret(secretKey);
            // 访问的域名
            config.endpoint = endpoint;
            Client client = null;
            try {
                client = new Client(config);
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException("创建xxx客户端失败!");
            }
    
            return client;
        }
    
    }
    
  • pom.xml添加依赖,全部相关依赖:

            <dependency>
                <groupId>com.xxx</groupId>
                <artifactId>dysmsapi20170525</artifactId>
                <version>2.0.21</version>
            </dependency>
            <dependency>
                <groupId>com.xxx</groupId>
                <artifactId>tea-util</artifactId>
                <version>0.2.14</version>
            </dependency>
    

4.2 测试

  • 测试代码:前端代码及后端接口根据业务需求自己设计,这里只展示业务实现层的短信发送方法的简单测试实现:
@Autowired
    private AliSms aliSms;

    @Override
    public void sendSms(Sms sms) {
        try {
            log.info("发送短信{}", JSON.toJSONString(sms, true));
            String templateParam = "{\"code\":\"" + "123456" + "\"}";
            Map<String, Object> info = aliSms.sendSms(sms.getTemplateCode(), templateParam, sms.getMobile());
            log.info("发送结果:{}", JSON.toJSONString(info, true));
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("发送短信失败");
        }
    }
  • 测试结果:

    • 控制台:

      {
          "basePath":"xxx",
      	"description":"发送短信",
      	"ip":"192.168.10.1",
      	"method":"com.gaogzhen.controller.SmsController.sendSms",
      	"parameter":{
      		"sms":{
      			"countryCode":"+86",
      			"mobile":"自己填写的手机号",
      			"templateCode":"自己的模板CODE"
      		}
      	},
      	"result":{
      		"code":200
      	},
      	"spendTime":0,
      	"uri":"/sms/sendTo",
      	"url":"xxx",
      	"username":"1014066909280374785"
      }
      
      
    • 手机截图:在这里插入图片描述

5 后记

tips:上述xxx为a-li-yun去掉-:卧槽这就涉嫌广告不给审核通过nb

​ 欢迎交流学习,下面为联系方式和仓库源代码地址

❓Q-Q:-806797785-

⭐️源代码仓库地址:->gitee.com/gaogzhen/coin-exchange<-

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

gaog2zh

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值