腾讯云短信服务实现 Java 发送手机验证码(SpringBoot+Redis 实现)
前置:需要腾讯云的账号,后期授权需要,不需要买云服务器,有需要的可以购买短信套餐(几块钱)
1、打开腾讯云短信服务
搜索框输入短信,可以买一个短信套餐包,便宜不贵,进入短信服务的控制台

发送短信有频率限制,企业用户可以修改设置

之后我们需要对短信内容进行设置

2、创建短信签名
??
??类型有网站、app、公众号、小程序等,如果大家只是想测试一下短信服务的功能,自己创建一个公众号使用最好,其他都需要企业注册等很多要求。

??
??最好自己创建一个微信公众号,类型是公众号,上传公众号设置界面的截图即可,签名必须为公众号名字,申请说明必须填上正当理由,之后等待审核

3、创建短信正文模板
输入模板内容,注意短信内容要求,可使用提供的短信内容模板

4、等待全部审核完毕即可
签名审核完毕,在之后的api中有一个参数必须写通过审核的签名,才能发送

??短信内容审核完毕,在之后的api中参数有需要填写 内容ID的,需要我们复制前面的 id

5、发送短信
我们使用 API发送短信,下面详细介绍

??点击通过api发送短信后,这里有接口描述,参数描述,返回信息描述等,有api的具体信息点击调试即可,我们会使用 Java SDK 来使用云短信服务,怎么使用呢? 点击 SDK,进入SDK文档

Java SDK 使用短信API说明
https://cloud.tencent.com/document/product/382/43194
按照文档的内容一步一步来即可,如果要使用短信相关的功能,直接复用代码即可
安装sdk,直接使用 maven 即可
<dependency>
<groupId>com.tencentcloudapi</groupId>
<artifactId>tencentcloud-sdk-java</artifactId>
<version>3.1.571</version>
</dependency>
6、短信业务实战(SpringBoot+Redis)
??我们提出一个业务要求,要求实现手机验证码注册或者登陆,同时设置验证码的有效期为5分钟,五分钟后失效
??使用SpringBoot创建项目,Redis实现过期的效果
(1)设置配置信息
# 应用名称
spring.application.name=demo
# 应用服务 WEB 访问端口
server.port=8080
#配置redis
spring.redis.host=
spring.redis.port=6379
spring.redis.password=
(2)使用腾讯云发送短信的API
(1)设置接口
public interface SendSms {
public boolean send(String phoneNum,String templateCode,String code);
}
(2)设置实现类,所有的信息都在注释里写的非常明确了,也是从腾讯云粘贴下来的,有些信息需要从腾讯云账户获取
package com.study.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.sms.v20210111.SmsClient;
import com.tencentcloudapi.sms.v20210111.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20210111.models.SendSmsResponse;
@Service
public class SendSmsImpl implements SendSms{
@Override
public boolean send(String phoneNum, String templateCode, String code) {
try {
Credential cred = new Credential("secreId", "SecretKey");
HttpProfile httpProfile = new HttpProfile();
httpProfile.setReqMethod("POST");
httpProfile.setConnTimeout(60);
httpProfile.setEndpoint("sms.tencentcloudapi.com");
ClientProfile clientProfile = new ClientProfile();
clientProfile.setSignMethod("HmacSHA256");
clientProfile.setHttpProfile(httpProfile);
SmsClient client = new SmsClient(cred, "ap-guangzhou",clientProfile);
SendSmsRequest req = new SendSmsRequest();
String sdkAppId = "XXXXX";
req.setSmsSdkAppId(sdkAppId);
String signName = "XXX公众号";
req.setSignName(signName);
String templateId = templateCode;
req.setTemplateId(templateId);
String[] templateParamSet = {code};
req.setTemplateParamSet(templateParamSet);
String[] phoneNumberSet = {"+86"+phoneNum};
req.setPhoneNumberSet(phoneNumberSet);
SendSmsResponse res = client.SendSms(req);
System.out.println(SendSmsResponse.toJsonString(res));
return true;
} catch (TencentCloudSDKException e) {
e.printStackTrace();
}
return false;
}
}
(3)重新配置Redis的序列化
??建一个config包,创建RedisConfig,加上@Config 注解,这些信息也是固定的套路,网上都有
package com.study.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.net.UnknownHostException;
@Configuration
public class RedisConfig {
@Bean
@SuppressWarnings("all")
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory)
throws UnknownHostException {
RedisTemplate<String, Object> template = new RedisTemplate<String,Object>();
template.setConnectionFactory(factory);
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
template.setKeySerializer(stringRedisSerializer);
template.setHashKeySerializer(stringRedisSerializer);
template.setValueSerializer(jackson2JsonRedisSerializer);
template.setHashValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
}
(4)设置接口,实现验证码的发送
要实现的业务
(1)生成6位数的随机验证码
(2)对手机号参数进行发送验证码
(3)验证码信息保存到 Redis 数据库中,时效性为5分钟
package com.study.controller;
import com.study.service.SendSmsImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.Random;
@RestController
@CrossOrigin
public class SmsApiController {
@Autowired
public SendSmsImpl sendSms;
@Autowired
public RedisTemplate<String,Object> redisTemplate;
public Random random = new Random();
@RequestMapping("/send")
public String sendCode(@RequestParam(value = "phone",required = true) String phone) {
String code = (String)redisTemplate.opsForValue().get(phone);
if (!StringUtils.isEmpty(code)) {
System.out.println("已存在,还没有过期,不能再次发送");
return phone+":"+code+" 已存在,还没有过期";
}
String newCode = "";
for (int i = 0; i < 6; i++) {
newCode += random.nextInt(10);
}
boolean idSend = sendSms.send(phone,"XXXXX",newCode);
if(idSend){
redisTemplate.opsForValue().set(phone, newCode, 300);
System.out.println("发送成功!");
return phone+":"+newCode+" 发送成功!";
}else{
System.out.println("发送失败!");
return "发送失败!";
}
}
}
(5)效果验证
第一次传递手机号参数发送验证码短信

手机收到腾讯云短信服务发送的短信

在5分钟内再次发送短信,此时验证码还未过期所以无法发送

5分钟之后再次查看redis客户端发现 验证码在5分钟后已经过期

结语
项目代码GitHub 链接,有需要的可以直接查看源代码
https://github.com/WorldBlueSky/MessageSend
|