SpringBoot整合阿里云短信服务

1. 准备工作

  • 注册阿里云账号:首先确保你有一个阿里云账号,并且已经开通了短信服务。
  • 获取AccessKey ID和AccessKey Secret:在阿里云控制台的安全管理页面创建AccessKey,这是访问阿里云API的凭证。
  • 申请短信签名和模板:在阿里云短信服务控制台申请短信签名和短信模板,签名用于标识发送者的身份,模板用于定义短信内容,需要审核通过才能使用。

在这里插入图片描述

2. 添加依赖

在Spring Boot项目的pom.xml文件中添加阿里云短信服务SDK的依赖。例如:

<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>aliyun-java-sdk-core</artifactId>
    <version>4.6.0</version>
</dependency>
<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>aliyun-java-sdk-dysmsapi</artifactId>
    <version>2.1.0</version>
</dependency>

3. 配置阿里云短信服务

application.ymlapplication.properties中配置AccessKey ID、AccessKey Secret以及其他可能需要的参数,例如:

sms:
  aliyun:
    accessKeyId: your-access-key-id
    accessKeySecret:  your-access-key-secret
    signName: ####
    # 是否开启短信服务
    pushSms: true
    templateCode: SMS_#########

4. 创建配置类

package com.example.demo.config.sms;

import com.aliyun.teaopenapi.models.*;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * @author xueyaoxuan
 */
@Data
@Component
@ConfigurationProperties(prefix = "sms.aliyun")
public class AliYunSmsConfig {

    private String accessKeyId;
    private String accessKeySecret;
    private String signName;
    private boolean isPushSms;

    /**
     * 使用AK&SK初始化账号Client
     *
     * @return Client
     * @throws Exception
     */
    public com.aliyun.dysmsapi20170525.Client createClient() throws Exception {
        Config config = new Config()
                // AccessKey ID
                .setAccessKeyId(this.getAccessKeyId())
                // AccessKey Secret
                .setAccessKeySecret(this.getAccessKeySecret());
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new com.aliyun.dysmsapi20170525.Client(config);
    }

}

5. 创建服务类

创建一个服务类来封装发送短信的逻辑

package com.example.demo.sms;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.example.demo.config.sms.AliYunSmsConfig;
import com.example.demo.config.ResultCode;
import com.example.demo.exception.base.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 阿里云短信服务实现
 * @author xueyaoxuan
 */
@Slf4j
@Component
public class AliYunSmsServiceImpl implements SmsService {

    @Autowired
    AliYunSmsServiceImpl (AliYunSmsConfig aliYunSmsConfig) {
        this.aliYunSmsConfig = aliYunSmsConfig;
    }

    private AliYunSmsConfig aliYunSmsConfig;

    @Override
    public void sendSms(List<String> mobiles, String message, String code) {
        SendSmsResponse sendSmsResponse = null;
        try{
            //调用阿里云api手机号上限1000
            if (mobiles.size()>1000){
                throw new BaseException(ResultCode.EM_SMS_MAX_LIMIT);
            }
            //检验手机号格式
            mobiles.forEach(mobile->{
                if (StrUtil.isAllEmpty(mobile)){
                    throw new BaseException(ResultCode.EM_SMS_INVALID_MOBILE);
                }
            });
            sendSmsResponse = sendALiYunSms(mobiles.stream().collect(Collectors.joining(",")),
                    message, code);
            log.info("阿里云短信服务响应:[{}]",JSON.toJSONString(sendSmsResponse));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送阿里云短信
     *
     * @param mobiles 手机号列表
     * @param message json格式的模板参数
     * @param code 阿里云短信模板code
     * @return
     * @throws Exception
     */
    private SendSmsResponse sendALiYunSms(String mobiles,String message,String code) throws Exception {

        //初始化Client对象
        Client client = aliYunSmsConfig.createClient();

        //构建请求参数
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setPhoneNumbers(mobiles)
                .setSignName(aliYunSmsConfig.getSignName())
                .setTemplateCode(code)
                .setTemplateParam(message);
        //发送短信
        return client.sendSms(sendSmsRequest);

    }

}

6.自定义异常

package com.example.demo.config;

import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;

import java.io.Serializable;

/**
 * ResultCode : 响应封装实现类
 *
 * @author zyw
 * @create 2023/6/15
 */
@AllArgsConstructor
@NoArgsConstructor
public enum ResultCode implements IResultCode, Serializable {

    //短信发送次数超过限制
    EM_SMS_MAX_LIMIT("10001","短信发送次数超过限制"),
    //无效的手机号码
    EM_SMS_INVALID_MOBILE("10002","无效的手机号码");

    @Override
    public String getCode() {
        return code;
    }

    @Override
    public String getMsg() {
        return msg;
    }

    private String code;

    private String msg;

    @Override
    public String toString() {
        return "{" +
                "\"code\":\"" + code + '\"' +
                ", \"msg\":\"" + msg + '\"' +
                '}';
    }


    // 默认系统执行错误
    public static ResultCode getValue(String code) {
        for (ResultCode value : values()) {
            if (value.getCode().equals(code)) {
                return value;
            }
        }
        return ECEPTION;
    }
}

7.使用服务类发送短信

在需要发送短信的地方注入SmsService并调用其方法发送短信。

package com.example.demo.controller;

import com.alibaba.fastjson.JSON;
import com.example.demo.sms.SmsService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * SmsController : 短信控制器
 *
 * @author zyw
 * @create 2024-06-11  15:56
 */

@RestController
@Tag(name = "短信控制器")
@RequestMapping("sms")
public class SmsController {

    @Resource
    private SmsService smsService;

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

    //发送短信
    @Operation(summary = "单个手机号发送短信验证码")
    @PostMapping("/SendATextMessageByhone")
    public String SendATextMessageByhone(String mobile, String message) {
        Map<String, String> tempContentMap = new HashMap<>();
        tempContentMap.put("code", String.valueOf(message));
        smsService.sendSms(List.of(mobile), JSON.toJSONString(tempContentMap), templateCode);
        return "短信发送成功";
    }


}

请确保替换成你自己的AccessKey信息、签名、模板CODE等,以及根据实际情况调整参数。此外,考虑到安全性,不要直接在版本控制系统中提交敏感信息,如AccessKey ID和AccessKey Secret,应使用环境变量或外部配置管理服务来管理这些信息。

8.测试短信

在这里插入图片描述

在这里插入图片描述

  • 18
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

柚几哥哥

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

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

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

打赏作者

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

抵扣说明:

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

余额充值