失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > SpringBoot整合腾讯云短信服务实现发送短信功能(一篇就够了)

SpringBoot整合腾讯云短信服务实现发送短信功能(一篇就够了)

时间:2024-02-24 22:18:15

相关推荐

SpringBoot整合腾讯云短信服务实现发送短信功能(一篇就够了)

废话不多说 直接开始

首先我们加入依赖

<dependency><groupId>com.tencentcloudapi</groupId><artifactId>tencentcloud-sdk-java</artifactId><version>3.1.62</version></dependency>

我把它封装在一个util类里面了 大家可以直接拿着用

package cn.kgc.qh.util;import flix.client.ClientException;import mon.Credential;import mon.exception.TencentCloudSDKException;import mon.profile.ClientProfile;import mon.profile.HttpProfile;import com.tencentcloudapi.sms.v0711.SmsClient;import com.tencentcloudapi.sms.v0711.models.SendSmsRequest;import com.tencentcloudapi.sms.v0711.models.SendSmsResponse;import org.ponent;/*** @Description: TODO* @author: 小孟* @date: 12月20日 13:23*/@Componentpublic class TengXunSMSUtils {public static final String VALIDATE_CODE = "866988";public boolean sendShortMessage(String templateCode, String phoneNum, String param) throws ClientException {try {/** CAM 密钥查询:https://console./cam/capi*/Credential cred = new Credential("secretId", "secretKey");// 无特殊需求可以跳过HttpProfile httpProfile = new HttpProfile();httpProfile.setReqMethod("POST");httpProfile.setConnTimeout(60);httpProfile.setEndpoint("");ClientProfile clientProfile = new ClientProfile();clientProfile.setSignMethod("HmacSHA256");clientProfile.setHttpProfile(httpProfile);/* 实例化 SMS 的 client 对象* 第二个参数是地域信息,可以直接填写字符串 ap-guangzhou,或者引用预设的常量 */SmsClient client = new SmsClient(cred, "ap-guangzhou", clientProfile);/* 实例化一个请求对象,根据调用的接口和实际情况,可以进一步设置请求参数* 您可以直接查询 SDK 源码确定接口有哪些属性可以设置* 属性可能是基本类型,也可能引用了另一个数据结构* 推荐使用 IDE 进行开发,可以方便地跳转查阅各个接口和数据结构的文档说明 */com.tencentcloudapi.sms.v0711.models.SendSmsRequest req = new SendSmsRequest();/* 填充请求参数,这里 request 对象的成员变量即对应接口的入参* 您可以通过官网接口文档或跳转到 request 对象的定义处查看请求参数的定义* 基本类型的设置:* 帮助链接:* 短信控制台:https://console./smsv2* sms helper:/document/product/382/3773 *//* 短信应用 ID: 在 [短信控制台] 添加应用后生成的实际 SDKAppID,例如1400006666 */String SdkAppid = "这里必填";req.setSmsSdkAppid(SdkAppid);/* 短信签名内容: 使用 UTF-8 编码,必须填写已审核通过的签名,可登录 [短信控制台] 查看签名信息 */String sign = "自己签名";req.setSign(sign);/* 国际/港澳台短信 senderid: 国内短信填空,默认未开通,如需开通请联系 [sms helper] */String senderid = "";req.setSenderId(senderid);/* 模板 ID: 必须填写已审核通过的模板 ID,可登录 [短信控制台] 查看模板 ID */req.setTemplateID(templateCode);/* 下发手机号码,采用 e.164 标准,+[国家或地区码][手机号]* 例如+8613711112222, 其中前面有一个+号 ,86为国家码,13711112222为手机号,最多不要超过200个手机号*/String[] phoneNumber = {"+86" + phoneNum + ""};req.setPhoneNumberSet(phoneNumber);/* 模板参数: 若无模板参数,则设置为空*/String[] templateParams = {param};req.setTemplateParamSet(templateParams);/* 通过 client 对象调用 SendSms 方法发起请求。注意请求方法名与请求对象是对应的* 返回的 res 是一个 SendSmsResponse 类的实例,与请求对象对应 */SendSmsResponse res = client.SendSms(req);// 输出 JSON 格式的字符串回包System.out.println(SendSmsResponse.toJsonString(res));// 可以取出单个值,您可以通过官网接口文档或跳转到 response 对象的定义处查看返回字段的定义System.out.println(res.getRequestId());} catch (TencentCloudSDKException e) {e.printStackTrace();}return true;}}

这里写个控制器测试一下:

第一个参数 模板ID第二个参数 手机号第三个参数 验证码 这里我没有用随机数产生

package cn.kgc.qh.controller;import cn.kgc.qh.util.TengXunSMSUtils;import flix.client.ClientException;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.RestController;import javax.annotation.Resource;/*** @Description: TODO* @author: 小孟* @date: 12月20日 13:34*/@RestController@RequestMapping("/TXController")public class TXController {@Resourceprivate TengXunSMSUtils tengXunSMSUtils;@PostMapping("/TX")public boolean TX(@RequestParam String templateCode, @RequestParam String phoneNum, @RequestParam String param) throws ClientException {return tengXunSMSUtils.sendShortMessage(templateCode, phoneNum, param);}}

下面是短信发送成功后 1分钟之内不能发送短信,redis中可以保存短信3分钟

@PostMapping("/codeTX")public CommonsResponse getCodeTX(@RequestParam String phone) {//判断存入的验证码是否在1分钟以内 如果在就不能在获取String TempCodeTx = (String) redisUtil.get("TX" + CacheConstants.CACHE_PREFIX_CODE + phone);if (!StringUtils.isBlank(TempCodeTx)) {long times1 = Long.parseLong(TempCodeTx.split("_")[1]);long times2 = new Date().getTime();if (times2 - times1 <= 60000) {return CommonsResponse.builder().code(200).data("-1").message("验证码没到1分钟不能获取").build();}}//产生随机数String sendCode = String.valueOf(RandomValueUtil.getNum(1000, 9999));String code = sendCode + "_" + new Date().getTime();redisUtil.set("TX" + CacheConstants.CACHE_PREFIX_CODE + phone, code, 180);tengXunYunSendMsgFeignClient.TX("自己模板的ID", phone, sendCode);return CommonsResponse.builder().code(200).data("1").message("发送成功!!!").build();}

一个非常简单的注册

从刚刚保存的redis 拿出code 来和用户输入的code 做对比 在通过MD5+盐的方式保存用户的密码

@PostMapping("/insert")public CommonsResponse insert(@RequestBody UmsMemberDTO umsMemberDTO) {String redisUms = (String) redisUtil.get("TX" + CacheConstants.CACHE_PREFIX_CODE + umsMemberDTO.getMobile());String dd = redisUms.split("_")[0];if (redisUms == null || !dd.equals(umsMemberDTO.getCode())) {return CommonsResponse.builder().code(200).data(false).message("失败").build();}BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();String tempPassword = bCryptPasswordEncoder.encode(umsMemberDTO.getPassword());umsMemberDTO.setPassword(tempPassword);umsClink.insert(umsMemberDTO);return CommonsResponse.builder().code(200).data(true).message("成功!").build();}

结果是成功的!短信发出!

如果没有签名可以去我的博客里看我的另一篇文章 百分百注册腾讯云签名!

如果觉得《SpringBoot整合腾讯云短信服务实现发送短信功能(一篇就够了)》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。