做项目用户登录注册模块的时候,想要使用短信验证码的方式进行登录和注册,然后就去看了阿里云和容联云的短信服务。但是很遗憾,阿里云的短信服务目前个人申请很困难,需要很多证明;容联云目前已经不支持个人进行认证了,只支持公司进行认证。

然后就去看了腾讯云的短信服务,与前两个平台不同的地方在于,腾讯云可以通过公众号的形式进行申请签名,只需要按照提示的内容进行申请就可以了。审核不通过的话按照审核的反馈结果进行修改基本上都能通过。这里要注意,在截公众号后台管理页面的时候,一定要把信息截完整,只截一部分是通过不了审核的。申请完签名并且通过审核之后。就要申请模板了

调用api需要API秘钥,位置在



第一次进入的话是没有密钥的,需要先生成一个,生成后记录一下SecretId和SecretKey,会用到

现在就可以进行在线测试了腾讯云短信服务API测试地址


填好参数之后点击下面的发起调用

还可以查看生成的代码

在SpringBoot测试:

首先先在pom文件中引入依赖:

       <dependency><groupId>com.tencentcloudapi</groupId><artifactId>tencentcloud-sdk-java</artifactId><version>3.1.464</version><!-- 注:这里只是示例版本号(可直接使用),可获取并替换为 最新的版本号,注意不要使用4.0.x版本(非最新版本) --></dependency>

可以使用镜像源加速下载,编辑 maven 的 settings.xml 配置文件,在 mirrors 段落增加镜像配置:

    <mirror><id>tencent</id><name>tencent maven mirror</name><url>https://mirrors.tencent.com/nexus/repository/maven-public/</url><mirrorOf>*</mirrorOf></mirror>

也可以通过码云进行下载:腾讯云短信服务API依赖JAR包下载

项目结构:

配置文件application.properties:

controller:

package com.atdesign.yygh.msm.controller;import com.atdesign.yygh.common.result.Result;
import com.atdesign.yygh.msm.service.MsmService;
import com.atdesign.yygh.msm.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import java.util.concurrent.TimeUnit;@RestController
@RequestMapping("/api/msm")public class MsmApiController {@Autowiredprivate MsmService msmService;@Autowiredprivate RedisTemplate<String,String> redisTemplate;//发送手机验证码@GetMapping("send/{phone}")public Result sendCode(@PathVariable String phone) {//先从redis获取验证码,如果获取到,返回ok//key:手机号  value:验证码String code = redisTemplate.opsForValue().get(phone);if(!StringUtils.isEmpty(code)) {return Result.ok();}//如果从redis获取不到,生成验证码,通过整合短信服务进行发送code = RandomUtil.getSixBitRandom();//通过整合腾讯云的短信服务进行发送boolean isSend = msmService.send(phone,code);//生成验证码放到redis里面,设置有效时间if(isSend) {redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);return Result.ok();} else {return Result.fail().message("发送短信失败");}}
}

service:

package com.atdesign.yygh.msm.service;public interface MsmService {//发送手机验证码boolean send(String phone, String code);
}
package com.atdesign.yygh.msm.service.impl;import com.atdesign.yygh.msm.service.MsmService;
import com.atdesign.yygh.msm.utils.ConstantPropertiesUtils;
import com.atdesign.yygh.msm.utils.RandomUtil;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.sms.v20210111.SmsClient;
import com.tencentcloudapi.sms.v20210111.models.*;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;@Service
public class MsmServiceImpl implements MsmService {//发送手机验证码@Overridepublic boolean send(String phone, String code) {//判断手机号是否为空if(StringUtils.isEmpty(phone)) {return false;}//整合腾讯云的短信服务try {//这里是实例化一个Credential,也就是认证对象,参数是密钥对;你要使用肯定要进行认证Credential credential = new Credential(ConstantPropertiesUtils.SECRET_ID, ConstantPropertiesUtils.SECRET_KEY);//HttpProfile这是http的配置文件操作,比如设置请求类型(post,get)或者设置超时时间了、还有指定域名了//最简单的就是实例化该对象即可,它的构造方法已经帮我们设置了一些默认的值HttpProfile httpProfile = new HttpProfile();//实例化一个客户端配置对象,这个配置可以进行签名(使用私钥进行加密的过程),对方可以利用公钥进行解密ClientProfile clientProfile = new ClientProfile();clientProfile.setHttpProfile(httpProfile);//实例化要请求产品(以sms为例)的client对象SmsClient smsClient = new SmsClient(credential, "ap-beijing", clientProfile);//实例化request封装请求信息SendSmsRequest request = new SendSmsRequest();String[] phoneNumber = {phone};request.setPhoneNumberSet(phoneNumber);     //设置手机号request.setSmsSdkAppId(ConstantPropertiesUtils.APP_ID);
//            System.out.println("APP_ID = "+ConstantPropertiesUtils.APP_ID);request.setSignName("你的短信签名内容");request.setTemplateId(ConstantPropertiesUtils.TEMPLATE_ID);
//            System.out.println("TEMPLATE_ID = "+ConstantPropertiesUtils.TEMPLATE_ID);//验证码String[] templateParamSet = {code};request.setTemplateParamSet(templateParamSet);
//            System.out.println("templateParamSet = "+templateParamSet);//发送短信SendSmsResponse response = smsClient.SendSms(request);// 输出json格式的字符串回包System.out.println(SendSmsResponse.toJsonString(response));return true;} catch (Exception e) {System.out.println(e.toString());return false;}}
}

