服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - SpringBoot实现阿里云短信发送的示例代码

SpringBoot实现阿里云短信发送的示例代码

2022-11-10 11:40指尖听戏 Java教程

这篇文章主要为大家介绍了如何利用SpringBoot实现阿里云短信发送,文中的示例代码讲解详细,对我们学习或工作有一定帮助,需要的可以参考一下

阿里云accessID和secret请自行进入阿里云申请

sms.template.code

请进入阿里云,进行短信服务进行魔板添加

开源代码地址在文章末尾

话不多说,直接上代码:

application.properties:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
server.port=8002
#server.servlet.context-path=/
spring.datasource.url=jdbc:mysql://localhost:3306/ssm_message?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=19961117Lhh
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#开启驼峰命名
mybatis.configuration.map-underscore-to-camel-case=true
#设置超时时间-可自行调整
sms.default.connect.timeout=sun.net.client.defaultConnectTimeout
sms.default.read.timeout=sun.net.client.defaultReadTimeout
sms.timeout=10000
#初始化ascClient需要的几个参数
#短信API产品名称(短信产品名固定,无需修改)
sms.product=Dysmsapi
#短信API产品域名(接口地址固定,无需修改)
sms.domain=dysmsapi.aliyuncs.com
#替换成你的AK (产品密)
#你的accessKeyId,填你自己的 上文配置所得  自行配置
sms.access.key.id=xxxx
#你的accessKeyId,填你自己的 上文配置所得  自行配置
sms.access.key.secret=xxxx
#阿里云配置你自己的短信模板填入
sms.template.code=SMS_238470888

messageController

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package com.example.demo.controller;
 
import com.alibaba.fastjson.JSON;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.example.demo.service.MessageService;
import com.example.demo.utils.MessageUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
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;
 
@Api(description = "短信接口")
@RequestMapping("/smsLogin")
@RestController
public class MessageController {
    @Autowired
    public MessageService messageService;
 
    @Autowired
    public MessageUtils messageUtils;
 
    @ApiOperation(value = "获取短信验证码接口", notes = "获取短信验证码接口")
    @GetMapping("/sendMessage")
    public Map<String, Object> getSMSMessage(String phone) {
        Map<String, Object> map = new HashMap<>();
        if (phone == null || phone == "") {
            map.put("code", "FAIL");
            map.put("msg", "手机号为空");
            return map;
        }
        Map smsMap = messageUtils.getPhoneMsg(phone);
        if("OK".equals(smsMap.get("status"))){
            Map data = messageService.selectSMSDataByPhone(phone);
            map.put("phone", phone);
            map.put("smsCode", smsMap.get("msg"));
            // 将验证码存入数据库  也可以考虑用redis等方式 这里就用数据库做例子
            if (data != null) {
                messageService.updateSMSDataByPhone(map);
            } else {
                messageService.insert(map);
            }
            smsMap.put("msg", "成功");
        }
        return smsMap;
    }
 
    @ApiOperation(value = "短信校验登录接口", notes = "短信校验登录接口")
    @GetMapping("/login")
    public Map<String, Object> login(String phone, String smsCode) {
        Map<String, Object> map = new HashMap<>();
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(smsCode)) {
            map.put("code", "FAIL");
            map.put("msg", "请检查数据");
            return map;
        }
        // 取出对应的验证码进行比较即可
        Map smsMap = messageService.selectSMSDataByPhone(phone);
        if (smsMap == null) {
            map.put("code", "FAIL");
            map.put("msg", "该手机号未发送验证码");
            return map;
        }
        String code = (String) smsMap.get("sms_code");
        if (!smsCode.equals(code)) {
            map.put("code", "FAIL");
            map.put("msg", "验证码不正确");
            return map;
        }
        map.put("code", "OK");
        map.put("msg", "success");
        return map;
    }
}

MessageUtils

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
package com.example.demo.utils;
 
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
 
import java.util.HashMap;
import java.util.Map;
 
 
@Component
public class MessageUtils {
    @Autowired
    RestTemplate restTemplate;
 
    @Value("${sms.default.connect.timeout}")
    private String DEFAULT_CONNECT_TIMEOUT;
 
    @Value("${sms.default.read.timeout}")
    private String DEFAULT_READ_TIMEOUT;
 
    @Value("${sms.timeout}")
    private String SMS_TIMEOUT;
 
    @Value("${sms.product}")
    private String SMS_PRODUCT;
 
    @Value("${sms.domain}")
    private String SMS_DOMAIN;
 
    @Value("${sms.access.key.id}")
    private String SMS_ACCESSKEYID;
 
    @Value("${sms.access.key.secret}")
    private String SMS_ACCESSKEYSECRET;
 
    @Value("${sms.template.code}")
    private String TEMPLATE_CODE;
 
    private static String code;//code对应你短信目标里面的参数
 
