API文档:短信 发送短信-API 文档-文档中心-腾讯云
1.依赖:在pom.xml添加腾讯云短信SDK
<dependency>
<groupId>com.tencentcloudapi</groupId>
<artifactId>tencentcloud-sdk-java</artifactId>
<version>3.1.789</version>
</dependency>
2.配置类:创建配置类SmsAutoConfiguration,将参数属性和实现类加入IOC容器管理,相当于注解@Component和@Service,注解@ConditionalOnProperty(prefix = "tencent.sms",name = "templateId")会先将配置文件中的属性加载成功后,在开始Bean初始化,初始化成功之后配置类才会生效。这样做的好处在于启动时能够先查看参数配置是否完整。
假设没有配置参数,那么Bean创建失败,在业务层加载时就会出现Bean不存在的错误。
@Configuration
//当classPath中 配置文件配置了 tencent.sms.templateId key ,然后再加载@Bean到容器中
@ConditionalOnProperty(prefix = "tencent.sms",name = "templateId")
public class SmsAutoConfiguration {
@Bean
public TencentSmsServiceImpl tencentSmsService(){
return new TencentSmsServiceImpl();
}
@Bean
@ConfigurationProperties(prefix = "tencent.sms")
public SmsProperties properties(){
return new SmsProperties();
}
}
3.参数:封装参数类
@Setter
@Getter
//从配置文件获取tencent.sms配置属性绑定到下面的属性中
public class SmsProperties {
private String secretId;
private String secretKey;
private String smsSdkAppId;
private String signName;
private String templateId;
}
在配置中心中找到所属的服务并在配置参数的属性,属性均在短信平台中获取
tencent:
sms:
secretId: 安全ID
secretKey: 安全密钥
smsSdkAppId: 短信平台AppId
signName: 签名
templateId: 短信模板ID
4.接口:将参数(验证码,验证码存活时间)封装成List集合
Arrays.asList(code,SystemConstant.VERIFY_CODE_TIME+""),phone
public interface ISmsService {
//发短信
void sendSms(List<String> param,String...phones);
}
5.实现类
public class TencentSmsServiceImpl implements ISmsService {
@Autowired
private SmsProperties smsProperties;
@Override
public void sendSms(List<String> param, String...phones) {
//3.手机发送短信
try{
Credential cred = new Credential(smsProperties.getSecretId(),smsProperties.getSecretKey());
// 实例化一个http选项,可选的,没有特殊需求可以跳过
HttpProfile httpProfile = new HttpProfile();
httpProfile.setEndpoint("sms.tencentcloudapi.com");
// 实例化一个client选项,可选的,没有特殊需求可以跳过
ClientProfile clientProfile = new ClientProfile();
clientProfile.setHttpProfile(httpProfile);
// 实例化要请求产品的client对象,clientProfile是可选的
SmsClient client = new SmsClient(cred, "ap-guangzhou", clientProfile);
// 实例化一个请求对象,每个接口都会对应一个request对象
SendSmsRequest req = new SendSmsRequest();
String[] phoneNumberSet1 = phones;
req.setPhoneNumberSet(phoneNumberSet1);
req.setSmsSdkAppId(smsProperties.getSmsSdkAppId());//appId
req.setSignName(smsProperties.getSignName());//签名
req.setTemplateId(smsProperties.getTemplateId());//模板
String[] templateParamSet1 = param.toArray(new String[]{});//模板参数
req.setTemplateParamSet(templateParamSet1);
// 返回的resp是一个SendSmsResponse的实例,与请求对象对应
SendSmsResponse resp = client.SendSms(req);
// 输出json格式的字符串回包
System.out.println(SendSmsResponse.toJsonString(resp));
for (int i = 0; i < phones.length; i++) {
//发短信结果处理
if (!resp.getSendStatusSet()[i].getCode().equalsIgnoreCase("ok")) {
throw new ServiceException("短信发送失败");
}
}
} catch (TencentCloudSDKException e) {
System.out.println(e.toString());
}
}
}
6.接口控制层
@PostMapping("/sendVerifyCode")
public R<?> sendVerifyCode(String phone){
pcLoginService.sendVerifyCode(phone);
return R.ok();
}
7.逻辑业务层
public void sendVerifyCode(String phone) {
if (!RegexUtils.isPhoneLegal(phone)) {
throw new ServiceException("手機格式錯吳");
}
//1.创建验证码
String code = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 4);
//2.拼接短信
StringBuilder stringBuilder = new StringBuilder(80);
stringBuilder.append("【腾讯云平台】你的登录验证码为").append(code)
.append(",请在").append(SystemConstant.VERIFY_CODE_TIME).append("分钟内完成注册");
//4.将验证码存到redis
/*String key = "verify_code:" + phone;*/
//直接編寫前綴可能会写错
/* //方式一: 定義常量
String key = SystemConstant.VERIFY_CODE_PREFIX + phone;
redisService.setCacheObject(key,code,SystemConstant.VERIFY_CODE_TIME * 60L, TimeUnit.SECONDS);
*/
//方式二:定义枚举类
String key1 = RedisKeys.VERIFY_CODE.join(phone);
redisService.setCacheObject(key1,code,RedisKeys.VERIFY_CODE.getTime(),TimeUnit.SECONDS);
//3.手机发送短信
System.out.println(stringBuilder);
smsService.sendSms(Arrays.asList(code,SystemConstant.VERIFY_CODE_TIME+""),phone);
}
}