java使用阿里云短信服务发送短信验证码

本文涉及的产品
云数据库 Redis 版,社区版 2GB
推荐场景:
搭建游戏排行榜
云原生内存数据库 Tair,内存型 2GB
数字短信套餐包(仅限零售电商行业),100条 12个月
简介: java使用阿里云短信服务发送短信验证码

需要依赖的pom:

<dependency><groupId>com.aliyun</groupId><artifactId>dysmsapi20170525</artifactId><version>2.0.1</version></dependency>


java代码:



packagecom.ehl.developerplatform.service.impl;
importcom.alibaba.fastjson.JSONObject;
importcom.aliyun.dysmsapi20170525.models.SendSmsRequest;
importcom.aliyun.dysmsapi20170525.models.SendSmsResponse;
importcom.aliyun.teaopenapi.models.Config;
importcom.ehl.developerplatform.config.SmsProperties;
importcom.ehl.developerplatform.enums.ResponseEnum;
importcom.ehl.developerplatform.exception.DeveloperPlatFormException;
importcom.ehl.developerplatform.pojo.DataResponse;
importcom.ehl.developerplatform.util.RedisPrefix;
importcom.ehl.developerplatform.util.RedisUtil;
importlombok.extern.slf4j.Slf4j;
importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.boot.context.properties.EnableConfigurationProperties;
importorg.springframework.stereotype.Service;
importjava.util.HashMap;
importjava.util.Map;
/*** #------------------------------------------------------------------- #* #                   CONFIDENTIAL --- CUSTOM STUDIOS                  #* #------------------------------------------------------------------- #* #                                                                    #* #                   @Project Name : develop                          #* #                                                                    #* #                   @File Name    : SmsService.java                  #* #                                                                    #* #                   @Programmer   : 王震                              #* #                                                                    #* #                   @Start Date   : 2021/4/28 18:08                  #* #                                                                    #* #                   @Last Update  : 2021/4/28 18:08                  #* #                                                                    #* #------------------------------------------------------------------- #* # Classes:                                                           #* #                                                                    #* #------------------------------------------------------------------- #*/@Slf4j@Service@SuppressWarnings("all")
@EnableConfigurationProperties(value=SmsProperties.class)
publicfinalclassSmsService {
@AutowiredprivateSmsPropertiessmsProperties;
@AutowiredprivateRedisUtilredisUtil;
privateSmsService() {
    }
/*** 功能描述: <br>* 〈根据用户输入的phone发送验证码〉** @Param: [phone] 电话号码* @Return: com.ehl.developerplatform.pojo.DataResponse* @Author: 王震* @Date: 2021/4/28 19:01*/publicDataResponse<?>sendSmsCode(finalStringphone) {
Stringcode=this.randomCode();
Stringmessage=this.sendMessage(phone, code).getBody().getMessage();
if (!"OK".equals(message)) {
log.error("手机号码:{},发送短信失败,失败原因:{},code:{}", phone, message,code);
returnDataResponse.fail(ResponseEnum.SEND_MESSAGE_ERROR);
        }
log.info("手机号码:{},发送短信成功,验证码为:{}", phone, code);
redisUtil.set(RedisPrefix.buildSendMessageKey(phone), code, 300);
returnDataResponse.success("短信发送成功!");
    }
publicSendSmsResponsesendMessage(finalStringphone, finalStringcode) {
try {
com.aliyun.dysmsapi20170525.Clientclient=createClient(smsProperties.getAccessKeyId(), smsProperties.getAccessKeySecret());
Map<String, Object>map=newHashMap<>();
map.put("code", code);
SendSmsRequestsendSmsRequest=newSendSmsRequest()
                    .setSignName(smsProperties.getSignName())
                    .setTemplateCode(smsProperties.getTemplate())
                    .setPhoneNumbers(phone)
                    .setTemplateParam(JSONObject.toJSONString(map));
// 复制代码运行请自行打印 API 的返回值returnclient.sendSms(sendSmsRequest);
        } catch (Exceptione) {
log.error("手机号码:{},发送短信失败,失败原因:{}", phone, e.getMessage());
thrownewDeveloperPlatFormException(ResponseEnum.SEND_MESSAGE_ERROR);
        }
    }
/*** 使用AK&SK初始化账号Client** @param accessKeyId* @param accessKeySecret* @return Client* @throws Exception*/publicstaticcom.aliyun.dysmsapi20170525.ClientcreateClient(finalStringaccessKeyId, finalStringaccessKeySecret) throwsException {
Configconfig=newConfig()
// 您的AccessKey ID                .setAccessKeyId(accessKeyId)
// 您的AccessKey Secret                .setAccessKeySecret(accessKeySecret);
// 访问的域名config.endpoint="dysmsapi.aliyuncs.com";
returnnewcom.aliyun.dysmsapi20170525.Client(config);
    }
/*** 功能描述: <br>* 〈随机数6位〉** @Return: com.ehl.developerplatform.pojo.DataResponse* @Author: 王震* @Date: 2021/4/28 19:34*/privateStringrandomCode() {
returnString.valueOf((int) ((Math.random() *9+1) *Math.pow(10, 5)));
    }
}