utils:

package com.atdesign.yygh.msm.utils;import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;@Component
public class ConstantPropertiesUtils implements InitializingBean {@Value("${tencent.msm.secretId}")private String secretID ;@Value("${tencent.msm.secretKey}")private String secretKey ;@Value("${tencent.msm.smsSdkAppId}")private String smsSdkAppId;//    @Value("${tencent.msm.signName}")
//    private String signName;@Value("${tencent.msm.templateId}")private String templateId;//六个相关的参数public static String SECRET_ID;public static String SECRET_KEY;public static String APP_ID;
//    public static String SIGN_NAME;public static String TEMPLATE_ID;@Overridepublic void afterPropertiesSet() throws Exception {SECRET_ID = secretID;SECRET_KEY = secretKey;APP_ID = smsSdkAppId;
//        SIGN_NAME = signName;TEMPLATE_ID = templateId;}}
package com.atdesign.yygh.msm.utils;import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;public class RandomUtil {private static final Random random = new Random();private static final DecimalFormat fourdf = new DecimalFormat("0000");private static final DecimalFormat sixdf = new DecimalFormat("000000");//生成四位验证码public static String getFourBitRandom() {return fourdf.format(random.nextInt(10000));}//生成六位验证码public static String getSixBitRandom() {return sixdf.format(random.nextInt(1000000));}public static ArrayList getRandom(List list, int n) {Random random = new Random();HashMap<Object, Object> hashMap = new HashMap<Object, Object>();// 生成随机数字并存入HashMapfor (int i = 0; i < list.size(); i++) {int number = random.nextInt(100) + 1;hashMap.put(number, i);}// 从HashMap导入数组Object[] robjs = hashMap.values().toArray();ArrayList r = new ArrayList();// 遍历数组并打印数据for (int i = 0; i < n; i++) {r.add(list.get((int) robjs[i]));System.out.print(list.get((int) robjs[i]) + "\t");}System.out.print("\n");return r;}
}

启动类:

package com.atdesign.yygh.msm;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.ComponentScan;//取消数据源自动配置
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
@EnableDiscoveryClient
@ComponentScan(basePackages = {"com.atdesign"})
public class ServiceMsmApplication {public static void main(String[] args) {SpringApplication.run(ServiceMsmApplication.class, args);}}

注意:如果你的短信签名内容里面有汉字,在传值的时候会乱码,所以最好这样写:request.setSignName(“你的短信签名内容”);
因为我上述写的代码中用到了我自己项目中的包和文件,所以我这样写只是具有参考价值,不要直接复制过去。
可以参考这位大佬的博客:接入腾讯云短信服务,我接入腾讯短信服务的时候也是参考这位大佬的博客来做的,在这里写博客记录一下自己学习接入短信服务的过程和历程。

腾讯云短信服务在项目中的使用相关推荐

  1. 腾讯云短信服务使用指南

    引入腾讯云短信服务依赖 <!-- 引入腾讯云短信服务 依赖 --> <dependency><groupId>com.tencentcloudapi</gro ...

  2. 腾讯云短信服务使用记录与.NET Core C#代码分享

    1.即使是相同的短信签名与短信正文模板,也需要针对"国内文本短信"与"海外文本短信"分别申请.开始不知道,以为只要申请一次,给国外手机发短信时给api传对应的国 ...

