SpringBoot+vue 使用阿里云的短信功能发送手机验证码

article/2025/8/27 19:20:06

前言: 小编后端用的是Springboot 前端用的是vue ,小编主要是写后台,前端页面比较简陋,后期还要调优,写的不对处还望多多包涵。

环境: 需要先准备好阿里云的账号和一些必要的参数。详情见我的另一篇博客。

            https://blog.csdn.net/tangthh123/article/details/103769542

阿里云

开发者可以按照阿里云的这个开发者手册开发。

https://help.aliyun.com/document_detail/101300.html?spm=a2c4g.11186623.6.610.5ed850a4DjrhHY

发送短信这个接口如何调用? 这个网址还提供了调试功能,很方便。

https://help.aliyun.com/document_detail/101414.html?spm=a2c4g.11186623.6.624.15b85f30AyGxea

 

效果图

输入手机号 ,点击获取验证码,调用后台接口每次给手机号码发送验证码,验证码是随机的。

发送到手机上的验证码图片

前端代码

前端使用vue写的,要配置路由,这部分我就先省略了

<template><el-card class="box-card"><div slot="header" class="clearfix"><span>绑定手机验证码</span></div><el-form><el-form-item><el-input v-model="phoneNumber" placeholder="请输入手机号"><el-button slot="append" @click="getVerifyCode" :disabled="disabled">{{btnTitle}}</el-button></el-input></el-form-item><el-form-item><el-input v-model="verifyCode" placeholder="请输入验证码"></el-input></el-form-item><el-button type="primary" @click="bindUserPhone">登录</el-button></el-form></el-card>
</template><script>
export default {name: "",data() {return {phoneNumber: "",verifyCode: "",codeStr:"",disabled: false,btnTitle: "获取验证码",};},methods: {bindUserPhone(){//绑定用户手机验证码const bindData = {phone: this.phoneNumber,verifyNumber : this.verifyCode}this.$axios.post('/api/boundUserByPhone', bindData).then(res => {console.log(res.data.message);alert(res.data.message);});},//请求发送验证码的方法getVerifyCode() {// 请求表格数据const data = {phone: this.phoneNumber}this.$axios.post('/api/sendMessage', data).then(res => {console.log("验证码发送成功");});}}
};</script><style lang="scss" scoped>
.el-input-group__append {.el-button {padding: 4px;}  
}
.el-button.is-disabled, .el-button.is-disabled:focus, .el-button.is-disabled:hover{background: none;
}
</style>

后端代码

(1)需要在pom.xml中引用jar包

<!--阿里云短信服务功能-->
<dependency><groupId>com.aliyun</groupId><artifactId>aliyun-java-sdk-core</artifactId><version>4.0.6</version> <!-- 注:如提示报错,先升级基础包版,无法解决可联系技术支持 -->
</dependency>
<dependency><groupId>com.aliyun</groupId><artifactId>aliyun-java-sdk-dysmsapi</artifactId><version>1.1.0</version>
</dependency>

 

 

(1).后端代码 我主要是写了俩个接口,sendMessage 这个接口是用来发送短信给手机号码,并且将发送的验证码返回给前端,用来和用户输入的验证码做判断。

需要注意的点:aliYunMessageService.sendSms(phoneNumber, code) 这个方便就是用来封装模板,调用阿里云接口。

(2).boundUserByPhone 这个接口是用户输入验证码以后绑定用户信息的接口,如果没有这个需求的话可以不需要。

 

接口部分

 /*** 使用阿里云发送手机验证码功能*/@PostMapping(value = "/sendMessage")public void sendMessageToIphone(@RequestBody AliyunMessageVo vo, HttpSession session) throws Exception {//1.准备好请求参数:phoneNumber、TemplateParamString phoneNumber = vo.getPhone();//随机生成手机验证码String code = CheckSumBuilder.getCheckSum();//2.调用接口,发短信SendSmsResponse response = aliYunMessageService.sendSms(phoneNumber, code);Thread.sleep(3000L);//查询发送消息接口记录if (response.getCode() != null && response.getCode().equals("OK")) {QuerySendDetailsResponse querySendDetailsResponse = aliYunMessageService.querySendDetails(response.getBizId(), phoneNumber);//对返回结果true 或者false进行一个全局判断String responseCode = querySendDetailsResponse.getCode();String responseMessage = querySendDetailsResponse.getMessage();//OK代表信息发送成功if ("OK".equals(responseCode) && "OK".equals(responseMessage)) {//将code 保存到session中,并且返回给前端,方便前端用来判断session.setAttribute("codeNumber", code);}}}/*** 根据手机号码绑定用户信息** @return*/@PostMapping(value = "/boundUserByPhone")public ResultData boundUserByPhone(@RequestBody AliyunMessageVo vo, HttpSession session) {BosUserModel userModel = (BosUserModel) session.getAttribute("user");vo.setUserModel(userModel);//阿里云发送的手机验证码String codeNumber = (String) session.getAttribute("codeNumber");vo.setNodeNumber(codeNumber);return userService.modifyUserModelByPhone(vo);}

业务逻辑层

调用阿里云的接口需要传一些参数,参数讲解部分

 

 

 

package com.bos.service.impl;import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsResponse;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.bos.service.AliYunMessageService;
import com.bos.util.AliYunParameterUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;import java.text.SimpleDateFormat;
import java.util.Date;/*** @Author tanghh* 阿里云的短信通知发送功能* @Date 2019/12/30 16:00*/
@Service
@Slf4j
public class AliYunMessageServiceImpl implements AliYunMessageService {/*** @param phoneNumber 手机号* @param code        验证码* @return* @throws ClientException SendSmsResponse* @desc :1.发送短信*/@Overridepublic SendSmsResponse sendSms(String phoneNumber, String code)  {SendSmsResponse sendSmsResponse = null;try{//1.准备好短信模板变量——验证码codeJSONObject jsonObject = new JSONObject();jsonObject.put("code", code);String TemplateParam = jsonObject.toJSONString();//2.可自助调整超时时间System.setProperty("sun.net.client.defaultConnectTimeout", "10000");System.setProperty("sun.net.client.defaultReadTimeout", "10000");//3.初始化acsClient,暂不支持region化IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", AliYunParameterUtil.accessKeyId, AliYunParameterUtil.accessSecret);DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", AliYunParameterUtil.PRODUCT, AliYunParameterUtil.DOMAIN);IAcsClient acsClient = new DefaultAcsClient(profile);//4.组装请求对象-具体描述见控制台-文档部分内容SendSmsRequest request = new SendSmsRequest();//必填:待发送手机号request.setPhoneNumbers(phoneNumber);//必填:短信签名-可在短信控制台中找到request.setSignName(AliYunParameterUtil.signName);//必填:短信模板-可在短信控制台中找到request.setTemplateCode(AliYunParameterUtil.TemplateCode);//可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为request.setTemplateParam(TemplateParam);//选填-上行短信扩展码(无特殊需求用户请忽略此字段)//request.setSmsUpExtendCode("90997");//可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者request.setOutId("sgaet2020168");//5.hint 此处可能会抛出异常,注意catchsendSmsResponse = acsClient.getAcsResponse(request);}catch (Exception e){log.error("发送阿里云短信失败",e);}return sendSmsResponse;}/*** @param bizId* @param phoneNumber* @return* @throws ClientException QuerySendDetailsResponse* @desc :2.短信发送记录查询接口* 用于查询短信发送的状态,是否成功到达终端用户手机*/@Overridepublic QuerySendDetailsResponse querySendDetails(String bizId, String phoneNumber) throws ClientException {//可自助调整超时时间System.setProperty("sun.net.client.defaultConnectTimeout", "10000");System.setProperty("sun.net.client.defaultReadTimeout", "10000");//初始化acsClient,暂不支持region化IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", AliYunParameterUtil.accessKeyId, AliYunParameterUtil.accessSecret);DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", AliYunParameterUtil.PRODUCT, AliYunParameterUtil.DOMAIN);IAcsClient acsClient = new DefaultAcsClient(profile);//组装请求对象QuerySendDetailsRequest request = new QuerySendDetailsRequest();//必填-号码request.setPhoneNumber(phoneNumber);//可选-流水号request.setBizId(bizId);//必填-发送日期 支持30天内记录查询,格式yyyyMMddSimpleDateFormat ft = new SimpleDateFormat("yyyyMMdd");request.setSendDate(ft.format(new Date()));//必填-页大小request.setPageSize(10L);//必填-当前页码从1开始计数request.setCurrentPage(1L);//hint 此处可能会抛出异常,注意catchQuerySendDetailsResponse querySendDetailsResponse = acsClient.getAcsResponse(request);return querySendDetailsResponse;}
}
/*** 手机验证码登录,绑定用户信息* @param vo* @return*/
@Override
public ResultData modifyUserModelByPhone(AliyunMessageVo vo) {ResultData resultData = new ResultData();try{//手机号码String phone = vo.getPhone();//阿里云发送的手机验证码String nodeNumber = vo.getNodeNumber();//用户输入的手机验证码String verifyNumber = vo.getVerifyNumber();//要保证绑定的手机号码是唯一的,如果已有,要提示当前手机号已被注册BosUserModel userModel = bosUserJPARepositoty.findBosUserModelByMobile(phone);if(userModel!=null){//只有阿里云发送的验证码和用户输入的验证码一致的时候,才能绑定到用户信息里面if(nodeNumber.equals(verifyNumber)){BosUserModel user = vo.getUserModel();BosUserModel bosUserModel = bosUserJPARepositoty.findOne(user.getId());bosUserModel.setMobile(phone);bosUserModel.setIsMobile("1");bosUserJPARepositoty.save(bosUserModel);resultData.setResult("true");resultData.setMessage("绑定手机验证码成功");}else{resultData.setResult("false");resultData.setMessage("验证码错误,请重新输入");}}else{resultData.setResult("false");resultData.setMessage("当前手机号码已注册");}}catch (Exception e){resultData.setResult("false");resultData.setMessage("绑定手机验证码失败");logger.error("绑定手机验证码失败",e);TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();}return resultData;
}

 

 

阿里云的参数配置类,参数配置类里面的参数需要替换。

package com.bos.util;/*** @Author tanghh* @Date 2019/12/30 15:45*/
public class AliYunParameterUtil {/*** 这个需要替换自己的AK(在阿里云的Accesskey管理中寻找)*/public static String accessKeyId = "*****";public static String  accessSecret = "*******";/*** 签名名称(需要替换以及只有审核后才能使用)在阿里云控制台中找到签名管理中的签名名称*/public static String signName ="******";/*** 模板code (需要替换 以及只有审核后才能使用) 在阿里云控制台中找到模板管理中的模板code*/public static String TemplateCode ="SMS_181236263";/*** 产品名称:云通信短信API产品,开发者无需替换*/public static final String PRODUCT = "Dysmsapi";/*** 产品域名,开发者无需替换*/public static final String DOMAIN = "dysmsapi.aliyuncs.com";public static String specialUrlEncode(String value) throws Exception {return java.net.URLEncoder.encode(value, "UTF-8").replace("+", "%20").replace("*", "%2A").replace("%7E", "~");}public static String sign(String accessSecret, String stringToSign) throws Exception {javax.crypto.Mac mac = javax.crypto.Mac.getInstance("HmacSHA1");mac.init(new javax.crypto.spec.SecretKeySpec(accessSecret.getBytes("UTF-8"), "HmacSHA1"));byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));return new sun.misc.BASE64Encoder().encode(signData);}
}

其他一些类。

package com.bos.data.model.vo;import com.bos.data.model.BosUserModel;
import lombok.Data;/*** @Author tanghh* @Date 2019/12/30 18:24*/
@Data
public class AliyunMessageVo {/*** 电话号码*/private String phone;/*** 用户信息*/private BosUserModel userModel;/*** 阿里云发送的手机验证码*/private String nodeNumber;/*** 用户输入的验证码*/private String verifyNumber;}

生成验证码的类

package com.bos.aliyun;import java.util.Random;/*** @Author tanghh* 验证码生成器* @Date 2019/12/30 16:07*/
public class CheckSumBuilder {/*** @param length 字符串长度* @param type   类型 (0: 仅数字; 2:仅字符; 别的数字:数字和字符)* @return String  随机串* @desc :1.随机产生字符串*/public static String getRandomStr(int length, int type) {String str = "";int beginChar = 'a';int endChar = 'z';// 只有数字if (type == 0) {beginChar = 'z' + 1;endChar = 'z' + 10;}// 只有小写字母else if (type == 2) {beginChar = 'a';endChar = 'z';}// 有数字和字母else {beginChar = 'a';endChar = 'z' + 10;}// 生成随机类Random random = new Random();for (int i = 0; i < length; i++) {int tmp = (beginChar + random.nextInt(endChar - beginChar));// 大于'z'的是数字if (tmp > 'z') {tmp = '0' + (tmp - 'z');}str += (char) tmp;}return str;}/*** @return String  6位数字验证码* @desc :2.获取6位数字验证码*/public static String getCheckSum() {return getRandomStr(6, 0);}
}

以上就是这次调用阿里云短信接口的全部代码,如果觉得对你有帮助的话,欢迎评论哦,共同进步。


http://chatgpt.dhexx.cn/article/VqajlMh5.shtml

相关文章

腾讯云短信服务实现 Java 发送手机验证码(SpringBoot+Redis 实现)

文章目录 腾讯云短信服务实现 Java 发送手机验证码&#xff08;SpringBootRedis 实现&#xff09;1、打开腾讯云短信服务2、创建短信签名3、创建短信正文模板4、等待全部审核完毕即可5、发送短信6、短信业务实战&#xff08;SpringBootRedis&#xff09;&#xff08;1&#xff…

Spring boot 发送手机验证码

由于阿里云现在的短信签名无法通过申请&#xff0c;所以我这里选择了中国网建SMS短信平台&#xff08;手机号注册即用&#xff0c;有免费赠送的几条短信测试&#xff09; demo代码地址&#xff1a;https://github.com/mer97/springboot-sendmessage Spring boot 实现发送手机验…

Java实现发送手机验证码,发送短信

要发送短信&#xff0c;我们需要第三方提供的短信接口&#xff0c;这里我使用阿里云的短信服务。 首先进入阿里云的官网&#xff0c;然后注册。登陆之后选择云通信——》短信服务 然后点击免费开通。 开通后进入控制中心&#xff0c;选择右上方的支持与服务&#xff0c;选择帮…

Java实现手机发送短信验证码

发送短信验证码首先要在互亿无线短信平台去开通短信服务,地址"ihuyi.com" 一定要留好自己申请的API ID,API key和模板参数说明:代码示例: pom导包 <!-- 短信 --> <dependency><groupId>dom4j</groupId><artifactId>dom4…

SSM发送手机验证码——以网建SMS为例

整理一下从大二开始写的东东 后台源码链接&#xff1a; 点我自取 到网建申请一个帐号&#xff0c;好像可以免费用10条短信 设置用户名、密钥&#xff0c;在发送的时候需要携带该信息 前端代码简化后如下&#xff0c;提交表单我用的是ajax&#xff0c;如果直接提交表单记得name…

Java实现发送手机验证码

向手机发送验证码在用户注册等等业务中会用到&#xff0c;下面我来介绍如何用Java实现向手机发送验证码。 笔者此处使用的是阿里云的短信服务&#xff0c;首先需要登录阿里云官方网站&#xff0c;找到并开通短信服务&#xff0c;然后需要申请短信签名和模版&#xff0c; 短信签…

java 实现发送手机验证码的功能 (超详细)

我这里使用的旦米&#xff08;http://www.danmi.com/&#xff09;你们用阿里的就去看看其他博客 1.首先注册一个旦米的账号,第一次注册会免费的送你10元。足够你去测试用&#xff0c;不用担心自己去充钱。 2.注册好了登录进去&#xff0c;必须要公司认证&#xff0c;认证通过之…

java实现发送手机验证码功能

1. 进入秒嘀科技&#xff08;http://www.miaodiyun.com/&#xff09;&#xff0c;注册一个账号 2. 注册好之后&#xff0c;点击 用户中心 -> 账户管理&#xff0c;就会进入如下界面 &#xff08;顺便提一下&#xff0c;新注册的用户&#xff0c;平台会免费赠送你10元&#…

vue使用element发送手机验证码倒计时

发送验证码倒计时 html <el-form class"form" :model"form" labeal-position"left"> <el-form-item label"姓名"><el-input v-model"form.Name" placeholder"请输入姓名"></el-input>…

C# WinForm 使用SMS接口发送手机验证码+图形验证码+IP限制

文章目录 前言功能实现一、功能界面二、创建图形验证码类三、创建存储IP地址的数据库表四、创建手机验证码类五、在Form1中调用以上两个类中的函数&#xff0c;实现功能 前言 1.发送手机验证码用的是网建的SMS接口&#xff08;http://sms.webchinese.cn/&#xff09;   2.手机…

uniapp | 发送手机验证码 button组件

一、功能和效果展示 1.组件功能 uniapp &#xff08;1&#xff09;按钮初始显示“发送”&#xff0c;点击按钮后按钮显示倒计时60s&#xff1b; &#xff08;2&#xff09;倒计时60s期间点击按钮&#xff0c;不会重置计时器&#xff1b; &#xff08;3&#xff09;倒计时60s结…

发送手机验证码

手机验证码不能自己生成&#xff0c;需要由第三方来完成发送。本文选择网易云作为第三方来发送验证码。 首先&#xff0c;我们要注册网易云账号&#xff0c;完成登陆。选择“产品与服务”选项中的“通信与视频”&#xff0c;点击创建应用&#xff0c;完成后&#xff0c;下方有…

java发送手机验证码实现

正文 今天来用java实现手机验证码的发送。 短信平台有很多&#xff0c;中国网建提供的SMS短信通&#xff0c;注册免费5条短信&#xff0c;3条彩信&#xff0c; http://sms.webchinese.cn/ 但是刚才试了&#xff0c;第一次用官方提供的demo发送成功&#xff0c;然后整合到自…

Excel 字符串拼接

例子&#xff1a;“exec sp_addextendedproperty N’MS_Description’, N’”&B1&“‘, N’SCHEMA’, N’dbo’,N’table’, N’”&A1&“” &#xff1a;公式 “ abc ” &#xff1a; “”中间为任意字符/字符串 & A1 &&#xff1a;&&中间为拼…

Excel如何插入文本字符串或字符

目录 1.用“&”连接的方法插入文本或字符的办法及实例 2.用TEXT函数插入“&#xffe5;”或“$"字符 3.用TEXT函数以及“&”连接符插入文本或符号 1.用“&”连接的方法插入文本或字符的办法及实例 &#xff08;1&#xff09;方法&#xff1a;关键在于用“&a…

excel连接字符串

Excel连接字符串的功能挺强大的。 很实用。 有2种方式。 1&#xff1a; 2&#xff1a; 1个是调用了concatnate函数&#xff0c;一个是使用了&(就是号的功能了)。

excel字符串和单元格拼接,Excel中将单元格的字符串进行合并的具体方法

在利用Excel进行办公时&#xff0c;对多个单元格的字符串进行合并是很常见的操作&#xff0c;但是对于刚接触Excel软件的小伙伴来说&#xff0c;可能有些困难。下面小编就与大家分享一下在Excel中实现字符串合并的方法&#xff0c;有需要的用户可以参考下。 Excel中如何合并文本…

excel中按条件合并字符串

若B列不为空则将A列和B列合并后给C列&#xff1b; C IF(ISBLANK(B1), B1,CONCAT(A1,B1)) 结果却出问题&#xff0c;当B列为空时&#xff0c;C列却显示0&#xff0c;解决方法是&#xff1a;选择C列设置单元格格式&#xff0c;选择自定义&#xff0c;在类型处添加 [0]" &q…

Excel技巧:巧用字符串连接

Excel中有一个基本的公式&#xff0c;就是把几个单元格中的字符串连接起来。 比如上面这个例子&#xff0c;A1&#xff0c;B1&#xff0c;C1单元格中字符串连接起来&#xff0c;只要在D1单元格中输入 A1&B1&C1即可。 下面我们开始使用字符串连接功能。 例1&#xff1a;…

Excel字符连接(concat)

Excel连接字符串有两个比较常用的方法。 1.concat函数 2.”&”连接符