【短信服务】----程序接入阿里云短信服务SMS保姆级教程2026

📅 2026/7/13 13:47:32
【短信服务】----程序接入阿里云短信服务SMS保姆级教程2026
前言我们使用阿里云短信SDK来进行发短信目前SDK V1.0不再维护现在使用的 V2.0 版本。了解流程一条短信由短信签名和短信模板组成因此在发送短信前您需要先完成短信资质以及签名、模板的申请工作并等待审核通过。通过模板变量自定义您可以实现短信内容的定制化。模版【阿里云】验证码为:587555有效期5分钟。如非本人操作请忽略。运营商实名报备流程平均需要5-7个工作日基于近期观测部分运营商实名报备流程需要7-10个工作日但运营商未对此时效进行承诺实际可能需要更长时间。建议您合理规划业务并提前申请相关资质和签名以确保在正式使用前有充足的时间完成实名报备。介绍短信服务 官方文档 短信服务(SMS)-阿里云帮助中心https://help.aliyun.com/zh/sms/?spma2c4g.11186623.0.0.68e85634txBQpj开通阿里云短信服务 点击国内消息 有资质管理、签名管理、模板管理这个要企业资质才能玩 正常就按照这个顺序配置 资质—签名—模板申请试用要先学习里面的步骤每个步骤点进去看看就行不需要操作就可以退出来即可完成因为是试用账号所有需要指定绑定的手机号才可以收到验证码准备工作需要提前准备申请 【资质管理】 【签名管理】【模版管理】调用API发送短信选择【专用】测试签名/模板 点击调用API发送短信点击发起调用 可以看到响应报文刚刚绑定的测试手机号就可以收到测试验证码SDK调用API找到SDK实例 点击SDK安装信息 获取maven依赖 添加进我们项目中。复制代码选择SDK代系V2.0 语言选择 Java 也可以选择异步,复制代码信息。替换AccessKeyId和AccessKeySecret由于工程代码使用的是更安全的无AK方式所以我们要改造一下代码使用我们自己配置的AK。然后运行代码发送短信即可。ConfigconfignewConfig();config.setAccessKeyId(xxxxx);config.setAccessKeySecret(xxxxx);returnnewClient(config);说明后续开发只需要把AK替换成自己的配置短信签名、模板代码、手机号码、模板变量即可。有问题可以查看官网文档短信服务_SDK中心-阿里云OpenAPI开发者门户 https://next.api.aliyun.com/api-tools/sdk/Dysmsapi?version2017-05-25languagejava-async-teatabprimer-doc常见验证码流程一般发送验证码由服务端生成验证码存储在Redis中存储在Redis中5分钟内有效调用阿里云短信发送验证码用户输入验证码从Redis拿到验证码进行校验一般只能1分钟发送一次验证码如果1分钟后重新获取之前验证码失效。代码实现参考public voidhandleSmsFlow(String phone){// 1.频率控制检查if(redisTemplate.hasKey(buildCoolingKey(phone))){thrownewBusinessException(操作过于频繁);}// 2.生成存储验证码String codegenerateRandomCode();redisTemplate.opsForValue().set(buildCodeKey(phone),code,5,MINUTES);redisTemplate.opsForValue().set(buildCoolingKey(phone),,1,MINUTES);// 3.异步发送短信CompletableFuture.runAsync(()-{try{smsClient.sendVerificationCode(phone,code);}catch(Exception e){alertService.notifySmsFailure(phone,code);}},smsThreadPool);}private StringbuildCoolingKey(String phone){returnsms:cooling:phone;}private StringbuildCodeKey(String phone){returnsms:code:phone;}工具 类使用 AI 对技术代码进行工具类封装。packagecom.taoran.sms.util;importcom.aliyun.dysmsapi20170525.Client;importcom.aliyun.dysmsapi20170525.models.SendSmsRequest;importcom.aliyun.dysmsapi20170525.models.SendSmsResponse;importcom.aliyun.teaopenapi.models.Config;importcom.aliyun.teautil.Common;importcom.aliyun.teautil.models.RuntimeOptions;importcom.aliyun.tea.TeaException;importlombok.extern.slf4j.Slf4j;importorg.springframework.beans.factory.annotation.Value;importorg.springframework.stereotype.Component;importjavax.annotation.PostConstruct;importjava.util.Map;/** * 阿里云短信服务工具类[3,6](ref) * 功能特性 * 1. 自动加载云资源配置 * 2. 动态模板参数支持 * 3. 异常重试机制 * 4. 全链路日志追踪 */Slf4j Component public class AliyunSmsUtil{// 通过Value注入配置参数生产环境推荐使用配置中心Value(${aliyun.sms.access-key-id})private String accessKeyId;Value(${aliyun.sms.access-key-secret})private String accessKeySecret;Value(${aliyun.sms.sign-name})private String signName;Value(${aliyun.sms.endpoint})private String endpointdysmsapi.aliyuncs.com;// 默认值private Client client;// 初始化客户端[6](ref)PostConstruct private voidinitClient()throws Exception{Config confignewConfig().setAccessKeyId(accessKeyId).setAccessKeySecret(accessKeySecret);config.endpointendpoint;this.clientnewClient(config);log.info(阿里云短信客户端初始化完成Endpoint: {},endpoint);}/** * 通用短信发送方法[3,6](ref) * param phoneNumbers 接收号码多个用逗号分隔 * param templateCode 模板CODE * param templateParams 模板参数键值对 * return 发送结果 */public SendSmsResponsesend(String phoneNumbers,String templateCode,MapString,StringtemplateParams){try{SendSmsRequest requestbuildRequest(phoneNumbers,templateCode,templateParams);returnexecuteSend(request);}catch(Exception e){log.error(短信发送异常 | phones:{} | template:{},phoneNumbers,templateCode,e);returnnull;}}// 构建请求对象[6](ref)private SendSmsRequestbuildRequest(String phoneNumbers,String templateCode,MapString,Stringparams){returnnewSendSmsRequest().setPhoneNumbers(phoneNumbers).setSignName(signName).setTemplateCode(templateCode).setTemplateParam(convertToJson(params));}// 执行发送操作[6](ref)private SendSmsResponseexecuteSend(SendSmsRequest request)throws Exception{RuntimeOptions runtimenewRuntimeOptions();try{SendSmsResponse responseclient.sendSmsWithOptions(request,runtime);log.debug(短信发送成功 | RequestId:{},response.getBody().requestId);returnresponse;}catch(TeaException e){handleTeaException(e);thrownewRuntimeException(阿里云服务异常,e);}}// 异常处理[6](ref)private voidhandleTeaException(TeaException e){log.error(阿里云API异常 || Code:{} | Message:{} | Recommend:{},e.getCode(),e.getMessage(),e.getData().get(Recommend));}// Map转JSON工具[3](ref)private StringconvertToJson(MapString,Stringparams){if(paramsnull||params.isEmpty())return{};StringBuilder jsonnewStringBuilder({);params.forEach((k,v)-json.append(\).append(k).append(\:\).append(v).append(\,));json.deleteCharAt(json.length()-1).append(});returnjson.toString();}}使用示例// 在Spring Boot控制器中使用RestController RequestMapping(/sms)public class SmsController{Autowired private AliyunSmsUtil smsUtil;PostMapping(/send-verification)public ResponseEntity?sendVerification(RequestParam String phone){MapString,StringparamsMap.of(code,generateRandomCode(6));SendSmsResponse responsesmsUtil.send(phone,SMS_154950909,params);if(response!nullOK.equals(response.getBody().getCode())){returnResponseEntity.ok(验证码发送成功);}returnResponseEntity.status(500).body(发送失败);}private StringgenerateRandomCode(intlength){// 生成随机验证码逻辑[6](ref)}}配置文件aliyun:sms:access-key-id:xxxxx access-key-secret:xxxx sign-name:阿里云短信测试 endpoint:dysmsapi.aliyuncs.com