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;
    }
}
相关推荐
2301_7807896618 分钟前
跨平台适配!SDK 游戏盾兼容全终端游戏场景
java·网络·ddos
学长毕设1 小时前
基于springboot的食品仓库管理系统
java·spring boot·后端
步行cgn2 小时前
FormHttpMessageConverter 详解:Spring MVC 中表单数据的读写转换器
java·spring·mvc
龙亘川2 小时前
构建城市公共安全数字底座:亘川智城智慧安防系统全维度解读
java·大数据·开发语言·人工智能·信息可视化
金銀銅鐵2 小时前
[Java] 用 CLI 展示 EnumMap 增删键值对时的内部变化
java·源码·ai编程
秋天的怀念_David2 小时前
第二十二夜 · 数字迷雾
java·程序人生·算法
Raas1003 小时前
AI网关部署方案?从部署到上线全流程
java·开发语言·人工智能·gateway·ai网关·企业级ai网关·企业级ai产品
niucloud-admin3 小时前
NIUCLOUD PHP SAAS上门家政使用文档:城市管理
java·前端·php
霸道流氓气质4 小时前
智能客服组件:分层意图识别、RAG Advisor 与人工转接状态机的 Vue3 + Spring AI 生产级实战
java·人工智能·spring
captain3764 小时前
MyBatis操作数据库(入门2)
java·数据库·spring boot·后端·spring·mybatis