java 腾讯云、阿里云SMS短信工具类
引入POM依赖
<!-- 腾讯云SMS SDK -->
<dependency>
<groupId>com.tencentcloudapi</groupId>
<artifactId>tencentcloud-sdk-java-sms</artifactId>
<version>3.1.754</version>
</dependency>
<!-- 阿里云SMS SDK -->
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>dysmsapi20170525</artifactId>
<version>2.0.23</version>
</dependency>
测测类
/**
* 测试邮箱机制
*
* @return
*/
@GetMapping("/testSms")
public Result testSms() {
//腾讯云
// Map<String, String> map1 = new HashMap<>();
// map1.put("1", "1234");
// SmsSendResult smsSendResult = SmsUtil.sendSms("+8618731055555,+8618754158888", "1794879", map1,"tencent");
//阿里云
Map<String, String> map2 = new HashMap<>();
map2.put("code", "6666");
SmsSendResult smsSendResult = SmsUtil.sendSms("+8618731055555,+8618754158888", "SMS_460755471", map2,"aliyun");
return Result.ok(smsSendResult);
}
工具类
读取redis那块自己改哦
package cn.daenx.myadmin.common.utils;
import cn.daenx.myadmin.common.constant.RedisConstant;
import cn.daenx.myadmin.system.constant.SystemConstant;
import cn.daenx.myadmin.system.po.SysConfig;
import cn.daenx.myadmin.system.vo.system.SmsSendResult;
import cn.daenx.myadmin.system.vo.system.SysSmsConfigVo;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.sms.v20190711.SmsClient;
import com.tencentcloudapi.sms.v20190711.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20190711.models.SendStatus;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
/**
* Sms短信工具类
*
* @author DaenMax
*/
public class SmsUtil {
/**
* 发送短信
* <p>
* <h4>关于phones参数</h4><br>
* 腾讯云:格式为+[国家或地区码][手机号],单次请求最多支持200个手机号且要求全为境内手机号或全为境外手机号,发送国内短信格式还支持0086、86或无任何国家或地区码的11位手机号码,前缀默认为+86。<br><br>
* 阿里云:国内短信:+/+86/0086/86或无任何前缀的11位手机号码,例如1390000****。国际/港澳台消息:国际区号+号码,例如852000012****。单次上限为1000个手机号码
* </p>
* <p>
* <h4>关于param参数</h4><br>
* 腾讯云:例如模板为:验证码为:{1},如非本人操作,请忽略本短信。那么key=1,value为1234<br><br>
* 阿里云:例如模板为:您的验证码为:${code},请勿泄露于他人!那么key=code,value为1234
* </p>
*
* @param phones 多个手机号用,隔开
* @param templateId
* @param param
* @return
*/
public static SmsSendResult sendSms(String phones, String templateId, Map<String, String> param) {
if (ObjectUtil.isEmpty(phones)) {
return SmsSendResult.builder().isSuccess(false).msg("手机号不能为空").build();
}
if (ObjectUtil.isEmpty(templateId)) {
return SmsSendResult.builder().isSuccess(false).msg("模板ID不能为空").build();
}
SysSmsConfigVo sysSmsConfigVo = getSysSmsConfigVo();
if (ObjectUtil.isEmpty(sysSmsConfigVo)) {
return SmsSendResult.builder().isSuccess(false).msg("系统短信配置不可用").build();
}
if ("aliyun".equals(sysSmsConfigVo.getConfig().getType())) {
return sendSmsAliyun(sysSmsConfigVo.getAliyun(), phones, templateId, param);
} else if ("tencent".equals(sysSmsConfigVo.getConfig().getType())) {
return sendSmsTencent(sysSmsConfigVo.getTencent(), phones, templateId, param);
}
return SmsSendResult.builder().isSuccess(false).msg("未知的type").build();
}
/**
* 发送短信
* <p>
* <h4>关于phones参数</h4><br>
* 腾讯云:格式为+[国家或地区码][手机号],单次请求最多支持200个手机号且要求全为境内手机号或全为境外手机号,发送国内短信格式还支持0086、86或无任何国家或地区码的11位手机号码,前缀默认为+86。<br><br>
* 阿里云:国内短信:+/+86/0086/86或无任何前缀的11位手机号码,例如1390000****。国际/港澳台消息:国际区号+号码,例如852000012****。单次上限为1000个手机号码
* </p>
* <p>
* <h4>关于param参数</h4><br>
* 腾讯云:例如模板为:验证码为:{1},如非本人操作,请忽略本短信。那么key=1,value为1234<br><br>
* 阿里云:例如模板为:您的验证码为:${code},请勿泄露于他人!那么key=code,value为1234
* </p>
*
* @param phones 多个手机号用,隔开
* @param templateId
* @param param
* @param type 指定平台,aliyun=阿里云,tencent=腾讯云
* @return
*/
public static SmsSendResult sendSms(String phones, String templateId, Map<String, String> param, String type) {
if (ObjectUtil.isEmpty(phones)) {
return SmsSendResult.builder().isSuccess(false).msg("手机号不能为空").build();
}
if (ObjectUtil.isEmpty(templateId)) {
return SmsSendResult.builder().isSuccess(false).msg("模板ID不能为空").build();
}
if (ObjectUtil.isEmpty(type)) {
return SmsSendResult.builder().isSuccess(false).msg("type不能为空").build();
}
SysSmsConfigVo sysSmsConfigVo = getSysSmsConfigVo();
if (ObjectUtil.isEmpty(sysSmsConfigVo)) {
return SmsSendResult.builder().isSuccess(false).msg("系统短信配置不可用").build();
}
if ("aliyun".equals(type)) {
return sendSmsAliyun(sysSmsConfigVo.getAliyun(), phones, templateId, param);
} else if ("tencent".equals(type)) {
return sendSmsTencent(sysSmsConfigVo.getTencent(), phones, templateId, param);
}
return SmsSendResult.builder().isSuccess(false).msg("未知的type").build();
}
/**
* 发送短信协议,阿里云
*
* @param smsInfo
* @param phones 多个手机号用,隔开
* @param templateId
* @param param 例如模板为:您的验证码为:${code},请勿泄露于他人!那么key=code,value为1234
* @return
*/
private static SmsSendResult sendSmsAliyun(SysSmsConfigVo.SmsInfo smsInfo, String phones, String templateId, Map<String, String> param) {
try {
Config config = new Config();
config.setAccessKeyId(smsInfo.getAccessKeyId());
config.setAccessKeySecret(smsInfo.getAccessKeySecret());
config.setEndpoint(smsInfo.getEndpoint());
Client client = new Client(config);
com.aliyun.dysmsapi20170525.models.SendSmsRequest req = new com.aliyun.dysmsapi20170525.models.SendSmsRequest()
.setPhoneNumbers(phones)
.setSignName(smsInfo.getSignName())
.setTemplateCode(templateId)
.setTemplateParam(JSON.toJSONString(param));
SendSmsResponse resp = client.sendSms(req);
System.out.println("OK".equals(resp.getBody().getCode()));
System.out.println(resp.getBody().getCode());
SmsSendResult smsSendResult = SmsSendResult.builder().isSuccess("OK".equals(resp.getBody().getCode())).msg(resp.getBody().getMessage()).aliyunRes(resp).build();
return smsSendResult;
} catch (Exception e) {
e.printStackTrace();
SmsSendResult smsSendResult = SmsSendResult.builder().isSuccess(false).msg(e.getMessage()).build();
return smsSendResult;
}
}
/**
* 发送短信协议,腾讯云
*
* @param smsInfo
* @param phones 多个手机号用,隔开,需要加+86等前缀
* @param templateId
* @param param 例如模板为:验证码为:{1},如非本人操作,请忽略本短信。那么key=1,value为1234
* @return
*/
private static SmsSendResult sendSmsTencent(SysSmsConfigVo.SmsInfo smsInfo, String phones, String templateId, Map<String, String> param) {
try {
Credential credential = new Credential(smsInfo.getAccessKeyId(), smsInfo.getAccessKeySecret());
HttpProfile httpProfile = new HttpProfile();
httpProfile.setEndpoint(smsInfo.getEndpoint());
ClientProfile clientProfile = new ClientProfile();
clientProfile.setHttpProfile(httpProfile);
SmsClient client = new SmsClient(credential, "", clientProfile);
com.tencentcloudapi.sms.v20190711.models.SendSmsRequest req = new SendSmsRequest();
Set<String> set = Arrays.stream(phones.split(",")).collect(Collectors.toSet());
req.setPhoneNumberSet(ArrayUtil.toArray(set, String.class));
if (CollUtil.isNotEmpty(param)) {
req.setTemplateParamSet(ArrayUtil.toArray(param.values(), String.class));
}
req.setTemplateID(templateId);
req.setSign(smsInfo.getSignName());
req.setSmsSdkAppid(smsInfo.getSdkAppId());
com.tencentcloudapi.sms.v20190711.models.SendSmsResponse resp = client.SendSms(req);
SmsSendResult smsSendResult = SmsSendResult.builder().isSuccess(true).msg("ok").tencentRes(resp).build();
for (SendStatus sendStatus : resp.getSendStatusSet()) {
if (!"Ok".equals(sendStatus.getCode())) {
smsSendResult.setSuccess(false);
sendStatus.setMessage(sendStatus.getMessage());
break;
}
}
return smsSendResult;
} catch (Exception e) {
e.printStackTrace();
SmsSendResult smsSendResult = SmsSendResult.builder().isSuccess(false).msg(e.getMessage()).build();
return smsSendResult;
}
}
/**
* 从redis里获取系统邮箱配置信息
* 不存在或者被禁用或者数量为0返回null
*
* @return
*/
private static SysSmsConfigVo getSysSmsConfigVo() {
Object object = RedisUtil.getValue(RedisConstant.CONFIG + "sys.sms.config");
if (ObjectUtil.isEmpty(object)) {
return null;
}
SysConfig sysConfig = JSON.parseObject(JSON.toJSONString(object), SysConfig.class);
if (!sysConfig.getStatus().equals(SystemConstant.STATUS_NORMAL)) {
return null;
}
SysSmsConfigVo sysSmsConfigVo = JSONObject.parseObject(sysConfig.getValue(), SysSmsConfigVo.class);
return sysSmsConfigVo;
}
}
实体类
SysSmsConfigVo
package cn.daenx.myadmin.system.vo.system;
import lombok.AllArgsConstructor;
import lombok.Data;
import java.io.Serializable;
/**
* 系统短信配置
*/
@Data
@AllArgsConstructor
public class SysSmsConfigVo implements Serializable {
private Config config;
private SmsInfo aliyun;
private SmsInfo tencent;
@Data
public static class Config {
/**
* 使用平台
* aliyun=阿里云,tencent=腾讯云
*/
private String type;
}
@Data
public static class SmsInfo {
/**
* 是否启用该平台,true/false
*/
private String enable;
/**
* 固定为:sms.tencentcloudapi.com
*/
private String endpoint;
private String accessKeyId;
private String accessKeySecret;
/**
* 签名
*/
private String signName;
/**
* 应用ID,腾讯云专属
*/
private String sdkAppId;
}
}
SmsSendResult
package cn.daenx.myadmin.system.vo.system;
import lombok.Builder;
import lombok.Data;
@Data
@Builder
public class SmsSendResult {
/**
* 是否成功
*/
private boolean isSuccess;
private String msg;
/**
* 阿里云的原始结果
*/
private com.aliyun.dysmsapi20170525.models.SendSmsResponse aliyunRes;
/**
* 腾讯云的原始结果
*/
private com.tencentcloudapi.sms.v20190711.models.SendSmsResponse tencentRes;
}
java 腾讯云、阿里云SMS短信工具类的更多相关文章
- php 阿里云短信服务及阿里大鱼实现短信验证码的发送
一:使用阿里云的短信服务 ① 申请短信签名 ②申请短信模板 ③创建Access Key,获取AccessKeyId 与 AccessKeySecret.(为了安全起见,这里建议使用子用户的Access ...
- java中用中国网建提供的SMS短信平台发送短信
接下来的项目需求中提到需要短信发送功能,以前没有做过,因此便在网上搜了一下.大体上说的都是有三种方法,分别是sina提供的webservice接口.短信mao和中国网建提供的SMS短信平台. 这三种方 ...
- Java通过SMS短信平台实现发短信功能
在项目中使用过发短信的功能,但那个由于公司内部的限制很麻烦,今天在网上找到一个简单的,闲来无事就把它记录如下: 本程序是通过使用中国网建提供的SMS短信平台实现的(该平台目前为注册用户提供5条免费短信 ...
- 中国网建SMS短信接口调用(java发送和接收手机短信)
1.先注册账号,一定要填写好签名格式.不填会返回-51错误. 代码信息接口详细==>http://sms.webchinese.cn/api.shtml . 2.测试代码 package ...
- asp.net C# 实现阿里大鱼和云片网短信接口类
云片网短信通用类 public class YunpianSMS { public YunpianSMS() { } /// <summary> /// 服务器HTTP地址 /// < ...
- 短信验证登陆-中国网建提供的SMS短信平台
一.JAVA发送手机短信常见的有三种方式(如下所列): 使用webservice接口发送手机短信,这个可以使用sina提供的webservice进行发送,但是需要进行注册 使用短信mao的方式进行短信 ...
- 基于SMS短信平台给手机发送短信
JAVA发送手机短信,我知道的有三种方式,恰逢项目需求,自己整理了基于SMS的短信发送,其他两种这里就说说一下 使用webservice接口发送手机短信,这个可以使用sina提供的webservice ...
- PHP阿里大于发短信教程
PHP阿里大于发短信教程 1 先去控制台 https://www.alidayu.com/center/user/account?spm=a3142.7791109.1999204004.5.ZtBQ ...
- sms短信服务
短信服务是app,电商类应用的基础功能.典型场景有: 用户注册,发送验证码 用户找回验证,发送验证码 用户账户异常,发送提示 用户账户变化,通知用户 短信服务开发有几个注意点: 供应商选型 短信模板 ...
- 发送SMS短信(JSON) 转载
http://blog.csdn.net/ldl22847/article/details/42553883 public static string GetMobileConfByUserId( ...
随机推荐
- @SpringBootApplication自动配置原理
@EnableAutoConfiguration 是核心,他会调用一个@Import注解.我们已知Import自动配置得实现是通过创建ImportSelector 接口的实现类并重写里面selectI ...
- TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
\3c span id="mce_marker" data-mce-type="bookmark">\3c /span>\3c span id=&q ...
- 客户端“自废武功”背后的深层秘密——CORS跨域是怎么回事?
客户端"自废武功"背后的深层秘密--CORS跨域是怎么回事? 嘿,对于刚入门的开发新手,你是不是曾经遇到过这样的情况:你正在愉快地开发一个 Web 应用,代码写得热火朝天,前后端配 ...
- vue3-webseek网页版AI问答|Vite6+DeepSeek+Arco流式ai聊天打字效果
2025 AI实战vue3+deepseek+arcoDesign仿DeepSeek/豆包网页版AI聊天助手. vue3-web-deepseek 实战网页PC版智能AI对话,基于vite6+vue3 ...
- 【Java】JavaWeb项目中使用SQLite免安装单文件数据库
Jsp项目中使用SQLite免安装单文件数据库 零.需求 有的同学电脑上安装MySQL或者其他数据库时出现问题,无法安装相关数据库供JavaWeb项目使用,可以使用SQLite数据库解决相关问题. 壹 ...
- 【Python】文件批量重命名
需求: 经常有很多相似的文件需要重命名,如果一个一个来太麻烦了,正好会Python,所以用Python写了个脚本,把符合要求的文件的文件名修改为新的. 代码: # coding:utf-8 # @Ti ...
- datasnap的Restful的接口方法
//Restful接口测试 //GET function Test(Value: string): string; //POST function updateTest(Value: string; ...
- 2025dsfz集训Day8:线段树
Day8:线段树 前言:线段树听起来很高大尚,就是儿子节点表示法的树.几乎一样. \[Designed\ By\ FrankWkd\ -\ Luogu@Lwj54joy,uid=845400 \] 特 ...
- 有的时候,会遇到DataGrid里面嵌套DataGrid(重叠嵌套),然后里面的鼠标滚轮无法响应外面的滚动,为此记录下解决方案
有的时候,会遇到DataGrid里面嵌套DataGrid(重叠嵌套),然后里面的鼠标滚轮无法响应外面的滚动,为此记录下解决方案 本实例是在DataGrid的详情行里再嵌入一个DataGrid,模拟重叠 ...
- Linux设置每晚定时备份Oracle数据表
先新建目录 该路径:/home/oracle/backup 该名称:DATA_PATH shell脚本 export ORACLE_BASE=/home/oracle/app export ORACL ...