一些项目中的redis工具类、就不贴了,朋友们可以自行替换成自己的。

相关文章
|
3月前
|
云安全 安全 API
阿里云——OpenAPI使用——短信服务
阿里云——OpenAPI使用——短信服务
223 0
|
8月前
|
安全
阿里云短信服务是可以发送包含下载链接的文本内容的,
阿里云短信服务是可以发送包含下载链接的文本内容的,但是需要注意以下几点:
470 1
|
3月前
|
Java 关系型数据库 应用服务中间件
阿里云RDS购买Linux完整过程——安装java环境并跑起来tomcat
阿里云RDS购买Linux完整过程——安装java环境并跑起来tomcat
76 0
|
3月前
|
弹性计算 前端开发 小程序
微信小程序上传文件至阿里云OSS直传(java后端签名+前端直传)
当前的通用文件上传方式是通过前端上传到服务器,再由服务器转存至对象存储。这种方式在处理小文件时效率尚可,但大文件上传因受限于服务器带宽,速度较慢。例如,一个100MB的文件在5Mbps带宽的阿里云ECS上上传至服务器需160秒。为解决此问题,可以采用后端签名的方式,使微信小程序直接上传文件到阿里云OSS,绕过服务器中转。具体操作包括在JAVA后端引入相关依赖,生成签名,并在微信小程序前端使用这个签名进行文件上传,注意设置正确的请求头和formData参数。这样能提高大文件上传的速度。
|
3月前
|
监控 Java 测试技术
阿里云推出 3.x Java 探针,解锁应用观测与治理的全新姿势
阿里云推出 3.x Java 探针,解锁应用观测与治理的全新姿势
174331 8
|
2月前
|
Java 对象存储
java对接阿里云OSS上传
java对接阿里云OSS上传
165 2
|
2月前
|
Java 对象存储
阿里云OSS上传下载文件java
阿里云OSS上传下载文件java
138 0
|
3月前
|
关系型数据库 MySQL Java
通过使用阿里云服务器,搭建Java程序的运行环境
通过使用阿里云服务器,搭建Java程序的运行环境
|
3月前
|
运维 NoSQL Java
Serverless 应用引擎产品使用之在函数计算上部署Java服务并访问阿里云MongoDB如何解决
阿里云Serverless 应用引擎(SAE)提供了完整的微服务应用生命周期管理能力,包括应用部署、服务治理、开发运维、资源管理等功能,并通过扩展功能支持多环境管理、API Gateway、事件驱动等高级应用场景,帮助企业快速构建、部署、运维和扩展微服务架构,实现Serverless化的应用部署与运维模式。以下是对SAE产品使用合集的概述,包括应用管理、服务治理、开发运维、资源管理等方面。
|
3月前
|
XML Java 开发工具
阿里云大学考试Java高级题目及解析-java高级
阿里云大学考试Java高级题目及解析-java高级
27 0