spring boot对接阿里短信

一:依赖包安装

复制代码
<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>dysmsapi20170525</artifactId>
    <version>4.2.0</version>
</dependency>

二:阿里短信配置

在application.yaml配置阿里短信,路径地址为:src/main/resources/application.yaml

复制代码
aliyun:
  sms:
    access-key-id: xxx
    access-key-secret: xxx
    endpoint: dysmsapi.aliyuncs.com
    sign-name: xxx
    template-code: xxx # 短信模板CODE

三:短信配置属性类

复制代码
package com.example.demo.properties;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Data
@Component
@ConfigurationProperties(prefix = "aliyun.sms")
public class AliSmsProperties {
    private String accessKeyId;
    private String accessKeySecret;
    private String endpoint;
    private String signName;
    private String templateCode;
}

四:短信服务

复制代码
package com.example.demo.service;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.dysmsapi20170525.models.SendSmsResponseBody;
import com.aliyun.teaopenapi.models.Config;
import com.example.demo.properties.AliSmsProperties;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tools.jackson.databind.ObjectMapper;

import static com.aliyun.teautil.Common.toJSONString;

import java.util.Map;

@Service
public class AliSmsService {

    @Resource
    private AliSmsProperties aliSmsProperties;
    @Autowired
    private ObjectMapper objectMapper;

    public Client createClient() throws Exception {
        Config config = new Config()
                .setAccessKeyId(aliSmsProperties.getAccessKeyId())
                .setAccessKeySecret(aliSmsProperties.getAccessKeySecret())
                .setEndpoint(aliSmsProperties.getEndpoint());
        return new Client(config);
    }


    public boolean send(String phone, Map params) throws Exception {
        //初始化请求客户端
        Client client = createClient();
        try {
            SendSmsRequest sendSmsRequest = new SendSmsRequest();

            //手机号
            sendSmsRequest.setPhoneNumbers(phone);
            // 短信签名
            sendSmsRequest.setSignName(aliSmsProperties.getSignName());
            // 模板CODE
            sendSmsRequest.setTemplateCode(aliSmsProperties.getTemplateCode());
            // 模板参数JSON
            sendSmsRequest.setTemplateParam(objectMapper.writeValueAsString(params));

            SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);

            SendSmsResponseBody body = sendSmsResponse.getBody();

            System.out.println(toJSONString(sendSmsResponse));
            System.out.println("ok".equals(body.getCode()));
            if ("OK".equals(body.getCode())) {
                //发送成功
                return true;
            } else {
                //发送失败
                return false;
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return false;
        }
    }
}

五:短信服务调用示例

复制代码
package com.example.demo.controller;

import com.example.demo.service.AliSmsService;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

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

@RestController
@RequestMapping("/sms")
public class SmsController {

    @Resource
    private AliSmsService aliSmsService;

    @GetMapping("/send")
    public Boolean send() throws Exception {

        String phone = "xxxxxxxx";
        Map<String, Object> params = new HashMap<>();
        params.put("code", "1234");

        boolean ok = aliSmsService.send(phone, params);
        return ok;
    }
}
相关推荐
KING-WU5121 小时前
Linux 工具之Make 与 Makefile
java·linux·服务器
马剑威(威哥爱编程)1 小时前
【AI全栈后端12-08】Spring Boot 用 MCP 统一接入内部系统:让 AI 接一次,全公司复用
java·人工智能·spring boot
顽疲1 小时前
从零用 Java 实现小红书 SpringBoot Vue UniApp(23)笔记话题多对多:一条笔记进多个话题池
java·vue.js·spring boot
做个文艺程序员2 小时前
MQ第02篇:RabbitMQ快速上手教程:AMQP模型详解+Spring Boot整合实战(附完整代码)
spring boot·消息队列·rabbitmq·java-rabbitmq·amqp
木井巳2 小时前
【BFS 解决拓扑排序】课程表
java·算法·leetcode·广度优先·宽度优先·推荐算法·图搜索算法
RuoyiOffice2 小时前
SpringBoot3 企业定时结算架构:考勤日结、合同到期、库存预警与财务结转如何可靠执行
spring boot·xxl-job·定时任务·分布式任务·spring boot 3·幂等设计·ruoyi office
Crazy________2 小时前
05Linux内存管理核心原理与运维实战
java·开发语言
Nebula_g2 小时前
JavaSE拓展:工具类Executors
java·开发语言·后端·spring·基础·javase
长弓三石2 小时前
企业级Harness开源平台BizBuddy适配AgentScope-2.0.4并发布0.7.0版本
java·人工智能·aigc