    public Map getPhoneMsg(String phone) {
        if (phone == null || phone == "") {
            System.out.println("手机号为空");
            return null;
        }
        // 设置超时时间-可自行调整
        System.setProperty(DEFAULT_CONNECT_TIMEOUT, SMS_TIMEOUT);
        System.setProperty(DEFAULT_READ_TIMEOUT, SMS_TIMEOUT);
        // 初始化ascClient需要的几个参数
        final String product = SMS_PRODUCT;
        final String domain = SMS_DOMAIN;
        // 替换成你的AK
        final String accessKeyId = SMS_ACCESSKEYID;
        final String accessKeySecret = SMS_ACCESSKEYSECRET;
        // 初始化ascClient,暂时不支持多region
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou",
                accessKeyId, accessKeySecret);
 
        Map map = new HashMap();
        try {
            DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product,
                    domain);
 
            //获取验证码
            code = vcode();
            IAcsClient acsClient = new DefaultAcsClient(profile);
            // 组装请求对象
            SendSmsRequest request = new SendSmsRequest();
            // 使用post提交
            request.setMethod(MethodType.POST);
            // 必填:待发送手机号。支持以逗号分隔的形式进行批量调用,批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式
            request.setPhoneNumbers(phone);
            // 必填:短信签名-可在短信控制台中找到
            request.setSignName("java学习");
            // 必填:短信模板-可在短信控制台中找到
            request.setTemplateCode(TEMPLATE_CODE);
            // 可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为$[code]"时,此处的值为
            // 友情提示:如果JSON中需要带换行符,请参照标准的JSON协议对换行符的要求,比如短信内容中包含\r\n的情况在JSON中需要表示成\\r\\n,否则会导致JSON在服务端解析失败
            request.setTemplateParam("{ \"code\":\"" + code + "\"}");
            // 可选-上行短信扩展码(无特殊需求用户请忽略此字段)
            // request.setSmsUpExtendCode("90997");
            // 可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
            request.setOutId("yourOutId");
            // 请求失败这里会抛ClientException异常
            SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
            map.put("status", sendSmsResponse.getCode());
            if (sendSmsResponse.getCode() != null
                    && sendSmsResponse.getCode().equals("OK")) {
                // 请求成功
                map.put("msg", code);
            } else {
                //如果验证码出错,会输出错误码告诉你具体原因
                map.put("msg", sendSmsResponse.getMessage());
            }
        } catch (Exception e) {
            e.printStackTrace();
            map.put("status", "FAIL");
            map.put("msg", "获取短信验证码失败");
        }
        return map;
    }
 
    /**
     * 生成6位随机数验证码
     *
     * @return
     */
    public static String vcode() {
        String vcode = "";
        for (int i = 0; i < 6; i++) {
            vcode = vcode + (int) (Math.random() * 9);
        }
        return vcode;
    }
 
}

主要代码已贴上

具体开源代码:

前端代码

后端代码

以上就是SpringBoot实现阿里云短信发送的示例代码的详细内容,更多关于SpringBoot阿里云短信发送的资料请关注服务器之家其它相关文章!

原文链接:https://blog.csdn.net/qq_38140292/article/details/124066755

延伸 · 阅读

精彩推荐
  • Java教程Java如何实现定时任务

    Java如何实现定时任务

    这篇文章主要介绍了Java如何实现定时任务,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小...

    chenssy2632020-07-31
  • Java教程详解spring boot 使用application.properties 进行外部配置

    详解spring boot 使用application.properties 进行外部配置

    这篇文章主要介绍了详解spring boot 使用application.properties 进行外部配置,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看...

    liuxg20133842020-08-29
  • Java教程springMvc请求的跳转和传值的方法

    springMvc请求的跳转和传值的方法

    本篇文章主要介绍了springMvc请求的跳转和传值的方法,这里整理了几种跳转方式,具有一定的参考价值,感兴趣的小伙伴们可以参考一下。...

    liuconglin5262020-08-11
  • Java教程java对数组进行排序的方法

    java对数组进行排序的方法

    这篇文章主要介绍了java对数组进行排序的方法,涉及java数组排序的技巧,需要的朋友可以参考下 ...

    damaolly2962019-12-12
  • Java教程聊聊Java动态线程池的九个场景

    聊聊Java动态线程池的九个场景

    hippo4j 不止于 Java ThreadPoolExecutor 的增强,Dubbo、RabbitMQ、RocketMQ、Hystrix、Tomcat、Jetty、Undertow 等框架线程池也都有进行监控和动态变更。...

    龙台的技术笔记4122022-08-29
  • Java教程Java Spring的refresh方法你知道吗

    Java Spring的refresh方法你知道吗

    这篇文章主要为大家详细介绍了Java Spring的refresh方法,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给...

    油头怪11082022-10-09
  • Java教程mybatis-generator如何自定义注释生成

    mybatis-generator如何自定义注释生成

    这篇文章主要介绍了mybatis-generator如何自定义注释生成的操作,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...

    一头磕在键盘上7022021-12-23
  • Java教程重新理解Java泛型

    重新理解Java泛型

    这篇文章主要介绍了重新理解Java泛型,具有一定参考价值,需要的朋友可以了解下。...

    mengwei5612021-02-21