【笔记整理】SpringBoot集成腾讯云短信
模板id:
应用列表的SDK AppId
签名SignName:
还有就是账号密钥 Secretid、SecretKey
地址:https://console.cloud.tencent.com/cam/capi
<!--腾讯sdk(目前用在短信上)--> <dependency> <groupId>com.tencentcloudapi</groupId> <artifactId>tencentcloud-sdk-java</artifactId> <version>3.1.390</version> </dependency>
package com.binlog.study.tencentSms.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 org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * @Describe: 腾讯云短信配置 * 发送短信接入文档:https://cloud.tencent.com/document/api/382/55981 * 使用SDK调用 * 参考使用腾讯云的API Explorer * @Author: * @Date: 2022/4/11 9:05 */ @Configuration public class TencentSmsConfig { /** * API相关 */ private static String URL ="sms.tencentcloudapi.com"; private static final String REGION = "ap-guangzhou"; /** * 账号相关 */ @Value("${tencent.sms.account.secret_id}") private String SECRET_ID; @Value("${tencent.sms.account.secret_key}") private String SECRET_KEY; @Bean public SmsClient smsClient(){ // 实例化一个认证对象,入参需要传入腾讯云账户secretId,secretKey,此处还需注意密钥对的保密 // 密钥可前往https://console.cloud.tencent.com/cam/capi网站进行获取 Credential cred = new Credential(SECRET_ID, SECRET_KEY); // 实例化一个http选项,可选的,没有特殊需求可以跳过 HttpProfile httpProfile = new HttpProfile(); httpProfile.setEndpoint(URL); // 实例化一个client选项,可选的,没有特殊需求可以跳过 ClientProfile clientProfile = new ClientProfile(); clientProfile.setHttpProfile(httpProfile); //实例化 SMS 的 client 对象 return new SmsClient(cred, REGION, clientProfile); } }
public interface SmsService { /** * 发送短信的验证码 * @param phone * @return */ String sendSms(String phone); /** * 验证验证码 * @param phone * @param code * @return */ Boolean validationCode(String phone, String code); }
package com.binlog.study.tencentSms.service.impl; import com.binlog.study.tencentSms.service.SmsService; import com.tencentcloudapi.common.exception.TencentCloudSDKException; import com.tencentcloudapi.sms.v20190711.SmsClient; import com.tencentcloudapi.sms.v20190711.models.SendSmsRequest; import com.tencentcloudapi.sms.v20190711.models.SendSmsResponse; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.RandomStringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Service; import java.util.concurrent.TimeUnit; /** * @Describe: 腾讯云短信实现类 * @Author: * @Date: 2022/4/11 8:58 */ @Service @Slf4j public class SmsServiceImpl implements SmsService { @Autowired private SmsClient smsClient; @Value("${tencent.sms.account.sms_sdk_app_id}") private String SMS_SDK_APP_ID; @Value("${tencent.sms.account.template_id}") private String TEMPLATE_ID; @Value("${tencent.sms.account.sign_name}") private String SIGN_NAME; /** * 短信验证码长度 */ private final Integer LENGTH = 6; /** * redis 缓存 */ @Autowired private StringRedisTemplate redisTemplate; @Override public String sendSms(String phone) { String[] phoneNumbers = {"+86" + phone}; //生成随机验证码 final String code = generateCode(); //加入数组 String[] templateParams = {code}; //实例请求,组装参数 SendSmsRequest sendSmsRequest = new SendSmsRequest(); sendSmsRequest.setSmsSdkAppid(SMS_SDK_APP_ID); sendSmsRequest.setTemplateID(TEMPLATE_ID); sendSmsRequest.setSign(SIGN_NAME); //发送的手机号 sendSmsRequest.setPhoneNumberSet(phoneNumbers); //发送的内容(验证码) sendSmsRequest.setTemplateParamSet(templateParams); try { //发送 final SendSmsResponse sendSmsResponse = smsClient.SendSms(sendSmsRequest); log.info("短信发送成功:{}", sendSmsResponse.toString()); //加入缓存 redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES); return "OK"; } catch (TencentCloudSDKException e) { log.error("发送失败,或者剩余短信数量不足", e); } return "发送失败,或者剩余短信数量不足"; } @Override public Boolean validationCode(String phone, String code) { final String data = (String) redisTemplate.opsForValue().get(phone); if (code.equals(data)) { return true; } else { return false; } } /** * 生成随机的验证码 * * @return */ public String generateCode() { return RandomStringUtils.randomNumeric(LENGTH); } }
package com.binlog.study.tencentSms.controller; import com.binlog.study.apiDesignCode.Result; import com.binlog.study.tencentSms.service.SmsService; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.Pattern; import java.io.IOException; /** * @Describe: 腾讯云短信接口测试 * @Author: * @Date: 2022/4/11 9:52 */ @RestController @RequestMapping("/api/tencentSms") public class TencentSmsController { @Autowired private SmsService smsService; @ApiOperation(value = "发送短信和验证") @GetMapping("/send") @ApiImplicitParams({ @ApiImplicitParam(name = "phone", value = "手机号", required = true, example = "13800000000", paramType = "query", dataTypeClass = Integer.class), @ApiImplicitParam(name = "code", value = "验证码验证", required = false, example = "889520", paramType = "query") }) public Result sendSms(@NotEmpty(message = "非法的手机号") @Pattern(regexp = "^1[0-9]{10}$", message = "非法的手机号") String phone, String code) throws IOException { if (StringUtils.isNotBlank(code)) { if (smsService.validationCode(phone, code)) { return Result.success("验证码正确"); } return Result.success("验证码错误"); } String result = smsService.sendSms(phone); return Result.success(result); } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异