java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > SpringBoot集成阿里云短信

SpringBoot集成阿里云短信的实战指南

作者:悟空码字

在SpringBoot项目中集成阿里云短信服务,核心是完成一系列前置申请,并调用其官方SDK发送短信,下面小编就和大家详细介绍一下具体的实现方法吧

在SpringBoot项目中集成阿里云短信服务,核心是完成一系列前置申请,并调用其官方SDK发送短信。整个流程从前置准备到代码集成,步骤清晰。

阿里云短信服务概述

阿里云短信服务提供高并发、安全的全球短信发送能力,支持验证码、通知、营销等场景。其主要特点如下:

特性维度具体说明
核心能力提供三网合一通道,秒级可达,支持国内及全球200多个国家/地区。
安全与管控基于阿里云账户与RAM权限管理,支持设置日发送量上限、单用户频次阈值,并具备验证码防盗刷监控。
计费模式采用短信套餐包优先抵扣,超出后按量计费的模式。国内验证码/通知短信低至0.045元/条起。
使用限制仅支持企业认证账号;发送前需完成资质、签名、模板的申请与审核;对发送频率有严格限制(例如验证码同一号码最多1条/分钟)。

集成前必须完成的控制台配置

编写代码前,你必须在阿里云控制台 完成一系列配置,这是短信发送的前提。

1.开通服务与购买资源包

2.创建AccessKey

3.申请短信签名与模板

SpringBoot项目集成详细步骤

完成控制台配置后,即可在SpringBoot项目中集成。

第1步:添加Maven依赖 在项目的pom.xml中添加阿里云短信服务SDK的依赖。

<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>dysmsapi20180501</artifactId>
    <version>2.0.24</version> <!-- 请使用Maven仓库中的最新版本 -->
</dependency>

第2步:配置应用参数application.ymlapplication.properties中配置必要的参数。

# application.yml 配置示例
aliyun:
  sms:
    # 从控制台获取的AccessKey信息
    access-key-id: your-access-key-id
    access-key-secret: your-access-key-secret
    # 短信服务接入点(Endpoint),国内一般为 dysmsapi.aliyuncs.com
    endpoint: dysmsapi.aliyuncs.com
    # 控制台申请并通过审核的签名名称(无需加【】)
    sign-name: 你的签名
    # 控制台申请并通过审核的模板CODE
    template-code: SMS_123456789

第3步:创建配置类与Service 创建一个配置类来初始化SDK客户端,并编写发送短信的服务类。

import com.aliyun.dysmsapi20180501.Client;
import com.aliyun.teaopenapi.models.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

@Configuration
public class AliyunSmsConfig {

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

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

    @Value("${aliyun.sms.endpoint}")
    private String endpoint;

    /**
     * 创建并返回阿里云短信服务的Client实例。
     * 该Bean可用于整个Spring容器。
     */
    @Bean
    public Client createClient() throws Exception {
        Config config = new Config()
                .setAccessKeyId(accessKeyId)
                .setAccessKeySecret(accessKeySecret);
        config.endpoint = endpoint;
        return new Client(config);
    }
}
import com.aliyun.dysmsapi20180501.Client;
import com.aliyun.dysmsapi20180501.models.SendMessageWithTemplateRequest;
import com.aliyun.dysmsapi20180501.models.SendMessageWithTemplateResponse;
import com.aliyun.teautil.models.RuntimeOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class SmsService {

    @Autowired
    private Client smsClient;

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

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

    /**
     * 发送短信验证码
     * @param phoneNumber 目标手机号(国内号码需带国际区号86)
     * @param templateParam 模板变量对应的JSON字符串,如:{"code":"123456"}
     * @return 是否发送成功
     */
    public boolean sendSms(String phoneNumber, String templateParam) {
        try {
            SendMessageWithTemplateRequest request = new SendMessageWithTemplateRequest()
                    .setTo(phoneNumber) // 接收方手机号
                    .setSignName(signName) // 短信签名
                    .setTemplateCode(templateCode) // 短信模板CODE
                    .setTemplateParam(templateParam); // 模板变量JSON

            RuntimeOptions runtime = new RuntimeOptions();
            SendMessageWithTemplateResponse response = smsClient.sendMessageWithTemplateWithOptions(request, runtime);

            // 根据响应判断是否成功,"OK"表示成功[citation:4]
            return "OK".equals(response.getBody().getResponseCode());
        } catch (Exception e) {
            // 此处应记录日志,并根据业务需要进行异常处理
            e.printStackTrace();
            return false;
        }
    }
}

第4步:在Controller中调用 创建一个简单的控制器来提供发送短信的HTTP接口。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SmsController {

    @Autowired
    private SmsService smsService;

    @GetMapping("/sendCode")
    public String sendVerificationCode(@RequestParam String phone) {
        // 生成随机验证码(示例)
        String code = String.valueOf((int)((Math.random() * 9 + 1) * 100000));
        // 构造模板参数(必须与申请模板时的变量名一致)
        String templateParam = "{\"code\":\"" + code + "\"}";

        boolean isSuccess = smsService.sendSms(phone, templateParam);
        if (isSuccess) {
            // 在实际业务中,此处应将验证码与手机号关联并存入缓存(如Redis),设置有效期
            return "验证码发送成功!";
        } else {
            return "验证码发送失败,请稍后重试。";
        }
    }
}

总结

按照上述步骤,即可在SpringBoot项目中集成阿里云短信。最后,有几个关键点需要注意:

到此这篇关于SpringBoot集成阿里云短信的实战指南的文章就介绍到这了,更多相关SpringBoot集成阿里云短信内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文