SpringBoot实现阿里云短信发送的示例代码
作者:指尖听戏 发布时间:2023-05-15 21:08:54
标签:SpringBoot,阿里云,短信
阿里云accessID和secret请自行进入阿里云申请
sms.template.code
请进入阿里云,进行短信服务进行魔板添加
开源代码地址在文章末尾
话不多说,直接上代码:
application.properties:
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
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
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;
}
}
主要代码已贴上
具体开源代码:
前端代码
后端代码
来源:https://blog.csdn.net/qq_38140292/article/details/124066755


猜你喜欢
- 使用正则抓捕网上邮箱这就是我们需要抓捕的网站。实现思路:1、使用java.net.URL对象,绑定网络上某一个网页的地址2、通过java.n
- 说到内存管理,笔者这里想先比较一下java与C、C++之间的区别:在C、C++中,内存管理是由程序员负责的,也就是说程序员既要完成繁重的代码
- 本文实例为大家分享了C#使用Socket实现本地多人聊天室的具体代码,供大家参考,具体内容如下【脚本一:Server端】使用本机地址:127
- 在Activity之间传递数据还可以利用一些技巧,不管windows还是Linux操作系统,都会支持一种叫剪切板的技术,也就是某一个程序将一
- 这几天恰好和朋友谈起了递归,忽然发现不少朋友对于“尾递归”的概念比较模糊,网上搜索一番也没有发现讲解地完整详细的资料,于是写了这么一篇文章,
- 本篇内容主要讲述了实现基于微软账户的第三方身份验证、实现双因子身份验证、 验证码机制这3个内容。实现基于微软账户的第三方身份验证在
- 要点1:cmd命令行的输入命令netsh wlan set hostednetwork mode=allow ssid=用户名
- 如今,手机应用渗透到各行各业,数量难以计数,其中大多数应用都会使用到网络,与服务器的交互势不可挡,那么android当中访问网络有哪些方式呢
- 本人一直使用的是Eclipse作为开发工具的,不过现在IDEA非常的受推崇,所以决定上手试一试。网上有很多旗舰版的文章,我没有仔细看,我这次
- 目录题目及要求:提示:原创代码:代码思路:题目及要求:给定一个字符串 s ,请你找出其中不含有重复字符的 最长子串 的长度。提示:0 <
- 一直想练习下java多线程抓取数据。有天被我发现,铃声多多的官网(http://www.shoujiduoduo.com/main/)有大量
- 本文实例为大家分享了android实现录屏小功能的具体代码,供大家参考,具体内容如下思路android实现录屏功能有两种方案,一种是直接使用
- 本文为大家分享了Android使用线程获取网络图片的具体代码,供大家参考,具体内容如下AndroidManifest.xml &n
- 在未分享整个查询分页的执行代码之前,先了解一下执行流程。1.总体上是利用mybatis的插件 * ,在sql执行之前拦截,为查询语句加上li
- 在看KMP算法时,想要简单的统计一下执行时间和性能。得出的结论是: Java的String的indexOf方法性能最好,其次是KMP算法,其
- 分部类(Partial Class)在C#2.0引入,分部方法(Partial Method)在C#3.0引入,这两个语法特性都具有相同的特
- 一、什么是跨域1.1、为什么会出现跨域问题出于浏览器的同源策略限制。同源策略(Sameoriginpolicy)是一种约定,它是浏览器最核心
- 一、业务需求实现省份与城市的二级联动二、实现效果三、代码实现1. province_city.jsp前端界面实现<%@ p
- 上篇文章中我们介绍了浅谈Spring的两种配置容器,接下来我们就了解下spring中的FactoryBean的相关内容,具体如下。从Sess
- C++编写的一个图书管理系统,供大家参考,具体内容如下2018大一的课设,搬到这纪念一下,共1200多行代码为图书管理人员编写一个图书管理系