  3. 腾讯云短信接口报错1014

    {"result":1014,"errmsg":"\u6A21\u7248\u672A\u5BA1\u6279\u6216\u5185\u5BB9\u ...

  4. 项目接入腾讯云短信服务SMS实现向用户发送手机验证码

    1.自述 早在18年的时候,我就在项目中使用过阿里云的短信服务,现在我上阿里云短信控制台看,还能看到当时创建的短信签名,如下图所示. 出于某种原因,我现在想重新申请一个新的签名,却审批失败了,原因是: ...

  5. Spring Boot中使用腾讯云短信服务

    第一步:在腾讯云官方网站开通短信服务 第二部:开通后,在短信控制面板中找到国内短信 第三步:点击签名管理并创建签名 第五步:点击正文模板管理并创建正文模板 第六步:在pom文件中添加腾讯云短信依赖 & ...

  6. Springboot+Redis接入腾讯云短信服务实现验证码发送

    目录 一.开通腾讯云短信服务 二.代码实现 三.测试 申请阿里云短信服务需要以上线APP或已备案网站,腾讯云短信服务可以使用微信公众号申请,注册个人微信公众号比较方便,改用腾讯云短信服务,参考官方SD ...

  7. Java后端利用腾讯云短信服务发短信

    利用手机验证码进行注册或进行下一步操作已经是非常普遍的,这篇文章就教你如何是用腾讯云短信服务发送手机验证码. 文章目录 一.前提条件 二.代码实现 1.引入依赖 2.Java代码实现 3.代码改进 4 ...

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

    文章目录 腾讯云短信服务实现 Java 发送手机验证码(SpringBoot+Redis 实现) 1.打开腾讯云短信服务 2.创建短信签名 3.创建短信正文模板 4.等待全部审核完毕即可 5.发送短信 ...

  9. Prometheus和Grafana告警服务创建与对接腾讯云短信告警平台(prometheus_alert)

    前言 在一个监控系统中,如果说数据链路是她的骨架,那么告警通知服务就是他的灵魂!所有的监控服务都是为了能够及时通知出来,减少人工查询状态,及时发现问题,避免不必要的大规模故障,为企业政府省钱,和保证安 ...

  10. python发送免费短信验证码(腾讯云 短信)

    第一步,首先去注册一个微信小程序,在腾讯云短信服务中创建签名的时候会用到哦. 点击此链接进入微信公众平台 注册好微信小程序,之后. 第二步,如果您还没有腾讯云账号,您需要 注册腾讯云 账号,并完成 实 ...

最新文章

  1. mysql导入sql文件限制,Mysql导入大容量SQL文件数据有关问题
  2. Nuget添加新项目的问题
  3. C#中FileStream的对比以及使用方法
  4. 差分放大电路单端输出和双端输出区别以及应用(转载)
  5. python编程工具是什么_python编程应该用什么工具
  6. SQL基础E-R图画法(二)
  7. C语言实现二叉树-04版
  8. C/C++排序算法(5)归并排序
  9. Java基础知识框图总结
  10. Tesseract OCR iOS 教程
  11. Hadoop安装教程详解
  12. 抖音旋转很炫的html,火爆抖音的旋转时钟屏保,超酷超炫的
  13. 如何系统学习 Ps、CAD、Office 等软件?
  14. 51.La网站统计邀您认知数据可视化
  15. redis 错误 Error reply to PING from master: '-DENIED Redis is running in protected mode because prote
  16. ReportingService报表入门
  17. 数据库事务的四大特性和隔离级别,一文带你看通透
  18. 中职计算机英语教学设计,中职英语教学设计三篇
  19. 让自己更优秀的 16 条法则(建议收藏)
  20. CSS深入理解z-index(z-index相关知识总结)

热门文章

  1. 淘宝API 搜索相似的商品
  2. 什么是LTE CAT1和CATM
  3. 如何通过python实现H.264视频推流与接收
  4. Java 中文姓名随机生成
  5. 三极管之——PNP与NPN
  6. 模电学习1. 三极管基础知识及常用电路
  7. 【动力学】汽车性能仿真系统含Matlab源码
  8. 电容器的 ESR 参数
  9. Java通过选择城市来计算运费(基础程序)
  10. iOS 最新AppStore申请加急审核 以及 apple联系方式大全